Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 228
Yan Zhu Avatar asked Jun 15 '13 00:06

Yan Zhu


Video Answer


2 Answers

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.

like image 147
unutbu Avatar answered Oct 11 '22 06:10

unutbu


You can get around this by allowing unknown arguments

Replace

args = parser.parse_args() 

with

args, unknown = parser.parse_known_args() 
like image 23
FacePalm Avatar answered Oct 11 '22 07:10

FacePalm