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.
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
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)
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()
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 )
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)
import traceback
import psutil
def kill(process_name):
"""Kill Running Process by using it's name
- Generate list of processes currently running
- Iterate through each process
- Check if process name or cmdline matches the input process_name
- Kill if match is found
Parameters
----------
process_name: str
Name of the process to kill (ex: HD-Player.exe)
Returns
-------
None
"""
try:
print(f'Killing processes {process_name}')
processes = psutil.process_iter()
for process in processes:
try:
print(f'Process: {process}')
print(f'id: {process.pid}')
print(f'name: {process.name()}')
print(f'cmdline: {process.cmdline()}')
if process_name == process.name() or process_name in process.cmdline():
print(f'found {process.name()} | {process.cmdline()}')
process.terminate()
except Exception:
print(f"{traceback.format_exc()}")
except Exception:
print(f"{traceback.format_exc()}")