Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse strings to look like sys.argv

I would like to parse a string like this:

-o 1  --long "Some long string"   

into this:

["-o", "1", "--long", 'Some long string'] 

or similar.

This is different than either getopt, or optparse, which start with sys.argv parsed input (like the output I have above). Is there a standard way to do this? Basically, this is "splitting" while keeping quoted strings together.

My best function so far:

import csv def split_quote(string,quotechar='"'):     '''      >>> split_quote('--blah "Some argument" here')     ['--blah', 'Some argument', 'here']      >>> split_quote("--blah 'Some argument' here", quotechar="'")     ['--blah', 'Some argument', 'here']     '''     s = csv.StringIO(string)     C = csv.reader(s, delimiter=" ",quotechar=quotechar)     return list(C)[0] 
like image 381
Gregg Lind Avatar asked May 22 '09 18:05

Gregg Lind


People also ask

Is SYS argv a list of strings?

sys. argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments.

What is the data type of SYS argv?

sys. argv is a list in Python, which contains the command-line arguments passed to the script. With the len(sys. argv) function you can count the number of arguments.

What is the value stored in SYS argv 0 in Python?

" sys. argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c' .


1 Answers

I believe you want the shlex module.

>>> import shlex >>> shlex.split('-o 1 --long "Some long string"') ['-o', '1', '--long', 'Some long string'] 
like image 82
Jacob Gabrielson Avatar answered Sep 21 '22 19:09

Jacob Gabrielson