【问题标题】:Argparse positional arguments with prefix带前缀的 argparse 位置参数
【发布时间】:2013-01-24 09:46:49
【问题描述】:

我的 python3 脚本适用于命令行上指定的输入和输出文件。 用法应该是这样的

xxxx.py [-h] --input=file --output=file

在我正在使用的代码中

parser.add_argument("input", help='Input file');
parser.add_argument("output", help='Output file');

但参数没有必要的前缀。有没有办法为每个参数指定前缀?

【问题讨论】:

    标签: python python-3.x argparse


    【解决方案1】:

    只需包含双破折号:

    parser.add_argument("--input", help='Input file');
    parser.add_argument("--output", help='Output file');
    

    参数要么是位置的,要么是可选的;以-- 开头的参数始终 是可选的。您不能创建带有 -- 前缀的位置参数,而且您确实不应该这样做。 -- 前缀是您真的不想破坏的用户界面约定。

    【讨论】:

    • 我同意并理解您的意思,但是这种格式是在我的课堂作业中定义的,因此我无法更改。在这种情况下,我想我会将它们视为可选的,然后检查它们是否都在命令行中定义,但我根本不喜欢这种解决方案,因为它会弄乱自动生成的帮助选项。
    • @skornos:我怀疑你在这种情况下误解了任务。
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2018-12-22
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多