标签: try-except

python退出无限循环与KeyboardInterrupt异常

按下Ctrl + C时,我的while循环不会退出.它似乎忽略了我的KeyboardInterrupt异常.循环部分如下所示:

while True:
  try:
    if subprocess_cnt <= max_subprocess:
      try:
        notifier.process_events()
        if notifier.check_events():
          notifier.read_events()
      except KeyboardInterrupt:
        notifier.stop()
        break
    else:
      pass
  except (KeyboardInterrupt, SystemExit):
    print '\nkeyboardinterrupt found!'
    print '\n...Program Stopped Manually!'
    raise
Run Code Online (Sandbox Code Playgroud)

同样,我不确定问题是什么,但我的终端甚至从未打印过我的异常中的两个打印警报.有人能帮我解决这个问题吗?

python systemexit infinite-loop keyboardinterrupt try-except

5
推荐指数
1
解决办法
3万
查看次数

在python中,为什么在"try except"之前和之后进行信号处理时异常存在差异

我最近开始使用python.当我遇到这种行为时,我正在玩处理键盘中断

import signal,sys

def handleInt(sign,no):
    print "interrupted"

signal.signal(signal.SIGINT,handleInt)    # exception raised is IOError

try:
    sys.stdin.read(1)
except IOError:
    print "io interrupt"
Run Code Online (Sandbox Code Playgroud)

但如果我将信号处理改为try-except之后

import signal,sys

def handleInt(sign,no):
    print "interrupted"

try:
    sys.stdin.read(1)
except KeyboardInterrupt:
    print "keyboard interrupt"

signal.signal(signal.SIGINT,handleInt)    # exception raised is KeyboardInterrupt
Run Code Online (Sandbox Code Playgroud)

当我按ctrl + c时,两种情况下的异常存在差异.那么为什么会出现这种情况?

python signals try-except

5
推荐指数
2
解决办法
2098
查看次数

except-clause删除局部变量

exc = None
try:
    raise Exception
except Exception as exc:
    pass

# ...

print(exc)
Run Code Online (Sandbox Code Playgroud)

NameError:未定义名称'exc'

这曾经在Python2中工作.为什么这样改变了?如果我至少可以重新分配exc,类似于类级属性

class Foo(object):
    Bar = Bar
Run Code Online (Sandbox Code Playgroud)

但这也不能使它工作:

exc = None
try:
    raise Exception
except Exception as exc:
    exc = exc
Run Code Online (Sandbox Code Playgroud)

有什么好的提示可以实现同样的目标吗?我不想写这样的东西:

exc = None
try:
    raise Exception("foo")
except Exception as e:
    exc = e

# ...

print(exc)
Run Code Online (Sandbox Code Playgroud)

python scope python-3.x try-except

5
推荐指数
1
解决办法
200
查看次数

在try和except语句中使用return语句是否正确?

如果我在函数末尾有这样的代码:

try:
    return map(float, result)
except ValueError, e:
    print "error", e
Run Code Online (Sandbox Code Playgroud)

在方法的返回部分中使用try /正确吗?有解决这个问题的更明智的方法吗?

python methods exception-handling return try-except

5
推荐指数
1
解决办法
5888
查看次数

如何追溯函数内引发异常的原因?

(这是Python try/ except: Showing the Cause of the error after Displaying my Variables 帖子的后续问题。)

我有以下内容script.py

import traceback


def process_string(s):
    """
    INPUT
    -----
    s:  string

        Must be convertable to a float

    OUTPUT
    ------
    x:  float
    """

    # validate that s is convertable to a float
    try:
        x = float(s)
        return x
    except ValueError:        
        print
        traceback.print_exc()


if __name__ == '__main__':

    a = process_string('0.25')
    b = process_string('t01')
    c = process_string('201')
Run Code Online (Sandbox Code Playgroud)

执行后script.py,终端窗口中将打印以下消息:

Traceback (most recent call last):
  File "/home/user/Desktop/script.py", …
Run Code Online (Sandbox Code Playgroud)

python function try-except

5
推荐指数
1
解决办法
262
查看次数

异常 AttributeError:“'NoneType' 对象没有属性 'path'”

我正在调试 python 代码(python2.7.12),因为我的代码可以工作,但是当我将推文流式传输到数据库时,所有变量都为 NULL。

我得到的错误是:

Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x10068f140> ignored
Run Code Online (Sandbox Code Playgroud)

我假设这个错误来自下面的代码:

def put_tweets_in_database(tweets):
    print "putting tweets in database"
    errors = 0
    count = 0

    for tweet in tweets:
        try:
            commit_tweet_to_database(tweet, count, len(tweets))
            count += 1  
        except Exception as e:
            print e
            session.rollback()
            errors += 1
    print 'there were {} errors'.format(errors)
Run Code Online (Sandbox Code Playgroud)

我不认为这个功能commit_tweet_to_database()有问题...

你有什么主意吗...?我将不胜感激任何帮助!

谢谢。

attributeerror python-2.7 try-except

5
推荐指数
1
解决办法
2万
查看次数

try/except的问题,尝试在可能的情况下将字符串转换为pandas数据框中的整数

我创建了一个函数来清理数据框中字符串的任何HTML代码/标记.该函数从数据框中获取每个值,使用remove_html函数清除它,并返回一个干净的df.在将数据帧转换为字符串值并清理它之后,我试图在可能的情况下将数据帧中的值转换回整数.我试过尝试/除了但没有得到我想要的结果.这就是我现在所拥有的:

def clean_df(df):
    df = df.astype(str)
    list_of_columns = list(df.columns)
    for col in list_of_columns:
        column = []
        for row in list(df[col]):
            column.append(remove_html(row))
            try:
                return int(row)
            except ValueError:
                pass

        del df[col]

        df[col] = column

    return df
Run Code Online (Sandbox Code Playgroud)

如果没有try/except语句,函数将返回一个干净的df,其中整数是字符串.所以它只是一个似乎是一个问题的try/except语句.我以多种方式尝试了try/except语句,但没有一个返回df.例如,当前代码返回一个'int'对象.

python pandas try-except

5
推荐指数
1
解决办法
426
查看次数

终止python程序时做一些事情

我想让一个python脚本做一些事情,比如在终止它之前发布一条消息.我尝试过signal,当我Ctrl+c在cmd窗口中输入时,它可以工作.但是,当我直接关闭cmd窗口或从Windows任务管理器中终止进程时,它似乎无法运行.那么在上述情况下如何才能达到目标呢?谢谢你的所有建议!

python signals try-except

5
推荐指数
1
解决办法
74
查看次数

如果最终返回值,则不会引发 python 异常

谁能解释为什么下面的例子没有提高Exception

def foo():
    try:
        0/0
    except Exception:
        print('in except')
        raise
    finally:
        print('in finally')
        return 'bar'

my_var = foo()
print(my_var)
Run Code Online (Sandbox Code Playgroud)

这只是返回:

in except
in finally
bar
Run Code Online (Sandbox Code Playgroud)

没有return 'bar'语句的相同代码抛出异常:

in except
in finally
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    my_var = foo()
  File "test.py", line 3, in foo
    0/0
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)

python exception-handling exception try-except

5
推荐指数
1
解决办法
222
查看次数

在 python 3 中,使用更短的回溯重新引发错误

我正在尝试创建一个 try- except 块,该块重新引发任意异常,但仅包含回溯堆栈中的最后一个块。

像这样的东西:

import traceback

def my_func(shorten_tracebacks=True):
    try:
        # Do stuff here

    except Exception as e:
        if shorten_tracebacks:
            raise TheSameTypeOfError, e, traceback.print_exc(limit=1)

        else:
            raise(e)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点?

如果重要的话,我这样做是为了方便调试 jupyter 笔记本中经常使用的某些 API——它们往往会生成非常长的堆栈跟踪,其中只有最后一个块提供信息。这迫使用户频繁滚动。如果你不想缩短回溯,你可以随时设置shorten_tracebacks=False

python try-except

5
推荐指数
1
解决办法
685
查看次数