1

I'm trying to use IronPython 2.7 with the subprocess module to run WMIC with output going to a temporary directory. However, I'm having very strange problems with escaping the spaces.

fn=r'C:\"Documents and Settings"\me\"Local Settings"\Temp\1\q'
out="/OUTPUT:"+fn
args[1]=out
args
['WMIC', '/OUTPUT:C:\\"Documents and Settings"\\me\\"Local Settings"\\Temp\\1\\q', 'path', 'win32_process', 'get', 'ProcessId,ExecutablePath', '/format:csv']
subprocess.check_output(args)

This fails, as do all of the other attempts I've made.

Any idea how to escape arguments that are file names passed to WMIC through subprocess?

The context of the code is:

with tempdir.TempDir() as tmpdir:
    filename = os.path.join(tmpdir, tempfile.mktemp(suffix='txt',`    prefix="process"))
    arg='/OUTPUT:'+filename
    cmd = 'WMIC path win32_process get ProcessId,ExecutablePath,CommandLine /format:csv'
    cmdargs=cmd.split(' ')
    cmdargs.insert(1, arg)  

    procs = subprocess.check_output(cmdargs)
gbronner
  • 1,907
  • 24
  • 39

1 Answers1

4

subprocess doesn't use the shell (unless you tell it to), so you don't need to escape any spaces. The problem you're having is that the quotes you added to the path were treated as part of the path, rather than protecting the whitespace from being interpreted by the shell.

args = ['WMIC',
        r'/OUTPUT:C:\Documents and Settings\me\Local Settings\Temp\1\q',
        'path', 'win32_process', 'get', 'ProcessId,ExecutablePath', '/format:csv']
subprocess.check_output(args)
chepner
  • 497,756
  • 71
  • 530
  • 681