社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中从内部函数提取退出代码

Jeff Xi • 5 年前 • 1505 次点击  

我有两个功能 bar() foo() . 巴尔) 执行 英尺() .

def foo():
    try:
        num = int( input("need an Integer") )
    except ValueError:
        print("input invalid")


def bar():
    foo()

当我跑步的时候 巴尔) 输入一个非整数值,我应该得到 "input invalid" 消息。但是,如果我想自定义此错误消息 “输入无效” 在里面 巴尔) 没有 修改 英尺() . 我该怎么办?

我试过以下方法,但这不起作用。

def foo():
    try:
        num = int( input("need an Integer") )
    except ValueError:
        print("input invalid")


def bar():
    try:
        foo()

    except Exception as result:  <-- this does not capture the error in foo()
        print("my customized error message")  


期望输出为: "my customized error message" 而不是 “输入无效” (但如果我能同时输出这两条消息,这是可以接受的)

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40630
 
1505 次点击  
文章 [ 2 ]  |  最新文章 5 年前
shup
Reply   •   1 楼
shup    6 年前

你基本上是在一个好的方式。你想做的是 raise 中的例外 foo 你能抓住的 bar . 这是通过如下所示的raise命令完成的:

def foo():
    try:
        num = int( input("need an Integer") )
    except ValueError:
        raise Exception("input invalid")


def bar():
    try:
        foo()

    except Exception as e:
        print("my customized error message")  

如果你现在执行 bar() 提出你的例外,你就可以抓住它 巴尔) 再打印一条信息。如果要获取原始邮件,可以通过打印 str(e) .

blhsing
Reply   •   2 楼
blhsing    6 年前

你可以使用 unittest.mock.patch 临时覆盖内置 print 具有自定义函数的函数,该函数使用原始的 打印 函数在传入的消息与要替换的消息匹配时打印所需消息,或者按原样打印消息:

from unittest.mock import patch

def custom_print(s, *args, **kwargs):
    orig_print("my customized error message" if s == "input invalid" else s, *args, **kwargs)

orig_print = print

def bar():
    with patch('builtins.print', new=custom_print):
        foo()

bar()