如何强制os.system()使用bash代替shell [英] How to force os.system() to use bash instead of shell
问题描述
我已经尝试了>如何强制/bin/bash解释器oneliners
这样做
os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')
但是,没有运气,不幸的是,我需要使用bash运行此命令,并且在这种环境下,subp并不是选项,我仅限于python 2.4.有什么建议可以使我朝正确的方向发展吗?
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?
推荐答案
两个命令都在不同的子shell中执行.
Both commands are executed in different subshells.
在第一个system
调用中设置变量不会影响第二个system
调用.
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
注意,您需要使用"$GREPDB"
而不是'$GREPDBS'
.否则,它将按字面意义进行解释,而不是进行扩展.
NOTE You need to use "$GREPDB"
instead of '$GREPDBS'
. Otherwise it is interpreted literally instead of being expanded.
如果可以使用subprocess
:
>>> import subprocess
>>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
... env={'GREPDB': 'echo 123'})
123
0
这篇关于如何强制os.system()使用bash代替shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!