在python中通过进程名称获取PID的跨平台方法

发布于 2024-07-13 20:41:20 字数 349 浏览 5 评论 0原文

主机上正在运行多个同名进程。 使用 pythonjython 按名称获取这些进程的 PID 的跨平台方法是什么?

  1. 我想要类似 pidof 的东西,但是用 python 编写。 (无论如何,我没有 pidof。)
  2. 我无法解析 /proc,因为它可能不可用(在 HP-UX 上)。
  3. 我不想运行 os.popen('ps') 并解析输出,因为我认为它很难看(不同操作系统中的字段顺序可能不同)。
  4. 目标平台是 Solaris、HP-UX 或其他平台。

Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using python or jython?

  1. I want something like pidof but in python. (I don't have pidof anyway.)
  2. I can't parse /proc because it might be unavailable (on HP-UX).
  3. I do not want to run os.popen('ps') and parse the output because I think it is ugly (field sequence may be different in different OS).
  4. Target platforms are Solaris, HP-UX, and maybe others.

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

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

发布评论

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

评论(9

ˉ厌 2024-07-20 20:41:20

您可以使用 psutil (https://github.com/giampaolo/psutil),它适用于 Windows 和UNIX:

import psutil

PROCNAME = "python.exe"

for proc in psutil.process_iter():
    if proc.name() == PROCNAME:
        print(proc)

在我的机器上打印:

<psutil.Process(pid=3881, name='python.exe') at 140192133873040>

EDIT 2017-04-27 - 这是一个更高级的实用函数,它根据进程的 name()、cmdline() 和 exe() 检查名称:

import os
import psutil

def find_procs_by_name(name):
    "Return a list of processes matching 'name'."
    assert name, name
    ls = []
    for p in psutil.process_iter():
        name_, exe, cmdline = "", "", []
        try:
            name_ = p.name()
            cmdline = p.cmdline()
            exe = p.exe()
        except (psutil.AccessDenied, psutil.ZombieProcess):
            pass
        except psutil.NoSuchProcess:
            continue
        if name == name_ or cmdline[0] == name or os.path.basename(exe) == name:
            ls.append(p)
    return ls

You can use psutil (https://github.com/giampaolo/psutil), which works on Windows and UNIX:

import psutil

PROCNAME = "python.exe"

for proc in psutil.process_iter():
    if proc.name() == PROCNAME:
        print(proc)

On my machine it prints:

<psutil.Process(pid=3881, name='python.exe') at 140192133873040>

EDIT 2017-04-27 - here's a more advanced utility function which checks the name against processes' name(), cmdline() and exe():

import os
import psutil

def find_procs_by_name(name):
    "Return a list of processes matching 'name'."
    assert name, name
    ls = []
    for p in psutil.process_iter():
        name_, exe, cmdline = "", "", []
        try:
            name_ = p.name()
            cmdline = p.cmdline()
            exe = p.exe()
        except (psutil.AccessDenied, psutil.ZombieProcess):
            pass
        except psutil.NoSuchProcess:
            continue
        if name == name_ or cmdline[0] == name or os.path.basename(exe) == name:
            ls.append(p)
    return ls
傲性难收 2024-07-20 20:41:20

没有单一的跨平台 API,您必须检查操作系统。 对于基于 posix 的使用 /proc。 对于 Windows,请使用以下代码获取具有相应进程名称的所有 pid 列表,

from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes]

然后您可以轻松筛选出您需要的进程。
有关 Win32_Process 可用属性的详细信息,请查看 Win32_Process 类< /a>

There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names

from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes]

You can then easily filter out processes you need.
For more info on available properties of Win32_Process check out Win32_Process Class

辞旧 2024-07-20 20:41:20
import psutil

process = filter(lambda p: p.name() == "YourProcess.exe", psutil.process_iter())
for i in process:
  print i.name,i.pid

给出“YourProcess.exe”的所有 pid

import psutil

process = filter(lambda p: p.name() == "YourProcess.exe", psutil.process_iter())
for i in process:
  print i.name,i.pid

Give all pids of "YourProcess.exe"

我做我的改变 2024-07-20 20:41:20

关于 ThorSummoner 的评论

process = [proc for proc in psutil.process_iter() if proc.name == "YourProcess.exe"].

我已经在 Debian 上用 Python 3 尝试过,我认为它必须是 proc.name() 而不是 proc.name。

A note on ThorSummoner's comment

process = [proc for proc in psutil.process_iter() if proc.name == "YourProcess.exe"].

I have tried it on Debian with Python 3, I think it has to be proc.name() instead of proc.name.

狂之美人 2024-07-20 20:41:20

首先,Windows(无论其所有版本)是一个非标准操作系统。

Linux(以及大多数专有的 unixen)是符合 POSIX 的标准操作系统。

C 库反映了这种二分法。 Python 反映了 C 库。

没有“跨平台”的方法可以做到这一点。 你必须用 ctypes 来破解一些东西Windows 的特定版本(XP 或 Vista)

First, Windows (in all it's incarnations) is a non-standard OS.

Linux (and most proprietary unixen) are POSIX-compliant standard operating systems.

The C libraries reflect this dichotomy. Python reflects the C libraries.

There is no "cross-platform" way to do this. You have to hack up something with ctypes for a particular release of Windows (XP or Vista)

送你一个梦 2024-07-20 20:41:20

我认为如果不使用 /proc 或命令行实用程序,您将无法找到纯粹基于 python 的可移植解决方案,至少在 python 本身中是这样。 解析 os.system 并不难看——有人必须处理多个平台,无论是你还是其他人。 老实说,为您感兴趣的操作系统实现它应该相当容易。

I don't think you will be able to find a purely python-based, portable solution without using /proc or command line utilities, at least not in python itself. Parsing os.system is not ugly - someone has to deal with the multiple platforms, be it you or someone else. Implementing it for the OS you are interested in should be fairly easy, honestly.

百变从容 2024-07-20 20:41:20

对于 jython,如果使用 Java 5,那么您可以获得 Java 进程 ID,如下所示:

from java.lang.management import ManagementFactory

pid = int(ManagementFactory.getRuntimeMXBean().getName().split("@")[0])

print(pid)

此代码段将打印您的 PID(在我的例子中 23968

For jython, if Java 5 is used, then you can get the Java process id as following:

from java.lang.management import ManagementFactory

pid = int(ManagementFactory.getRuntimeMXBean().getName().split("@")[0])

print(pid)

This snippet will print your PID (in my case 23968)

苍暮颜 2024-07-20 20:41:20

恐怕没有。 进程由 pid 而不是名称来唯一标识。 如果您确实必须按名称查找 pid,那么您将使用您所建议的类似方法,但它不能移植,并且可能无法在所有情况下工作。

如果您只需找到某个应用程序的 pid 并且您可以控制该应用程序,那么我建议更改此应用程序以将其 pid 存储在脚本可以找到它的某个位置的文件中。

There isn't, I'm afraid. Processes are uniquely identified by pid not by name. If you really must find a pid by name, then you will have use something like you have suggested, but it won't be portable and probably will not work in all cases.

If you only have to find the pids for a certain application and you have control over this application, then I'd suggest changing this app to store its pid in files in some location where your script can find it.

甜点 2024-07-20 20:41:20

只需使用:

def get_process_by_name(name):
    import re, psutil
    ls = list()
    for p in psutil.process_iter():
        if hasattr(p, 'name'):
            if re.match(".*" + name + ".*", p.name()):
                ls.append(p)
    return ls

返回 Process 对象

Just use:

def get_process_by_name(name):
    import re, psutil
    ls = list()
    for p in psutil.process_iter():
        if hasattr(p, 'name'):
            if re.match(".*" + name + ".*", p.name()):
                ls.append(p)
    return ls

returns Process object

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