Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argparse and unittest.main()

I just added a graph utility to a unittest — basically, the fully automatic version of the test just does a numerical compare, but I want a human to be able to ask for plots.

Just using argparse, unittest.main() was choking if I used my new argument. What I’m currently doing is checking for that argument, then deleting it from sys.argv which just seems wrong.

Is there a better way to skin this cat?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • A way to tell argparse to consume arguments from sys.argv. Probably still wrong, but it’s not me doing it, so it’s OK.
  • A way to tell argparse to cough up version of sys.argv with all the "used arguments" taken out — this would be cool, because it looks like unittest.main() will take an alternate argv.
  • A way to tell unittest.main() to ignore arguments.
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Test correction'
    )
    parser.add_argument(
        '--plot-results',
        help='Plot results of cal test',
        action='store_true'
    )
    args = parser.parse_args()

    if args.plot_results:
        while '--plot-results' in sys.argv:
            sys.argv.remove('--plot-results')

    unittest.main()

>Solution :

Argument.parse_known_args is basically your second option: parse the arguments you define, and get back the ones you don’t recognize to pass on to unittest.main.

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Test correction'
    )
    parser.add_argument(
        '--plot-results',
        help='Plot results of cal test',
        action='store_true'
    )
    args, remaining = parser.parse_known_args()

    unittest.main(argv=remaining)

Probably goes without saying, but don’t add any arguments to parser that conflict with the parsers used by unittest itself. These are (mostly?) documented here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading