Python调用VMware虚拟机示例

import os
import subprocess


class VM:
    def __init__(self, path):
        os.putenv("path", path)

    def run_command(self, command):  # 取DOS执行结果
        """运行cmd命令"""
        result = subprocess.run(command, capture_output=True, shell=True, encoding='gbk')
        return result.stdout

    def StartVirtualMachine(self, VirtualMachinePath: str, gui: bool):
        """启动指定虚拟机"""
        if gui:
            command = f'vmrun.exe -T ws start "{VirtualMachinePath}" gui'
        else:
            command = f'vmrun.exe -T ws start "{VirtualMachinePath}" nogui'
        return self.run_command(command)


if __name__ == '__main__':
    vm = VM(r'E:\VMwareWorkstation')
    vm.StartVirtualMachine(r"D:\WinXp_52Pojie_2.0\WinXp_52Pojie_2.0.vmx", True)