python树莓派运行代码报错

python树莓派运行代码报错
原文:https://blog.csdn.net/a497785609/article/details/78060029?utm_source=app&app_version=4.21.0&code=app_1562916241&uLinkId=usr1mkqgl919blen

#coding: utf8
import sys
import RPi.GPIO as GPIO
import time
import os
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import define,options
 
#初始化?
def init():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
#设置GPIO针脚电平输出
def SetPinStatus(pin,status):
    GPIO.cleanup(int(pin))
    GPIO.setup(int(pin),GPIO.OUT)
    if(int(status)==0):
        GPIO.output(int(pin),GPIO.LOW)
    else:
        GPIO.output(int(pin),GPIO.HIGH)
    
#路由处理    
class IndexHandler(tornado.web.RequestHandler):
        def get(self):
                self.render("index.html")
        def post(self):
                init()
        action=self.get_argument('action')
        #设置GPIO针脚电平输出
        if(action=="set-gpio-pin"):
            pin = self.get_argument('pin')
                    status = self.get_argument('status')
            SetPinStatus(pin,status)
            self.write("true")
        #执行shell脚本,如:关机,重启
        elif(action=="run-shell-cmd"): 
            cmd = self.get_argument('cmd')
                    os.system(cmd)                    
                
if __name__ == '__main__':
    #控制台输出响应结果,正式环境可以不开?
    #tornado.options.parse_command_line()
    settings={
        "static_path":os.path.join(os.path.dirname(__file__),"static")
        }
    app = tornado.web.Application(
        handlers=[
            (r"/",IndexHandler),
            (r"(apple-touch-icon\.png)",tornado.web.StaticFileHandler,dict(path=settings['static_path']))
        ],**settings)
    
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8020)
    tornado.ioloop.IOLoop.instance().start()
    GPIO.cleanup()
        

报错:

Traceback (most recent call last):
  File "/home/pi/gpio/gpio.py", line 26, in <module>
    class IndexHandler(tornado.web.RequestHandler):
  File "/home/pi/gpio/gpio.py", line 31, in IndexHandler
    action=self.get_argument('action')
NameError: name 'self' is not defined

这块代码的归属是哪个方法? 层次错啦?

img

python 對縮進(空格)的要求非常嚴格。

從這個錯誤訊息顯示:

Traceback (most recent call last):

  File "/home/pi/gpio/gpio.py", line 26, in <module>

    class IndexHandler(tornado.web.RequestHandler):

  File "/home/pi/gpio/gpio.py", line 31, in IndexHandler

    action=self.get_argument('action')

NameError: name 'self' is not defined

在第 26 行開始的 class IndexHandler 裡面的第 31 行 (簡略:錯誤在第 31 行)

觀察源碼,是對齊錯誤。
需要仔細觀察對齊,不要混合 tab / 空格。
 

 

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632