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

Python 如何在argparse中接受无穷多的参数?,python,argparse,Python,Argparse,我正在用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 pla

我正在用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

如何接受更多的参数而不仅仅是第一个单词?

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

MorseCli.py -e Hello there
解析器看到的sys.argv是

['MorseCli.py', '-e', 'Hello', 'there']
使用
nargs='+'
可以告诉解析器接受多个单词,但解析结果是字符串列表:

args.encode = ['Hello', 'there']
引用建议避免了外壳分裂这些单词

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

顺便说一句,当只有一个参数时,它可以完美地工作。传递参数时请使用双引号:
MorseCli.py-e“你好”
非常感谢@PaulM。它现在可以工作并提供正确的输出。