首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果设置为repeat,则Python - Function不能执行

如果设置为repeat,则Python - Function不能执行
EN

Stack Overflow用户
提问于 2020-06-20 01:15:19
回答 2查看 53关注 0票数 0

我刚开始学习Python,但我搞不清楚这一点,基本上我想监控我的网络流量,运行下面的代码将只显示当前捕获的结果,但不会更新

代码语言:javascript
复制
from tkinter import*
import psutil,os
from psutil._common import bytes2human
from threading import Timer
import time

netmon = Tk()
netmon.title("NetMonitor")
netmon.geometry("200x80")

def getresults():
    total_before = psutil.net_io_counters()
    time.sleep(1)
    total_after = psutil.net_io_counters()
    download_rate = "Download : " + bytes2human(total_after.bytes_recv - total_before.bytes_recv) + " KB/S"
    upload_rate = "Upload : " + bytes2human(total_after.bytes_sent - total_before.bytes_sent) + " KB/S"
    text = Label(netmon, text = "\n" + download_rate + "\n\n" + upload_rate, anchor = NW)
    text.pack()
    #Timer(5, getresults).start

getresults()

netmon.mainloop()

我尝试过while循环:

代码语言:javascript
复制
.
.
.
while True:
   getresults()

netmon.mainloop()

我已经尝试了线程计时器,但是在这两种情况下,“程序”甚至不会启动,直到我恢复到上面提到的第一个代码,谁能告诉我如何让它每秒更新一次?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-20 01:37:03

您走上了正确的道路,需要使用while循环。我将它放入它自己的线程中(并将文本作为构造函数参数传递给thread类)。

代码语言:javascript
复制
from tkinter import*
import psutil,os
from psutil._common import bytes2human
from threading import Timer
import time
import threading

netmon = Tk()
netmon.title("NetMonitor")
netmon.geometry("200x80")

text = Label(netmon, text = "\n" + 'Download : TBD' + "\n\n" + 'Upload : TBD', anchor = NW)
text.pack()

class GetUpdates(threading.Thread):
    def __init__(self, text):
        threading.Thread.__init__(self)
        self._stop_event = threading.Event()
        self._text = text

    def stop(self):
        self._stop_event.set()

    def run(self):
        while not self._stop_event.is_set():
            total_before = psutil.net_io_counters()
            time.sleep(1)
            total_after = psutil.net_io_counters()
            download_rate = "Download : " + bytes2human(total_after.bytes_recv - total_before.bytes_recv) + " KB/S"
            upload_rate = "Upload : " + bytes2human(total_after.bytes_sent - total_before.bytes_sent) + " KB/S"
            self._text['text'] = "\n" + download_rate + "\n\n" + upload_rate


getupdates = GetUpdates(text)
getupdates.start()


netmon.mainloop()
票数 0
EN

Stack Overflow用户

发布于 2020-06-20 02:07:21

一种更简单的方法是通过APScheduler的BackgroundScheduler实现一个解决方案:

代码语言:javascript
复制
from apscheduler.schedulers.background import BackgroundScheduler
backgroundScheduler = BackgroundScheduler(daemon=True)

backgroundScheduler.add_job(lambda : backgroundScheduler.print_jobs(),'interval',seconds=4)
backgroundScheduler.start()

..。然后在完成时

代码语言:javascript
复制
backgroundScheduler.shutdown()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62475413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档