【发布时间】:2023-03-26 22:56:01
【问题描述】:
我正在尝试使用 Django 应用程序中的树莓派控制 LED。 我写了一个 python 脚本来设置 LED 的颜色,一切正常。 但是,当我从 views.py 调用脚本时,我得到一个 AttributeError :模块没有属性。
Views.py
import sys, os
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(PROJECT_DIR, 'static/lampe/scripts'))
import launcher, lampe
"""Vue utilisee pour appliquer une couleur"""
class Appliquer_couleur(View):
def get(self, context, **reponse_kwargs):
print(self.kwargs['pk'])
couleur_serialized = CouleurSerializer(Couleur.objects.get(pk=self.kwargs['pk']))
launcher.launch(couleur_serialized.data['code'])
return HttpResponse('')
在“lampe/static/lampe/scripts”目录中,我有三个文件: 一个空的 init.py、lampe.py 和 launcher.py
Lampe.py
import sys
import RPi.GPIO as GPIO
def setCouleur(arg1):
..
Launcher.py
import sys, os
from multiprocessing import Process
import lampe as LED
def launch(arg1):
try:
process = Process(target=LED.setCouleur, args=(arg1,))
process.start()
process.join()
except KeyboardInterrupt:
pass
if __name__== "__main__":
sys.exit(launch(sys.argv[1]))
追溯
Internal Server Error: /lampe/appliquer_couleur/1/
Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/pyrotecnix/Projet/aurore/lampe/views.py", line 85, in get
launcher.launch(couleur_serialized.data['code'])
File "/home/pyrotecnix/Projet/aurore/lampe/static/lampe/scripts/launcher.py", line 9, in launch
process = Process(target=LED.setCouleur, args=(arg1,))
AttributeError: module 'lampe' has no attribute 'setCouleur'
[16/May/2016 17:29:00] "GET /lampe/appliquer_couleur/1/ HTTP/1.1" 500 69516
【问题讨论】:
-
使用回溯编辑的帖子
-
在
launcher.py或views.py你能试试print(LED.__file__)看看正在导入什么lampe模块吗?您可能不小心将static/lampe文件夹或项目文件夹作为包导入。 -
target=LED.setCouleur是否正确?你确定它不应该是`target=LED.setCouleur()?通常 setter 和 getter 是 AFAIK 的函数,但也许这是预期的。 -
@TadhgMcDonald-Jensen :我在 views.py 中添加了这一行,我得到了一个 nameError :name LED is not defined。 SeanM :我认为这是正确的,因为当我直接启动 launcher.py 时它可以工作。
-
您的项目名称“lampe”在lampe/static/lampe/scripts中隐藏了“lampe.py”,请重命名您的lampe.py并重试。