python argparse: unrecognized arguments

python argparse: unrecognized arguments

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


args = parser.parse_args()


args, unknown = parser.parse_known_args()

python argparse: unrecognized arguments

Also, as a complement to unutbus answer, storing the arguments in a dictionary this way makes the tests easy:

args = vars(parser.parse_args())
print args

Prints the dictionary:

{sort: [bw], filename: [hehe]}

Like :

if args[sort] == bw:
    # code here


Leave a Reply

Your email address will not be published.