使用Popen在Python中运行子进程并启动/ wait时无法获取退出代码

史蒂夫·韦默伦

我正在尝试创建一个Python脚本,该脚本将启动一个新窗口并等待其完成,然后检索退出代码。因此,我正在使用Popen withstart /wait为它创建一个单独的窗口,但这不能正确转发退出代码。

这段代码总结了这个问题:

import subprocess

params = {}
params['stdout'] = subprocess.PIPE
params['stderr'] = subprocess.PIPE
params['shell'] = True

proc = subprocess.Popen('start /wait cmd /c exit 1', **params)

# This works but the above line does not
#proc = subprocess.Popen('exit 1', **params)

resultCode = proc.wait()

print(resultCode)

的文档start /wait建议它应该返回退出代码,并且当我手动运行它然后检查%ERRORLEVEL%它是否显示正确时,所以我不确定自己做错了什么

孙ry

如果CMD的start命令通过CreateProcess成功执行了给定的命令,则命令总会成功执行ShellExecuteEx即使得到指示,它也会成功,/wait并最终将其设置%errorlevel%为非零值。您可以通过运行看到这一点(start /wait exit 1) && echo success&&操作仅在左侧的表达式成功执行右边的表达式。

要解决此问题,您可以使用!errorlevel!设置手动退出初始外壳start例如:

command = 'exit 1'
shell_path = os.environ.get('ComSpec', 'cmd.exe')
start_command = 'start "" /wait {}'.format(command)
cmdline = '"{shell}" /v:on /c "({command}) & exit !errorlevel!"'.format(
          shell=shell_path, command=start_command)

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

请注意,上述Popen调用不使用shell=True参数,因为需要使用该/v:on选项手动运行外壳程序这样可以使用“!”延迟扩展环境变量。代替 ”%”。

就是说,您不需要外壳即可实现既定目标。只需让子进程通过传递CREATE_NEW_CONSOLE创建标志来创建一个新的控制台,如下所示:

proc = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_CONSOLE,
           stdout=subprocess.PIPE, stderr=subprocess.PIPE)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Python子进程通讯方法时如何获取退出代码?

无法从Boost子进程获取分段故障退出代码

当我从作为Linux服务运行的python脚本调用Popen时,它无法启动进程

Sublimetext 3:无法在外部 cmd 中获取退出代码

Python:退出后保持由 subprocess.Popen 启动的进程

使用xargs时如何获取退出代码(并行)

使用PowerShell远程安装时获取MSI退出代码

在Python子进程中运行时,使用仪器获取iDevice卡住了

子进程的python退出代码

获取终止进程的退出代码

无法使用python子进程运行linux .sh脚本?

Python-如何在退出程序(在独立屏幕上运行)之前启动子进程?

在python子进程中退出无限进程

Docker在启动时以退出代码退出

使用`wait_variable()`时无法从tkinter应用程序退出python脚本

管道输出时,Python子进程挂起为Popen

无法从python子进程启动make命令

Mongo退出代码45,无法启动mongod,MongoDB无法打开或获取文件锁

从Python获取退出状态代码

当应用程序退出时,不会终止以Python子进程模块启动的进程

Bash获取在子Shell中启动的进程的进程ID

无效参数:无法杀死退出的进程,使用 geckodriver 在 Python 中运行 Selenium

如何从subprocess.Popen获取退出代码?

无法删除用户-运行'/ usr / sbin / userdel'失败:子进程已退出,代码为16

通过init.d脚本启动UWSGI时退出,退出代码为1并显示“ failed”,但进程运行正常

从进程返回的退出代码100-从TFS获取源时出错

获取外部进程退出代码时的PowerShell 3.0行为

为什么在python中退出主进程时子进程(daemon = True)没有退出?

使用带有“set -o pipefail”设置的 Python 脚本从 stdin 读取时获取退出代码 141