如何在网页中运行 Python 脚本

我对巨蟒很陌生,我只知道巨蟒是什么。

我已经创建了以下代码(在 Python 闲着中) :

print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;

然后在本地主机中将此页保存为 Index.py

我使用

Http://localhost/index.py

但是它没有显示已执行的 Python 脚本。相反,它将上面的代码显示为 HTML。问题出在哪里?如何在网页中运行 Python 文件?

305016 次浏览

为了显示代码,您需要以下几点:

首先,需要有一个处理 HTTP 请求的服务器。目前,您只是在本地硬盘上打开一个带有 Firefox 的文件。需要像 Apache 这样的服务器或类似的东西。

其次,假设您现在有一个服务器来提供这些文件,那么您还需要一些东西来将代码解释为服务器的 Python 代码。对于 Python 用户来说,现在的解决方案是 mod _ wsgi。但是对于更简单的情况,你可以坚持使用 CGI (更多信息 给你) ,但是如果你想方便地生成网页,你应该使用现有的 Python web 框架,比如 Django。

设置这个可能相当麻烦,所以要做好准备。

正如其他人指出的那样,有许多用于 Python 的 Web 框架。

但是,鉴于您刚刚开始使用 Python,一个简单的 CGI 脚本可能更合适:

  1. 将脚本重命名为 index.cgi。您还需要执行 chmod +x index.cgi来赋予它执行权限。

  2. 在文件的开头添加以下两行:

#!/usr/bin/python
print('Content-type: text/html\r\n\r')

在此之后,Python 代码应该像在终端中一样运行,除了输出到浏览器。当您使之工作时,您可以使用 CGI 模块从浏览器中获取数据。

注意: 这里假设你的网络服务器正在运行 Linux。对于 Windows,#!/Python26/python可能会工作。

如果您使用自己的计算机,安装一个名为 XAMPP 的软件(或者 WAMP也可以)。这基本上是一个网站服务器,只有在您的计算机上运行。然后,一旦安装,转到 Xampp文件夹并双击 Htdocs文件夹。轮到你了 需要创建一个 HTML 文件(我将它命名为 Runpython.html)。(还要记住将 Python 文件移动到 Htdocs。)

将其添加到 HTML 主体中(并根据需要输入)。

<form action = "file_name.py" method = "POST">
<input type = "submit" value = "Run the Program!!!">
</form>

现在,在 Python 文件中,我们基本上要打印出 HTML 代码。

# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.


import cgitb
import cgi


cgitb.enable() # This will show any errors on your webpage


inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']


print "Content-type: text/html" # We are using HTML, so we need to tell the server


print # Just do it because it is in the tutorial :P


print "<title> MyPythonWebpage </title>"


print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

使用 Python 中的 酒瓶库可以实现这一点。 请记住将 HTML 页面存储到名为“ template”的文件夹中,并在其中运行 Python 脚本。

所以你的文件夹看起来

  1. 模板(包含 HTML 文件的文件夹)
  2. 你的 Python 脚本

这是 Python 脚本的一个小例子。

from flask import Flask
from flask import request
from flask import render_template
import stringComparison


app = Flask(__name__)


@app.route('/')
def my_form():
return render_template("my-form.html") # This should be the name of your HTML file


@app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"


if __name__ == '__main__':
app.run()

这是一个 HTML 文件的小模板,用于:

<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>

这是一个小小的方法,通过它您可以实现比较两个字符串的简单任务,并且可以轻松地更改以满足您的需求。

按照你目前的要求,这个方法可行:

    def start_html():
return '<html>'


def end_html():
return '</html>'


def print_html(text):
text = str(text)
text = text.replace('\n', '<br>')
return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
webpage_data =  start_html()
webpage_data += print_html("Hi Welcome to Python test page\n")
webpage_data += fd.write(print_html("Now it will show a calculation"))
webpage_data += print_html("30+2=")
webpage_data += print_html(30+2)
webpage_data += end_html()
with open('index.html', 'w') as fd: fd.write(webpage_data)

打开 Html文件,您将看到您想要的内容。

OP 没有说服务器端或客户端,所以我就把这个留在这里,以防像我这样的人在寻找客户端:

Skulpt 是在客户端运行的 Python 实现,非常有趣,不需要插件,只需要简单的 JavaScript 代码。