Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force os.system() to use bash instead of shell

I've tried what's told in How to force /bin/bash interpreter for oneliners

By doing

os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')

However no luck, unfortunately I need to run this command with bash and subp isn't an option in this environment, I'm limited to python 2.4. Any suggestions to get me in the right direction?

like image 796
sunshinekitty Avatar asked Feb 17 '14 06:02

sunshinekitty


2 Answers

Both commands are executed in different subshells.

Setting variables in the first system call does not affect the second system call.

You need to put two command in one string (combining them with ;).

>>> import os
>>> os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
123
0

NOTE You need to use "$GREPDB" instead of '$GREPDBS'. Otherwise it is interpreted literally instead of being expanded.

If you can use subprocess:

>>> import subprocess
>>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
...                 env={'GREPDB': 'echo 123'})
123
0
like image 91
falsetru Avatar answered Sep 22 '22 19:09

falsetru


The solution below still initially invokes a shell, but it switches to bash for the command you are trying to execute:

os.system('/bin/bash -c "echo hello world"')
like image 24
mgoldwasser Avatar answered Sep 25 '22 19:09

mgoldwasser