Python的Subprocess.Popen with Shell = True.等到完成 [英] Python's Subprocess.Popen With Shell=True. Wait till it is completed
问题描述
提交一个复杂的 cmd 字符串,该字符串由可执行文件的完整文件路径组成,多个标志,参数,参数,输入和输出似乎需要我设置 shell = True strong>否则为子进程.Popen除了简单的可执行文件路径(文件路径中没有空格)之外,还无法理解其他任何复杂的东西.
Submitting a complex cmd string made of a full file path to an executable, the multiple flags, arguments, parameters, inputs and outputs seems to require me to set shell=True otherwise subprocess.Popen is not able understand anything more complex than just a simple path to executable (with no spaces in a filepath).
在我的示例中,我有一个很长的cmd:
In my example I have quite a long 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 会导致错误,提示有关路径的某些内容而无法找到它.
Submitting this cmd to subprocess.Popen " results to an error that complains on something about the path and not being able to find it.
所以不要使用:
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一起使用.
the subprocess.check_call works with a supplied cmd.
副作用是其余代码似乎可以继续运行,而无需等待 subprocess.check_call(cmd,shell = True)首先完成.
The side effect is that the rest of the code seems proceeds running without waiting for subprocess.check_call(cmd, shell=True) to finish first.
设计代码的方式是,其余执行依赖于subprocess.check_call(cmd, shell=True)
的结果.
The code is designed the way that the rest of the execution is dependent on a result of subprocess.check_call(cmd, shell=True)
.
我想知道是否有强制代码执行以等待subprocess.check_call(cmd,shell = True)完成的方法.预先感谢!
I wonder if there is anyway to enforce the code execution to wait till subprocess.check_call(cmd, shell=True) is finished. Thanks in advance!
推荐答案
正如@mikkas建议将其用作list
一样,这是一个有效的示例:
As @mikkas suggest just use it as a list
here is a working example:
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
By using communicate()
you can get the stdout
and stderr
as a Tuple
您可以使用python方法split()
将字符串拆分为列表,例如:
You can use python method split()
to split your string to a list for example:
cmd = "python.exe myfile.py arg1 arg2"
cmd.split(" ")
输出:
['python.exe', 'myfile.py', 'arg1', 'arg2']
这篇关于Python的Subprocess.Popen with Shell = True.等到完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!