2014-03-30 36 views
0

我正在使用Python 2.7和pyinstaller來創建一個程序。我的程序使用「打印」來顯示我的程序的當前進度。我想要的是我的程序在發生錯誤時創建一個錯誤日誌,這將顯示打印到屏幕上的各種語句,以便我可以看到它的進度。下面是一個簡單的程序,將導致zerodivisionerror:在登錄時創建一個錯誤Python

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一個文本文件(或者如果可以自動與日期生成名稱和時間),以顯示上述顯示的信息,以便我可以檢查錯誤。

+0

看看[日誌包](https://docs.python.org/2/library/logging.html)。 – Thomas

回答

1

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 
0

如果你希望你的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更適合這個目的。