简体   繁体   English

如何通过Python查找进程的pid?

[英]How to find pid of a process by Python?

friends:朋友们:

I am running a script in Linux:我在 Linux 中运行一个脚本:

I can use the ps command get the process.我可以使用ps命令获取进程。

ps -ef | grep "python test09.py&"

but, how can I know the pid of the running script by given key word python test09.py& using python code?但是,如何通过给定的关键字python test09.py&使用 python 代码知道正在运行的脚本的 pid?


EDIT-01编辑-01

I mean, I want to use the python script to find the running script python test09.py& 's pid.我的意思是,我想使用 python 脚本来查找正在运行的脚本python test09.py&的 pid。


EDIT-02编辑-02

When I run anali's method I will get this error:当我运行 anali 的方法时,我会收到此错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py", line 363, in catch_zombie
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py", line 429, in cmdline
    return cext.proc_cmdline(self.pid)
ProcessLookupError: [Errno 3] No such process (originated from sysctl)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test11.py", line 29, in <module>
    print(get_pids_by_script_name('test09.py'))
  File "test11.py", line 15, in get_pids_by_script_name
    cmdline = proc.cmdline()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/__init__.py", line 694, in cmdline
    return self._proc.cmdline()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py", line 342, in wrapper
    return fun(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py", line 429, in cmdline
    return cext.proc_cmdline(self.pid)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 77, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py", line 376, in catch_zombie
    raise AccessDenied(proc.pid, proc._name)
psutil.AccessDenied: psutil.AccessDenied (pid=1)

Use this code and do a string matching against the cmd line使用此代码并对 cmd 行进行字符串匹配

import psutil
# Iterate over all running process
for proc in psutil.process_iter():
    try:
        # Get process name & pid & cmd line from process object.
        processName = proc.name()
        processID = proc.pid
        print(proc.cmdline())
        print(processName , ' ::: ', processID)
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass

If you just want the pid of the current script, then use os.getpid :如果您只想要当前脚本的 pid,请使用os.getpid

import os
pid = os.getpid()

However, below is an example of using psutil to find the pids of python processes running a named python script.但是,下面是使用psutil查找运行命名 python 脚本的 python 进程的 pid 的示例。 This could include the current process, but the main use case is for examining other processes, because for the current process it is easier just to use os.getpid as shown above.这可能包括当前进程,但主要用例是检查其他进程,因为对于当前进程,使用os.getpid更容易,如上所示。

sleep.py

#!/usr/bin/env python
import time
time.sleep(100)

get_pids.py

import os
import psutil


def get_pids_by_script_name(script_name):

    pids = []
    for proc in psutil.process_iter():

        try:
            cmdline = proc.cmdline()
            pid = proc.pid
        except psutil.NoSuchProcess:
            continue

        if (len(cmdline) >= 2
            and 'python' in cmdline[0]
            and os.path.basename(cmdline[1]) == script_name):

            pids.append(pid)

    return pids


print(get_pids_by_script_name('sleep.py'))

Running it:运行它:

$ chmod +x sleep.py

$ cp sleep.py other.py

$ ./sleep.py &
[3] 24936

$ ./sleep.py &
[4] 24937

$ ./other.py &
[5] 24938

$ python get_pids.py 
[24936, 24937]

Use Subprocess Library使用子流程库

import subprocess
script_name = "test09.py"
ps_out = subprocess.Popen("ps -ef".split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read().decode('UTF-8').split("\n") # Launch command line and gather output
for entry in ps_out:  # Loop over returned lines of ps
    if script_name in entry:
        script_pid = entry.split()[1] # retrieve second entry in line
        break
print(script_pid)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM