0

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

1
  • there is no format string in the powershell that i can see in your python sub-process call. are you certain the error is in the powershell code? Commented Jan 6, 2019 at 10:00

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.