简体   繁体   中英

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 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 .

>>> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM