簡體   English   中英

Python腳本使用cpu過多

[英]Python script too much cpu usage

我不是編程專家,因此我在Google上進行了大量搜索,以使該腳本可以正常工作。 它在串行接口上​​偵聽ans正在搜索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負載百分比很小的情況下也能很好地工作。

感謝您的提示,它幫助我解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM