Skip to content

argparse exits with code 2 on (usage) errors, should be mapped to UsageError #2753

@blueyed

Description

@blueyed

With pytest-watch I've noticed that pytest.main exits with code 2 (via SystemExit) in case there is an argparse error (unrecognized args).

This could be mapped into throwing UsageError instead:

diff --git i/_pytest/config.py w/_pytest/config.py
index 364ac13c..0e879f34 100644
--- i/_pytest/config.py
+++ w/_pytest/config.py
@@ -801,6 +801,9 @@ def parse_args(self, args=None, namespace=None):
             getattr(args, FILE_OR_DIR).extend(argv)
         return args
 
+    def error(self, message):
+        raise UsageError(self.format_usage(), message)
+
 
 class DropShorterLongHelpFormatter(argparse.HelpFormatter):
     """shorten help for long options that differ only in extra hyphens

But at least it sounds sensible to wrap it and exit with pytest's "usage error" code, which would be 4 according to https://docs.pytest.org/en/latest/_modules/_pytest/main.html.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: enhancementnew feature or API change, should be merged into features branchtype: feature-branchnew feature or API change, should be merged into features branch

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions