使用Python内置模块检查Windows中的进程是否正在运行

3
3个回答

6
也许这会对你有所帮助:
import subprocess

s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    print s

1

0

如果你只是想通过进程名称测试进程是否正在运行,那么你可以从subprocess模块中导入check_output方法(而不是整个模块):

from subprocess import check_output

print('Test whether a named process appears in the task list.\n')
processname = input('Enter process name: ')   # or just assign a specific process name to the processname variable 
tasks = check_output('tasklist')
if processname in str(tasks):
    print('{} is in the task list.'.format(processname))
else:
    print('{} not found.'.format(processname))

输出:

>>> Discord.exe
Discord.exe is in the task list.

>>> NotARealProcess.exe
NotARealProcess.exe not found.

(这在我使用Python 3.10的Windows 10上有效。)请注意,由于这只是在整个任务列表输出中搜索特定字符串,因此它会对部分进程名称(例如“app.exe”或“app”,如果“myapp.exe”正在运行)和其他非进程文本输入产生误报:
>>> cord.ex
cord.ex is in the task list.

>>> PID Session Name
PID Session Name is in the task list.

如果您只想在任务列表中查找已知进程名称并按整个名称搜索,则此代码通常应该正常工作,但对于更严格的用途,您可能希望使用更复杂的方法,例如将任务列表解析为字典并分离名称以进行更专注的搜索,同时添加一些错误检查以处理边缘情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接