【发布时间】:2021-07-09 15:23:21
【问题描述】:
我的代码如下。
__version__ = 'v10'
class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
def _get_help_string(self, action):
return action.help
def main():
parser = argparse.ArgumentParser(
formatter_class=MyHelpFormatter,
description=__version__
)
parser.print_usage = parser.print_help
parser.add_argument("file", help="path to file/directory")
parser.add_argument(
"-t",
"--type",
type=str,
default=False,
help="file type",
)
parser.add_argument(
"-c",
"--config",
action="store_true",
help="change custom text",
)
parser.add_argument(
"-v",
"--version",
action='version',
version=__version__,
help="thumb-gen version",
)
在我的代码中,它总是需要“文件”参数。没关系。
现在我想在使用“--config”参数调用时调用一个函数。但是当我运行 main.py --config 时,它还需要 'file' 参数。
如何在不输入所需参数的情况下使用“-config”参数?
【问题讨论】:
-
您的代码从不调用
parser.parse_args()或main(),而且还有很多看起来与问题无关的东西。请提供minimal reproducible example。如果你想用,我写了一个here in a gist。 -
@MauriceMeyer 当我使用该解决方案时,“文件”参数需要一个标志。我的代码中不需要“文件”标志。有解决办法吗?
-
通常最干净的解决方案是使
--file具有良好默认值的可选。这样你就不用关心用户是否提供了值。 -
类似这样的:
group.add_argument('--file', nargs='?')或默认值。
标签: python python-3.x argparse