【问题标题】:Python subprocess exception handlingPython子进程异常处理
【发布时间】:2014-11-13 18:15:26
【问题描述】:

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

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

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

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

【问题讨论】:

  • 根据您需要多少控制,您需要处理 stdout 和 stderr 管道 + wait() 返回值。也许check_output 能帮到你?
  • 当这行代码执行时,p 是一个非零值,意味着发生了错误 - 不,这不是发生的情况。 subprocess.Popen 返回一个从不为零的 Popen 对象。如果您愿意,可以致电p.wait() 并获取返回码。

标签: python c++ exception visual-studio-2012 subprocess


【解决方案1】:

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

HTH, 出租车

【讨论】:

  • 当我用windbg运行进程时,它会跟踪异常并记录错误,所以它一定是可能的,是吗?在我的情况下,浏览 C++ 代码并对其进行修改不是一个选项。
  • 您可以使用 python 与平台的调试工具进行交互。我搜索了call windows debug hooks from python,得到了一些有趣的答案,比如winappdbg。但是为了公平起见@cabbi,您在这里没有提到您正在尝试编写调试器,这有点让他措手不及。对于大多数用户而言,您不会尝试从其他程序中获取异常。
  • 我发现并可能有效的最佳解决方案(我没有测试过)是在新的应用程序域中启动进程。这是 C# 中的一个示例:social.msdn.microsoft.com/Forums/vstudio/en-US/…
  • @tdelaney winappdbg 最终解决了我的问题,谢谢!
【解决方案2】:

试试这个

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

我没有 Windows,所以这没有经过测试,但可能会对您有所帮助,更多信息请查看 here

【讨论】:

    【解决方案3】:

    您还可以将其他参数传递给 subprocess.Popen 以指定 stdin 和 stderr 的位置。

    然后你可以说 something 比如:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 2015-01-11
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多