python return 中的 wmic 调用无效查询错误

wmic call in python return invalid query error

我正在尝试创建一个 python 可执行文件,它将 运行 多个 wmic 调用来检查可移植可执行文件的版本。

以下代码在命令提示符下有效,因此我尝试 运行 来自 python

的同一行
wmic datafile where name="C:\Program Files\Internet Explorer\iexplore.exe" get Version /value 

Python代码:

import subprocess

spath = r'C:\Program Files\Internet Explorer\iexplore.exe'
cargs = ["wmic","datafile","where", r'name="{0}"'.format(spath), "get", "Version", "/value"]

process = subprocess.check_output(cargs)

我收到以下错误

---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-59-3271c59ed48f> in <module>()
----> 1 process = subprocess.check_output(cargs)

c:\users\jhsiang\appdata\local\programs\python\python35\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    624 
    625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 626                **kwargs).stdout
    627 
    628 

c:\users\jhsiang\appdata\local\programs\python\python35\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    706         if check and retcode:
    707             raise CalledProcessError(retcode, process.args,
--> 708                                      output=stdout, stderr=stderr)
    709     return CompletedProcess(process.args, retcode, stdout, stderr)
    710 

CalledProcessError: Command '['wmic', 'datafile', 'where', 'name="C:\Program Files\Internet Explorer\iexplore.exe"', 'get', 'Version', '/value']' returned non-zero exit status 2147749911

我认为错误消息末尾的命令是正确的。我哪里错了?

从控制台(cmd)执行查询时,路径中的反斜杠加倍(转义):
wmic datafile where name="C:\Program Files\Internet Explorer\iexplore.exe" get Version /value

根据[MSDN]: WHERE Clause

You may use string literals, such as "NTFS", in a WHERE clause. If you wish to include the following special characters in your string, you must first escape the character by prefixing the character with a backslash (\):

  • backslash (\)
  • double quotes (\")
  • single quotes (\')

Python中做同样的事情:

>>> spath = r"C:\Program Files\Internet Explorer\iexplore.exe"
>>> cargs = ["wmic", "datafile", "where", r"name=\"{0}\"".format(spath), "get", "Version", "/value"]
>>> process = subprocess.check_output(cargs)
>>> process.strip().decode()
'Version=11.0.16299.15'