1

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?

1
  • Does your command (Get-Counter -Counter "\memory\available mbytes" -MaxSamples 10 -SampleInterval 1) work in an interactive powershell session? Commented May 29, 2017 at 21:22

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.