2013-01-02 81 views
1

我遇到了这个问题,其中下面的命令通过python脚本失败,如果我尝试手动运行此命令在任何它通过的Linux机器上的命令行上,只能通过脚本它是失败的,任何输入什么是错误的地方或提示调试?命令失败,通过python脚本,但手动工作

source= Popen(['source build/envsetup.sh'],stdout=PIPE,stderr=PIPE, shell=True) 
stdout,stderr=source.communicate() 
print stdout 
print stderr 
lunchcommand=Popen(['lunch 12'],stderr=PIPE,shell=True) 
stdout,stderr= lunchcommand.communicate() 
print "Printing lunch stdout and stderr" 
print stderr 

/bin/sh: lunch: command not found 
+0

'哪个午餐'的输出是什么?您应该使用脚本中的完整路径。 –

+0

@DiegoBasch - 它不是一个unix实用程序..它是一个本地脚本,所以哪个午餐不会给任何东西 – user1927396

+0

'哪个'不仅仅适用于unix实用程序。它会搜索你的PATH的可执行文件。 –

回答

0

你实际上应该使用th是:

import shlex 
from subprocess import Popen 

the_command = '/path/to/lunch 12' 
result = Popen(shlex.split(the_command)) 

由于12是一个命令的变量的lunch,而不是一部分,shlex将自动拆分命令及其参数的照顾。

你应该通过Popen列表,当你有一个命令和参数在一起。确保你真的需要shell=True?你知道吗what it actually does

+1

你说过:“当你有一个命令和参数时,你应该把Popen列出来。”shlex如何做到这一点?午餐12也是一个命令和论点,对吗? – user1927396

+0

其实我只是意识到在运行午餐命令之前,“午餐”是正在运行的shell脚本中的函数名称(更新了脚本的问题),所以此shell脚本将午餐功能添加到环境中......我可以看到shell脚本是成功的,所以不知道为什么午餐命令失败 - – user1927396

+0

这是因为通过调用不保留环境(请注意,'source'是一个双击,并且您正在使用'sh'运行命令)。 –

1

由于lunchbuild/envsetup.sh定义一个bash功能,您既可以创建调用lunch 12前源build/envsetup.sh bash脚本,或者你可以有Popen执行bash命令如

bash -c "source /tmp/envsetup.sh && lunch 12" 

对于例如:

import subprocess 
import shlex 

with open('/tmp/envsetup.sh', 'w') as f: 
    f.write('function lunch() { KEY="[email protected]"; firefox "www.google.com/search?q=${KEY}" ; }') 
proc = subprocess.Popen(shlex.split('bash -c "source /tmp/envsetup.sh && lunch stackoverflow"')) 
proc.communicate() 
+0

Popen可以同时采用字符​​串和列表,但是当你传入参数时(如这里的情况),最好将它们作为一个列表,以便可以正确完成shell转义。 –

相关问题