我正在尝试创建一个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%
它是否显示正确时,所以我不确定自己做错了什么
如果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] 删除。
我来说两句