如何使用Python获取Unix或Linux中程序的进程ID?

时间:2010-09-21 15:05:25

标签: python

我正在用Python编写一些监控脚本,并且我试图找到最简洁的方法来获取任何随机运行程序的进程ID,并给出该程序的名称

类似

ps -ef | grep MyProgram

我可以解析它的输出,但我认为在python中可能有更好的方法

9 个答案:

答案 0 :(得分:283)

From the standard library

os.getpid()

答案 1 :(得分:17)

如果你不是限制自己使用标准库,我喜欢psutil

例如找到所有“python”进程:

>>> import psutil
>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']]
[{'name': 'python3', 'pid': 21947},
 {'name': 'python', 'pid': 23835}]

答案 2 :(得分:13)

试试pgrep。它的输出格式更简单,因此更容易解析。

答案 3 :(得分:6)

此外: Python: How to get PID by process name?

适应之前发布的答案。

def getpid(process_name):
    import os
    return [item.split()[1] for item in os.popen('tasklist').read().splitlines()[4:] if process_name in item.split()]

getpid('cmd.exe')
['6560', '3244', '9024', '4828']

答案 4 :(得分:3)

适用于Windows

无需下载任何模块即可在您的计算机上获取所有程序的方法:

import os

pids = []
a = os.popen("tasklist").readlines()
for x in a:
      try:
         pids.append(int(x[29:34]))
      except:
           pass
for each in pids:
         print(each)

如果您只是想要一个程序或所有具有相同名称的程序,并且您想要终止该过程或其他内容:

import os, sys, win32api

tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()

print(tasklistr)

def kill(process):
     process_exists_forsure = False
     gotpid = False
     for examine in tasklistrl:
            if process == examine[0:len(process)]:
                process_exists_forsure = True
     if process_exists_forsure:
         print("That process exists.")
     else:
        print("That process does not exist.")
        raw_input()
        sys.exit()
     for getpid in tasklistrl:
         if process == getpid[0:len(process)]:
                pid = int(getpid[29:34])
                gotpid = True
                try:
                  handle = win32api.OpenProcess(1, False, pid)
                  win32api.TerminateProcess(handle, 0)
                  win32api.CloseHandle(handle)
                  print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
                except win32api.error as err:
                  print(err)
                  raw_input()
                  sys.exit()
    if not gotpid:
       print("Could not get process pid.")
       raw_input()
       sys.exit()

   raw_input()
   sys.exit()

prompt = raw_input("Which process would you like to kill? ")
kill(prompt)

这只是我的进程终止程序的一个粘贴我可以让它变得更好但是没关系。

答案 5 :(得分:1)

对于posix(Linux,BSD等...只需要挂载/ proc目录),在/ proc

中使用os文件更容易

适用于python 2和3(唯一的区别是异常树,因此" 除了异常",我不喜欢但保持兼容性。也可以&# 39; ve创建了自定义异常。)

#!/usr/bin/env python

import os
import sys


for dirname in os.listdir('/proc'):
    if dirname == 'curproc':
        continue

    try:
        with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
            content = fd.read().decode().split('\x00')
    except Exception:
        continue

    for i in sys.argv[1:]:
        if i in content[0]:
            # dirname is also the number of PID
            print('{0:<12} : {1}'.format(dirname, ' '.join(content)))

示例输出(它的工作方式类似于pgrep):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

答案 6 :(得分:1)

使用psutil

(可以安装[sudo] pip install psutil

import psutil

# Get current process pid
current_process_pid = psutil.Process().pid
print(current_process_pid)  # e.g 12971

# Get pids by program name
program_name = 'chrome'
process_pids = [process.pid for process in psutil.process_iter() if process.name == program_name]
print(process_pids)  # e.g [1059, 2343, ..., ..., 9645]

答案 7 :(得分:0)

这是费尔南多答案的简化版本。这适用于Linux和Python 2或3。不需要外部库,也不需要运行外部进程。

import glob

def get_command_pid(command):
    for path in glob.glob('/proc/*/comm'):
        if open(path).read().rstrip() == command:
            return path.split('/')[2]

仅返回找到的第一个匹配过程,该过程对于某些目的非常有用。要获取多个匹配进程的PID,只需将return替换为yield,然后使用pids = list(get_command_pid(command))获取列表。

或者,作为单个表达式:

对于一个过程:

next(path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command)

对于多个进程:

[path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command]

答案 8 :(得分:-1)

可以使用以下代码解决任务,[0:28]是保持名称的间隔,而[29:34]包含实际的pid。

import os

program_pid = 0
program_name = "notepad.exe"

task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
    try:
        if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
            program_pid = int(line[29:34])
            break
    except:
        pass

print(program_pid)