一种。处理程序的输入/输出:Pexpect。它相当容易使用,阅读其中随附的一些示例应该足以使您掌握基础知识。
b。Javascript介面:
好吧,我使用gevent及其内置的WSGI服务器。(查找WSGI服务器(另一个)是什么)。我应该注意,该程序将保持状态,因此您可以通过将会话ID返回到javascript客户端并将pexpect会话存储在全局变量或其他容器中来管理打开的会话,以便完成程序的输入和输出跨多个独立的AJAX请求。但是,我将其留给您,因为这并不那么简单。
我所有的示例所要做的就是在单击您选择的内容后将POST请求放入其中。(由于未设置某些变量,因此实际上不起作用。对其进行设置。)
以下是相关部分:
<!-- Javascript --><script src="jquery.js"></script><script type="text/javascript">function toPython(usrdata){ $.ajax({ url: "http://yoursite.com:8080", type: "POST", data: { information : "You have a very nice website, sir." , userdata: usrdata }, dataType: "json", success: function(data) { <!-- do something here --> $('#somediv').html(data); }});$("#someButton").bind('click', toPython(something));</script>然后服务器:
# Python and Geventfrom gevent.pywsgi import WSGIServerfrom gevent import monkeymonkey.patch_all() # makes many blocking calls asynchronousdef application(environ, start_response): if environ["REQUEST_METHOD"]!="POST": # your JS uses post, so if it isn't post, it isn't you start_response("403 Forbidden", [("Content-Type", "text/html; charset=utf-8")]) return "403 Forbidden" start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")]) r = environ["wsgi.input"].read() # get the post data return raddress = "youraddresshere", 8080server = WSGIServer(address, application)server.backlog = 256server.serve_forever()如果您的程序是面向对象的,则将其集成起来相当容易。编辑:不需要面向对象。现在我包含了一些Pexpect代码
global dd = someClass()def application(environ, start_response): # get the instruction password = somethingfromwsgi # read the tutorials on WSGI to get the post stuff # figure out WHAT to do global d success = d.doSomething() # or success = funccall() prog = pexpect.spawn('python someprogram.py') prog.expect("Password: ") prog.sendline(password) i = prog.expect(["OK","not OK", "error"]) if i==0: start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")]) return "Success" elif i==1: start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")]) return "Failure" elif i==2: start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")]) return "Error"我建议的另一个选择是Nginx + uWSGI。如果您愿意,我也可以举一些例子。它为您带来了将Web服务器合并到设置中的好处。



