test.py代码示例如下:
if __name__ == '__main__':
try:
init_result_file()
# パラメータを読込
parser = argparse.ArgumentParser()
parser.add_argument('--amount', type=int, required=False)
args = parser.parse_args()
except Exception as err:
print(err)
write_error_to_file(f"エラー: {err}")
使用python .test.py --amount时候,由于amount没有赋值,会报错
error: argument --amount: expected one argument
不过这个异常无法捕获,看代码应该是提前退出了,退出代码是2,所以导致无法捕获异常。
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
当通过调用cmd调用python脚本的时候,这种错误很难发现。因此还是需要想办法获取到这个异常,于是想到了windows重定向,不过这里要使用错误重定向。参考windows命令行输出重定向和错误重定向。
python test.py --amount 2>1.txt
更多内容,欢迎关注我的微信公众号:半夏之夜的无情剑客