我有一个 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 版本的代码时,我收到以下错误: Traceback (most recent call last): File "", line 3, in % (processToCheck)], stdout=subprocess.PIPE) TypeError: not enough arguments for format string