gpt4 book ai didi

python - 代码设计和错误处理 : exit program with an error in python

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:57 24 4
gpt4 key购买 nike

我知道有几种终止 python 脚本的方法,但在这里我正在寻找一种良好且健壮的代码设计(这是一种推荐的方法)。

我的大部分代码都是在从主函数调用的函数中编写的。

我想知道从给定函数(从 main 调用)停止运行 python 脚本/程序并向用户提供错误消息的最值得推荐的方法是什么。

我当前设计的示例(如果有一些想法,请评论更好的做法):

import sys


def run_function(x):
if x == 4:
print 'error, x cannot be 4'
sys.exit(0)
else:
print 'good x'
return 0


def main():
x=4
run_function(x)
return 0

最佳答案

只需打印消息,然后使用sys.exit() 结束程序。 argparse 模块使用实用函数(调整为或多或少独立):

def exit(status=0, message=None):
if message:
_print_message(message, sys.stderr)
sys.exit(status)

其中_print_message()将消息写入指定的文件对象,这里是sys.stderr;基本上只是使用 print

关于python - 代码设计和错误处理 : exit program with an error in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com