如何在 argparse 中获取无限数量的参数?

How to take infinite number of arguments in argparse?

我正在制作一个 Python 带有 argparse 的命令行工具,它可以对摩尔斯电码进行解码和编码。这是代码:

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 .")

当我在编码或解码后键入多个参数时 returns this:

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

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

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

MorseCli.py -e Hello there

sys.argv 解析器看到的是

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

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

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

引用建议避免 shell 拆分这些词

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