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
  •  | 
  •  

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?

有帮助吗?

解决方案 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?

其他提示

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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top