Skip to content
Advertisement

How to take infinite number of arguments in argparse?

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:

H4k3rDesktop> 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?

Advertisement

Answer

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

MorseCli.py -e Hello there

sys.argv that the parser sees is

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

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

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

The quoting suggestion keeps the shell from splitting those words

['MorseCli.py', '-e', 'Hello there']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement