답변:
유닉스 계열 플랫폼에 있다고 가정하면 ( ps -A존재합니다),
>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
변수 (문자열)로 ps -A출력을 제공합니다 out. 줄로 나누고 반복 할 수 있습니다 ... :
>>> for line in out.splitlines():
... if 'iChat' in line:
... pid = int(line.split(None, 1)[0])
... os.kill(pid, signal.SIGKILL)
...
(가져 오기를 피하고 대신을 signal사용할 수 있지만, 저는 그 스타일이 특히 마음에 들지 않으므로이 방식으로 명명 된 상수를 사용하고 싶습니다).9signal.SIGKILL
물론이 라인에서 훨씬 더 정교한 처리를 할 수 있지만 이것은 쉘에서 수행하는 작업을 모방합니다.
피하는 것이 ps, 다른 유닉스 계열 시스템에서 수행하기 어렵다 ps면 (어떤 의미에서 프로세스 목록을 얻는 공통 API입니다). 그러나 특정 Unix 계열 시스템을 염두에두고 있다면 (크로스 플랫폼 이식성이 필요하지 않음) 가능할 수 있습니다. 특히 Linux에서는 /proc의사 파일 시스템이 매우 유용합니다. 그러나이 후반부에 도움을 드릴 수 있으려면 정확한 요구 사항을 명확히해야합니다.
psutil 은 이름으로 프로세스를 찾고 종료 할 수 있습니다.
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
psutil대상 컴퓨터에 없을 수 있는 패키지 가 필요하다는 것 입니다.
크로스 플랫폼이되기 위해 Windows 사례를 고려해야하는 경우 다음을 시도하십시오.
os.system('taskkill /f /im exampleProcess.exe')
killall이있는 경우 :
os.system("killall -9 iChat");
또는:
os.system("ps -C iChat -o pid=|xargs kill -9")
pkill나는 또한 그것을 대신 사용하는 세상에서 유일한 사람이라고 생각하지만killall
killall java있습니까?
pkill유일한 killall것은 "모든 것을 죽이는"하나 이기 때문에 사용 합니다 .
이것을 시도 할 수 있습니다. 하지만 당신은 설치해야합니다 전에 psutil 사용sudo pip install psutil
import psutil
for proc in psutil.process_iter(attrs=['pid', 'name']):
if 'ichat' in proc.info['name']:
proc.kill()
특정 제목을 포함하는 프로세스 또는 cmd.exe를 종료하려는 경우.
import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]
# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
for title in titles:
if title in line['Window Title']:
print line['Window Title']
PIDList.append(line['PID'])
# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
os.system('taskkill /pid ' + id )
도움이되기를 바랍니다. 그들은 광산에 대한 수많은 더 나은 솔루션이 될 수 있습니다.
Alex Martelli 답변은 out바이트 객체 이기 때문에 Python 3에서 작동하지 않으므로 TypeError: a bytes-like object is required, not 'str'테스트 할 때if 'iChat' in line: .
하위 프로세스 문서 에서 인용 :
communication ()은 튜플 (stdout_data, stderr_data)을 반환합니다. 스트림이 텍스트 모드에서 열린 경우 데이터는 문자열이됩니다. 그렇지 않으면 바이트.
Python 3의 경우 생성자에 text=True(> = Python 3.7) 또는 universal_newlines=True인수를 추가하여이 문제를 해결합니다 Popen. out그런 다음 문자열 객체로 반환됩니다.
import subprocess, signal
import os
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE, text=True)
out, err = p.communicate()
for line in out.splitlines():
if 'iChat' in line:
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
또는 바이트의 decode () 메서드를 사용하여 문자열을 만들 수 있습니다.
import subprocess, signal
import os
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'iChat' in line.decode('utf-8'):
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)