簡體   English   中英

Python - sys.stderr 未保存到 .txt 或 .log

[英]Python - sys.stderr not getting saved to .txt or .log

我正在檢查標准流的工作情況,目前我正在使用 python 處理stderr 為了解釋清楚,以下是我的代碼:

print("Python")
testt()

當我運行代碼時,我得到以下信息:

Python
Traceback (most recent call last):
File "C:/Python34/s3.py", line 5, in <module>
testt()
NameError: name 'testt' is not defined

現在我想將錯誤消息保存到一個文本文件中,所以我的代碼如下:

import sys

sys.stderr = open('err.txt', 'w') # I tried with 'err.log' also
print("Python")
testt()

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

現在,當我運行程序時,python shell 中沒有顯示錯誤。 它也沒有保存到err.txt文件中。

當我檢查err.txt文件屬性時,它顯示該文件最近已被修改(即程序運行的時間),但該文件是空白的。 可能是什么問題? 我正在使用 Windows 和 python 3.4。


我安裝了 python 3.5,但仍然遇到同樣的問題。 我也嘗試過使用contextlib,但還是沒有成功。 我使用contextlib修改后的代碼如下:

from contextlib import redirect_stdout, redirect_stderr

with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/outfile.txt', 'w') as file, redirect_stdout(file):
    help(pow)

with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/errfile.log', 'a') as file1, redirect_stderr(file1):
    testt()

redirect_stdout(file)工作正常,它將輸出保存到文件中; redirect_stderr(file1)沒有將stderr保存到文件中。

可能是什么問題?

似乎sys.stderr從未關閉過。 testt()出錯時,程序退出——只是錯誤信息被重定向。 所以文件是空白的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM