简体   繁体   English

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

[英]Error while trying to use wmi objects (python)

I'm trying to write a script which detects whether the machine that the script is run on is a virtual machine or a physical machine and I don't understand the error and how to fix it.我正在尝试编写一个脚本来检测运行该脚本的机器是虚拟机还是物理机,但我不明白错误以及如何修复它。

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"

The error:错误:

    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)

I'm hoping someone can help, I'm pretty new to python.我希望有人可以提供帮助,我对 python 还很陌生。 Thanks.谢谢。

Do things improve if you change:如果你改变了,事情会有所改善:

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

to

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

The '\\r' sequence in '\\root' will be interpreted as a <CR> character in your code. '\\root' 中的 '\\r' 序列将被解释为代码中的<CR>字符。 You either have to doubleup the '\\'s to escape them so they will be treated as backslashes, or precede the first double quote with 'r' (as I have done), to indicate to Python that this should be a "raw" string literal.您要么必须将 '\\' 加倍以将它们转义,以便将它们视为反斜杠,或者在第一个双引号前加上 'r'(正如我所做的那样),以向 Python 表明这应该是“原始”字符串字面量。 Raw strings are no different from regular strings, but the raw string syntax tells the Python compiler to not interpret backslashes.原始字符串与常规字符串没有区别,但原始字符串语法告诉 Python 编译器不要解释反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM