【原创】python http标准库搭建服务器解析php脚本
http.server.CGIHTTPRequestHandler
这个是python的http标准库的服务器。我们用它来解析php脚本,搭建个简单的基于python的php服务器。
首先创建一个python脚本,脚本同目录下写一个php脚本。
php脚本内容:
<?php phpinfo(); ?>
python脚本内容:
import http.server
import socketserver
server_address = ('', 8000)
import subprocess
import os
class CGIhandler(http.server.CGIHTTPRequestHandler):
def run_cgi(self):
if(self.path.endswith('.php')):
# 获取 CGI 脚本的路径
script_name = os.path.basename(self.path)
script_path = os.path.join("E:\\aiohttp_study\\", script_name)
print(script_name)
print(script_path)
php_interpreter = 'D:\\phpStudy\\PHPTutorial\\php\\php-7.1.13-nts\\php-cgi.exe '
process = subprocess.Popen([php_interpreter, script_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout)
# 设置 HTTP 响应头
self.send_response(200)
self.send_header('Content-type', 'text/html')
elf.end_headers()
# 返回执行结果
self.wfile.write(stdout)
else:
super().run_cgi()
# 启用CGI处理程序
httpd = http.server.HTTPServer(server_address, CGIhandler)
# 启动服务器
print("Serving on port 8000 with CGI support...")
httpd.serve_forever()
然后访问网站即可。

浙公网安备 33010602011771号