RuntimeError: lost sys.stdout

RuntimeError: lost sys.stdout

我试图调试 abc.ABCMeta 的问题 - 特别是子类检查没有按预期工作,我想从简单地向 [=13] 添加 print 开始=] 方法(我知道有更好的方法来调试代码,但为了这个问题假装别无选择)。然而,当开始 Python 之后 Python 崩溃(如分段错误) 我得到这个异常:

Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
  File "C:\...\lib\io.py", line 84, in <module>
  File "C:\...\lib\abc.py", line 158, in register
  File "C:\...\lib\abc.py", line 196, in __subclasscheck__
RuntimeError: lost sys.stdout

所以把 print 放在那里可能不是个好主意。但是异常到底是从哪里来的呢?我只更改了 Python 代码,应该不会崩溃吧?

有人知道这个异常是从哪里来的吗 if/how 我可以避免它但仍然在 abc.ABCMeta.__subclasscheck__ 方法中放置一个 print

我正在使用 Windows 10,Python-3.5(以防万一它可能很重要)。

此异常源于 CPython imports io, and, indirectly, abc.py during the initialization of the standard streams:

if (!(iomod = PyImport_ImportModule("io"))) {
    goto error;
}

io 导入 abc 模块和 registers FileIO 作为 RawIOBase 的虚拟子类,另外几个 类 用于 BufferedIOBase和其他 TextIOBaseABCMeta.register 在此过程中调用 __subclasscheck__

如您所知,当 sys.stdout 不是 设置时,在 __subclasscheck__ 中使用 print 是一个很大的禁忌;初始化失败,您返回错误:

if (initstdio() < 0)
    Py_FatalError(
        "Py_NewInterpreter: can't initialize sys standard streams");

你可以通过 hasattr(sys, 'stdout') 保护它来绕过它,此时 sys 已经初始化,而 stdout 还没有(因此,不会存在于 sys 早期初始化阶段):

if hasattr(sys, 'stdout'):
    print("Debug")

你现在应该在发射 Python 时获得大量输出。