带前缀的Argparse位置参数

3 投票
1 回答
866 浏览
提问于 2025-04-17 15:15

我的Python3脚本需要在命令行中指定输入文件和输出文件。使用方法应该是这样的:

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

在代码中,我使用了:

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

但是这些参数没有加上必要的前缀。有没有办法为每个参数指定前缀呢?

1 个回答

5

只需要加上两个短横线:

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

参数可以分为位置参数和可选参数;以 -- 开头的参数是总是可选的。你不能用 -- 开头来创建位置参数,而且最好也不要这样做。因为 -- 这个开头是用户界面的一种约定,你真的不想打破这个规则。

撰写回答