You want shlex.split()
:
s = 'first_item second\ item "third item"'
import shlex
shlex.split(s)
Out[3]: ['first_item', 'second item', 'third item']
Question
I have a python script that takes its input from the command line arguments. For example:
./myscript.py first_item second\ item "third item"
I can output separate items and escape spaces and special characters using pipes.quote
.
print " ".join(map(pipes.quote, outputItems))
Is there any existing "unquote
" interface that will parse a bash argument string, keeping escaped spaces and quoted strings intact?
Something that would allow the same python script to handle this:
echo 'first_item second\ item "third item"' | ./myscript.py
Solution
You want shlex.split()
:
s = 'first_item second\ item "third item"'
import shlex
shlex.split(s)
Out[3]: ['first_item', 'second item', 'third item']