Python 根据CPU使用率循环执行事件

180it 2022-07-28 PM 909℃ 0条
def hello() :
    import urllib.request
    import ssl
    
    context = ssl._create_unverified_context()
    # url = 'https://baike.baidu.com/item/vivo'
    url ="http://xxxx.com/xxxx/"
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(url=request,context=context)
    print (response.read().decode('utf-8'))


import psutil
import time
# cpu_res = psutil.cpu_percent()
# print(cpu_res)
# 每一秒获取获取cpu的占有率 --->持久化保存
# 如何将时间和对应的cpu占有率去匹配
while True:
    # 获取当前时间和cpu的占有率
    t = time.localtime()
    cpu_time = '%d:%d:%d' % (t.tm_hour, t.tm_min, t.tm_sec)
    cpu_res = psutil.cpu_percent()
    print(cpu_res)
    # 保存在文件中
    with open('cpu.txt', 'a+') as f:
       # f.write('%s %s \n' % (cpu_time, cpu_res))
        print(str(cpu_res))
        if (cpu_res<5):#当CPU使用率小于5%则执行
                       hello()
                       time.sleep(5)
                       
        
    time.sleep(1)

调用方法:

python main.py
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

Python 根据CPU使用率循环执行事件