psutil返回已停止警告的模块

2024-10-08 18:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能为这个问题举一个可复制的例子;请仔细检查我的逻辑是否有误解,或者我是否遗漏了什么

我正在尝试编写一个脚本,检查python应用程序是否应该持续运行,如果它停止工作,请给我发一封电子邮件。我正在使用psutil检查正在运行的进程。下面是我的函数,它检查有问题的程序是否正在运行(我定期调用这个函数)

def programRunning():
    cmdLines = []

    for pid in psutil.pids():
            p = psutil.Process(pid)
            if p.name() == "pythonw.exe":
                    cmdLines.append(p.cmdline()[-1])
           #scheduler.py is my script
    if any('scheduler' in process for process in cmdLines):
        return True  
    else:
        return False

现在,我的主程序产生了一个错误并停止运行,但是这个函数仍然返回True,就像我得到的cmdLineslist一样(除其他外):

['C:\\Users\\..omitted..\\scheduler.py', ..omitted..]

因此,我在理解psutils的工作原理时,显然遗漏了一些东西。你知道这是什么,怎么解决吗


Tags: 函数inpytrueforreturnifprocess
1条回答
网友
1楼 · 发布于 2024-10-08 18:25:50

“psutil.pids()”的docs表示:

Return a list of current running PIDs. To iterate over all processes and avoid race conditions process_iter() should be preferred.

所以听起来您的进程正在生成pids列表和您在迭代期间到达该项之间退出

您可能想使用psutil.process_iter,它表示:

Return an iterator yielding a Process class instance for all running processes on the local machine. Every instance is only created once and then cached into an internal table which is updated every time an element is yielded. Cached Process instances are checked for identity so that you’re safe in case a PID has been reused by another process, in which case the cached instance is updated.

相关问题 更多 >

    热门问题