Python (3.6.3) argparse: default value of optional parameter to be another parameter's value

旧城冷巷雨未停 提交于 2020-02-06 07:58:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!