擅长:python、mysql、java
<p>由于<code>.htaccess</code>文件对内置http服务器没有任何意义,因此您使用<code>CGIHTTPRequestHandler</code>的方法是正确的。有一个<code>CGIHTTPRequestHandler.cgi_directories</code>变量指定可执行文件被视为cgi脚本的目录(<a href="http://hg.python.org/cpython/file/cbdd6852a274/Lib/http/server.py#l951" rel="noreferrer">here is the check itself</a>)。您应该考虑将<code>test.py</code>移动到<code>cgi-bin</code>或<code>htbin</code>目录并使用以下脚本:</p>
<p><em><strong>cgiserver.py:</strong></em></p>
<pre><code>#!/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()
</code></pre>
<p><em><strong>cgi-bin/test.py:</strong></em></p>
<pre><code>#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')
</code></pre>
<p>最后你应该:</p>
<pre><code>|- cgiserver.py
|- cgi-bin/
` test.py
</code></pre>
<p>使用<code>python3 cgiserver.py</code>运行并向<code>localhost:8123/cgi-bin/test.py</code>发送请求。干杯。</p>