pythonwindowssubprocesswmic

wmic call in python return invalid query error


I'm trying to create a python executable that will run multiple wmic calls to check the versions of portable executables.

The following code works in the command prompt, so I attempted to run the same line from python

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

Python Code:

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)

I get the following error

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

The command at the end of the error message looks correct to me. Where am I going wrong?


Solution

  • When executing the query from console (Cmd), the BackSlashes in the path are doubled (escaped):
    wmic datafile where name="C:\\Program Files\\Internet Explorer\\iexplore.exe" get Version /value

    According to [MS.Learn]: WHERE Clause (WMI) (emphasis is mine):

    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 (\')

    Do the same thing in Python:

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