【问题标题】:Is there a way to find out if a line of code is being executed within a "try" in Python?有没有办法找出是否在 Python 的“尝试”中执行了一行代码?
【发布时间】:2014-07-09 04:20:05
【问题描述】:

环境:Python 2.6.5,Eclipse Standard/SDK(版本 Kepler SR2)和 Pydev

有没有办法查出一行代码是否正在执行 Python中的“尝试”?

我正在处理的代码有时会包含调用方法的 try 块,并且在某些情况下,我需要一个条件,这取决于脚本是否会以异常退出以及脚本何时会继续。

我需要在没有在每个 try 语句之前设置标志的情况下完成此操作,但是如果有一种方法可以全局覆盖每个 try 语句以在它处于 try 语句时设置标志并在它超出时清除标志可行的 try 语句。

由于我正在处理一个庞大的代码库,因此在开始每个 try 块之前设置一个标志会太费力了。

我尝试在调试模式下比较变量,而不是在尝试中,但我没有注意到我可以关闭任何东西。

例子:

def raise_exception():
    # need way to find out if executing within a 'try' and set the boolean in_try
    # Todo: define 'in_try' here
    if in_try == True:
       raise Exception('Continuing script')
    else:
       raise Exception('Exiting script')

def hello():
    print 'hello'
    try:
        self.raise_exception()
    except:
        pass

def goodbye():
   print 'goodbye'
   self.raise_exception()

【问题讨论】:

  • 您的问题不清楚。为什么不直接在 try 块开始时将 in_try 设置为 True 并在块外将其设置为 False
  • 如果有办法做到这一点,你可能不应该使用它:) - 块的行为不应该依赖于这种事情
  • 您的编辑并没有明确您想要做什么。这次检查的目的是什么?也许有更好的方法来实现你的目标。
  • 感谢您的快速回复。我在描述中补充说,这是一个巨大的代码库,我正在使用比我的示例更复杂的代码库。尝试块是在许多不同的文件和方法中创建的,而且很多时候不是。在引发异常的方法之一中,我需要知道在引发异常之前脚本是否会退出。
  • 安迪,如果可以在启动每个 try 块时全局覆盖 try 语句以设置一个标志,并在每个可行的 try 块结束时取消设置它。检查的目的是因为当脚本继续时它会打印出异常,但是当脚本结束时它会添加 html 格式以在 html 文件中显示异常。如果在 try 块中调用该方法,我不希望打印 html 标签。

标签: python exception exception-handling try-catch


【解决方案1】:

在我看来,您想根据是否从 try 块调用所述函数来更改函数的行为。为什么不简单地将你的函数定义为

def my_func(param0, param1, called_from_try_block=False):
    pass

然后可以像这样调用你的函数:

my_func(4, 2)
try:
    my_func(4, 2, True)
except:
    pass

【讨论】:

  • 该函数被调用了数百次。有没有办法全局覆盖所有 try 语句以设置标志并在退出每个 try 语句时清除标志?
  • 不,没有办法做到这一点。即使有黑客攻击,它只会增加复杂性并使代码的可读性大大降低。
  • 我会发现哪种情况更常见 - 该函数更常见于 try 块中,还是不是?然后采用最常见的情况,并将该关键字参数设为默认值 - 然后您只需要更改一些函数调用(参见我的示例)
【解决方案2】:

你不需要一个变量就可以了

try:
    # need way to find out if executing within a 'try' and set the boolean in_try
    # Todo: define 'in_try' here
    print 'try is being executed'
except:
    pass

【讨论】:

    【解决方案3】:

    如何在程序顶部设置一个名为in_try 的变量为False,并在try 的开头,将in_try 设置为True,如下所示:

    in_try = False
    
    if in_try == True:
        print 'In try-except!'
    else:
        print 'Not in try-except!'
    
    try:
        in_try = True
        if in_try == True:
            print 'In try-except!'
        else:
            print 'Not in try-except!'
        in_try = False
    except:
        pass
    
    if in_try == True:
        print 'In try-except!'
    else:
        print 'Not in try-except!'
    

    运行时:

    bash-3.2$ python tryexcept.py
    Not in try-except!
    In try-except!
    Not in try-except!
    bash-3.2$
    

    【讨论】:

    • 是否可以全局覆盖所有try语句来设置flag?
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2016-08-01
    • 2014-04-22
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多