Python argparse 错误到文件 [英] Python argparse errors to file
问题描述
我正在尝试制作一个脚本,该脚本接收所有错误并将它们记录到日志文件中.我想在这个文件中包含任何 argparse
错误.我已经使用 logging
包和 sys.excepthook
来驱动日志文件的意外异常.
I am trying to make a script that takes all errors and logs them to a log file. I want to include any argparse
errors to this file. I already use the logging
package and a sys.excepthook
to drive unexpected exceptions to the log file.
这是一个示例代码:
import argparse
import logging
import sys
import traceback
def log_uncaught_exceptions(ex_cls, ex, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
logging.basicConfig(
level=logging.DEBUG,
filename='foo.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s')
sys.excepthook = log_uncaught_exceptions
logging.debug('This is a typical debug line')
parser = argparse.ArgumentParser(description='Foo String')
parser.add_argument('foo',type=int)
args = parser.parse_args()
logging.debug('Input was %i'%(args.foo))
当我使用 python logger_argparse.py 1
运行它时,一切都很好.如果我运行 python logger_argparse.py a
我会在控制台中得到输出而不是日志文件:
When I run it with python logger_argparse.py 1
everything works great. If I run python logger_argparse.py a
I get the output in the console and not the log file:
usage: logger_argparse.py [-h] foo
logger_argparse.py: error: argument foo: invalid int value: 'a'
如何获取该信息以转到日志文件?
How do I get that information to go to the log file?
推荐答案
你可以使用 logging.exception 在异常处理程序中?那么只从 ArgumentParser.error()
记录怎么样?
Can you use logging.exception in an exception handler?
so how about just logging from ArgumentParser.error()
?
import sys
import logging
import argparse
class argparse_logger(argparse.ArgumentParser):
def error(self, message):
logging.error(message)
super().error(message)
logging.basicConfig(
level=logging.DEBUG,
filename='foo.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s')
# parser = argparse.ArgumentParser(description="Foo")
parser = argparse_logger(description="Foo")
parser.add_argument('foo',type=int)
logging.debug("Start")
try:
args = parser.parse_args(sys.argv[1:])
except:
print("Error handling arguments")
raise
logging.debug(f"Finish - {args.foo}")
print(f"Exiting! - {args.foo}")
这将显示以下内容:
J:\>python arg_parse_log.py 5
Exiting! - 5
J:\>more foo.log
2018-02-07 11:34:45,647 - DEBUG - Start
2018-02-07 11:34:45,648 - DEBUG - Finish - 5
J:\>python arg_parse_log.py
usage: arg_parse_log.py [-h] foo
arg_parse_log.py: error: the following arguments are required: foo
Error handling arguments
J:\>more foo.log
2018-02-07 11:34:54,577 - DEBUG - Start
2018-02-07 11:34:54,578 - ERROR - the following arguments are required: foo
这篇关于Python argparse 错误到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!