2013-10-11 40 views
12

我试图从蟒蛇执行shell脚本(而不是命令):的Python:执行shell脚本参数(变量),但参数不是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

回答

12

问题出在shell=True。或者删除这样的说法,或者通过所有参数作为一个字符串,如下所示:

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

壳只会把你的Popen的过程中,第一个参数提供的参数,因为它的参数本身的解释。 看到一个类似的问题回答here.实际情况是你的shell脚本没有参数,所以$ 1和$ 2是空的。

POPEN将继承python脚本输出和错误,所以通常没有必要提供stdin=stderr=参数POPEN(除非你用输出重定向脚本,如>)。只有当您需要读取python脚本中的输出并以某种方式操作时,才应该这样做。

如果你需要的是让输出(并且不介意同步运行),我建议你尝试check_output,因为它更容易获得产量比Popen

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

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

+0

是的...这是有用的它解决了我的问题。 – creativeDrive

+0

@ user2837135如果它解决了你的问题,你应该接受它(点击复选标记),也可以考虑upvoting。 – SethMMorton

+0

在这种情况下''= True''不应该被使用,但是如果你使用它,那么你应该使用['shlex.quote()'](http://docs.python)来转义'var1','var2'。 org/3/library/shlex.html#shlex.quote):'output = check_output(“./ childdir/execute.sh”+“”.join(pipes.quote(str(v))for v in [var1, var2]),shell = True)' – jfs

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 
+1

此外,他们可以使用'subprocess.call(['./ childdir/execute.sh',str(var1),str(var2)],shell = True)'如果他们想要做的只是看到输出。 – SethMMorton

+0

@Joran:我能够看到shell = True的shell脚本输出,我可以看到$ 0('./ childdir/execute.sh'),即正在执行的脚本,但不是参数var1,var2。 – creativeDrive

+0

可能会在shell脚本的顶部添加一个shebang ...它可能不会在bash中运行,但是我保证你发送的是参数(可能参数不是你认为的那些参数) –