RuntimeError:丢失了sys.stdout [英] RuntimeError: lost sys.stdout
问题描述
我正尝试调试 abc.ABCMeta
的问题-特别是子类检查未按预期工作,我想从简单地添加 print
到 __ subclasscheck __
方法(我知道有更好的方法来调试代码,但是为了这个问题而假装别无选择)。但是,在随后启动Python时,Python崩溃(如分段错误)并且,我得到了这个异常:
I was trying to debug an issue with abc.ABCMeta
- in particular a subclass check that didn't work as expected and I wanted to start by simply adding a print
to the __subclasscheck__
method (I know there are better ways to debug code, but pretend for the sake of this question that there's no alternative). However when starting Python afterwards Python crashes (like a segmentation fault) and I get this exception:
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
将打印
放在其中是一个好主意。但是异常从何而来呢?我只更改了Python代码,不应该崩溃,对吧?
So it probebly wasn't a good idea to put the print
in there. But where exactly does the exception come from? I only changed Python code, that shouldn't crash, right?
有人知道此异常来自何处,如果/如何避免,但仍然放置了 print
在 abc.ABCMeta .__ subclasscheck __
方法中?
Does someone know where this exception is coming from and if/how I can avoid it but still put a print
in the abc.ABCMeta.__subclasscheck__
method?
我正在使用Windows 10,Python-3.5(以防万一,这可能很重要)。
I'm using Windows 10, Python-3.5 (just in case it might be important).
推荐答案
此异常源于以下事实:CPython 在 abc.py
https://github.com/python/cpython/blob/a77a35d70ba8aed047e63d4d9f7d0554e98d4c4b/Python/pylifecycle.c#L784 rel = nofollow noreferrer>标准流的初始化:
This exception stems from the fact that CPython imports io
, and, indirectly, abc.py
during the initialization of the standard streams:
if (!(iomod = PyImport_ImportModule("io"))) {
goto error;
}
io
会导入 abc
模块和将 FileIO
注册为 RawIOBase
的虚拟子类,以及<$ c的其他两个类$ c> BufferedIOBase 和其他 TextIOBase
。 ABCMeta.register
在此过程中调用 __ subclasscheck __
。
io
imports the abc
module and registers FileIO
as a virtual subclass of RawIOBase
, a couple of other classes for BufferedIOBase
and others for TextIOBase
. ABCMeta.register
invokes __subclasscheck__
in the process.
如您所知,在 __ subclasscheck __
中使用 print
sys.stdout
不是设置是一个很大的禁止。初始化失败并返回错误:
As you understand, using print
in __subclasscheck__
when sys.stdout
isn't set-up is a big no-no; the initialization fails and you get back your error:
if (initstdio() < 0)
Py_FatalError(
"Py_NewInterpreter: can't initialize sys standard streams");
您可以通过使用 hasattr(sys,' stdout')
, sys
已被初始化,而 stdout
尚未(并且因此在早期初始化阶段的 sys
中将不存在):
You can get around it by guarding it with a hasattr(sys, 'stdout')
, sys
has been initialized by this point while stdout
hasn't (and, as such, won't exist in sys
in the early initialization phase):
if hasattr(sys, 'stdout'):
print("Debug")
现在启动Python时,您应该获得大量输出。
you should get good amount of output when firing Python up now.
这篇关于RuntimeError:丢失了sys.stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!