[英]Python subprocess exception handling
我有一个用C ++编写的程序,它所做的就是将1/0除以产生异常。
我通过Python的子进程库运行该程序的.exe。 我的目标是在Python内捕获并记录C ++程序产生的异常。
p = subprocess.Popen(['C:\\Users\\name\\Desktop\\Win32Project1.exe'])
当这行代码执行时,p为非零值,表示发生了错误。 我正在运行Windows 7并使用Python 3.4.1
我非常确定您无法跟踪来自其他流程的异常。 您应该尝试在C ++程序中捕获该异常,并通过许多进程间通信方式之一将其传递。
HTH,卡比
尝试这个
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
我没有窗户,因此未经过测试,但可能会对您有所帮助,有关更多信息,请参见此处
您还可以将其他参数传递给subprocess.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.