Skip to content Skip to sidebar Skip to footer

How Do I Convert A String Into A Vector Of Command Line Arguments?

In python, how do a parse a string in the same way that the command line argument string is parsed in order to construct sys.argv? I'd like to do the following First: allow for pas

Solution 1:

Use shlex.split:

>>> import shlex
>>> shlex.split('''-f text.txt -o -q "Multi word argument" arg2 "etc."''')
['-f', 'text.txt', '-o', '-q', 'Multi word argument', 'arg2', 'etc.']

Also, Python mutable defaults are the source of all evil. Don't use argv=[] as the default argument for main, use argv=None and then check its type inside the body of main:

def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

# ... 

Post a Comment for "How Do I Convert A String Into A Vector Of Command Line Arguments?"