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

标签 python error-handling exit

我知道有几种终止 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/

相关文章:

python - 如何在背景中绘制文字和图像?

angular - 如何测试Promise catch block 是否设置了this.error

node.js - 在调用另一个函数的函数中处理 UnhandledPromiseRejectionWarning

python - os.system ('exit' ) 在 python 中

C#控制台应用程序,退出缓慢

python - 利用Elasticsearch dsl python分析api

python - 在python中将日期时间转换为时间

python - pandas dataframe 从元素频率大于 1 的列创建唯一 ID

ios - Swift 嵌套在闭包内尝试

c++ - 如何在 mainloop 正在监听消息的特定时间退出程序?