Spaces in path name

joep josef.pktd at gmail.com
Sat Mar 15 17:42:07 EDT 2008


>
> http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa...

Note: this works for subprocess.call but for subprocess.Popen this
does not work if there are two arguments in the command line with
spaces. Especially, even after trying out many different versions, I
never managed to get subprocess.Popen to work, when both the
executable and one argument have spaces in the file path.

subprocess.Popen requires the same extra double quoting at front or
around the entire command as os.system. It took me many hours to find
the versions of quoting that work. Explanation by Fredrik Lundh
 in thread
http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5

Here is a test file checking several cases:

<code>
'''use winrar to get file information of a rar file
testing double quotes for windows file paths with spaces using
subprocess.Popen

see:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5

result:
 * most robust: use double quotes around entire command string
 * command as list argument never works when 2 file paths have spaces
'''
import sys, os
import subprocess

def rargetinfo(filename,version=0):
    '''use winrar to get file information of a rar file
    '''
    if version == 0:
        rarcmd = '"%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"',
"v",  filename)
    elif version == 1:
        rarcmd = '"%s %s %s" ' % (r'"C:\Program Files\WinRAR
\Rar.exe"', "v",  filename)
    elif version == 2:
        rarcmd = '%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"',
"v",  filename)
    elif version == 3:
        rarcmd = [r'"C:\Program Files\WinRAR\Rar.exe"', "v",
filename]
    elif version == 4:
        executable_name = os.path.join(r'C:\Program Files\WinRAR',
'Rar.exe')
        rarcmd = [executable_name, "v",  filename]

    p = subprocess.Popen(rarcmd, shell=True, stdout=subprocess.PIPE)
    rettext,reterror = p.communicate()
    retcode = p.wait()
    p.stdout.close()
    print rarcmd
    print 'this is rettext',rettext[:50]
    return rettext, rarcmd


filenames = [r'"C:\temp\Copy of papers.rar"']
filenames.append(r'"C:\temp\papers.rar"')
filenames.append(r'C:\temp\papers.rar')

positives = {}
negatives = {}

for filename in filenames:
    for version in range(5):
        print '\n%s version: %d' % (filename,version)
        rettext, cmd = rargetinfo(filename,version)
        if rettext :
            print 'success'
            positives.setdefault(version,[]).append(cmd)
        else:
            print 'failure'
            negatives.setdefault(version,[]).append(cmd)
from pprint import pprint
print 'positives:'
pprint(positives)
print 'negatives:'
pprint(negatives)
</code>




More information about the Python-list mailing list