Python执行powershell命令

时间:2017-03-01 07:37:36

标签: python powershell subprocess

我尝试执行PowerShell命令以获取内存使用情况并获得结果。

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

执行命令成功,但只获得以下结果:

subproces CalledProcessError.output = 
0

如何获取PowerShell结果?

2 个答案:

答案 0 :(得分:1)

你需要这样做:

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

请注意 True 而不是TRUE"powershell.exe"提供check_outputr字符串前\ in。

但是我强烈建议您使用psutil而不是尝试获取和解析PowerShell结果:

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)

答案 1 :(得分:0)

与上面相同,但对于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())