Python:使用参数(变量)执行shell脚本,但是在shell脚本中不读取参数

时间:2013-10-11 19:26:22

标签: 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

var1和var2是我用作shell脚本输入的一些字符串。我错过了什么或有其他办法吗?

简称:How to use subprocess popen Python

3 个答案:

答案 0 :(得分:16)

问题在于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,因此通常不需要向Popen提供stdin=stderr=参数(除非您使用输出重定向运行脚本,例如{{ 1}})。只有在需要读取python脚本中的输出并以某种方式操作它时,才应该这样做。

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

Popen

请注意,output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)]) print(output) check_outputcheck_call参数的规则与shell=具有相同的规则。

答案 1 :(得分: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

答案 2 :(得分:1)

如果要以简单的方式将参数从python脚本发送到shellscript,则可以使用python os模块:

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

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

相关问题