Cherrypy服务器运行python脚本

时间:2016-03-11 13:55:33

标签: python linux python-2.7 cherrypy

我想当我按下一个按钮时,一个特定的python脚本被执行我尝试添加它,但当然不起作用,这是正确的方法
   我想要执行的是(ser = serial.Serial(' / dev / ttyUSB0')    ser.write(b'你好'))

import cherrypy
import string

class HelloWorld:

    """ Sample request handler class. """
    @cherrypy.expose
    def index(self):
       return """<html>
          <head></head>
          <body>
            <form method="get" action="generate">
              <button type="submit">Press!</button>
            </form>
          </body>
          ser = serial.Serial('/dev/ttyUSB0')
          ser.write(b'hello') 
        </html>"""


if __name__ == '__main__':
   cherrypy.config.update({'server.socket_host': '0.0.0.0'} )
   cherrypy.quickstart(HelloWorld())

1 个答案:

答案 0 :(得分:0)

您必须在字符串外的return之前输入您的代码:

@cherrypy.expose
def index(self):
   ser = serial.Serial('/dev/ttyUSB0')
   ser.write(b'hello') 
   return """<html>
      <head></head>
      <body>
        <form method="get" action="generate">
          <button type="submit">Press!</button>
        </form>
      </body>
    </html>"""

这会将hello发送到串口。如果你想在按钮上点击它,它必须进入一个名为generate的方法,但与上面的index类似。