[英]How to convert this Powershell function to work within Python?
I have a Powershell function (which checks the % of CPU that a process uses) that I need to run WITHIN my Python code, and not just within Powershell. 我有一个Powershell函数(它检查进程使用的CPU的百分比),我需要在我的Python代码中运行,而不仅仅是在Powershell中运行。 However, I am having trouble converting it to work there.
但是,我在将其转换为可以工作时遇到了麻烦。
#Powershell code to convert:
$Processname = "notepad"
$CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors
$Samples = (Get-Counter “\Process($Processname)\% Processor Time”).CounterSamples
($Samples | Select InstanceName, @{Name=”CPU”;Expression= {[Decimal]::Round(($_.CookedValue / $CpuCores), 2)}}).CPU
#My attempt at converting it to Python:
import subprocess
processToCheck = "notepad"
process = subprocess.Popen(["powershell",
"""Invoke-Command -ScriptBlock {$CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors | $Samples = (Get-Counter “\Process(%s)\% Processor Time”).CounterSamples ; Write-Host $Samples}"""
% (processToCheck)], stdout=subprocess.PIPE)
print process.communicate()[0]
When running Python version of the code, I get the following error: Traceback (most recent call last): File "", line 3, in % (processToCheck)], stdout=subprocess.PIPE) TypeError: not enough arguments for format string 当运行Python版本的代码时,出现以下错误:追溯(最近一次调用为最新):文件“”,第3行,以%(processToCheck)],stdout = subprocess.PIPE)TypeError:格式字符串的参数不足
import subprocess
processToCheck = "notepad"
script = """
$CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors;
$Samples = (Get-Counter "\Process(%s)\%% Processor Time").CounterSamples.CookedValue;
[Decimal]::Round($Samples / $CpuCores, 2);
""" % (processToCheck)
proc = subprocess.Popen(["powershell", script], stdout=subprocess.PIPE)
print(proc.communicate()[0])
proc.wait()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.