我有一个Powershell函数(用于检查进程使用的CPU的百分比),我需要在我的Python代码中运行,而不仅仅是在Powershell中运行。但是,我无法将其转换为可以在这里工作。
#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]
运行Python版本的代码时,出现以下错误: 追溯(最近一次通话): 文件“”,第3行,在 %(processToCheck)],stdout = subprocess.PIPE) TypeError:格式字符串的参数不足
答案 0 :(得分:1)
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()