如何在argparse中获取无数个参数? [英] How to take infinite number of arguments in argparse?

查看:77
本文介绍了如何在argparse中获取无数个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作带有argparse的Python命令行工具,该工具可以解码和编码摩尔斯电码.这是代码:

I am making a Python command line tool with argparse that decodes and encodes Morse code. Here is the code:

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

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

when I type more that one argument after encode or decode it 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

我将如何接受更多的争论,而不仅是第一个单词?

How will I take more arguments and not just the first word?

推荐答案

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

The shell splits the input into separate strings on space, so

MorseCli.py -e Hello there

解析器看到的

sys.argv

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

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

With nargs='+' you can tell the parser to accept multiple words, but the parsing result is a list of strings:

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

引用建议可以防止shell拆分这些单词

The quoting suggestion keeps the shell from splitting those words

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

这篇关于如何在argparse中获取无数个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆