title: Python: Catching an exception works outside of a function but not inside a function
body: <p>I have a strange problem which I can't solve myself.</p>
  
  <p>If I execute <code>outside_func.py</code> in two separate terminals, the second execution catches the BlockingIOError exception and the message is printed:</p>
  
  <p><strong>outside_func.py</strong></p>
  
  <pre><code>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)
  </code></pre>
  
  <p>If I do the same with <code>inside_func.py</code> nothing is caught and no message is printed:</p>
  
  <p><strong>inside_func.py</strong></p>
  
  <pre><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('Script already running.')
  
  script_already_running()
  
  time.sleep(20)
  </code></pre>
  
  <p>Any ideas?</p>