首页 > 解决方案 > 将子进程的输出拆分为列表/数组并在列表/数组中查找特定字符串。(Python)

问题描述

我正在寻找使用子进程来检查进程是否按名称运行以打开“powershell ps | findstr processname”并在它正在运行/未运行时执行某些操作。我不想使用 psutil 来完成此操作。

到目前为止,这是我想出的代码。

import subprocess
import sys

p = subprocess.Popen(['powershell.exe', 'ps | findstr chrome'], 
stdout=subprocess.PIPE)
output = p.stdout.read()
s = output.split()

chrome = "chrome"
for _ in s:
    if chrome in s:
        print("chrome running")
    else:
        print("chrome not running")

这似乎不起作用。有谁知道如何完成这项任务?

标签: pythonstringsplitprocess

解决方案


import subprocess
import sys

p = subprocess.Popen(['powershell.exe', 'ps | findstr chrome'],
stdout=subprocess.PIPE)
output = p.stdout.read()
s = output.split()

chrome = b"chrome"

if chrome in s:
    print("chrome running")
else:
    print("chrome not running")

推荐阅读