Split into N elements a string by spaces preserving quoted substrings
<p>I would like to split a string into 3 elements by spaces but I don't want the quoted substrings to be split (they can also contain backslash to escape the quotes).</p>

<p>For instance:</p>

<pre><code>"command argument other arguments and options"
&gt;&gt; ['command', 'argument', 'other arguments and options']

'command "my argument" other arguments and options'
&gt;&gt; ['command', 'my argument', 'other arguments and options']

'command "my \"ugly\" argument" other "arguments" and options'
&gt;&gt; ['command', 'my "ugly" argument', 'other "arguments" and options']
</code></pre>

<p>I had a look at this <a href="http://stackoverflow.com/questions/79968/split-a-string-by-spaces-preserving-quoted-substrings-in-python">similar question</a> but <code>shlex.split()</code> will also split the end of the string (and it will remove the quotes and the spaces) whereas I want to keep the third element intact.</p>

<p>I tried to use <code>shlex.split(mystring)[0:2]</code> in order to get the first two elements but then I can't manage to find a good solution to extract the third element from the original string. Actually I wish I could use <code>shlex.split()</code> like the <code>str.split()</code> method with a <code>maxsplit</code> argument.</p>

<p>Is there a better way to do this than using <code>shlex.split()</code>? Perhaps regexes? Thanks!</p>
