为什么我的Python程序停止工作并开始使用100%CPU?

问题描述 投票:0回答:1

我在Raspberry Pi上运行的Python程序遇到了一个奇怪的问题。要编程,应该接收一个Webhook,然后执行一些代码,该代码应该可以控制便宜的LED灯带。该程序可以正常启动并且可以正常运行,但是如果我让它运行一会儿然后触发Webhook,程序将中断并开始在单个CPU内核上使用100%。这在我的PyCharm电脑和Raspberry Pi上都会发生。真正让我失望的是,'prints()'确实得到了执行,而其余部分却没有得到执行。

import time
import datetime
import magichue
from bottle import route, run

light = magichue.Light('192.168.1.36')


def flash(r, g, b):
    light.mode = magichue.NORMAL
    light.rgb = (0, 0, 0)
    time.sleep(0.5)
    light.rgb = (r, g, b)
    time.sleep(0.4)
    light.rgb = (0, 0, 0)
    time.sleep(0.5)
    light.rgb = (r, g, b)
    time.sleep(0.4)


def fadein(r, g, b, tr=1):
    light.mode = magichue.NORMAL
    while tr <= 25:
        r = r + 10
        g = g + 10
        b = b + 10
        light.rgb = (r, g, b)
        time.sleep(0.5)
        tr = tr + 1
    else:
        light.rgb = (255, 255, 255)


@route('/flashgreen')
def index():
    try:
        print("Im here")
        x = datetime.datetime.now()
        if 10 <= x.hour <= 22:
            time.sleep(0.1)
            light.update_status()
            if light.on:
                pr = light.rgb
                flash(0, 255, 0)
                light.rgb = pr
            else:
                flash(0, 255, 0)
                light.on = False
    except:
        pass


@route('/fadein')
def index():
    try:
        print("Im here")
        fadein(0, 0, 0)
    except:
        pass


@route('/setcolor/<r>/<g>/<b>')
def index(r, g, b):
    try:
        print("Im here")
        light.mode = magichue.NORMAL
        light.rgb = (int(r), int(g), int(b))
    except:
        pass


run(host='0.0.0.0', port=4783)

python-3.x raspberry-pi bottle
1个回答
0
投票

打印消息是在这种情况下打印的,并且其他所有内容均未执行,因为您可能在fadein函数中或更改了light对象的属性时遇到了异常。通常,传递异常是一种不好的编程习惯,应该避免。

我的猜测是,一段时间后重新激活页面时,由于浏览器的行为,从Webhook中反复调用了这些函数。调试的最佳方法是打印完整的异常数据。这应该可以为您揭开神秘面纱。

© www.soinside.com 2019 - 2024. All rights reserved.