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
4
  • 5
    Exit codes have different meanings for different systems. The errno codes are an entirely different standard. Commented May 17, 2014 at 18:07
  • @MartijnPieters, I didn't realize that. Is there any info out there about the standard (if any) argparse is using? Commented May 17, 2014 at 18:11
  • possible duplicate of Meaning of error numbers in Python exceptions Commented May 17, 2014 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. Commented May 17, 2014 at 18:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.