Python: Using Argparser

Using Argparser can I separate multiple command line arguments with a comma rather than a whitespace? Currently " -i NY, Philly, Baltimore" gives ['NY, Philly, Baltimore'] instead of ['NY', 'Philly', 'Baltimore'].
Who is Participating?
mish33Connect With a Mentor Commented:
You can easily convert  ['NY, Philly, Baltimore'] to ['NY', 'Philly', 'Baltimore'] by
iargs = iargs[0].replace(',',' ').split()

Open in new window

Can you post your code?  And explain more what you want to do?   Do you really want NY, Philly and Baltimore to be individual arguments or do you want them as options to your '-i' argument?  

Based on the command-line you posted (rather than what you asked), it seems like you'd want something like this (handles commas or spaces) and returns NY, Philly, Baltimore as a list of values for '-i':

import sys
import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument("-i", nargs="*")
args = parser.parse_args()
args.i = re.split(r'[\s,]+'," ".join(args.i))
print args.i


If you really are asking to get the comma to count as a command-line separator-- I don't think that's what you really want to do but it's what you said you wanted to do--- then this would probably work:

arg = parser.parse_args(re.split(r'[\s,]+'," ".join(sys.argv[1:])))
I'd do argument parsing in two steps.

let the argument parser parse the fields separately and get "NY,Phily,..." in one variable.

use then split to split further.

should NY,Phily,..." all belong to command option ;-i; or is I independent?

If you don't know whether the user passes the argument separated with spaces or with ',', then you had to write slightly more complicated cocde.

Ideally you show usyour existing code snippet,
 the command line,
the expected result

 (From your expected result it's not really clear what happened with tthe '-i' for example.
mish33 is the correct answer beceause it's simple, quick to use and solves your proble, you should accept it.
All Courses

From novice to tech pro — start learning today.