【问题标题】:Why does my Python program stop working and starts using 100% CPU? [duplicate]为什么我的 Python 程序停止工作并开始使用 100% CPU? [复制]
【发布时间】:2020-03-31 22:49:41
【问题描述】:

我遇到了一个在 Raspberry Pi 上运行的 Python 程序的奇怪问题。编程应该接收一个 webhook,然后执行一些应该控制廉价 LED-Strip 的代码。 该程序可以正常启动并正常执行,但是如果我让它运行一段时间然后触发 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】:

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

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

    【讨论】:

    • 哦,是的,我只是尝试传递错误以尝试获取错误消息或其他内容。可能应该在发布之前再次删除它。
    • 与我们分享您到达那里的例外情况
    • 在我的 windows 机器上我得到:[WinError 10053] An established connection was aborted by the software in your host machine 在我的树莓派上:[Errno 32] Broken pipe
    • 好的,这是一个主要线索!连接可能反复断开,我们应该关注您的 webhook 以查看发生了什么。
    • 那么您的意思是调查我触发 webhook 的方式还是您认为瓶子库有问题?因为我尝试使用 PC 浏览器、Android 浏览器和 Android 应用 Tasker 触发。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 2012-07-21
    • 2021-10-31
    • 1970-01-01
    • 2013-01-07
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多