Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

python - How to use subprocess when multiple arguments contain spaces?

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('
'):
            print line

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

$ ./vmware_control.py --list                                                
C:Virtual MachinesQAW2K3ServerWindows Server 2003 Standard Edition.vmx
C:Virtual MachinesubunturouterUbuntu.vmx
C:Virtual Machinesvaccvacc.vmx
C:Virtual MachinesEdgeAS-4.4.xOther Linux 2.4.x kernel.vmx
C:Virtual MachinesUbuntuServer1Ubuntu.vmx
C:Virtual MachinesOther Linux 2.4.x kernelOther Linux 2.4.x kernel.vmx
C:Virtual MachinesQAClientWindows XP Professional.vmx

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 MachinesubunturouterUbuntu.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...