方法一:利用sys.stdout将print行导向日志文件中
import sys
# make a copy of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file
print "Now all print info will be written to message.log"
# any command line that you will execute
...
log_file.close()
# restore the output to initial pattern
sys.stdout = stdout_backup
print "Now this will be presented on screen"
方法二:利用logging模块(规范化日志输出,推荐!!)
但是,logging的屏幕输出会有类型前缀,所以本人用了法一。
#a simple sample
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
output
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too