Harry Adams
Harry Adams

Reputation: 487

Flag to not require mandatory arguments in Argparse?

I have a program that accepts input file, input format, and output format as required arguments via argparse. However, I'd like to have "--test" as a flag, where it will run through all of my unit tests.

How do I set this to be a flag that can run without the required arguments? In the same way that a traditional -h flag does?

def process_args():
    global args
    parser = argparse.ArgumentParser(description="Convert quantum circuits into different environments")
    parser.add_argument("input_filename", help="input filename")
    parser.add_argument("input_format", help="input format of your script", choices=valid_program_types)
    parser.add_argument("output_format", help="output format of your script", choices=valid_program_types)
    parser.add_argument("-o", "--output_filename", help="set output filename, without file extension "
                                                        "(default: convertqc_result.<filetype>")
    parser.add_argument("-d", "--debug", help="enable debug mode", action="store_true")
    args = parser.parse_args()

Upvotes: 0

Views: 153

Answers (1)

chepner
chepner

Reputation: 531055

-h works by triggering a specific action of type _HelpAction, as if defined by something like

parser.add_argument('-h', action='help')

This action calls (eventually) sys.exit, and so bypasses the rest of the parsing algorithm, rendering the issue of required arguments moot.

You can define your own custom action TestAction by subclassing Action (see https://docs.python.org/3/library/argparse.html#action for details), then defining --test with

class TestAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        """ Run your tests and exit the script here """

parser.add_argument("--test", action=TestAction)

Alternatively, define separate subcommands test and run, so that only the run subcommand has required arguments, and the test subcommand simply runs your tests and exists.


However, the best thing to do is to decouple running your unit tests from running your script. There's no reason to even deploy your unit tests in an environment where you expect to run your script. Use a separate test runner script (or something like nosetests) to run your tests without running your script itself.

Upvotes: 1

Related Questions