python - Python - 如果设置为重复,函数不会执行
问题描述
我刚开始学习Python,但我无法弄清楚这一点,基本上我想监控我的网络流量,下面运行这段代码只会显示目前捕获的结果,但它不会更新
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 循环:
.
.
.
while True:
getresults()
netmon.mainloop()
我已经尝试过 Threading 中的计时器,但是在这两种情况下,“程序”甚至不会启动,直到我恢复到上面提到的第一个代码,谁能告诉我如何让它每秒更新一次?
解决方案
更简单的方法是通过 APScheduler 的 BackgroundScheduler 实现解决方案:
from apscheduler.schedulers.background import BackgroundScheduler
backgroundScheduler = BackgroundScheduler(daemon=True)
backgroundScheduler.add_job(lambda : backgroundScheduler.print_jobs(),'interval',seconds=4)
backgroundScheduler.start()
...然后当完成
backgroundScheduler.shutdown()
推荐阅读
- ios - 如何将数据库放入iOS App的沙盒区域并访问路径?
- r - R:在字符串中显示匹配的特殊字符
- desire2learn - 学生科目和课程完成
- css - 为什么 Firefox 和 Chrome 在 flex 子项中呈现这个可滚动区域的方式不同,我如何让 Firefox 像 Chrome 一样工作?
- java - POST 请求不适用于 Python,但可以使用 Java
- angular - 从 asp.net 核心 web api 返回存储在数据库中的多个图像,以显示在轮播/滚动视图中
- asp.net-core - 为什么 EF Core 生成带有基于字符串的索引的 asp.net 标识表(在我将其更改为 int 之后)?
- javascript - 如果条件卡住,InboxSDK 会发送事件
- javascript - 授予 s3 中对象的下载权限
- android - 如何像微软待办那样在空的 RecyclerView 中显示分隔符?