running command via subprocess on Windows with spaces in filenames
Question: To run a command in python, for Windows, I do:

    
    
    import subprocess
    subprocess.check_output(lsCommand, shell=True)
    

where `lsCommand` is a list of strings that make up the bash command. This
works, except when it contains some input with spaces in it. For example,
copying + changing a name:

To try and do `cp "test 123" test123`:

    
    
    lsCommand = ['cp', 'test 123', 'test123']
    subprocess.check_output(lsCommand, shell=True)
    

fails because it thinks I am trying to do `cp "test" "123" test123`. Error
(doing google storage stuff):

    
    
    python: can't open file 'c:\GSUtil\gsutil.py cp -n gs://folderl/test': [Errno 22] Invalid argument
    

Then I try

    
    
    subprocess.check_output('cp "test 123" test123', shell=True)
    

Same shit. Any ideas?


Answer: `cp` is not an [internal command](http://ss64.com/nt/) and therefore you don't
need `shell=True` ([though you might need to specify a full path to
`cp.exe`](http://stackoverflow.com/q/24789749/4279)).

The internal interface for starting a new subprocess on Windows uses a string
i.e., it is up to the specific application how to interpret a command-line.
[The default MS C runtime rules (imlemented in `subprocess.list2cmdline()`
that is called implicitly if you pass a list on
Windows)](https://docs.python.org/3/library/subprocess.html#converting-an-
argument-sequence-to-a-string-on-windows) should work fine in this case:

    
    
    #!/usr/bin/env python
    from subprocess import check_call
    
    check_call(['cp', 'test 123', 'test123'])
    

If you want to use `shell=True` then the program that interprets the command
line is `cmd.exe` and you should use its escape rules ([e.g., `^` is a meta-
character](http://stackoverflow.com/q/27864103/4279)) and pass the command as
a string as is (as you see it in the Windows console):

    
    
    check_call('copy /Y /B "test 123" test123', shell=True)
    

Obviously, you don't need to start an external process, to [copy a file in
Python](http://stackoverflow.com/q/12842997/4279):

    
    
    import shutil
    
    shutil.copy('test 123', 'test123')
    

