Python 具有可重复参数对的 argparse 参数

Python argparse arguments with repeatable parameter pairs

我正在开发一个 Python 脚本,它将利用 CLI 参数将 .xls/.xlsx 文件转换为 .csv。因为 .xsl/.xlsx 文件可以有多个 sheet,每个 sheet 需要单独转换成单独的 .csv 文件。我想做的是使用 argparse 添加一个必需参数来指定要转换的 sheet 和一个可选参数来指定生成的 .csv 应该命名的内容。这是我希望命令看起来如何的示例:

python converter.py --sheets <sheet-name> [sheet-rename]

所以我不确定如何使用 argparse 添加带有两个参数的参数。

此外,我想为这个论点添加更多功能。如果可能的话,我希望能够重复参数以允许转换更多 sheet。我不确定命令语法会是什么样子,但是是这样的:

python converter.py --sheets (<sheet-name> [sheet-rename])...
python converter.py --sheets sheet1 sheet1_rename sheet2 sheet2_rename

这可能最终会变得太复杂,但任何输入都会很棒。

--sheet 可以定义为带有两个参数的选项,这两个参数都累积在一个列表中。

p.add_argument('--sheet', action='append', nargs=2)

调用 python converter.py --sheet old1 new1 --sheet old2 new2 将生成列表列表:

>>> print p.parse_args("--sheet old1 new1 --sheet old2 new2".split())
Namespace(sheet=[['old1', 'new1'], ['old2', 'new2']])