python - 如何让 argparse 识别跟随可变长度可选参数的位置参数?

标签 python argparse optional-parameters positional-parameter

我正在编写一个脚本,用于合并多个输入文件,生成一个输出文件,我想使用 argparse 构建一个小型命令行界面.对我来说,最自然的做法是使用一个可选输入 -i,它接受一个或多个输入文件名,后跟一个位置参数,代表输出文件姓名。这是我的想法的一个例子:

#!/usr/bin/env python3
"""
Script for merging input files
"""
import argparse

script_docstring = 'Read some input files and create a merged output.'
parser = argparse.ArgumentParser(description=script_docstring)
# Optional input file names
parser.add_argument('-i --inputs', nargs='+', type=str, required=True,
                    help='Input file names', dest='inputs')
# Positional output file name
parser.add_argument('fname_out', type=str, help='Output file name')
args = parser.parse_args()

# Display what the user chose at the command line
print(args.inputs)
print(args.fname_out)

当我打印由 argparse 创建的自动生成的帮助消息时,调用签名看起来像我想要的:

> ./mergefiles.py --help
usage: mergefiles.py [-h] -i --inputs INPUTS [INPUTS ...] fname_out

Read some input files and create a merged output.

positional arguments:
  fname_out             Output file name

optional arguments:
  -h, --help            show this help message and exit
  -i --inputs INPUTS [INPUTS ...]
                        Input file names

但是,当我实际尝试运行该脚本时,它给出了一个错误,提示我 argparse 错误地解析了最终的位置参数,就好像它被包含在可选列表中一样:

> ./mergefiles.py -i a.in b.in c.in test.out
usage: mergefiles.py [-h] -i --inputs INPUTS [INPUTS ...] fname_out
mergefiles.py: error: the following arguments are required: fname_out

我的问题:是否有可能让 argparse 正确处理这样的情况,将最后一个参数视为位置参数?或者是我接受“解决方法”解决方案的唯一选择,例如将输出文件名也转换为可选参数,例如 -f --fname_out 或类似的。

如果无法实现我想要的结果,那么我计划将其作为我的后备解决方案来实现。然而,在我接受一个不优雅的解决方法之前,我很好奇是否真的有可能让 argparse 以“正确”的方式处理这个问题。

最佳答案

当使用位置作为最后一个参数时,您必须使用 -- 来分隔参数:

python3 args.py -i infile1 infile2 -- outfile
['infile1', 'infile2']
outfile

希望对你有帮助

关于python - 如何让 argparse 识别跟随可变长度可选参数的位置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920363/

相关文章:

python - 连接来自两种不同输入模态的两个不同形状的张量

python - 从脚本中捕获标准输出?

Python Argparse "radio"默认标志?

python - 无法找出 cv.mat.step[0] 的 Numpy 等价物

python - pip安装getch Python3.5报错

python - 如何在 python argparse 中使用子解析器定义全局选项?

Python argparse 静态参数

javascript - 有没有办法在js中将特定参数传递给函数(无顺序)?

reflection - 带有可选参数的 Activator.CreateInstance

php - PHP 是否允许命名参数以便可以在函数调用中省略可选参数?