杀死Python中的所有线程

2023-12-10

我有一个 python 脚本,它将不断 ping 一些 IP 并将结果打印到屏幕上。 但我想通过按键终止脚本(最好使用 q 键或通过 ctrl c),然后终止所有线程。

实现这一目标的最佳方法是什么?我的代码如下...

import os
import re
import time
import sys
import subprocess
import Queue
import threading

def screen_output(x, y, text):
     sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
     sys.stdout.flush()

class pingo:

    def __init__(self,hosts):
        self.q = Queue.Queue()
        self.all_results = {}
        self.hosts = hosts

    def send_ping(self,q,ip):
        self.q.put(self.record_results(ip))

    def record_results(self,ip):
        ping_count = 0

        host_results = {
            "device" : None,
            "sent_count" : 0,
            "success_count": 0,
            "fail_count": 0,
            "failed_perc": 0,
            "curr_status": None
            }


        while True:
            rc = subprocess.call(['ping', '-c', '1', '-W', '1', ip], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
            ping_count += 1

            # update stats

            sent_count = host_results['sent_count']
            success_count = host_results['success_count']
            fail_count = host_results['fail_count']
            failed_perc = host_results['failed_perc']
            curr_status = host_results['curr_status']

            sent_count += 1

            if rc == 0:
                success_count += 1
                curr_status = "Successful Response"
            else:
                fail_count += 1
                curr_status = "Request Timed Out"

            failed_perc =  ( fail_count / sent_count ) * 100

            host_results.update({'failed_perc': failed_perc, 'fail_count': fail_count, 'success_count': success_count, 'curr_status': curr_status, 'sent_count': sent_count})
            time.sleep(0.5)
            self.all_results.update({ip:host_results})
            screen_output(0,0,self.all_results)
        return True

    def go(self):
        for i in self.hosts:
            t = threading.Thread(target=self.send_ping, args = (self.q,i))
            #t.daemon = True
            t.start()

p =  pingo(["8.8.8.8"])
p.go()

编辑:我已经尝试按照建议添加全局 ALIVE 标志,但这仍然无法通过 CTRL-C 杀死线程。

import sys
import subprocess
import Queue
import threading
import signal

def screen_output(x, y, text):
     sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
     sys.stdout.flush()

class pingo:

    def __init__(self,hosts):
        self.q = Queue.Queue()
        self.all_results = {}
        self.hosts = hosts
        self.ALIVE = True

    def signal_handler(self,signal, frame):
        self.ALIVE = False

    def send_ping(self,q,ip):
        self.q.put(self.record_results(ip))

    def record_results(self,ip):
        ping_count = 0

        host_results = {
            "device" : None,
            "sent_count" : 0,
            "success_count": 0,
            "fail_count": 0,
            "failed_perc": 0,
            "curr_status": None
            }


        while self.ALIVE:
            try:
                rc = subprocess.call(['ping', '-c', '1', '-W', '1', ip], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
                ping_count += 1

                # update stats

                sent_count = host_results['sent_count']
                success_count = host_results['success_count']
                fail_count = host_results['fail_count']
                failed_perc = host_results['failed_perc']
                curr_status = host_results['curr_status']

                sent_count += 1

                if rc == 0:
                    success_count += 1
                    curr_status = "Successful Response"
                else:
                    fail_count += 1
                    curr_status = "Request Timed Out"

                failed_perc =  ( fail_count / sent_count ) * 100

                host_results.update({'failed_perc': failed_perc, 'fail_count': fail_count, 'success_count': success_count, 'curr_status': curr_status, 'sent_count': sent_count})
                time.sleep(0.5)
                self.all_results.update({ip:host_results})
                screen_output(0,0,self.all_results)
            except KeyboardInterrupt:
                signal.signal(signal.SIGINT, self.signal_handler)
        return True


    def go(self):
        for i in self.hosts:
            t = threading.Thread(target=self.send_ping, args = (self.q,i))
            #t.daemon = True
            t.start()

p =  pingo(["8.8.8.8"])
p.go()

设置全局标志ALIVE(或者不一定是全局的,您可以使用字典或类属性),绑定到 SIGINT 并对其进行更改:

import signal

ALIVE = True

def signal_handler(signal, frame):
    global ALIVE
    ALIVE = False

signal.signal(signal.SIGINT, signal_handler)

然后只需将循环更改为:

def record_results(self,ip):
    # some code
    while ALIVE:
        # some code

这样它就会优雅地退出(收到信号后一段时间)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

杀死Python中的所有线程 的相关文章

  • 熊猫按 n 最大总和分组

    我正在尝试使用groupby nlargest and sum在 Pandas 中一起运行 但在运行时遇到困难 State County Population Alabama a 100 Alabama b 50 Alabama c 40
  • 如何把父母和孩子联系起来?

    有两个简单的类 一个只有parent属性 并且两者兼而有之parent and children属性 这意味着同时具备两者的人parent and children继承自唯一的parent 这是只有parent属性 我们就这样称呼它吧Chi
  • docker 容器中的“(pygame parachute)分段错误”

    尝试在 docker 容器中使用 pygame 时出现以下错误 我想从容器中获取显示 Fatal Python error pygame parachute Segmentation Fault 重现 Docker已安装 docker ru
  • Python 不考虑 distutils.cfg

    我已经尝试了给出的所有内容 并且所有教程都指向相同的方向 即使用 mingw 作为 python 而不是 Visual C 中的编译器 我确实有 Visual C 和 mingw 当我想使用 pip 安装时 问题开始出现 它总是给Unabl
  • Python:json_normalize pandas 系列给出 TypeError

    我在 pandas 系列中有数万行像这样的 json 片段df json IDs lotId 1 Id 123456 date 2009 04 17 bidsCount 2 IDs lotId 2 Id 123456 date 2009 0
  • 使用 Python 和 lmfit 拟合复杂模型?

    我想适合椭偏仪 http en wikipedia org wiki Ellipsometry使用 LMFit 将数据转换为复杂模型 两个测量参数 psi and delta 是复杂函数中的变量rho 我可以尝试将问题分离为实部和虚部共享参
  • 将整数系列转换为交替(双元)二进制系列

    我不知道如何最好地表达这个问题 因为在这里谷歌搜索和搜索总是让我找到更复杂的东西 我很确定这是基本的东西 但对于我的生活来说 我找不到一个好的方法来做到这一点下列 给定一个整数序列 比如说 for x in range 0 36 我想将这些
  • 如何用函数记录一个文件?

    我有一个带有函数 lib py 但没有类的python 文件 每个函数都有以下样式 def fnc1 a b c This fonction does something param a lalala type a str param b
  • Python speedtest.net,或等效的[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 是否有一个 Python 库可以实现 SpeedTest net 测试或等效的互联网连接速度测试 GitHub上有一个项目叫速度检查 https gi
  • NSUserNotificationCenter.defaultUserNotificationCenter() 使用 PyInstaller 返回 None

    我正在尝试将通知发送到通知中心 Mac OSX 我正在使用 PyObjC 绑定来使用我们的 python 应用程序中的 cocoa api 我正在使用以下代码片段 import Foundation import objc NSUserNo
  • 为什么需要设置WORKON_HOME环境变量?

    我已经有一段时间没有使用 python 虚拟环境了 但我也安装了虚拟环境包装器 我的问题是 在文档页面中它说要这样做 export WORKON HOME Envs mkdir p WORKON HOME source usr local
  • 如何知道python运行脚本的路径?

    sys arg 0 给我 python 脚本 例如 python hello py 返回 sys arg 0 的 hello py 但我需要知道 hello py 位于完整路径中的位置 我怎样才能用Python做到这一点 os path a
  • 列表推导式和 for 循环中的 Lambda 表达式[重复]

    这个问题在这里已经有答案了 我想要一个 lambda 列表 作为一些繁重计算的缓存 并注意到这一点 gt gt gt j for j in lambda i for i in range 10 9 9 9 9 9 9 9 9 9 9 Alt
  • 了解 Python 2.7 中的缩进错误

    在编写 python 代码时 我往往会遇到很多缩进错误 有时 当我删除并重写该行时 错误就会消失 有人可以为菜鸟提供 python 中 IndentationErrors 的高级解释吗 以下是我在玩 CheckIO 时收到的最近 inden
  • 如何从 python 脚本执行 7zip 命令

    我试图了解如何使用 os system 模块来执行 7zip 命令 现在我不想用 Popen 或 subprocess 让事情变得复杂 我已经安装了 7zip 并将 7zip exe 复制到我的用户文件夹中 我只想提取我的测试文件 inst
  • Pandas 字典键到列[重复]

    这个问题在这里已经有答案了 我有一个像这样的数据框 index column1 e1 u c680 5 u c681 1 u c682 2 u c57 e2 u c680 6 u c681 2 u c682 1 u c57 e3 u c68
  • 使用 python 脚本更改 shell 中的工作目录

    我想实现一个用户态命令 它将采用其参数之一 路径 并将目录更改为该目录 程序完成后 我希望 shell 位于该目录中 所以我想实施cd命令 但需要外部程序 可以在 python 脚本中完成还是我必须编写 bash 包装器 Example t
  • 如何有效地比较 pandas DataFrame 中的行?

    我有一个 pandas 数据框 其中包含雷击记录以及时间戳和全球位置 格式如下 Index Date Time Lat Lon Good fix 0 1 20160101 00 00 00 9962692 7 1961 60 7604 1
  • 从 Django 运行 shell 命令

    我正在 Django 中开发一个网页 使用 apache 服务器 需要调用 shell 命令来启用 禁用一些守护进程 我尝试这样做 os system service httpd restart 1 gt HOME out 2 gt HOM
  • 超过两个点的Python相对导入

    是否可以使用路径中包含两个以上点的模块引用 就像这个例子一样 Project structure sound init py codecs init py echo init py nix init py way1 py way2 py w

随机推荐