Is there something wrong with splitting a command line with split(' ')?
Question: In most [answers](http://stackoverflow.com/questions/89228/calling-an-
external-command-in-python) (I found) to the question _"How to run an external
command"_ I see something along the lines

> If you want to run `ls -l` you need to use `subprocess.call(["ls", "-l"])`

What I normally do when I know what I will be running is to call
`subprocess.call('ls -l'.split(' '))` to have visually the command line in one
piece (it is usually a variable).

Is there anything inherently wrong with using `split()` as opposed to building
the list manually (again, when the command is known). Or are these answers
crafted to explicitly show that a list is needed?

I tried to find some drawbacks (multiple spaces, escaped spaces, ...) but I do
not see where that approach could go wrong?

Note: this question is specifically about the robustness of splitting on
spaces, not the security issues or other (very important) considerations as
such.


Answer: Observe that this works:

    
    
    >>> import subprocess
    >>> subprocess.call(['ls', '-l', "my file"])
    -rw-rw---- 1 john john 0 May  5 10:46 my file
    0
    

But this does not:

    
    
    >>> subprocess.call('ls -l "my file"'.split(' '))
    ls: cannot access "my: No such file or directory
    ls: cannot access file": No such file or directory
    2
    

And this does work:

    
    
    >>> import shlex
    >>> shlex.split('ls -l "my file"')
    ['ls', '-l', 'my file']
    >>> subprocess.call(shlex.split('ls -l "my file"'))
    -rw-rw---- 1 john john 0 May  5 10:46 my file
    0
    

### Recommendation

In python philosphy, [explicit is better than
implicit](https://www.python.org/dev/peps/pep-0020/). Thus, of those three
forms, use this one:

    
    
    subprocess.call(['ls', '-l', 'my file'])
    

This avoids all preprocessing and shows you clearly and unambiguously and
_explicitly_ what will be executed and what its arguments are.

