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]
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.
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.
" 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' .
I believe you want the shlex module.
>>> import shlex >>> shlex.split('-o 1 --long "Some long string"') ['-o', '1', '--long', 'Some long string']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With