【问题标题】:Arguments get mixed up with argparse参数与 argparse 混淆
【发布时间】:2021-11-22 07:33:53
【问题描述】:
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('p', 'projectType', type=str, help = 'c or c++ project type', choices=['c', 'c++']) 
parser.add_argument('i', 'inputfile', type=pathlib.Path, help = 'the input file path')
parser.add_argument('o',"outputfile",type=pathlib.Path, help= 'the output file path')
parser.add_argument
args = parser.parse_args()

当我在命令提示符下运行此代码时,例如首先输入输入文件.. 它给了我一个错误。 Argparse 是否有类似 getopt 的选项(我在输入之前用字母调用某些内容,因此不会混淆 ex,'-i ...input...')。这里这个选项只适用于可选参数。

有没有办法让位置参数做到这一点?

【问题讨论】:

  • 向我们展示给出错误的实际命令行(“例如,首先输入文件”完全不清楚)。然后向我们展示 what 错误(“它给我一个错误”不清楚)。然后解释你希望你的解析器接受什么命令行。
  • 您想要optional 阅读文档。还要重新阅读它对type 参数的说明。

标签: python argparse getopt


【解决方案1】:

根据argparse documentation,您可以将其定义为“可选”参数,但将required 标志设置为true,例如:

parser.add_argument('-i', '--inputfile', required=True, type=pathlib.Path, help='the input file path')

【讨论】:

    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2013-05-23
    • 2011-12-21
    • 2021-10-07
    • 2015-02-12
    相关资源
    最近更新 更多