Python的Subprocess.Popen Shell = True。等到它完成

时间:2013-12-08 07:56:32

标签: python subprocess popen

提交由完整文件路径构成的复杂 cmd 字符串到可执行文件,多个标志,参数,参数,输入和输出似乎要求我设置 shell = True 否则subprocess.Popen无法理解任何比简单的可执行路径更复杂的东西(文件路径中没有空格)。

在我的例子中,我有一个很长的cmd:

cmd = " '/Application/MyApp.app/Contents/MacOS/my_executable' '/Path/to/input/files' -some -flags -here -could -be -a -lot '/full/path/to/output/files' "

将此cmd提交到 subprocess.Popen “会导致错误,该错误会引发有关路径的某些内容并且无法找到它。

所以不要使用:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

check_call 似乎运作良好:

proc = subprocess.check_call(cmd, shell=True)

有趣的是,只有在 shell 设置为 True

之后
shell=True 

subprocess.check_call 适用于提供的cmd。

副作用是代码的其余部分似乎继续运行而不等待 subprocess.check_call(cmd,shell = True)先完成。

代码的设计方式是执行的其余部分依赖于subprocess.check_call(cmd, shell=True)的结果。

我想知道是否还有强制执行代码执行以等待subprocess.check_call(cmd,shell = True)完成。提前谢谢!

3 个答案:

答案 0 :(得分:2)

正如@mikkas建议只使用list这是一个有效的例子:

mainProcess = subprocess.Popen(['python', pyfile, param1, param2], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# get the return value from the method
communicateRes = mainProcess.communicate()

stdOutValue, stdErrValue = communicateRes

您正在呼叫python.exe pyfile param1 param2

使用communicate(),您可以将stdoutstderr视为Tuple

您可以使用python方法split()将字符串拆分为列表,例如:

cmd = "python.exe myfile.py arg1 arg2"

cmd.split(" ")

输出:

['python.exe', 'myfile.py', 'arg1', 'arg2']

答案 1 :(得分:1)

我认为check_call函数应该等待命令完成。

请参阅此处的文档 http://docs.python.org/2/library/subprocess.html

答案 2 :(得分:-1)

检查电话不等待。你需要这样一个process.wait()并明确检查返回代码以获得你想要的功能。

Process = subprocess.Popen('%s' %command_string,stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            Process.wait()
            if Process1.returncode!=0:
                    print Process1.returncode
                    sendMail()
                    return
            else:
                    sendMail()