在Python中创建日志错误

2024-04-25 06:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python2.7和pyinstaller创建一个程序。我的程序使用“打印”来显示程序的当前进度。我想让我的程序在发生错误时创建一个错误日志,它将显示打印到屏幕上的各种语句,以便我可以看到它的进度。下面是一个简单的程序,它将导致零分错误:

import os
os.chdir("C:")
logname="Error 30032014 1832"

def subroutine():
    print "Subroutine started"
    print "Stage1 is complete"
    print "Stage2 is complete"
    a=1
    b=0
    c=a/b
subroutine()

结果如下:

Subroutine started
Stage1 is complete
Stage2 is complete

Traceback (most recent call last):
File "C:/Users/Joseph/Desktop/a.py", line 8, in <module>
subroutine()
File "C:/Users/Joseph/Desktop/a.py", line 7, in subroutine
 c=a/b
ZeroDivisionError: integer division or modulo by zero        

我希望生成一个名为logname的文本文件(或者如果可以自动生成带有日期和时间的名称),显示上面显示的信息,以便检查错误。你知道吗


Tags: 程序isos错误usersfilecompleteprint
2条回答

如果要将print语句打印到日志文件,可以将输出流重定向到日志文件:

import sys
stdout = sys.stdout #save the original stdout stream
log_file = open("C:/logfile.log", 'w')
sys.stdout = log_file
print "This happened"  #goes to the log file
print "And that too!"

您可以对sys.stderr执行相同的操作,将异常重定向到可写对象。当然,logging更适合这个目的。你知道吗

Python内置了日志记录工具,您应该使用这些工具进行日志记录。你知道吗

这里有一个链接到日志库的文档:https://docs.python.org/2/library/logging.html

以下是如何使用它的文档示例:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

相关问题 更多 >