Wes Howard
Wes Howard

Reputation: 23

python argparse passing a delimited list

With the following:

parser.add_argument("-l", "--library", type=str, nargs="*", dest="scanLibrary")

There are going to be cases where the list of names passed may contain spaces. argparse is breaking the list up on whitespace so

mything.py -l test of foo, game of bar, How I foo bar your mother

nets me:

scanLibrary=['test', 'of', 'foo,', 'game', 'of', 'bar,', 'How', 'I', 'foo', 'bar', 'your', 'mother']

So how do I get argeparse to use a delimiter of my choosing?

Update: Based on advice from Martijn Pieters, I made the following change:

parser.add_argument("-l", "--library", type=str, nargs="*", dest="scanLibrary")
print args.scanLibrary
print args.scanLibrary[0].split(',')

Which gave a result of:

mything.py -l "test of foo, game of bar, How I foo bar your mother"
['test of foo, game of bar, How I foo bar your mother']
['test of foo', ' game of bar', ' How I foo bar your mother']

I can clean up the leading space easy enough. Thanks

Upvotes: 2

Views: 4099

Answers (3)

Cloudkollektiv
Cloudkollektiv

Reputation: 14689

In my opinion, an even better way to accomplish this, is to use a lambda function. This way you don't have to post-process your list, which keeps your code clean. You can do this neat little trick as follows:

# mything.py -l test of foo, game of bar, How I foo bar your mother

parser.add_argument("-l",
                    "--library",
                    type=lambda s: [i for i in s.split(',')],
                    dest="scanLibrary")

print(args.scanLibrary)

# ['test of foo', 'game of bar', 'How I foo bar your mother']

Upvotes: 2

nullp0tr
nullp0tr

Reputation: 485

Can't comment on your question because of the 50 reps. I just wanted to say that you can use:

'   some string '.strip()

To get:

'some string'

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121864

You can't. It is the shell that does the parsing here; it passes in the arguments to the process as a parsed list.

To prevent this, quote your argument:

mything.py -l "test of foo, game of bar, How I foo bar your mother"

Upvotes: 2

Related Questions