如何终止线程中调用的系统进程

2024-04-25 17:00:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在线程中调用top进程。你知道吗

如何在其他进程完成后或在一段时间后终止线程和顶层进程?你知道吗

class ExternalProcess(threading.Thread):   
    def run(self):
        os.system("top")


def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here

Tags: andtherunselfhere进程topdef
2条回答

使用进程组来处理子进程,这样就可以向子进程发送一个信号kill。你知道吗

导入操作系统 输入信号 导入子流程

class ExternalProcess(threading.Thread):   
    def run(self):
        # The os.setsid() is passed in the argument preexec_fn so
        # it's run after the fork() and before  exec() to run the shell. 
        proc = subprocess.Popen("top", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) 

        os.killpg(proc.pid, signal.SIGTERM)  # Send the signal to all the process groups

def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here

如果您使用的是类Unix平台,则可以使用ps -A列出您的进程,因此请尝试以下操作:

import subprocess, signal
import os
def killproc(procname):
 p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
 out, err = p.communicate()
 for line in out.splitlines():
   if procname in line:
    pid = int(line.split(None, 1)[0])
    os.kill(pid, signal.SIGKILL)

killproc('firefox') #this is an example 

如果您不在unix中,请使用正确的命令来代替ps -A

相关问题 更多 >