问题
I'm trying to kill a process (specifically iChat). On the command line, I use these commands:
ps -A | grep iChat
Then:
kill -9 PID
However, I'm not exactly sure how to translate these commands over to Python.
回答1:
Assuming you're on a Unix-like platform (so that ps -A
exists),
>>> import subprocess, signal
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
gives you ps -A
's output in the out
variable (a string). You can break it down into lines and loop on them...:
>>> for line in out.splitlines():
... if 'iChat' in line:
... pid = int(line.split(None, 1)[0])
... os.kill(pid, signal.SIGKILL)
...
(you could avoid importing signal
, and use 9
instead of signal.SIGKILL
, but I just don't particularly like that style, so I'd rather used the named constant this way).
Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.
If what you're after is avoiding ps
, that's hard to do across different Unix-like systems (ps
is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc
pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.
回答2:
psutil can find process by name and kill it:
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
回答3:
If you have to consider the Windows case in order to be cross-platform, then try the following:
os.system('taskkill /f /im exampleProcess.exe')
回答4:
If you have killall:
os.system("killall -9 iChat");
Or:
os.system("ps -C iChat -o pid=|xargs kill -9")
回答5:
this worked for me in windows 7
import subprocess
subprocess.call("taskkill /IM geckodriver.exe")
回答6:
The below code will kill all iChat oriented programs:
p = subprocess.Popen(['pgrep', '-l' , 'iChat'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
line = bytes.decode(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
回答7:
If you want to kill the process(es) or cmd.exe carrying a particular title(s).
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 )
Hope it helps. Their might be numerous better solutions to mine.
回答8:
you can try this..
before you have to install psutil using sudo pip install psutil
import psutil
for proc in psutil.process_iter(attrs=['pid', 'name']):
if 'ichat' in proc.info['name']:
proc.kill()
回答9:
You can use pkill <process_name>
in a unix system to kill process by name.
Then the python code will be:
>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)
回答10:
you can use WMI module to do this on windows, though it's a lot clunkier than you unix folks are used to; import WMI
takes a long time and there's intermediate pain to get at the process.
回答11:
For me the only thing that worked is been:
For example
import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()
回答12:
9 represents SIGKILL signal. So you can use KILL
in place of 9
os.system("kill -s KILL 1234")
0r
os.sytem("kill -KILL 1234")
回答13:
import os, signal
def check_kill_process(pstring):
for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
fields = line.split()
pid = fields[0]
os.kill(int(pid), signal.SIGKILL)
回答14:
import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
p = psutil.Process(i)
p_name=p.name
print str(i)+" "+str(p.name)
if p_name=="PerfExp.exe":
print "*"*20+" mam ho "+"*"*20
p.kill()
来源:https://stackoverflow.com/questions/2940858/kill-process-by-name