gpt4 book ai didi

python - 如何在python创建的BaseHTTPSERVER上执行python脚本?

转载 作者:可可西里 更新时间:2023-11-01 16:25:12 24 4
gpt4 key购买 nike

我简单地创建了一个 python 服务器:

python -m SimpleHTTPServer

我有一个 .htaccess(我不知道它是否对 python 服务器有用)与:

AddHandler cgi-script .py
Options +ExecCGI

现在我正在编写一个简单的 python 脚本:

#!/usr/bin/python
import cgitb
cgitb.enable()
print 'Content-type: text/html'
print '''
<html>
<head>
<title>My website</title>
</head>
<body>
<p>Here I am</p>
</body>
</html>
'''

我使 test.py(我的脚本的名称)成为一个执行文件:

chmod +x test.py

我在 firefox 中使用这个地址启动:(http ://) 0.0.0.0:8000/test.py

问题,脚本没有执行...我看到网页中的代码...服务器错误是:

localhost - - [25/Oct/2012 10:47:12] "GET / HTTP/1.1" 200 -
localhost - - [25/Oct/2012 10:47:13] code 404, message File not found
localhost - - [25/Oct/2012 10:47:13] "GET /favicon.ico HTTP/1.1" 404 -

如何简单地管理python代码的执行?是否可以在 python 服务器中编写来执行 python 脚本,就像这样:

import BaseHTTPServer
import CGIHTTPServer
httpd = BaseHTTPServer.HTTPServer(\
('localhost', 8123), \
CGIHTTPServer.CGIHTTPRequestHandler)
###  here some code to say, hey please execute python script on the webserver... ;-)
httpd.serve_forever()

或者别的……

最佳答案

CGIHTTPRequestHandler 你走在正确的轨道上,因为 .htaccess 文件对内置的 http 服务器没有任何意义。有一个 CGIHTTPRequestHandler.cgi_directories 变量指定可执行文件被视为 cgi 脚本的目录 (here is the check itself)。您应该考虑将 test.py 移动到 cgi-binhtbin 目录并使用以下脚本:

cgiserver.py:

#!/usr/bin/env python3

from http.server import CGIHTTPRequestHandler, HTTPServer

handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin'] # this is the default
server = HTTPServer(('localhost', 8123), handler)
server.serve_forever()

cgi-bin/test.py:

#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')

你应该得到:

|- cgiserver.py
|- cgi-bin/
` test.py

使用 python3 cgiserver.py 运行并将请求发送到 localhost:8123/cgi-bin/test.py。干杯。

关于python - 如何在python创建的BaseHTTPSERVER上执行python脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13065306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com