Skip to main content
 首页 » 编程设计

python之如何在命令行中使用 http.server 作为参数传递 file.py

2025年02月15日9yyy_WW

考虑一个简单的 server.py

from http.server import CGIHTTPRequestHandler, HTTPServer 
PORT = 5005 
handler = CGIHTTPRequestHandler 
handler.cgi_directories = ['/']  # this is the current directory 
server = HTTPServer(('localhost', PORT), handler) 
print ('Server is ready at', PORT, 'PORT') 
server.serve_forever() 

如果我在 命令行 中使用 python.exe -u server.py 调用此文件,我将能够在 '/中提供 python 脚本' 主目录。

我也可以直接使用 python -m http.server --bind localhost --cgi 5005。

在这两种情况下,我都需要在浏览器中打开一个特定的 python 文件,比方说:http://localhost:5005/myfunction.py

是否有直接在命令行中使用 http.server 包含 file.py 的替代方法?

例如,根据 micro npm 模块,等同于 micro -p 5005 file.js 的东西?

请您参考如下方法:

the base code 似乎不支持重定向到 index.html 或 index.htm(或文件列表)以外的任何内容:

    #if <path is a directory>: 
 
        for index in "index.html", "index.htm": 
            index = os.path.join(path, index) 
            if os.path.exists(index): 
                path = index 
                break 
        else: 
            return self.list_directory(path) 

一个解决方案是简单地修改原始源,使元组 ("index.html", "index.htm") 指向可以在运行时更容易更改的内容。或者,您可以定义自己的包装器来自己进行检查,基本上只需复制整个 def send_head 函数并覆盖该循环以将 path 分配给您要重定向的文件到。

希望我有一个不涉及重写源代码的解决方案,但我想不出另一个(理智的)解决方案。