用于 Linux 进程管理的 Python 库

发布于 2024-08-10 20:24:09 字数 1539 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

情绪失控 2024-08-17 20:24:09

要启动/停止 python 子进程,您可以使用 subprocess 模块。
要检查它们是否正在运行,您可以使用 psutil:

>>> import psutil
>>> pid = 1034  # some pid
>>> psutil.pid_exists(pid)
True
>>>

...或者这个(它还会检查是否PID已被重用):

>>> p = psutil.Process(pid)
>>> p.is_running()
True
>>>

To start/stop python sub processes you can use the subprocess module.
To check whether they are running you might use psutil:

>>> import psutil
>>> pid = 1034  # some pid
>>> psutil.pid_exists(pid)
True
>>>

...or this (it will also check if the PID has been reused):

>>> p = psutil.Process(pid)
>>> p.is_running()
True
>>>
弥枳 2024-08-17 20:24:09

通过查看 /proc 目录的内容来检查正在运行的进程列表(即使是通过“ps”等核心实用程序)。

因此,您对查询正在运行的进程感兴趣的库与用于处理任何其他文件和目录的库相同(即 sysos,具体取决于风格不过,请特别注意 os.path,它可以完成您所追求的大部分功能)。要终止进程或以其他方式与进程交互,您可以向它们发送信号,这是通过 os.kill 完成的。最后,您使用 os.popen 和朋友启动新进程。

Checking the list of running processes is accomplished (even by core utilities like "ps") by looking at the contents of the /proc directory.

As such, the library you're interested for querying running processes is the same as used for working with any other files and directories (i.e. sys or os, depending on the flavor you're after. Pay special attention to os.path though, it does most of what you're after). To terminate or otherwise interact with processes, you send them signals, which is accomplished with os.kill. Finally, you start new processes using os.popen and friends.

夏雨凉 2024-08-17 20:24:09

既然您说这是一个 Linux 服务器,那么调用外部 ps 二进制文件通常比直接使用 /proc 中的信息更慢、使用更多资源并且更容易出错。

由于没有其他人提到,一种简单的方法是:

glob.glob('/proc/[0-9]*/')

祝你好运。

Since you said this is a Linux server, calling the external ps binary is usually slower, uses more resources and is more error prone than using the information from /proc directly.

Since nobody else mentioned, one simple way is:

glob.glob('/proc/[0-9]*/')

Good luck.

羅雙樹 2024-08-17 20:24:09

这就是我用的。它使用 procfs(所以你仅限于类 Unix 系统,我认为不适用于 Mac)和前面提到的 glob。它还获取命令行,使您可以识别进程。要终止进程,您可以使用 os.kill(signal.SIGTERM, pid) 。要使用子进程,请查看这篇文章 Python、Popen 和 select - 等待进程终止或超时

def list_processes():
    """
    This function will return an iterator with the process pid/cmdline tuple

    :return: pid, cmdline tuple via iterator
    :rtype: iterator

    >>> for procs in list_processes():
    >>>     print procs
    ('5593', '/usr/lib/mozilla/kmozillahelper')
    ('6353', 'pickup -l -t fifo -u')
    ('6640', 'kdeinit4: konsole [kdeinit]')
    ('6643', '/bin/bash')
    ('7451', '/usr/bin/python /usr/bin/ipython')
    """
    for pid_path in glob.glob('/proc/[0-9]*/'):

        # cmdline represents the command whith which the process was started
        f = open("%s/cmdline" % pid_path)
        pid = pid_path.split("/")[2] # get the PID
        # we replace the \x00 to spaces to make a prettier output from kernel
        cmdline = f.read().replace("\x00", " ").rstrip()
        f.close()

        yield (pid, cmdline)

This is what i use. It uses procfs (so you are limited to Unix like systems, will not work on macs i think) and the previously mentioned glob. It also gets the cmdline, which allows you to identify the process. For killing the process you can use os.kill(signal.SIGTERM, pid). For using subprocess, please check this post Python, Popen and select - waiting for a process to terminate or a timeout

def list_processes():
    """
    This function will return an iterator with the process pid/cmdline tuple

    :return: pid, cmdline tuple via iterator
    :rtype: iterator

    >>> for procs in list_processes():
    >>>     print procs
    ('5593', '/usr/lib/mozilla/kmozillahelper')
    ('6353', 'pickup -l -t fifo -u')
    ('6640', 'kdeinit4: konsole [kdeinit]')
    ('6643', '/bin/bash')
    ('7451', '/usr/bin/python /usr/bin/ipython')
    """
    for pid_path in glob.glob('/proc/[0-9]*/'):

        # cmdline represents the command whith which the process was started
        f = open("%s/cmdline" % pid_path)
        pid = pid_path.split("/")[2] # get the PID
        # we replace the \x00 to spaces to make a prettier output from kernel
        cmdline = f.read().replace("\x00", " ").rstrip()
        f.close()

        yield (pid, cmdline)
拥抱我好吗 2024-08-17 20:24:09

os 模块可能是你的朋友。例如,有 os.kill 来终止进程。

在获取进程列表方面,您可能需要使用 ps 命令。 这个问题有更多相关信息。

The os module is probably your friend. There's os.kill, for instance to kill a process.

In terms of getting a list of processes, you'll probably want to shell out to the ps command. This question has more information on that.

小霸王臭丫头 2024-08-17 20:24:09

Python 子进程 http://docs.python.org/library/subprocess.html 可能帮助你。如果您创建一个带有子进程的进程,您可以使用 Popen.terminate() 函数来停止它。

Python subprocess http://docs.python.org/library/subprocess.html might help you. If you create a process with subprocess, you can use Popen.terminate() function to stop it.

桃扇骨 2024-08-17 20:24:09

我会使用 PSutil。提供一个实际示例:

import psutil

for proc in psutil.get_process_list():
    if proc.username == 'yourusername':
        if myappname in proc.cmdline:
            print 'App is running'

或者,Red Hat 使用并维护一个名为 python-linux-procfs 的 Python 模块,该模块本机解析 /proc 来管理进程。它没有得到很好的宣传,但提供了一些额外的 Linux 特定功能(例如,调度类),这些功能有时很有用。

http://pkgs.fedoraproject.org/gitweb/?p=python -linux-procfs.git

I'd use PSutil. To provide a practical example:

import psutil

for proc in psutil.get_process_list():
    if proc.username == 'yourusername':
        if myappname in proc.cmdline:
            print 'App is running'

Alternatively, Red Hat use and maintain a Python module called python-linux-procfs , which natively parses /proc, to manage processes. it's not very well publicized, but provides some additional Linux-specific features (eg, scheduling class) which are sometimes useful.

http://pkgs.fedoraproject.org/gitweb/?p=python-linux-procfs.git

舟遥客 2024-08-17 20:24:09

探索 Supervisor,它是一个基于 Python 的 Linux 过程控制系统。它提供了一个基于 Web 的 UI,可以在崩溃时自动检查进程状态/启动/停止/重新启动。
另外还有 superlance 插件,您可以在进程崩溃时发送邮件。

Explore Supervisor which is a Python based process control system for Linux. It gives a web based UI to check the process status/start/stop/restart automatically on crash.
Also there are superlance plugins available where you can send mail in case of process crash.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文