Reputation: 25
I am try to execute a PowerShell command to get the memory usage and get the result.
import subprocess
output = subprocess.call(["powershell.exe", "Get-Counter -Counter "+'"\memory\\available mbytes"'+" -MaxSamples 10 -SampleInterval 1"])
try:
subprocess.check_output("Get-Counter -Counter "+'"\memory\\available mbytes"'+" -MaxSamples 10 -SampleInterval 1", shell=TRUE)
except subprocess.CalledProcessError, e:
print "subproces CalledProcessError.output = " + e.output
print output
It is success to execute the command, but only get the following result:
subproces CalledProcessError.output =
0
How can I get the PowerShell result back?
Upvotes: 1
Views: 11795
Reputation: 101
Same example as above but for Python 3:
try:
output = subprocess.check_output(
["powershell.exe", "Get-Counter",
"-Counter "+r'"\memory\available mbytes"',
"-MaxSamples 10", "-SampleInterval 1"],
shell=True)
except subprocess.CalledProcessError as e:
print ("subproces CalledProcessError.output =", e.output)
print (output.decode())
Upvotes: 0
Reputation: 28370
You need to do:
try:
output = subprocess.check_output(
["powershell.exe", "Get-Counter",
"-Counter "+r'"\memory\available mbytes"',
"-MaxSamples 10", "-SampleInterval 1"],
shell=True)
except subprocess.CalledProcessError, e:
print "subproces CalledProcessError.output = " + e.output
print output
Notice True
rather than TRUE
supplying the "powershell.exe"
to check_output
and the r
before strings with \
in.
But I would strongly recommend using psutil instead of trying to get and parse PowerShell results:
In [4]: import psutil
In [5]: psutil.virtual_memory()
Out[5]: svmem(total=17087684608L, available=8599142400L, percent=49.7, used=8488542208L, free=8599142400L)
In [6]: psutil.swap_memory()
Out[6]: sswap(total=38059204608L, used=14400655360L, free=23658549248L, percent=37.8, sin=0, sout=0)
Upvotes: 1