2017年7月15日 星期六

[ Python 常見問題 ] Python argparse command line flags without arguments

Source From Here 
Question 
How do I add an optional flag to my command line args? eg. so I can write 
# python myprog.py

or 
# python myprog.py -w // No value required for argument -w


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 
  1. #!/usr/bin/env python  
  2. import argparse  
  3.   
  4. import argparse  
  5.   
  6. parser = argparse.ArgumentParser(description='For testing')  
  7. parser.add_argument('-w', action='store_true', default=False)  
  8. args = parser.parse_args()  
  9.   
  10. if args.w:  
  11.     print("Turn on switch")  
  12. else:  
  13.     print("Turn off switch")  
Test it this way: 
# ./test.py 
Turn off switch 
# ./test.py -w 
Turn on switch


沒有留言:

張貼留言

[Linux 常見問題] What's the best way to send a signal to all members of a process group?

Source From  Here   Question   I want to  kill a whole process tree.  What is the best way to do this using any common scripting languages? ...