我正在编写一个代码来分析 PDF 文件。我想在控制台上显示输出,并在文件中保存输出的副本,我使用以下代码将输出保存在文件中:
import sys
sys.stdout = open('C:\\users\\Suleiman JK\\Desktop\\file.txt',"w")
print "test"
但是我是否也可以将输出显示到控制台,但不使用类,因为我不擅长它们?
(这个答案使用 Python 3,如果您更喜欢 Python 2,则必须对其进行调整。)
首先导入Pythonlogging https://docs.python.org/3/library/logging.html包(和sys
用于访问标准输出流):
import logging
import sys
在你的入口点,设置一个处理程序 https://docs.python.org/3/howto/logging.html#useful-handlers对于标准输出流和输出文件:
targets = logging.StreamHandler(sys.stdout), logging.FileHandler('test.log')
and 配置日志包 https://docs.python.org/3/library/logging.html#logging.basicConfig仅输出不带日志级别的消息:
logging.basicConfig(format='%(message)s', level=logging.INFO, handlers=targets)
现在您可以使用它:
>>> logging.info('testing the logging system')
testing the logging system
>>> logging.info('second message')
second message
>>> print(*open('test.log'), sep='')
testing the logging system
second message
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)