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

喜欢而已 提交于 2019-11-30 05:49:15

问题


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?


回答1:


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



回答2:


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"')



回答3:


I use this:

subprocess.call(["bash","-c",cmd])

//OK, ignore this because I have not notice subprocess not considered.




回答4:


Is it possible, for you, to change the default shell of the user who starts the application ? You could try to use chsh to do it.




回答5:


I searched this command for some days and found really working code:

import subprocess

def bash_command(cmd):
    subprocess.Popen(['/bin/bash', '-c', cmd])

code="abcde"
// you can use echo options such as -e
bash_command('echo -ne "'+code+'"')

Output:

abcde



回答6:


subprocess.Popen(cmd, shell=True, executable='/bin/bash')


来源:https://stackoverflow.com/questions/21822054/how-to-force-os-system-to-use-bash-instead-of-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!