cre*_*ive 15 python shell subprocess popen
我试图从python执行shell脚本(而不是命令):
main.py
-------
from subprocess import Popen
Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True)
execute.sh
----------
echo $1 //does not print anything
echo $2 //does not print anything
Run Code Online (Sandbox Code Playgroud)
var1和var2是我用作shell脚本输入的一些字符串.我错过了什么或者有其他办法吗?
mic*_*ses 17
问题在于shell=True.删除该参数,或将所有参数作为字符串传递,如下所示:
Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)
Run Code Online (Sandbox Code Playgroud)
shell只会将您在第一个参数中提供的参数Popen传递给进程,因为它会对参数本身进行解释.看到这里回答的类似问题.实际发生的是你的shell脚本没有参数,所以$ 1和$ 2都是空的.
Popen将从python脚本继承stdout和stderr,因此通常不需要为Popen 提供stdin=和stderr=参数(除非你使用输出重定向运行脚本,例如>).只有在需要读取python脚本中的输出并以某种方式操作它时,才应该这样做.
如果您只需要输出(并且不介意同步运行),我建议尝试check_output,因为它比输出更容易Popen:
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
Run Code Online (Sandbox Code Playgroud)
请注意,check_output并且参数的check_call规则与...相同.shell=Popen