如何为子进程转义空格?

时间:2015-05-20 18:46:42

标签: python subprocess ironpython wmic

我尝试使用IronPython 2.7和子进程模块来运行WMIC,输出转到临时目录。但是,我在逃离空间方面遇到了非常奇怪的问题。

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)

这失败了,我所做的所有其他尝试都失败了。

知道如何转义通过子进程传递给WMIC的文件名的参数吗?

代码的上下文是:

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)

1 个答案:

答案 0 :(得分:3)

subprocess不使用shell(除非你告诉它),所以你不需要转义任何空格。您遇到的问题是您添加到路径中的引号被视为路径的一部分,而不是保护外壳不被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)