python - 运行时错误 : lost sys. 标准输出

标签 python python-3.x cpython python-internals

我试图调试 abc.ABCMeta 的问题 - 特别是子类检查没有按预期工作,我想从简单地添加 print 开始> 到 __subclasscheck__ 方法(我知道有更好的方法来调试代码,但为了这个问题假装别无选择)。然而,当之后启动 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 代码,应该不会崩溃,对吧?

有人知道这个异常是从哪里来的吗?我是否/如何避免它,但仍然在 abc.ABCMeta.__subclasscheck__ 方法中放置一个 print

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

最佳答案

此异常源于 CPython imports io ,并且在 initialization of the standard streams 期间间接地 abc.py :

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

io 导入 abc 模块和 registers FileIO作为 RawIOBase 的虚拟子类,BufferedIOBase 的几个其他类和 TextIOBase 的其他类。 ABCMeta.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 时应该会得到大量输出。

关于python - 运行时错误 : lost sys. 标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43987751/

相关文章:

python - 获取字典值的 value_counts()

python-3.x - 移除 HoloViews 中的 Bokeh Logo

python - 从 HTML 中提取标题不起作用

python - 为什么类中的print语句在一个对象还没有创建的时候就被执行了?

python - 当人们说 CPython 是用 C 编写的时,这意味着什么?

python - list() 使用的内存比列表推导略多

python - 对Python对象的许多属性执行相同的操作

python - python threading.Lock() 是否锁定所有需要锁定的东西?

python - flask 中的奇怪错误 :

python - 如何在 Python 中获取 mmap-ed 内存的地址?