Use the value of one of the positional arguments as the default value of one of the optional arguments

StackOverflow https://stackoverflow.com/questions/21293484

  •  01-10-2022
  •  | 
  •  

Question

As in the topic, I want to

import argparse
parser = argparse.ArgumentParser()
parser.add_argument( "input" )
args = parser.parse_args() # <--- breaks if one of the optional arguments given
parser.add_argument( "-o", "--output", action="store", default=args.input+".out" )
parser.add_argument( "-s", "--skip-fields", action="store", default=1 )
args = parser.parse_args()

A possible solution could be inserting args = parser.parse_args() before the declaration of optional arguments but it breaks the code if any of the optional arguments is actually given.

Can it be done?

Was it helpful?

Solution 2

Replace the first parse_args with

args,rest = parser.parse_known_args()

Now parser handles input, but ignores the rest (actually puts it in rest).

However, conditionally setting the default after you are done with argparse should work just as well. Conceptually it can be simpler.

Think about what you want to see when there's an error, or you ask for help. Does the default value need to be set?

OTHER TIPS

Maybe you can give the optional parameter a default of None or something similar, and then replace that later in the post-processing of the arguments?

import argparse
parser = argparse.ArgumentParser()
parser.add_argument( "input" )
parser.add_argument( "-o", "--output", action="store", default=None)
args = parser.parse_args()

if args.output is None:
    args.output = args.input+".out"
print args

You could even leave out default=None, since the default value for default is None.

Quick test:

In [2]: run test.py my_filename
Namespace(input='my_filename', output='my_filename.out')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top