【问题标题】:wmic call in python return invalid query errorpython中的wmic调用返回无效查询错误
【发布时间】:2018-02-21 15:51:00
【问题描述】:

我正在尝试创建一个 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

错误消息末尾的命令对我来说是正确的。我哪里错了?

【问题讨论】:

  • 命令行 wmic datafile where name="C:\Program Files\Internet Explorer\iexplore.exe" get Version /value 也不适合我

标签: python windows subprocess wmic


【解决方案1】:

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

根据[MSDN]: WHERE Clause:

您可以在 WHERE 子句中使用字符串文字,例如“NTFS”。如果您希望在字符串中包含以下特殊字符,则必须首先通过在字符前加上反斜杠 (\) 来转义该字符:

  • 反斜杠 (\)
  • 双引号 (\")
  • 单引号 (\')

在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'

【讨论】:

  • 所以这不是一个真正的 python 问题,但你的代码有效,很好的答案。微软有时很难阅读。他们发明了反斜杠路径分隔符来惹恼 unix 用户,现在它适得其反......
  • @Jean-FrançoisFabre:没错,这是一个 WMI / WQL 问题,Python 只是一个包装器,这与问题本身没有任何关系。
  • 但是您提供了如何从 python 调用的解决方案,使用原始字符串 + 双斜杠。
  • @Jean-FrançoisFabre:你说得对,轮到我糊涂了 :)
猜你喜欢
  • 1970-01-01
  • 2019-06-17
  • 2011-05-01
  • 1970-01-01
  • 2015-05-24
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多