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

℡╲_俬逩灬. 提交于 2019-12-07 08:50:25

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