[英]How to run .py files on server?
如何在浏览器上运行 .py 文件? 我在运行 python 脚本和 html 表单时遇到了一个主要问题,因为浏览器在浏览器窗口中显示了源代码。 如何通过在服务器端运行 html 而不是将其暴露给客户端的浏览器来打印输出?
我找到了我的问题的答案:第 1 步:将您的 python 文件命名为.cgi
而不是.py
。 .py
文件仅在 python 终端内运行,或者如果您可以编辑服务器配置文件以将.py
文件扩展名显示为.cgi
文件。如果您没有该权限,您可以使用.cgi
作为您的文件扩展名来运行python 在您的服务器上,并在客户端打印输出。
注意:您可以在服务器端使用您的 python 代码,但您无法在客户端运行它,因此始终知道您在做什么.cgi gives you that power
Step-2:将您的.html
代码与 python 代码链接您可以通过简单地将.cgi
文件的链接提供给表单元素的 action 属性来做到这一点。 见下文:-
<form action="server_action.cgi"> <input name="Message" type="input"> </form>
这只是一个例子,我没有在上面链接真正的.cgi
文件。
注意:要在同一 html 页面中打印输出,只需使用此代码print('Content-Type:text/html')
print()
print(
在以上两行之后,只需将您的 html 代码复制并粘贴到此括号内)
功能。 只需复制并粘贴上面的代码,看看它是如何工作的。
注意"
应该在括号内写成\\"
,否则python将在呈现整个代码之前关闭它的打印"
。它也会在客户端产生错误。
第 3 步:(最重要的)处理:这一步是 Python 函数发挥作用的地方,它可以理解用户在输入中所说的内容,并根据需要进行输出。 我在下面写了一个例子,不要在这里运行这个代码,它不会产生输出,因为在 STACKOVERFLOWS 编辑器上没有安装 Python 库。[ SKIP THIS CODE BELOW IF YOU ALREADY HAVE XAMPP INSTALLED AND KNOW HOW TO RUN CGI FILES ON IT
] SKIP THIS CODE BELOW IF YOU ALREADY HAVE XAMPP INSTALLED AND KNOW HOW TO RUN CGI FILES ON IT
如果您没有托管服务器,请安装https://www.apachefriends.org/index.html XAMPP。 在 xampp for windows 中运行 Python 下面是如何设置 xampp 以运行.cgi
文件的说明:
STEP-1:[Download Python]
Download & install the latest version of python from www.python.org Download
Python & click on the windows installer of any version [ex. python-3.6.2]
STEP 2: [Install Python] Install in any directory of your harddrive [ex.
D:\python-3.6.2]
Click on config button just right to the Start Button and open `httpd.conf`
file and make the changes as said in the linked post BELOW ⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇
[RUN PYTHON SCRIPTS WITH XAMPP][1]
使用 Xampp 运行 Python 脚本
我在安装 XAMPP 之前谈到的server_action.cgi
的代码Note that #!C:\\Python39\\python.exe
用于代码的开头。 这是您的python解释器的位置(尽管如果您的服务器提供自己的库来解释cgi文件,则不需要)
#!C:\Python39\python.exe
import cgi
import cgitb
import cgitb
cgitb.enable()
import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
print("<TITLE>CGI script output</TITLE>")
print("<H1>This is my first CGI script</H1>")
print("Hello, world!")
print("""<form action="server_action.cgi">
<input name="Message" type="input">
</form>""")
form = cgi.FieldStorage()
text=form["Message"].value
#'Message' is the value of my 'name' attribute used in my <input name=""> tag
Use
print("""
this
format
""") to print multiple lines in one print output.
import cgitb cgitb.enable(display=0, logdir="/path/to/logdir") This was used to prevent displaying error on the clients browser if any occured. ```/path/to/logdir``` is the path where you want to store the error that was prevented directly on the browser window ```display=0```
尝试使用流行的 Python Web 框架 django。 有关更多信息,请访问https://www.djangoproject.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.