尝试使用wmi对象时出错(python)

时间:2011-03-03 13:41:09

标签: python wmi

我正在尝试编写一个脚本,用于检测运行脚本的计算机是虚拟机还是物理计算机,我不了解错误以及如何修复错误。

import wmi

def sys_info():

    objWMIService = wmi.GetObject("winmgmts:\root\cimv2")
    colItems = objWMIService.ExecQuery("Select * from Win32_BaseBoard")

    for objItem in colItems:
        print "inside"
        Manufacturer = objItem.Manufacturer
        if Manufacturer == "Microsoft Corporation":
            print "Virtual Machine"
        else:
            print "Not in one"

错误:

    Traceback (most recent call last):
  File "C:\Documents and Settings\xxx\Desktop\Python\Practice Code\System information\trial.py", line 16, in <module>
    sys_info()
  File "C:\Documents and Settings\xxx\Desktop\Python\Practice Code\System information\trial.py", line 5, in sys_info
    objWMIService = wmi.GetObject("winmgmts:""\root\cimv2")
  File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 72, in GetObject
    return Moniker(Pathname, clsctx)
  File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 87, in Moniker
    moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
com_error: (-2147217375, 'OLE error 0x80041021', None, None)

我希望有人可以提供帮助,我对python很新。感谢。

1 个答案:

答案 0 :(得分:5)

如果你改变了,事情会有所改善:

objWMIService = wmi.GetObject("winmgmts:\root\cimv2") 

objWMIService = wmi.GetObject(r"winmgmts:\root\cimv2") 

'\ root'中的'\ r'序列将被解释为代码中的<CR>字符。你要么必须加倍'\'来逃避它们,所以它们将被视为反斜杠,或者在第一个双引号之前加上'r'(正如我所做的那样),以向Python表明这应该是“原始的”字符串字面量。原始字符串与常规字符串没有区别,但原始字符串语法告诉Python编译器解释反斜杠。