在不使用网页服务器的情况下从浏览器调用程序

2 投票
7 回答
3439 浏览
提问于 2025-04-15 12:25

有没有办法从本地的HTML页面调用一个程序(Python脚本)呢?我在这个页面上有一个YUI颜色选择器,需要把它的值通过rs232发送给一个微控制器。(页面上还有其他内容,所以我不能用应用程序来替代HTML页面。)

以后这个会迁移到服务器上,但我现在需要一个快速简单的解决方案。

谢谢。

7 个回答

1

如果你想让一个HTML页面有一些服务器端的编程功能,那你就需要一个网络服务器来处理这些请求。

我的建议是,在你的开发电脑上运行一个网络服务器,或者试着用本地的桌面应用程序或脚本来完成你想做的事情。

3

Python自带了一个小型的网页服务器。如果你已经让Python和RS232一起工作了,可能需要去这里看看怎么设置一个非常简单的网页服务器。还有一个更简单的例子可以参考这个

import SimpleHTTPServer
import SocketServer

port = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", port), Handler)
httpd.serve_forever()

尽量把你的代码分开,这样在把它移到一个可以用Python运行的正式网页服务器时,就不会遇到太多麻烦。

6

我看到Daff提到了简单的HTTP服务器,但我这里给你举个例子,说明你可以怎么解决这个问题(使用 BaseHTTPServer):

import BaseHTTPServer

HOST_NAME = 'localhost'
PORT_NUMBER = 1337

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(s):
        s.send_response(200)
        s.send_header('Content-Type', 'text/html')
        s.end_headers()

        # Get parameters in query.
        params = {}
        index = s.path.rfind('?')
        if index >= 0:
            parts = s.path[index + 1:].split('&')
            for p in parts:
                try:
                    a, b = p.split('=', 2)
                    params[a] = b
                except:
                    params[p] = ''

        # !!!
        # Check if there is a color parameter and send to controller...
        if 'color' in params:
            print 'Send something to controller...'
        # !!!

        s.wfile.write('<pre>%s</pre>' % params)

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass

    httpd.server_close()

现在,从你的JavaScript代码里,你可以调用 http://localhost:1337/?color=ffaabb

撰写回答