我如何在文件中写入cmd错误来检查我的python程序?



我想在使用cmd时编写我的python程序的报告。在我的python程序中有几行打印命令。

当我写:

C:/monchemin>program.py>report.txt

好的,很酷,我在一个txt文件中找到了我所有的打印,但是我搜索打印的错误是谁写在我的cmd中。例如,如果cmd说我:

variable x doesn't exist

我需要在报告中保留这个错误。

谢谢你的帮助

您可以使用:

stderr重定向到stdout
C:/monchemin>program.py>report.txt 2>&1

Python的logging模块是处理输出到文件的最佳方式。在处理大型项目时,这将证明比RAW打印更灵活和有用。处理来自标准输出和标准错误的重定向可以像在答案中那样添加。

import logging, sys
class LoggerWriter:
def __init__(self, level):
self.level = level
def write(self, message):
if message != 'n':
self.level(message)
def flush(self):
pass
log = logging.basicConfig(level = logging.WARN, filename="log.txt")

logging.error("This will be logged") # level error > warn
logging.info("This will not be logged") # level info < warn
print("This will not be logged")
#raise TypeError("This will not be logged")
sys.stdout = LoggerWriter(logging.debug)
sys.stderr = LoggerWriter(logging.warning)
print("This will BE logged")
raise TypeError("This will BE logged")

正如你所看到的,可以更好地控制什么要打印,什么不打印到控制台,什么要保存到文件中。

脚本从命令行执行,将所有消息写入文件"report.txt",您可以使用下面提到的语法

C:/monchemin>program.py 1> report.txt 2>&1
  • 标准输出被定向到"report.txt"文件确认1.
  • 重定向数字2标识的标准错误输出到编号为1的输出文件

您还可以通过将输出重定向到NUL而不是文件来关闭标准输出或标准错误。

For example
C:/monchemin>program.py 1> report.txt 2>nul

只重定向标准输出(report.txt文件),但错误不会在控制台中显示,也不会创建错误日志文件。

另一个选项是添加日志调用";program.py"指示已发生某些事件的代码。事件也有一个重要性,也称为级别或严重性。

  • DEBUG:详细信息,通常仅在以下情况下感兴趣诊断问题。
  • INFO: Confirmation that things are working as expected.
  • 警告:表示发生了意想不到的事情,或者表明在不久的将来会出现一些问题(例如"磁盘空间")低")。软件仍按预期工作
  • 错误:由于一个更严重的问题,软件无法执行某些功能。
  • CRITICAL:一个严重的错误,表明程序本身可能是错误的无法继续运行。

script: program.py (add import logging module)

import logging
# The basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.
#  If you run the above script several times, the messages from successive runs are appended to the file ==> default filemode='a'
logging.basicConfig(filename='report.txt', encoding='utf-8', level=logging.DEBUG)
# If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument to filemode='w'
# logging.basicConfig(filename='report.txt', filemode='w', level=logging.DEBUG)
#Logs a message with level DEBUG on the root logger (to report.txt file).
logging.debug('This message should go to the log file')
#Logs a message with level INFO on the root logger (to report.txt file).
logging.info('So should this')
# Logs a message with level WARNING  on the root logger (to report.txt file).
logging.warning('And this, too')
# Logs a message with level ERROR  on the root logger (to report.txt file) .
logging.error('variable x doesn't exist')

链接:请查看https://docs.python.org/3/howto/logging.html

最新更新