Python: Catching an exception works outside of a function but not inside a function

懵懂的女人 提交于 2019-12-08 05:40:23

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/37220460/python-catching-an-exception-works-outside-of-a-function-but-not-inside-a-funct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!