我正在开发一个包装器脚本,它将运行一个vmware可执行文件,允许虚拟机启动/关闭/注册/注销操作的自动化。我试图使用子进程来处理调用可执行文件,但是子进程没有正确处理可执行文件路径和参数中的空格。下面是代码片段:
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函数,将得到以下输出:
$ ./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参数的路径),则会得到以下输出:
$ ./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.
显然,第二个嵌入空间的参数的存在改变了子进程解释第一个参数的方式。对如何解决这个问题有什么建议吗?
Python2.5.2/cygwin/winxp
在MS Windows上的Python中,subprocess.Popen类使用CreateProcessAPI启动进程。CreateProcess接受一个字符串,而不是一个参数数组。Python使用subprocess.list2cmdline将参数列表转换为CreateProcess的字符串。
如果我是你,我会看到subprocess.list2cmdline(args)返回什么(其中args是Popen的第一个参数)。看看它是否在第一个论点周围加了引号,会很有意思。
当然,这种解释可能不适用于Cygwin环境。
说了这么多,我没有微软视窗。
如果路径中有空格,我找到的最简单的方法就是正确解释它们。
我不知道为什么它需要双引号,但这就是工作。
要获取此消息,您可以:
使用
shell=True
:更改代码其他部分的vmrun_cmd
要尝试的事情:
打开python提示符,运行以下命令:
如果这行得通,那么引用问题是不可能的。如果不是,你就把问题隔离了。
相关问题 更多 >
编程相关推荐