Skip to main content
 首页 » 编程设计

python之将 Python 错误写入 txt 文件

2025年05月04日9fff_TT

我在让它正常工作时遇到了问题(很明显)——我几乎就在那里,而且我很清楚为什么它不工作——只是不确定如何让它工作。

这是假设尝试将文件读入内存,如果失败则转到代码块的“except”子句(该部分是“duh”)。错误文件打印:“<ma​​in.DebugOutput instance at 0x04021EB8>”。我想要它做的是打印实际的错误。就像 FileIOError 或 TraceBackError 或该错误文件的任何内容。这只是开始阶段,我计划添加日期戳之类的东西并让它附加,而不是写入/创建——我只需要将实际错误打印到文件中。有什么建议吗?

import os, sys 
 
try: 
    myPidFile = "Zeznadata.txt" 
    myOpenPID_File = open(myPidFile, "r") #Attempts to open the file 
    print "Sucessfully opened the file: \"" + myPidFile + "\"." 
 
except: 
    print "This file, \"" + myPidFile + "\", does not exist.  Please check the file name and try again.  " 
    myFileErr = open("PIDErrorlog.txt", "w") 
    myStdError = str(sys.stderr) 
    myFileErr.write(myStdError) 
    myFileErr.close() 
    print "\nThis error was logged in the file (and stored in the directory): " 

请您参考如下方法:

首先,您应该使用日志记录库。它将帮助您处理不同的日志记录级别(信息/警告/错误)、时间戳等。

http://docs.python.org/library/logging.html

其次,您需要捕获错误,然后您可以记录有关它的详细信息。此示例来自 Python 文档。

import sys 
 
try: 
    f = open('myfile.txt') 
    s = f.readline() 
    i = int(s.strip()) 
 
except IOError as (errno, strerror): 
    print "I/O error({0}): {1}".format(errno, strerror) 
except ValueError: 
    print "Could not convert data to an integer." 
except: 
    print "Unexpected error:", sys.exc_info()[0] 
    raise 

看看它是如何捕获 IOError 并将错误编号和错误消息分配给变量的?对于要处理的每种类型的错误,您都可以有一个 except block 。在最后一个(一般错误) block 中,它使用 sys.exc_info()[0] 获取错误详细信息。

http://docs.python.org/tutorial/errors.html