python argparse: unrecognized arguments

When I run parsePlotSens.py -s bw hehe, it says that hehe is an unrecognized argument. However, if I run parsePlotSens.py hehe -s bw, it's OK. Ideally, I would like it work for both cases.

Any tips? The following is my code:

if __name__ == '__main__' :

    parser = argparse.ArgumentParser(prog='parsePlotSens');
    parser.add_argument('-s', '--sort', nargs =1, action = 'store', choices = ['mcs', 'bw'], default='mcs', help=sorthelp)
    parser.add_argument('filename', nargs ='+', action = 'store')
    option = parser.parse_args(sys.argv)

Do not pass sys.argv as an argument to parse_args. Just use

option = parser.parse_args()

If you do pass sys.argv to parse_args, then the path or name of the script itself is the first item in sys.argv and thus becomes the value of option.filename. The hehe then becomes an unknown argument.

If you omit sys.argv then parse_args parses sys.argv as expected.


You can get around this by allowing unknown arguments

Replace

args = parser.parse_args()

with

args, unknown = parser.parse_known_args()