本文介绍了Python执行powershell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行 PowerShell 命令以获取内存使用情况并获得结果.
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
如何取回 PowerShell 结果?
How can I get the PowerShell result back?
推荐答案
你需要做的:
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_output
和 r
前面带有 \
的字符串.
Notice True
rather than TRUE
supplying the "powershell.exe"
to check_output
and the r
before strings with \
in.
但是我强烈建议使用 psutil 而不是尝试获取和解析 PowerShell 结果:
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)
这篇关于Python执行powershell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!