问题
I want to use my script in this way: python script.py -x now I run it using this command python script.py -x y
My code:
parser = ArgumentParser()
parser.add_argument('-x', '--x', dest="x", default="n")
options = parser.parse_args()
if option.x == 'y':
f()
It is possible to write it in this way
python script.py -x
parser = ArgumentParser()
parser.add_argument('-x', '--x', dest="x")
options = parser.parse_args()
if isset(option.x):
f()
回答1:
Just use the 'store_true' action:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-x', action='store_true')
then you can simply test for the truthiness of that argument:
options = parser.parse_args()
if options.x:
f()
In use, just printing whether or not that argument is truth-y:
C:\Python27>python so.py
x is not set
C:\Python27>python so.py -x
x is set
来源:https://stackoverflow.com/questions/32884131/framework-argparse-check-if-flag-is-set