用网站输入运行python脚本

问题描述:

我已经有了一些webdev的经验,并开始学习python。我创建了一个接受参数的python脚本,然后运行一个程序,并将打印语句打印到控制台中。我很好奇,如果有可能把这个程序放在网页后面。用网站输入运行python脚本

即带有下拉的网页,选择了该选项并单击“开始”按钮。然后python脚本运行你选择的选项,你的报告显示在页面上。

我已经看了几个相近岗位:Execute a python script on button click

run python script with html button

但他们似乎提供了非常不同的解决方案,人们似乎认为PHP的想法是不安全的。我也在寻找更明确的东西。我很好地改变python脚本来返回ajson或其他东西,而不仅仅是打印语句。

在网页和python程序之间进行通信的一种非常常见的方式是运行python作为WSGI server。有效地,python程序是一个单独的服务器,它使用GET和POST与网页进行通信。

这种方法的一个好处是,它将Python应用程序与网页本身解耦。您可以在开发过程中直接向测试服务器发送http请求来测试它。

Python包含一个built-in WSGI implementation,所以创建一个WSGI服务器非常简单。这是一个非常简单的例子:

from wsgiref.simple_server import make_server 

# this will return a text response 
def hello_world_app(environ, start_response): 
    status = '200 OK' # HTTP Status 
    headers = [('Content-type', 'text/plain')] # HTTP Headers 
    start_response(status, headers) 
    return ["Hello World"] 

# first argument passed to the function 
# is a dictionary containing CGI-style environment variables 
# second argument is a function to call 
# make a server and turn it on port 8000 
httpd = make_server('', 8000, hello_world_app) 
httpd.serve_forever() 
+0

感谢您的回复!你能解释一下从Javascript的一面来看这是怎么回事?假设你上面编写的代码被称为“helloWorld.py”,并且在命令行中使用了参数“hello”,那么你如何传递脚本“hello”并接收脚本的JS方面的响应? – Acoustic77

+0

WSGI服务器只是在监听http请求,它的返回值 - 无论它们是什么 - 将被发送以回应请求。这个问题包括一些在JS中使用不同方法的例子:http://*.com/questions/247483/http-get-request-in-javascript – theodox

+0

我感谢你的帮助,但我仍然没有运气。我修改了python脚本来简单地创建一个html页面。所以我所需要的就是弄清楚这个javascript的一面。我只需要传递一个字符串并运行它。 (整个脚本,而不仅仅是一个函数,例如:$ python3 myscript.py inputString – Acoustic77