Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse error: Option not recognized

I have a question about argparse. Here is part of my code:

(...)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-g', '--gfirst', dest="a", type=int, required=True)
    args = parser.parse_args()
    print args.a #Testing
    print args.a #Testing

if __name__ == '__main__':
    main()
    print "3"
    unittest.main(verbosity=2)
    print "4"

(...)

I am trying to set 'a' as a required value to execute the test cases, because I will need this value in the future. However...

$ python regular_test.py --gfirst 2
2
2
3
option --gfirst not recognized
Usage: regular-test.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

...as you can see, the program accepts the argument and prints it, but the test case itself does not execute. I've inserted some prints to show whats executing and what isnt.

What am I doing wrong? Thanks in advance

ps.: I am using python 2.7.3
ps2.:The tests were running properly (before adding argparse to the program.)

like image 657
almanegra Avatar asked Oct 24 '25 18:10

almanegra


1 Answers

unittest.main() itself parses command-line arguments and it cannot understand/recognize your custom defined arguments (see parseArgs() method of the TestProgram class).

Instead, run tests using TextTestRunner:

runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase))

Also see related threads:

  • argparse and unittest python
  • Call a python unittest from another script and export all the error messages
like image 110
alecxe Avatar answered Oct 26 '25 08:10

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!