将Pythons错误写入txt文件

Jus*_*oll 1 python error-handling

我无法正常工作(很明显) - 我几乎就在那里,我很清楚为什么它不起作用 - 只是不知道如何让它工作.

这是假设尝试将文件读入内存,如果失败则转到代码块的"except"子句(该部分为'duh').错误文件打印:"< main .DebugOutput instance in 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): "
Run Code Online (Sandbox Code Playgroud)

Ali*_* R. 7

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

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
Run Code Online (Sandbox Code Playgroud)

了解它如何捕获IOError并将错误号和错误消息分配给变量?您可以except为要处理的每种类型的错误设置一个块.在最后一个(通用错误)块中,它用于sys.exc_info()[0]获取错误详细信息.

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