Python Urwid:如何查看错误?

Python Urwid:如何查看错误?,python,urwid,Python,Urwid,我正在使用urwid库使用交互式控制台界面(第htop行,顶部实用程序)构建应用程序,所以我的问题是:由于界面占用了控制台窗口中的所有空间-我看不到python的错误,所以我尝试这样做: import sys f = open("test_err", "w") original_stderr = sys.stderr sys.stderr = f print a #a is undefined sys.stderr = original_stderr f.close() 它在我不使用ur

我正在使用
urwid
库使用交互式控制台界面(第htop行,顶部实用程序)构建应用程序,所以我的问题是:由于界面占用了控制台窗口中的所有空间-我看不到python的错误,所以我尝试这样做:

import sys
f = open("test_err", "w")
original_stderr = sys.stderr
sys.stderr = f

print a #a is undefined

sys.stderr = original_stderr
f.close() 

它在我不使用urwid时有效,但在我使用它时无效…

您可以尝试将错误重定向到文件。每次运行程序后,都需要刷新文件。大多数编辑器都可以通过按f5轻松完成此操作

def main():
    #your code here
    print someError #raises an error

try: #run main function
    main()
except BaseException as err: #catch all errors
    with open('errors.txt','a') as errors: #open a file to write the errors to
        errors.write(err.message+'\n')#write the error
如果您一次只想在文件中看到一个错误(而不是在一个文件中长时间出现多个错误),请在open函数中将“a”更改为“w”

如果希望在错误发生时正确地看到错误,可以让错误捕获器打开一个包含错误的窗口

def main():
    #your code here
    print someErr

try: #run main function
   main()
except BaseException as err: #catch all errors
    import Tkinter as tk #imports the ui module

    root = tk.Tk() #creates the root of the window

    #creates the text and attaches it to the root
    window = tk.Label(root, text=err.message)
    window.pack()

    #runs the window
    root.mainloop()

如果您想构建自己的窗口来捕获错误,可以了解Tkinter。(它内置于python中,您无需安装任何东西)

以下是我的想法。我正在利用unicode rxvt(urxvt)特性在文件描述符中传递。当然,这意味着您需要在X环境中开发它,而不是在控制台中

from __future__ import print_function

import os
from datetime import datetime

_debugfile = None

def _close_debug(fo):
    fo.close()

def DEBUG(*obj):
    """Open a terminal emulator and write messages to it for debugging."""
    global _debugfile
    if _debugfile is None:
        import atexit
        masterfd, slavefd = os.openpty()
        pid = os.fork()
        if pid: # parent
            os.close(masterfd)
            _debugfile = os.fdopen(slavefd, "w+", 0)
            atexit.register(_close_debug, _debugfile)
        else: # child
            os.close(slavefd)
            os.execlp("urxvt", "urxvt", "-pty-fd", str(masterfd))
    print(datetime.now(), ":", ", ".join(map(repr, obj)), file=_debugfile)
这将在您第一次调用DEBUG时自动打开一个新的终端窗口,并在退出时关闭它。然后,传递给它的任何消息都将显示在此新窗口中。这是您的“调试窗口”。因此,您的主应用程序工作正常,不会出现消息混乱,但您仍然可以在这个新终端中看到调试输出