Python的Subprocess.Popen,带有Shell = True。等到完成为止

问题描述 投票:6回答:3

将复杂的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)完成的过程。预先感谢!

将由完整文件路径组成的复杂cmd字符串提交给可执行文件,多个标志,参数,参数,输入和输出似乎要求我设置shell = True否则为子进程。...

python subprocess popen
3个回答
2
投票
通过使用communicate(),您可以将stdoutstderr作为Tuple获得

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

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

cmd.split(" ")

输出:

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


1
投票

检查呼叫不等待。您需要执行一个process.wait()并显式检查返回码以获得所需的功能。

© www.soinside.com 2019 - 2024. All rights reserved.