s123
s123

Reputation: 471

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. 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

Upvotes: 0

Views: 136

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89221

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()

Upvotes: 1

Related Questions