3

When I give Python's argparse input it doesn't like, it raises a SystemExit with a code of 2, which seems to mean "No such file or directory". Why use this error code?

import argparse
import errno

parser = argparse.ArgumentParser()
parser.add_argument('arg')

try:
    parser.parse_args([])
except SystemExit as se:
    print("Got error code {} which is {} in errno"
        .format(se.code, errno.errorcode[se.code]))

produces this output:

usage: se.py [-h] arg
se.py: error: too few arguments
Got error code 2 which is ENOENT in errno
kuzzooroo
  • 6,788
  • 11
  • 46
  • 84
  • 5
    Exit codes have different meanings for different systems. The `errno` codes are an entirely *different* standard. – Martijn Pieters May 17 '14 at 18:07
  • @MartijnPieters, I didn't realize that. Is there any info out there about the standard (if any) argparse is using? – kuzzooroo May 17 '14 at 18:11
  • possible duplicate of [Meaning of error numbers in Python exceptions](http://stackoverflow.com/questions/22955720/meaning-of-error-numbers-in-python-exceptions) – vaultah May 17 '14 at 18:24
  • 1
    @frostnational: that is about `errno` error codes, **not** about why `argparse` uses 2 as the exit code. You are making the same mistake as the OP here. – Martijn Pieters May 17 '14 at 18:28

1 Answers1

13

You are confusing C errno error codes with a process exit status; the two concepts are entirely unrelated.

Exit status values have no official standard, but by convention 2 is taken to mean Incorrect usage; this is the exit code used by Bash built-ins, for example.

The os module exposes os.EX_* constants that represent the sysexit.h constants used by many POSIX systems. os.EX_USAGE is exit code 64 and could be used as well, although argparse doesn't actually use this constant as it is only available on UNIX systems while argparse needs to work on Windows and other platforms too.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I agree with most that you write, but ironically, on the TLDP site you linked it is stated that error code 2 "should therefore be avoided for user-specified exit parameters". Since it is called "Misuse of shell builtins", I think that this is also relevant to Python interpreters, because they are not shell builtins. So I would not call it a really established convention (for example, `rsync` uses error code 1 for CL argument errors, `git` - 129 and `wget`, indeed, 2). – Yaroslav Nikitenko Jun 15 '22 at 16:45