Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Framework argparse - check if flag is set

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()
like image 868
Bartłomiej Bartnicki Avatar asked Dec 18 '22 23:12

Bartłomiej Bartnicki


1 Answers

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
like image 107
jonrsharpe Avatar answered Dec 29 '22 11:12

jonrsharpe