提交由完整文件路径组成的复杂 cmd 字符串到可执行文件,多个标志、参数、参数、输入和输出似乎需要我设置 shell=True 否则 subprocess.Popen 无法理解比可执行文件的简单路径(文件路径中没有空格)更复杂的东西。
在我的示例中,我有一个很长的命令:
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) 完成。提前致谢!
最佳答案
正如@mikkas 所建议的那样,只需将它用作列表
,这是一个工作示例:
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()
,您可以获得 stdout
和 stderr
作为 Tuple
您可以使用 python 方法 split()
将您的字符串拆分为一个列表,例如:
cmd = "python.exe myfile.py arg1 arg2"
cmd.split(" ")
输出:
['python.exe', 'myfile.py', 'arg1', 'arg2']
关于Python 的 Subprocess.Popen With Shell=True。等到它完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20451133/