Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argument with or without value, specified or not

Scenario is as follows:

I need to implement a command line argument system that allows both

-p <value>

and

-p

(no value for -p given)

Is there any way to achieve this using argparse, or will I have to manually parse sys.argv?

Thank u so much!!!

like image 339
glezo Avatar asked Jun 16 '26 07:06

glezo


2 Answers

What you need is three states, absent, present, present with value.

The argparse module provides at least two simple ways to do this.

For the simplest, and most flexible, you only need add action='store' and nargs='*'.

#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-p', action='store', nargs='*')

args = parser.parse_args()

if args.p is not None:
    print( '-p present' )
else:
    print( '-p not present' )

print( '-p value', args.p )

Here is your output for this method:

# ./testpar.py
-p not present
-p value None

# ./testpar.py -p
-p present
-p value []

# ./testpar.py -p something
-p present
-p value ['something']

# ./testpar.py -p something anotherthing
-p present
-p value ['something', 'anotherthing']

For the second method, you can set a specific value for the second of the three states, const=somevalue and nargs='?'. This method supports one value only, and the value for 'const' has to be something that would not be a valid input by the user.

#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-p', action='store', const='NoValue', nargs='?')

args = parser.parse_args()

if args.p:
    print( '-p present' )
else:
    print( '-p not present' )

print( '-p value', args.p )

And here is your output for the three cases,

# ./testpar.py
-p not present
-p value None

# ./testpar.py -p
-p present
-p value NoValue

# ./testpar.py -p something
-p present
-p value something
like image 109
DrM Avatar answered Jun 18 '26 21:06

DrM


This will set args.param to None when the option is not specified (or specified without parameter) and to the specified value otherwise

import argparse

UNSPECIFIED = object()

parser = argparse.ArgumentParser()
parser.add_argument('-p', action='store', dest='param', default=UNSPECIFIED, nargs='?')

args = parser.parse_args()

if args.param == UNSPECIFIED:
    print("Param unspecified")
else:
    print(args.param)
like image 35
kristaps Avatar answered Jun 18 '26 21:06

kristaps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!