Python 子进程异常处理

Python subprocess exception handling

本文关键字:异常处理 子进程 Python      更新时间:2023-10-16

我有一个用C++编写的程序,它所做的只是除以 1/0 以产生异常。

我通过 Python 的子进程库运行该程序的.exe。我的目标是捕获并记录程序在 Python 中C++异常。

p = subprocess.Popen(['C:\Users\name\Desktop\Win32Project1.exe'])

当这行代码执行时,p 是一个非零值,这意味着发生了错误。我正在运行Windows 7并使用Python 3.4.1

我很

确定您无法跟踪来自不同进程的异常。您应该尝试在C++程序中捕获异常,并通过许多进程间通信方式之一传递它。

呵呵,卡比

试试这个

cmd = ['C:\Users\name\Desktop\Win32Project1.exe']
out, err = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print out  # this prints the output of the execution
print err  # this prints if any error is returned

我没有窗口,所以这没有经过测试,但可能会对您有所帮助,有关更多信息,请查看此处

您还可以将其他参数传递给子进程。Popen 指定 stdin 和 stderr 去哪里。

然后你可以这样说

p = subprocess.Popen('C:\Users\name\Desktop\Win32Project1.exe', stdout=PIPE, stderr=PIPE)
(stdout_data, stderr_data) = p.communicate()
rc = p.returncode
# assume 0 return code means o.k.
if rc:
  parse_error(stderr_data)
  # end if