I am using python argparse to read an optional parameter that defines an "exemplar file" that users sometimes provide via the command line. I want the default value of the variable to be empty, that is no file found.
parser.add_argument("--exemplar_file", help = "file to inspire book", default = '')
Will this do it?
Just don't set a default:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--exemplar_file', help='file to inspire book')
args = parser.parse_args()
print(args.exemplar_file)
# Output:
# None
The default default
is None
(for the default store
action). A nice thing about is that your user can't provide that value (there's no string that converts to None
). It is easy to test
if args.examplar_file is None:
# do your thing
# args.exampler_file = 'the real default'
else:
# use args.examplar_file
But default=''
is fine. Try it.
I think you are looking for this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fix", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
if args.fix: #this is True for python file_name.py -f
print("fix is ON")
else: #it will trigger if python file_name.py
print("fix is OFF")
'action' enable args.fix to use as None. For more info: https://docs.python.org/3/howto/argparse.html
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.