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

标签 python subprocess popen

提交由完整文件路径组成的复杂 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(),您可以获得 stdoutstderr 作为 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/

相关文章:

C 检测 popen 子进程中的错误

python - 将终端输出捕获到 pandas 数据框中,而不创建外部文本文件

Python:如何生成按键?

python - 我应该如何解释 numpy.fft.rfft2 的输出?

Javascript 生成的验证码

python - 将带有列表和内部字典的字典转换为 df

python - 如何在管道中使用 `subprocess` 命令

python - 实时读取/写入子进程标准输入/标准输出

python-3.x - 从子进程中流式读取

jquery - 迭代 Select 选项时出现 Python Selenium StaleElementReferenceException