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
-s
- store the following integer-p
- store the following integers
The final part can be only one of the three o开发者_如何学编程ptions (-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
.
>>> 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)
精彩评论