Python 脚本太多 cpu 使用

Python script too much cpu usage

我不是编程专家,所以我在谷歌上搜索了很多东西才让这个脚本起作用。它在串行接口上​​侦听并搜索 3 个值(温度、湿度和电池电量)。如果找到 zhem 之一,它会将其保存到文本文件并检查该值是高于还是低于某个级别。如果是这种情况,它会发送一封电子邮件进行警告。

我的问题是它经常使用大约 99% 的 cpu 电量... 你能帮我把 CPU 的使用量限制在最低限度吗?

谢谢

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

import serial
import time
import sys
import smtplib
from time import sleep

def mail(kind, how, value, unit):
    fromaddr = 'sender@domain.com'
    toaddrs  = 'recipient@domain.com'
    msg =  "\r\n".join([
    "From: sender",
    "To: recipient",
    "Subject: Warning",
    "",
    "The " + str(kind) + " is too " + str(how) + ". It is " + str(value) + str(unit)
    ])
    username = 'user'
    password = 'password'
    server = smtplib.SMTP('server:port')
    server.ehlo()
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()

def main():

        port = '/dev/ttyAMA0'
        baud = 9600

        ser = serial.Serial(port=port, baudrate=baud)

        sleep(0.2)    

        while True:
            while ser.inWaiting():
                # read a single character
                char = ser.read()
                # check we have the start of a LLAP message
                if char == 'a':
                # start building the full llap message by adding the 'a' we have
                llapMsg = 'a'
                # read in the next 11 characters form the serial buffer
                # into the llap message
                llapMsg += ser.read(11)


        if "TMPB" in llapMsg:
            TMPB = llapMsg[7:]
            with open("TMPB.txt", "w") as text_file:
                text_file.write(TMPB)
                if float(TMPB) >= 19:
                    mail("temperature", "high", TMPB, "°C")
                elif float(TMPB) <= 15:
                    mail("temperature", "low", TMPB, "°C")
                else:
                    pass

        elif "HUMB" in llapMsg:
            HUMB = llapMsg[7:]
            with open("HUMB.txt", "w") as text_file:
                text_file.write(HUMB)
                if float(HUMB) >= 80:
                    mail("humidity", "high", HUMB, "%")
                elif float(HUMB) <= 70:
                    mail("humidity", "low", HUMB, "%")
                else:
                    pass

        elif "BATT" in llapMsg:
            BATT = llapMsg[7:11]
            with open("BATT.txt", "w") as text_file:
                text_file.write(BATT)
                if float(BATT) < 1:
                    mail("battery level", "low", BATT, "V")
                else:
                    pass

        sleep(0.2)

if __name__ == "__main__":
        main()

我自己解决了这个问题。

while ser.inWaiting(): 循环导致 cpu 负载过重。 我删除了它并更正了缩进,它在几个 % cpu 负载下工作得很好。

感谢您的提示,帮助我解决了问题。