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

时间:2021-07-11 12:15:41

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?

在主机上运行几个同名的进程。通过使用python或jython来获得这些进程的PIDs的跨平台方法是什么?

  1. I want something like pidof but in python. (I don't have pidof anyway.)
  2. 我想要一些类似pidof的东西,但是在python中。(反正我也没有pidof。)
  3. I can't parse /proc because it might be unavailable (on HP-UX).
  4. 我无法解析/proc,因为它可能不可用(在HP-UX上)。
  5. 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).
  6. 我不想运行OS .popen('ps')并解析输出,因为我认为它很难看(不同OS中的字段序列可能不同)。
  7. Target platforms are Solaris, HP-UX, and maybe others.
  8. 目标平台是Solaris、HP-UX,也许还有其他平台。

8 个解决方案

#1


64  

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

您可以使用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)

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():

编辑2017-04-27 -这里有一个更高级的实用函数,它根据进程的名称()、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(name)
    return ls

#2


11  

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

没有单一的跨平台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]

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

然后,您可以轻松地过滤掉所需的流程。有关Win32_Process可用属性的更多信息,请参阅Win32_Process类

#3


7  

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"

给出“你的进程。exe”

#4


3  

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.

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

#5


3  

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

首先,Windows(它是所有的化身)是一个非标准的操作系统。

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

Linux(和大多数专有的unixen)是兼容posix的标准操作系统。

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

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

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)

没有“跨平台”的方法可以做到这一点。你必须为某个特定版本的Windows (XP或Vista)设计ctype

#6


1  

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.

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

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.

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

#7


1  

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

对于jython,如果使用Java 5,则可以将Java进程id设置为:

from java.lang.management import *
pid = ManagementFactory.getRuntimeMXBean().getName()

. lang。管理导入* pid = ManagementFactory.getRuntimeMXBean().getName()

#8


0  

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.

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

#1


64  

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

您可以使用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)

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():

编辑2017-04-27 -这里有一个更高级的实用函数,它根据进程的名称()、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(name)
    return ls

#2


11  

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

没有单一的跨平台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]

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

然后,您可以轻松地过滤掉所需的流程。有关Win32_Process可用属性的更多信息,请参阅Win32_Process类

#3


7  

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"

给出“你的进程。exe”

#4


3  

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.

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

#5


3  

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

首先,Windows(它是所有的化身)是一个非标准的操作系统。

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

Linux(和大多数专有的unixen)是兼容posix的标准操作系统。

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

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

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)

没有“跨平台”的方法可以做到这一点。你必须为某个特定版本的Windows (XP或Vista)设计ctype

#6


1  

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.

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

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.

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

#7


1  

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

对于jython,如果使用Java 5,则可以将Java进程id设置为:

from java.lang.management import *
pid = ManagementFactory.getRuntimeMXBean().getName()

. lang。管理导入* pid = ManagementFactory.getRuntimeMXBean().getName()

#8


0  

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.

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