Python:捕获异常在函数之外工作,但不在函数内 [英] Python: Catching an exception works outside of a function but not inside a function

查看:118
本文介绍了Python:捕获异常在函数之外工作,但不在函数内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我执行 outside_func.py 在两个单独的终端中,第二个执行会捕获BlockingIOError异常并打印消息:



outside_func.py

  import fcntl 
import time

#如果同一个脚本已经在运行,则提高BlockingIOError。
try:
lockfile = open('lockfile','w')
fcntl.flock(lockfile,fcntl.LOCK_EX | fcntl.LOCK_NB)
除了BlockingIOError:
打印('脚本已经运行')

time.sleep(20)

如果我使用 inside_func.py 做同样的事情,没有任何东西被捕获,没有打印消息:



inside_func.py

  import fcntl 
import time

#如果相同的脚本已经运行,则提高BlockingIOError。
def script_already_running():
try:
lockfile = open('lockfile','w')
fcntl.flock(lockfile,fcntl.LOCK_EX | fcntl.LOCK_NB)
除了BlockingIOError:
print('脚本已经运行')

script_already_running()

time.sleep(20)

任何想法?

解决方案

当您离开函数时,该文件关闭,因此两个代码段不相同,在try 之外的代码片段中仍然存在该范围中的文件对象的引用的睡眠呼叫,所以进一步调用打开 lockfile 正确的错误。如果您通过移动功能中的睡眠来更改功能,您将看到现在提供的错误,具有可比较的代码:

  import fcntl 
import time

#如果同一个脚本已经在运行,则会引发BlockingIOError。
def script_already_running():
try:
lockfile = open('lockfile','w')
fcntl.flock(lockfile,fcntl.LOCK_EX | fcntl.LOCK_NB)
除了BlockingIOError:
print('except')
sleep(20)


I have a strange problem which I can't solve myself.

If I execute outside_func.py in two separate terminals, the second execution catches the BlockingIOError exception and the message is printed:

outside_func.py

import fcntl
import time

# Raise BlockingIOError if same script is already running.
try:
    lockfile = open('lockfile', 'w')
    fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    print('Script already running.')

time.sleep(20)

If I do the same with inside_func.py nothing is caught and no message is printed:

inside_func.py

import fcntl
import time

# Raise BlockingIOError if same script is already running.
def script_already_running():
    try:
        lockfile = open('lockfile', 'w')
        fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        print('Script already running.')

script_already_running()

time.sleep(20)

Any ideas?

解决方案

The file is closed when you leave the function so the two snippets are not the same, in the code snippet where the try is outside of a function there is still a reference to the file object in the scope of the sleep call so further calls to open the lockfile rightfully error. If you change the function by moving the sleep inside the function you will see the error raised as now you have comparable code:

import fcntl
import time

# Raise BlockingIOError if same script is already running.
def script_already_running():
    try:
        lockfile = open('lockfile', 'w')
        fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        print('except')
    sleep(20)

这篇关于Python:捕获异常在函数之外工作,但不在函数内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆