未显示Pyhton运行时错误消息

问题描述 投票:0回答:1

我编写的Python代码如下。

stderr = sys.stderr
sys.stderr = open(error_file, 'w')

# main code in between 

sys.stderr.close()
sys.stderr = stderr

出现错误时,不会显示,但会写入以下消息

Traceback (most recent call last):
  File "/Users/burcakotlu/developer/python/EUMaster4HPC/eumaster4hpc_venv/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 424, in dispatch_shell
    await result
  File "/Users/burcakotlu/developer/python/EUMaster4HPC/eumaster4hpc_venv/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 770, in execute_request
    sys.stderr.flush()
ValueError: I/O operation on closed file.
[IPKernelApp] ERROR | Error in message handler
Traceback (most recent call last):
  File "/Users/burcakotlu/developer/python/EUMaster4HPC/eumaster4hpc_venv/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 529, in dispatch_queue
    await self.process_one()
  File "/Users/burcakotlu/developer/python/EUMaster4HPC/eumaster4hpc_venv/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 518, in process_one
    await dispatch(*args)
  File "/Users/burcakotlu/developer/python/EUMaster4HPC/eumaster4hpc_venv/lib/python3.9/site-packages/ipykernel/kernelbase.py", line 437, in dispatch_shell
    sys.stderr.flush()
ValueError: I/O operation on closed file.

如何获取准确的错误信息? 为什么它没有写入error_file?里面是空的。

python runtime-error
1个回答
0
投票

open 根据此处的 Python 文档返回一个文件对象https://docs.python.org/3/library/functions.html#open

您共享的代码将 sys.stderr 设置为与您的 error_file 相关的文件对象。

如果您想写入文件,正确的语法是:

with file_obj = open(error_file, "w")
  write operations here

with命令用于在块执行完毕后自动关闭文件。

从你的代码中我收集到你想要的是向 stderr 写入一些内容。 这可以通过以下方式之一完成: 在 Python 3 中,您可以使用 print 写入 stderr

import sys

print('Hello world', file=sys.stderr)

或者您在 stderr 本身上使用 write 方法,但这不会将换行符附加到行尾,因此请务必自己附加它。

import sys

sys.stderr.write('Hello world')
© www.soinside.com 2019 - 2024. All rights reserved.