Takkun
Takkun

Reputation: 8659

How to use argparse to grab command line arguments in Python?

I want to be able to save integer values after an option is passed through the command line. Ideally it would be:

python thing.py -s 1 -p 0 1 2 3 -r/-w/-c

The final part can be only one of the three options (-r, -w, or -c), depending on what it is I need to do.

I've been trying to read tutorials but they all use the same two examples that don't explain how to store integers after a -option.

Upvotes: 2

Views: 2002

Answers (1)

Wooble
Wooble

Reputation: 90037

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-s', type=int)
[...]
>>> parser.add_argument('-p', type=int, nargs='*')
[...]
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('-r', action='store_true')
[...]    
>>> group.add_argument('-w', action='store_true')
[...]    
>>> group.add_argument('-c', action='store_true')
[...]    
>>> parser.parse_args("-s 1 -p 0 1 2 3 -r".split())
Namespace(c=False, p=[0, 1, 2, 3], r=True, s=1, w=False)

Upvotes: 4

Related Questions