Python执行powershell命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python执行powershell命令相关的知识,希望对你有一定的参考价值。
我尝试执行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结果?
答案
你需要这样做:
try:
output = subprocess.check_output(
["powershell.exe", "Get-Counter",
"-Counter "+r'"memoryavailable 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
之前用字符串。
但我强烈建议使用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)
另一答案
与上面相同,但对于Python 3:
try:
output = subprocess.check_output(
["powershell.exe", "Get-Counter",
"-Counter "+r'"memoryavailable mbytes"',
"-MaxSamples 10", "-SampleInterval 1"],
shell=True)
except subprocess.CalledProcessError as e:
print ("subproces CalledProcessError.output =", e.output)
print (output.decode())
以上是关于Python执行powershell命令的主要内容,如果未能解决你的问题,请参考以下文章