如何在网页中运行python脚本

时间:2011-09-18 10:37:31

标签: python

我对python很新。只知道什么是python。 我创建了以下代码(在python IDLE中):

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

然后我将此页面保存在我的localhost中作为index.py

我使用脚本运行 http://localhost/index.py

但它没有显示已执行的python脚本。相反,它将上述代码显示为HTML。问题出在哪儿?请有人告诉我如何在网页上运行python?

6 个答案:

答案 0 :(得分:41)

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

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

其次,假设您现在拥有一个服务于文件的服务器,您还需要将代码解释为服务器的Python代码。对于Python用户来说,解决方案现在是mod_wsgi。但是对于更简单的情况,你可以坚持使用CGI(更多信息here),但如果你想轻松制作网页,你应该使用像Django这样的现有Python网页框架。

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

答案 1 :(得分:20)

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

但是,看到你刚刚开始使用Python,一个简单的CGI脚本可能更合适:

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

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

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

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

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

答案 2 :(得分:11)

在Python中使用flask库可以实现这一点。 记得将HTML页面存储到运行python脚本的名为“templates”的文件夹中。

所以你的文件夹看起来像

  1. templates(包含HTML文件的文件夹)
  2. 你的python脚本
  3. 这是你的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>
    

    这是一个很小的方法,您可以通过它来完成比较两个字符串的简单任务,并且可以轻松更改以满足您的要求

答案 3 :(得分:9)

如果您使用自己的计算机,请安装名为XAMPP的软件(或WAMPP可以使用)。这基本上是一个只能在您的计算机上运行的网站服务器。然后,安装完成后,转到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"

答案 4 :(得分:0)

根据您当前的要求,这将起作用:

    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)

打开index.html,您会看到想要的内容

答案 5 :(得分:0)

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

http://skulpt.org/using.html

Skulpt是Python的一种实现,可以在客户端运行。非常有趣,不需要插件,只需一个简单的JS。