问题
I have a function that takes as parameters an input folder (required) and output folder (optional), but I want the default value of the (optional) output folder to be the input folder.
I can do this of course using, e.g.
p = argparse.ArgumentParser(description="blah")
p.add_argument('inpath', type=str, help="Path to input")
p.add_argument('--outpath', required=False, type=str, help="Path to output")
argin = p.parse_args()
if argin.outpath is None:
argin.outpath = argin.inpath
but I want to set the default value in the definition. In another post, the answer is that this is impossible, but i do not trust it, because I have tried
p = argparse.ArgumentParser(description="blah")
p.add_argument('inpath', type=str, help="Path to input")
p.add_argument('-o', '--outpath', required=False, type=str,
default=p.parse_args().inpath, help="Path to output")
and this works. The only problem is that if I run my function with the -h
option, I don't see the --outpath
option there; I get
usage: argparse_test.py [-h] inpath
positional arguments:
inpath Path to input files.
optional arguments:
-h, --help show this help message and exit
The same happens, if I make function, say
def assign():
return p.parse_args().inpath
and set the default
parameter in the add_argument()
method to assign
:
p.add_argument('-o', '--outpath', required=False, type=str, default=assign(),
help="Path to output")
Any ideas?
来源:https://stackoverflow.com/questions/60000280/python-3-6-3-argparse-default-value-of-optional-parameter-to-be-another-param