Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string with spaces from command line in Python

Is there a way to call my program in python and pass it a string I want it to parse without declaring the string as 'String I want to parse' but as String I want to parse

import argparse

#Parse command line for input
parser = argparse.ArgumentParser(description='Parse input string')
#position input argument
parser.add_argument('string', help='Input String')

args = parser.parse_args()
arg_str = args.string

print(arg_str)

when I run $ python test.py String I want to parse I get the error: test.py: error: unrecognized arguments: I want to parse

Is there anyway to tell the script to account for spaces and take the input as one string until either the end of the input is reached or another parse argument such as -s is reached?

like image 297
wprins Avatar asked Nov 22 '25 06:11

wprins


2 Answers

The "correct" approach is as already mentioned. But OP specifically asked:

I want it to parse without declaring the string as 'String I want to parse' but as String I want to parse

It is possible to do this with a custom action. The advantage of this approach over simply joining sys.argv[1:] is to address the following:

Is there anyway to tell the script to account for spaces and take the input as one string until either the end of the input is reached or another parse argument such as -s is reached?

We can add other options without them being mopped up into the 'string' argument:

import argparse

class MyAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, ' '.join(values))

parser = argparse.ArgumentParser(description='Parse input string')
parser.add_argument('string', help='Input String', nargs='+', action=MyAction)
parser.add_argument('--extra', '-s', help='Another Option!')

args = parser.parse_args()
print args

Demo:

$ python example.py abc def ghi
Namespace(extra=None, string='abc def ghi')
$ python example.py abc def ghi -s hello
Namespace(extra='hello', string='abc def ghi')
$ python example.py -s hello abc def ghi 
Namespace(extra='hello', string='abc def ghi')
like image 58
wim Avatar answered Nov 23 '25 21:11

wim


The problem is you give five arguments instead of one. Put your string with space between double quote and it will work.

~ ❯❯❯ python test.py asd asd
usage: test.py [-h] string
test.py: error: unrecognized arguments: asd
~ ❯❯❯ python test.py "asd asd"
asd asd
~ ❯❯❯
like image 41
Just1602 Avatar answered Nov 23 '25 21:11

Just1602