按名称杀死进程?

发布于 2024-09-03 21:54:35 字数 175 浏览 5 评论 0原文

我正在尝试终止一个进程(特别是 iChat)。在命令行上,我使用以下命令:

ps -A | grep iChat 

然后:

kill -9 PID

但是,我不太确定如何将这些命令转换为 Python。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

淡莣 2024-09-10 21:54:35

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 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()
岁月苍老的讽刺 2024-09-10 21:54:35

假设您使用的是类 Unix 平台(因此存在 ps -A),则

>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

outps -A 的输出> 变量(字符串)。您可以将其分解为几行并对其进行循环...:(

>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

您可以避免导入 signal,并使用 9 而不是 signal.SIGKILL >,但我只是不太喜欢这种风格,所以我宁愿以这种方式使用命名常量)。

当然,您可以对这些线路进行更复杂的处理,但这模仿了您在 shell 中所做的事情。

如果您想要避免使用 ps,那么在不同的类 Unix 系统中很难做到这一点(从某种意义上来说,ps 是它们获取进程列表的通用 API) 。但是,如果您只考虑一个特定的类 Unix 系统(不需要任何跨平台可移植性),那么这是可能的;特别是,在 Linux 上,/proc 伪文件系统非常有用。但您需要先明确您的具体要求,然后我们才能为后一部分提供帮助。

Assuming you're on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> import os
>>> 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.

隔岸观火 2024-09-10 21:54:35

如果您必须考虑 Windows 情况才能跨平台,请尝试以下操作:

os.system('taskkill /f /im exampleProcess.exe')

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')
旧城烟雨 2024-09-10 21:54:35

如果你有killall:

os.system("killall -9 iChat");

或者:

os.system("ps -C iChat -o pid=|xargs kill -9")

If you have killall:

os.system("killall -9 iChat");

Or:

os.system("ps -C iChat -o pid=|xargs kill -9")
楠木可依 2024-09-10 21:54:35

你可以试试这个。
但在您需要使用 sudo pip install psutil 安装 psutil 之前

import psutil
for proc in psutil.process_iter(attrs=['pid', 'name']):
    if 'ichat' in proc.info['name']:
        proc.kill()

You can try this.
but before you need 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()
临风闻羌笛 2024-09-10 21:54:35

这在 Windows 7 中对我有用

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")

this worked for me in windows 7

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")
不必在意 2024-09-10 21:54:35

下面的代码将杀死所有面向 iChat 的程序:

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)

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)
肥爪爪 2024-09-10 21:54:35

使用Process获取流程对象。

>>> import psutil
>>> p = psutil.Process(23442)
>>> p
psutil.Process(pid=23442, name='python3.6', started='09:24:16')
>>> p.kill()
>>> 

Get the process object using the Process.

>>> import psutil
>>> p = psutil.Process(23442)
>>> p
psutil.Process(pid=23442, name='python3.6', started='09:24:16')
>>> p.kill()
>>> 
醉城メ夜风 2024-09-10 21:54:35

您可以使用 psutil 模块使用其名称来终止进程。在大多数情况下,这应该是跨平台的。

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()}")

我基本上扩展了@Giampaolo Rodolà的答案

  • 添加了异常处理
  • 添加了检查以查看 cmdline

我还将此代码段发布为 gist

注意:一旦您对观察到的所需行为感到满意,就可以删除打印语句。

You can use the psutil module to kill a process using it's name. For the most part, this should be cross platform.

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()}")

I have basically extended @Giampaolo Rodolà's answer.

  • Added exception handling
  • Added check to see cmdline

I have also posted this snippet as a gist.

Note: You can remove the print statements once you are satisfied that the desired behavior is observed.

握住你手 2024-09-10 21:54:35

你可以使用 WMI 模块在 Windows 上执行此操作,尽管它比你的 Unix 用户习惯的要笨重得多; 导入 WMI 需要很长时间,而且整个过程会很痛苦。

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.

月依秋水 2024-09-10 21:54:35

如果您想终止带有特定标题的进程或 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 ) 

希望有帮助。他们可能有很多比我更好的解决方案。

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.

情深如许 2024-09-10 21:54:35

Alex Martelli 的答案在 Python 3 中不起作用,因为 out 将是一个字节对象,从而导致 TypeError: a bytes-like object is required, not 'str' 测试 if 'iChat' in line: 时。

引用 subprocess 文档

communicate() 返回一个元组 (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)

The Alex Martelli answer won't work in Python 3 because out will be a bytes object and thus result in a TypeError: a bytes-like object is required, not 'str' when testing if 'iChat' in line:.

Quoting from subprocess documentation:

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

For Python 3, this is solved by adding the text=True (>= Python 3.7) or universal_newlines=True argument to the Popen constructor. out will then be returned as a string object.

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)

Alternatively, you can create a string using the decode() method of bytes.

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)
笙痞 2024-09-10 21:54:35

与 Giampaolo Rodolà 的回答风格相同,但作为一个衬里,不区分大小写,并且不必匹配整个进程名称,在 Windows 中,您必须包含 .exe 后缀。

[x.kill() for x in psutil.process_iter() if 'ichat' in x.name().lower()]

In the same style as Giampaolo Rodolà' answer but as one liner, case insensitive and without having to match the whole process name, in windows you would have to include the .exe suffix.

[x.kill() for x in psutil.process_iter() if 'ichat' in x.name().lower()]
千里故人稀 2024-09-10 21:54:35

对我来说唯一有效的是:

例如

import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()

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()
俯瞰星空 2024-09-10 21:54:35
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)
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)
扭转时空 2024-09-10 21:54:35

您可以在 unix 系统中使用 pkill 按名称终止进程。

那么Python代码将是:

>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)

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)
温柔一刀 2024-09-10 21:54:35
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 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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文