프로세스가 아직 실행 중이면 Python을 사용하여 Linux에서 어떻게 확인합니까?[복제하다]

StackOverflow https://stackoverflow.com/questions/38056

  •  09-06-2019
  •  | 
  •  

문제

유일한 멋진 내가 찾은 방법은 다음과 같습니다.

import sys
import os

try:
        os.kill(int(sys.argv[1]), 0)
        print "Running"
except:
        print "Not running"

(원천)
그런데 이게 믿을만한 걸까요?모든 프로세스와 모든 배포판에서 작동합니까?

도움이 되었습니까?

해결책

Mark의 대답은 결국 /proc 파일 시스템이 존재하는 이유입니다.좀 더 복사/붙여넣기 가능한 내용을 보려면 다음을 수행하세요.

 >>> import os.path
 >>> os.path.exists("/proc/0")
 False
 >>> os.path.exists("/proc/12")
 True

다른 팁

Linux에서는 /proc/$PID 디렉토리를 보면 해당 프로세스에 대한 정보를 얻을 수 있습니다.실제로 디렉터리가 존재하면 프로세스가 실행 중입니다.

이는 모든 POSIX 시스템에서 작동해야 합니다(비록 /proc 다른 사람들이 제안한 것처럼 파일 시스템이 거기에 있을 것이라는 것을 안다면 더 쉽습니다).

하지만: os.kill 프로세스에 신호를 보낼 권한이 없으면 실패할 수도 있습니다.다음과 같은 작업을 수행해야 합니다.

import sys
import os
import errno

try:
    os.kill(int(sys.argv[1]), 0)
except OSError, err:
    if err.errno == errno.ESRCH:
        print "Not running"
    elif err.errno == errno.EPERM:
        print "No permission to signal this process!"
    else:
        print "Unknown error"
else:
    print "Running"

나를 위해 해결한 솔루션은 다음과 같습니다.

import os
import subprocess
import re

def findThisProcess( process_name ):
  ps     = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE)
  output = ps.stdout.read()
  ps.stdout.close()
  ps.wait()

  return output

# This is the function you can use  
def isThisRunning( process_name ):
  output = findThisProcess( process_name )

  if re.search('path/of/process'+process_name, output) is None:
    return False
  else:
    return True

# Example of how to use
if isThisRunning('some_process') == False:
  print("Not running")
else:
  print("Running!")

저는 Python + Linux 초보자이므로 이것이 최적이 아닐 수도 있습니다.그것은 내 문제를 해결했고 다른 사람들에게도 도움이 되길 바랍니다.

// 그런데 이게 믿을만한가요?모든 프로세스와 모든 배포판에서 작동합니까?

예, 모든 Linux 배포판에서 작동합니다.하지만 Unix 기반 시스템(FreeBSD, OSX)에서는 /proc를 쉽게 사용할 수 없다는 점에 유의하세요.

제가 보기에는 PID 기반 솔루션이 너무 취약한 것 같습니다.상태를 확인하려는 프로세스가 종료된 경우 해당 PID는 새 프로세스에서 재사용될 수 있습니다.그래서 IMO ShaChris23는 Python + Linux 초보자가 문제에 대한 최상의 솔루션을 제공했습니다.심지어 문제의 프로세스가 명령 문자열로 고유하게 식별될 수 있거나 한 번에 하나만 실행될 것이라고 확신하는 경우에만 작동합니다.

나는 이것을 사용하여 프로세스와 지정된 이름의 프로세스 수를 가져옵니다.

import os

processname = 'somprocessname'
tmp = os.popen("ps -Af").read()
proccount = tmp.count(processname)

if proccount > 0:
    print(proccount, ' processes running of ', processname, 'type')

위의 버전에 문제가 있습니다 (예 : 함수는 문자열의 일부도 발견되었습니다 ...) 그래서 나는 Maksym Kozlenko의 수정 된 버전을 썼다.

#proc    -> name/id of the process
#id = 1  -> search for pid
#id = 0  -> search for name (default)

def process_exists(proc, id = 0):
   ps = subprocess.Popen("ps -A", shell=True, stdout=subprocess.PIPE)
   ps_pid = ps.pid
   output = ps.stdout.read()
   ps.stdout.close()
   ps.wait()

   for line in output.split("\n"):
      if line != "" and line != None:
        fields = line.split()
        pid = fields[0]
        pname = fields[3]

        if(id == 0):
            if(pname == proc):
                return True
        else:
            if(pid == proc):
                return True
return False

내 생각에는 이것이 더 안정적이고 읽기 쉬우며 프로세스 ID나 이름을 확인할 수 있는 옵션이 있습니다.

ShaChris23 스크립트의 약간 수정된 버전입니다.proc_name 값이 프로세스 인수 문자열 내에 있는지 확인합니다(예: python 으로 실행된 Python 스크립트).

def process_exists(proc_name):
    ps = subprocess.Popen("ps ax -o pid= -o args= ", shell=True, stdout=subprocess.PIPE)
    ps_pid = ps.pid
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()

    for line in output.split("\n"):
        res = re.findall("(\d+) (.*)", line)
        if res:
            pid = int(res[0][0])
            if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:
                return True
    return False
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top