Python: Catching an exception works outside of a function but not inside a function
Question: 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?


Answer: 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)
    

