作为开发人员尝试从 php 转换为 python。当前正在尝试调试运行大约需要 45 分钟的 python 脚本。从命令行运行时还没有死。从 cron 运行时死掉大约一半的时间。
使用 php,我可以回到它运行的那个框,检查它运行时间的日志文件,如果脚本被炸毁,则查找/修复错误。 python有类似的吗?
请您参考如下方法:
Python 可以在文件中打印日志,但这不是您开箱即用的行为。默认情况下,它会在 stderr 上打印日志级别等于或高于 WARNING 的日志:
import logging
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
运行此脚本时会发生以下情况:
$ python log.py
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
$ python log.py 2>/dev/null # does not print anything
$
因此,如果您在 cron 作业中将 stderr 重定向到一个文件,您至少应该在该文件中看到警告和错误。如果您想轻松地直接登录到一个文件中,您可以使用 logging.basicConfig:
import logging
# print log in example.log instead of the console, and set the log level to DEBUG (by default, it is set to WARNING)
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
现在如果你运行它,你应该不会再在控制台中有任何输入,但所有内容都应该在 example.log 中:
$ python log.py
$ cat example.log
DEBUG:root:debug
INFO:root:info
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
您将在 logging HOWTO page 中找到更多详细信息和配置选项
