![](/img/trans.png)
[英]Python argparse for infinite number of inputs and flag requiring multiple arguments?
[英]How to take infinite number of arguments in 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 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']
引用建议可以防止 shell 拆分这些单词
['MorseCli.py', '-e', 'Hello there']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.