Spaces in path name

joep josef.pktd at
Sat Mar 15 22:42:07 CET 2008


Note: this works for 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

Here is a test file checking several cases:

'''use winrar to get file information of a rar file
testing double quotes for windows file paths with spaces using


 * 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",
    elif version == 4:
        executable_name = os.path.join(r'C:\Program Files\WinRAR',
        rarcmd = [executable_name, "v",  filename]

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

filenames = [r'"C:\temp\Copy of 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'
            print 'failure'
from pprint import pprint
print 'positives:'
print 'negatives:'

More information about the Python-list mailing list