developer tip

Python을 사용하여 Unix 또는 Linux에서 프로그램의 프로세스 ID를 얻는 방법은 무엇입니까?

optionbox 2020. 11. 9. 08:03
반응형

Python을 사용하여 Unix 또는 Linux에서 프로그램의 프로세스 ID를 얻는 방법은 무엇입니까?


저는 Python으로 모니터링 스크립트를 작성 중이며 해당 프로그램의 이름이 주어지면 임의 실행 프로그램의 프로세스 ID를 얻는 가장 깨끗한 방법을 찾으려고합니다.

뭔가

ps -ef | grep MyProgram

나는 그 출력을 파싱 할 수 있지만 파이썬에서 더 나은 방법이있을 것이라고 생각했습니다.


시도해보십시오 pgrep. 출력 형식은 훨씬 간단하므로 구문 분석이 더 쉽습니다.


표준 라이브러리에서 :

os.getpid()

표준 라이브러리로 제한하지 않는다면 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}]

또한 : Python : 프로세스 이름으로 PID를 얻는 방법?

이전에 게시 된 답변에 대한 적응.

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']

Windows의 경우

모듈을 다운로드하지 않고 컴퓨터의 모든 프로그램 pid를 얻는 방법 :

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)

그것은 내 프로세스 킬 프로그램의 붙여 넣기 일뿐입니다. 훨씬 더 좋게 만들 수는 있지만 괜찮습니다.


posix (Linux, BSD 등 ... / proc 디렉토리 만 마운트하면 됨)의 경우 / proc에서 os 파일로 작업하는 것이 더 쉽습니다.

파이썬 2 및 3에서 작동합니다 (유일한 차이점은 예외 트리이므로 " except Exception "이 싫지만 호환성을 유지하기 위해 유지했습니다. 또한 사용자 지정 예외를 만들 수도 있습니다.)

#!/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

와 함께 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]

This is a simplified variation of Fernando's answer. This is for Linux and either Python 2 or 3. No external library is needed, and no external process is run.

import glob

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

Only the first matching process found will be returned, which works well for some purposes. To get the PIDs of multiple matching processes, you could just replace the return with yield, and then get a list with pids = list(get_command_pid(command)).

Alternatively, as a single expression:

For one process:

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

For multiple processes:

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

The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual 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)

참고URL : https://stackoverflow.com/questions/3761639/how-do-you-get-the-process-id-of-a-program-in-unix-or-linux-using-python

반응형