2

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.

1
  • If the last part should be exactly one of three, you may want to make it a required positional argument, like commands in many other tools (e.g. install of apt-get). Commented Jun 10, 2011 at 16:48

1 Answer 1

4
>>> 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.