【问题标题】:capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)从 python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) 捕获标准错误
【发布时间】:2009-05-27 06:51:33
【问题描述】:

我在这里看到这个帖子很多次了;但未能从命令中捕获故意错误。到目前为止我发现的最好的部分工作..

from Tkinter import *
import os
import Image, ImageTk
import subprocess as sub
p = sub.Popen('datdsade',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()

root = Tk()
text = Text(root)
text.pack()
text.insert(END, output+ "Error: " + errors )
root.mainloop()

【问题讨论】:

  • 感谢您对 SpliFF 的回答。为了清楚起见,“PyMOTW:Doug Hellmann 的子流程”在这里 [oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html] from Tkinter import * import subprocess proc=subprocess.Popen('TestSomeCommandThatDoesNotExisit',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr= subprocess.STDOUT,) stdout_value, stderr_value = proc.communicate() root = Tk() text = Text(root) text.pack() text.insert(END, repr(stdout_value)) root.mainloop() 我没有合并stderr=sub.STDOUT 再次感谢 ombre :) ~nolo

标签: python subprocess


【解决方案1】:

这对我来说非常适合:

import subprocess
try:
    #prints results
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex:
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output

【讨论】:

    【解决方案2】:

    您是否 100% 确定“datdsade”实际上会写入标准错误?如果是这样,那么它可能正在缓冲它的标准错误,或者阻塞它。

    编辑:我建议在 bash 中运行“datdsade”(你的程序)(假设你有 linux,你可以 dl sh.exe 用于 windows)并查看你是否可以将你的 stderr 捕获到文件 datdsade 2> 错误。文本。请注意,如果您在 Windows 上,stderr 将不会在 DOS 窗口中输出。您可能会更幸运地先写入日志文件并将其读回或让 python 将其存储在变量中。

    或者 stderr=sub.STDOUT 会将您的错误与标准输出合并。

    再次编辑:忽略上述内容,因为communicate() 正在捕获所有这些内容。我会说问题肯定是您选择的程序永远不会写入stderr,或者您实际上并没有触发错误。这就是程序的编写方式。程序是什么?

    【讨论】:

    • 你有什么建议?花了不少时间阅读;但大多数指向已弃用的用法。 o.spawn 等。在此先感谢 :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 2013-11-26
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多