Source From Here
Question
How do I add an optional flag to my command line args? eg. so I can write
or
How-To
As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look at http://docs.python.org/dev/library/argparse.html#action (specifically store_true and store_false). e.g.:
- test.py
Test it this way:
Question
How do I add an optional flag to my command line args? eg. so I can write
or
How-To
As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look at http://docs.python.org/dev/library/argparse.html#action (specifically store_true and store_false). e.g.:
- test.py
- #!/usr/bin/env python
- import argparse
- import argparse
- parser = argparse.ArgumentParser(description='For testing')
- parser.add_argument('-w', action='store_true', default=False)
- args = parser.parse_args()
- if args.w:
- print("Turn on switch")
- else:
- print("Turn off switch")
沒有留言:
張貼留言