我正在尝试从 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
var1 和 var2 是我用作 shell 脚本输入的一些字符串。我是否遗漏了什么或者是否有其他方法可以做到这一点?
最佳答案
问题出在shell=True
.要么删除该参数,要么将所有参数作为字符串传递,如下所示:
Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)
shell 只会传递您在 Popen
的第一个参数中提供的参数过程,就像它对论点本身的解释一样。
查看类似问题的回答here.实际发生的是您的 shell 脚本没有参数,因此 $1 和 $2 为空。
Popen 将从 python 脚本继承 stdout 和 stderr,所以通常不需要提供 stdin=
和 stderr=
Popen 的参数(除非您使用输出重定向运行脚本,例如 >
)。仅当您需要读取 python 脚本中的输出并以某种方式对其进行操作时才应执行此操作。
如果您只需要获取输出(并且不介意同步运行),我建议您尝试 check_output
,因为它比 Popen
更容易获得输出:
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
注意 check_output
和 check_call
对 shell=
有相同的规则参数为 Popen
.
关于Python:使用参数(变量)执行 shell 脚本,但参数未在 shell 脚本中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325761/