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

标签 python python-3.x localhost httpserver

考虑一个简单的 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.htmlindex.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 分配给您要重定向的文件到。

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

关于python - 如何在命令行中使用 http.server 作为参数传递 file.py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42740143/

相关文章:

python - 如何使用 opencv - python 去除图像噪声?

python - 算法 : how to split list data into fixed size sub-lists without having separate numbers

python - 为什么我的 Ubuntu 20.04 DEV 机器上安装了多个 Python 版本?

python - GNS3 错误 : WaitForConnectionWorker thread stopping with an error: Could not connect to 127. 0.0.1 在端口 3090 上:[Errno 111] Conexión rehusada

php - 本地主机 header 重定向到本地主机/链接

python - 按钮上的图像

python - Pandas 使用日期在数据框中附加周列

python - 将 h5py 数据集输出到文本的快速方法是什么?

iphone - 在 localhost 服务器上为 iphone 和 ipad 测试网站

localhost - MAMP本地主机不工作