首页 > 解决方案 > N00b 问题:ValueError:尝试在非包中进行相对导入

问题描述

我希望你们能提供帮助。

我正在编写一个小代码,以便在按下按钮时让 yeelights 闪烁随机颜色。我正在为一个项目导入一些东西,但我的代码中出现了一个值错误。

从我的代码:

#!/usr/bin/python

import time
import random
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from yeelight import Bulb
from yeelight import *
from .utils import _clamp

ChangeTableLight = Bulb("192.xxx.xx.xx") #Change Table Lightbulb
brightness = 100
count = _clamp(count, 1, 9)
#HSVTransition(hue, saturation, duration, brightness)

transitions = [
    HSVTransition(random.randint(0, 360), 100, duration=duration, brightness=brightness) for _ in range(count)
]

flow = Flow(
    count=5,
    action=Flow.actions.recover,
    transitions=transitions
)

def button_callback(channel):
    ChangeTableLight.start_flow(flow)

然后我在我的代码中(出现错误的地方 - 第 8 行)

count = _clamp(count, 1, 9)

当我运行脚本并收到此错误时:

from .utils import _clamp ValueError: Attempted relative import in non-package

我试过搜索是否必须下载特定的实用程序模块才能导入,我试过导入不同的模块等,但我找不到任何东西。

在另一个论坛上,有人建议我删除导入中 utils 之前的句点,但这给了我这个错误:

从实用程序导入_clamp ImportError:无法导入名称_clamp

Yeelight python代码来自这里

有什么建议可以帮助指导我找到正确的答案吗?

标签: pythonpython-3.x

解决方案


这是更正确的(1 个错误而不是 2 个),因为您使用已安装的模块进行绝对导入。

from utility import _clamp

这是相对导入。

from .utils import _clamp

_clamp 是一个受保护的变量,因为它有一个前导的下划线访问修饰符。不应该是进口的。我们不知道“_clamp”是来自“utility”还是“utils”。


推荐阅读