subprocess module exec 'wmic datafile' command no result and how to fix it?
i can get reply in cmd.exe like this:
comand
wmic datafile where name="C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" get Version /value
reply
Version=110.0.5481.178
but when i use python's subprocess,it will give me just empty reply
anyone has the same question?how to resolve it?
回答:
import subprocessspath = r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
cargs = ["wmic", "datafile", "where", "name=\"{0}\"".format(spath), "get", "Version", "/value"]
process = subprocess.check_output(cargs)
print(process.strip().decode())
回答:
If you want to get the result from subprocess
module, you can try these functions as below.
1. subprocess.check_output
- Run command with arguments and return its output.
- Example:
In [70]: r = subprocess.check_output("ls ~", shell=True)In [72]: r.decode()
Out[72]: 'Applications\nDesktop\nDocuments\nDownloads\nLibrary\nMovies\nMusic\nPictures\nPostman\nPublic\nSunlogin Files\nfineagent.jar\nget-poetry.py\ngo\nlogfile\npip.conf\npythonlogs\nrequirements.txt\nssh.sh\n'
2. subprocess.getoutput
- Return output (stdout and stderr) of executing cmd in a shell.
- Example:
In [79]: r = subprocess.getoutput("ls ~")In [80]: r
Out[80]: 'Applications\nDesktop\nDocuments\nDownloads\nLibrary\nMovies\nMusic\nPictures\nPostman\nPublic\nSunlogin Files\nfineagent.jar\nget-poetry.py\ngo\nlogfile\npip.conf\npythonlogs\nrequirements.txt\nssh.sh'
and also subprocess.getstatusoutput
, etc.
You have more choice. Refer official website: portal1 | portal2
But the functions metioned above are either legacy functions from the 2.x commands module or old high level api...
Now the recommended way to invoke subprocess is to use run()
function. For more advanced use cases, the underlying Popen
「It's also a nice choice.」interface can be used directly.
3. subprocess.run
- Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.
- Example:
In [76]: r = subprocess.run("ls ~", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)In [77]: r
Out[77]: CompletedProcess(args='ls ~', returncode=0, stdout=b'Applications\nDesktop\nDocuments\nDownloads\nLibrary\nMovies\nMusic\nPictures\nPostman\nPublic\nSunlogin Files\nfineagent.jar\nget-poetry.py\ngo\nlogfile\npip.conf\npythonlogs\nrequirements.txt\nssh.sh\n', stderr=b'')
In [78]: r.stdout
Out[79]: b'Applications\nDesktop\nDocuments\nDownloads\nLibrary\nMovies\nMusic\nPictures\nPostman\nPublic\nSunlogin Files\nfineagent.jar\nget-poetry.py\ngo\nlogfile\npip.conf\npythonlogs\nrequirements.txt\nssh.sh\n'
Refer to the detailed description: subprocess.run
Hope it helps you.
以上是 subprocess module exec 'wmic datafile' command no result and how to fix it? 的全部内容, 来源链接: utcz.com/p/938782.html