15

The following have worked throughout Python 3.X and is not broke in 3.3.3, can't find what's changed in the docs.

import os

def pid_alive(pid):
    pid = int(pid)
    if pid < 0:
        return False
    try:
        os.kill(pid, 0)
    except (OSError, e):
        return e.errno == errno.EPERM
    else:
        return True

Tried different variations of the except line, for instance except OSError as e: but then errno.EPERM breaks etc.

Any quick pointers?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Torxed
  • 22,866
  • 14
  • 82
  • 131

1 Answers1

42

The expression except (OSError, e) never worked in Python, not in the way you think it works. That expresion catches two types of exception; OSError or whatever the global e refers to. Your code breaks when there is no global name e.

The correct expression for Python 3 and Python 2.6 and newer is:

except OSError as e:

Python 2 also supports the syntax:

except OSError, e:

without parenthesis, or:

except (OSError, ValueError), e:

to catch more than one type. The syntax was very confusing, as you yourself discovered here.

The change was added in Python 2.6 and up, see PEP 3110 - Catching Exceptions in Python 3000 and the Exception-handling changes section of the 2.6 What's New document.

As for an exception for errno.EPERM; you didn't import errno, so that is a NameError as well.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Missed `import errno` as well, that was the root cause and again a stupid question on my part which i spent a few hours on.. What's the difference between `(OSError, e)` and `X as Y`? Edit: Thanks for clairifying the syntax of it! – Torxed Dec 11 '13 at 11:25
  • 1
    @Torxed: `except X, Y` (*without* parenthesis) was replaced by `except X as Y`, because it was too close to `except (X, Y)`, which means 'catch one of these *two* types'. – Martijn Pieters Dec 11 '13 at 11:33
  • Yea I see it/understand it now, simple answer once you get it in front of you which makes the question rather silly. Sorry to bother you and thank you for the answer, opened my eyes a bit :) – Torxed Dec 11 '13 at 11:40
  • Thank you! It's 2018 and Dropbox has still not cared to fix that! – ToniAz Sep 04 '18 at 21:25
  • @ToniAz I’m not sure what you mean. What should Dropbox fix? – Martijn Pieters Sep 04 '18 at 21:33
  • @MartijnPieters Yes, excuse me. This python script from Dropbox https://www.dropbox.com/download?dl=packages/dropbox.py is rife with these "Errors"! – ToniAz Sep 04 '18 at 21:37
  • 1
    @ToniAz that file uses the valid Python 2 syntax, no parentheses. So the code will work correctly under older Python 2 releases, including Python 2.5. That’s probably deliberate. – Martijn Pieters Sep 04 '18 at 21:45
  • @MartijnPieters typed python2 dropbox.py and it worked like a charm! Thanks! Didn't expect help with this. – ToniAz Sep 04 '18 at 21:50