ArgParse有条件地添加带有基础标志的参数
我想用他们的参数创建一个用于作业的解析器。每个工作都有各种参数,除了每个工作都必须有一个日期参数。
我想要的是:
script.py --job base_job_name --date today
script.py --job similar_job --date today --additional_input_location /path/to/file
我拥有的
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-j", "--job", choices=jobs)
parser.add_argument("-d", "--date", type=validate_date, required=True)
subparsers = parser.add_subparsers()
specific_job_parser = subparsers.add_parser(specific_job_name, parents=[parser])
specific_job_parser.add_argument("-a", "--additional_input_location")
设置迫使我创建一个丑陋的CLI,例如script.py -job tered_job-date $ date $ date tered_job -a/file/path
我如何才能更接近<<<代码> script.py-job tered_job -date $ date -a/file/path and script.py-job base_job -date $ date $ date
I want to create a parser for jobs with their params. Each job has varying kinds of arguments, except every job has to have a date argument.
What I want:
script.py --job base_job_name --date today
script.py --job similar_job --date today --additional_input_location /path/to/file
What I have
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-j", "--job", choices=jobs)
parser.add_argument("-d", "--date", type=validate_date, required=True)
subparsers = parser.add_subparsers()
specific_job_parser = subparsers.add_parser(specific_job_name, parents=[parser])
specific_job_parser.add_argument("-a", "--additional_input_location")
This setup forces me to create an ugly CLI like script.py --job specific_job --date $date specific_job -a /file/path
How can I get closer to script.py --job specific_job --date $date -a /file/path
and script.py --job base_job --date $date
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过直接的
subparser
?这应该接受
从主要解析器中省略
- date
,并将其添加到每个子份子 - 是的,它需要更多的键入,但可以使用更好的功能。不要将主要解析器作为地下店员的父。您可以使用专门为此目的编写的单独解析器。子份子机制无法正常工作,您尝试在主要解析器和地下阶层中提出相同的论点。将其放在一个地方或另一个地方,而不是两者。
Have you tried a straightforward
subparsers
?This should accept
Alternatively omit the
--date
from the main parser, and add it each of the subparsers - yes that will require more typing, but better something that works.Don't use the main parser as parent to the subparsers. You could use a separate parser that's written specifically for the purpose. The subparsers mechanism does not work well you try to put the same argument in both the main parser and the subparsers. Put it in one place or the other, not both.