当多个参数包含空格时如何使用子进程? [英] How to use subprocess when multiple arguments contain spaces?

查看:30
本文介绍了当多个参数包含空格时如何使用子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包装脚本,它将执行 vmware 可执行文件,允许虚拟机启动/关闭/注册/注销操作的自动化.我正在尝试使用子进程来处理调用可执行文件,但是子进程没有正确处理可执行文件路径和可执行文件参数中的空格.下面是一段代码:

I'm working on a wrapper script that will exercise a vmware executable, allowing for the automation of virtual machine startup/shutdown/register/deregister actions. I'm trying to use subprocess to handle invoking the executable, but the spaces in the executables path and in parameters of the executable are not being handled correctly by subprocess. Below is a code fragment:

vmrun_cmd = r"c:/Program Files/VMware/VMware Server/vmware-cmd.bat"
def vm_start(target_vm):
    list_arg = "start"
    list_arg2 = "hard"
    if vm_list(target_vm):
            p = Popen([vmrun_cmd, target_vm, list_arg, list_arg2],   stdout=PIPE).communicate()[0]
            print p
    else:
            vm_register(target_vm)
            vm_start(target_vm)
def vm_list2(target_vm):
    list_arg = "-l"
    p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0]
    for line in p.split('\n'):
            print line

如果我调用 vm_list2 函数,我会得到以下输出:

If I call the vm_list2 function, I get the following output:

$ ./vmware_control.py --list                                                
C:\Virtual Machines\QAW2K3Server\Windows Server 2003 Standard Edition.vmx
C:\Virtual Machines\ubunturouter\Ubuntu.vmx
C:\Virtual Machines\vacc\vacc.vmx
C:\Virtual Machines\EdgeAS-4.4.x\Other Linux 2.4.x kernel.vmx
C:\Virtual Machines\UbuntuServer1\Ubuntu.vmx
C:\Virtual Machines\Other Linux 2.4.x kernel\Other Linux 2.4.x kernel.vmx
C:\Virtual Machines\QAClient\Windows XP Professional.vmx

如果我调用 vm_start 函数,它需要一个路径到 vm 参数,我会得到以下输出:

If I call the vm_start function, which requires a path-to-vm parameter, I get the following output:

$ ./vmware_control.py --start "C:\Virtual Machines\ubunturouter\Ubuntu.vmx"
'c:\Program' is not recognized as an internal or external command,
operable program or batch file.

显然,带有嵌入空格的第二个参数的存在正在改变子进程解释第一个参数的方式.有关如何解决此问题的任何建议?

Apparently, the presence of a second parameter with embedded spaces is altering the way that subprocess is interpreting the first parameter. Any suggestions on how to resolve this?

python2.5.2/cygwin/winxp

python2.5.2/cygwin/winxp

推荐答案

如果路径中有空格,我发现让它们正确解释的最简单方法是这样.

If you have spaces in the path, the easiest way I've found to get them interpreted properly is this.

subprocess.call('""' + path + '""')

我不知道为什么它需要双双引号,但这是有效的.

I don't know why exactly it needs double double quotes, but that is what works.

这篇关于当多个参数包含空格时如何使用子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆