18

我正在尝试从 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 脚本输入的一些字符串。我错过了什么还是有其他方法可以做到这一点?

参考:如何使用子进程popen Python

4

3 回答 3

19

问题出在shell=True. 删除该参数,或将所有参数作为字符串传递,如下所示:

Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)

shell 只会将您在第一个参数中提供的参数传递Popen给进程,因为它会解释参数本身。请参阅此处回答的类似问题实际发生的是你的 shell 脚本没有参数,所以 $1 和 $2 是空的。

Popen 将从 python 脚本继承 stdout 和 stderr,因此通常不需要向 Popen 提供stdin=andstderr=参数(除非您使用输出重定向运行脚本,例如>)。仅当您需要读取 python 脚本中的输出并以某种方式对其进行操作时,才应该这样做。

如果您只需要获取输出(并且不介意同步运行),我建议您尝试check_output,因为它比获取输出更容易Popen

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)

请注意check_outputcheck_call具有与 相同的shell=参数规则Popen

于 2013-10-11T20:09:05.647 回答
3

你实际上是在发送参数......如果你的 shell 脚本写了一个文件而不是打印你会看到它。你需要沟通才能看到脚本的打印输出......

from subprocess import Popen,PIPE

Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True,stdin=PIPE,stderr=PIPE)
print Process.communicate() #now you should see your output
于 2013-10-11T19:29:34.030 回答
3

如果你想以一种简单的方式从 python 脚本向 shellscript 发送参数。你可以使用 python os 模块:

import os  
os.system(' /path/shellscriptfile.sh {} {}' .format(str(var1), str(var2)) 

如果您有更多参数.. 增加花括号并添加参数.. 在 shellscript 文件中.. 这将读取参数,您可以相应地执行命令

于 2020-07-01T18:32:57.050 回答