Splitting a string by spaces without space-splitting elements in double-quotes I need to split a command like:

r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'`


into:

['"C:\\Program Files (x86)\\myeditor"',
 '"$FILEPATH"',
 '-n$LINENO',
 '"c:\\Program Files"',
 '-f$FILENAME',
 '-aArg2']


That is, I want to split by spaces, but avoid splitting the elements in double-quotes.

I have this code:

import re

s = r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'

start = end = 0
split = []

for elem in re.findall('".*?"', s):
    end = s.find(elem)
    split.append(s[start:end])
    split.append(elem)
    start = end + len(elem)

split.extend(s[start:].split())
split = [elem.strip() for elem in split]
split = list(filter(None, split))


It works, but I'm wondering if there's some more elegant/shorter/more readable way to do that in Python(3) ?
The best way to do what you want with the standard library would be shlex.split():

&gt;&gt;&gt; import shlex
&gt;&gt;&gt; s = r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'
&gt;&gt;&gt; shlex.split(s)
['C:\\Program Files (x86)\\myeditor', '$FILEPATH', '-n$LINENO', 'c:\\Program Files', '-f$FILENAME', '-aArg2']


Note that the quotes are not retained.