如何在argparse中接受无穷多的参数?

2024-05-23 14:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用argparse制作一个Python命令行工具,用于解码和编码莫尔斯电码。代码如下:

parser.add_argument('-d','--decode',dest="Morse",type=str,help="Decode Morse to Plain text .")
parser.add_argument('-e','--encode',dest="text",type=str,help="Encode plain text into Morse code .")

当我在编码或解码后键入多个参数时,它将返回以下内容:

H4k3r\Desktop> MorseCli.py -e Hello there
usage: MorseCli.py [-h] [-d MORSE] [-e TEXT] [-t] [-v]
MorseCli.py: error: unrecognized arguments: there

我如何接受更多的论点,而不仅仅是第一个词


Tags: textpyaddparser编码morsetypeargparse
1条回答
网友
1楼 · 发布于 2024-05-23 14:11:09

shell将输入拆分为空间上的单独字符串,因此

MorseCli.py -e Hello there

解析器看到的sys.argv

['MorseCli.py', '-e', 'Hello', 'there']

使用nargs='+'可以告诉解析器接受多个单词,但解析结果是字符串列表:

args.encode = ['Hello', 'there']

引用建议避免了外壳分裂这些单词

['MorseCli.py', '-e', 'Hello there']

相关问题 更多 >