我找到了问题的答案:
第1步:将您的python文件命名为.cgi而不是.py。.py文件仅在python终端内运行,或者如果您可以编辑服务器配置文件以显示.py文件扩展名,就好像它们是.cgi文件一样.如果你没有这个权限,你可以使用.cgi作为你的文件扩展名,在你的服务器上运行python并在客户端打印输出。
注意:您可以在服务器端使用您的 python 代码,但您无法在客户端运行它,因此请始终知道您在做什么.cgi gives you that power
第 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 函数发挥作用的地方,以了解用户在其输入中所说的内容并根据需要携带输出。我在下面写了一个示例,不要在此处运行此代码,因为 Python 库未安装在 STACKOVERFLOWS 编辑器上。[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。
Run Python in xampp for windows 下面解释了如何设置 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]
Running Python scripts with Xampp
server_action.cgi 的代码,我在
XAMPP 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.
如何在客户端/浏览器上隐藏 python 错误? 在上面的 sn-p 中,我使用了一行来防止在用户的浏览器窗口上显示错误.
如果您认为在浏览器窗口上看到错误而不是打开另一个目录更容易,您可以将其关闭。
请参阅下文以了解我在说哪一行:-
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```