python, unittest: is there a way to pass command line options to the app

Building on Alex’s answer, it’s actually pretty easy to do using argparse:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', default="My Input")
    parser.add_argument('filename', default="some_file.txt")
    parser.add_argument('unittest_args', nargs="*")

    args = parser.parse_args()
    # TODO: Go do something with args.input and args.filename

    # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
    sys.argv[1:] = args.unittest_args
    unittest.main()

I haven’t tested all of the flags you can pass into unittest to see if they work or not, but passing test names in does work, e.g.:

python test.py --input=foo data.txt MyTest

Runs MyTest with foo and data.txt.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)