【问题标题】:How to pass file.py using http.server in command line as parameter?如何在命令行中使用 http.server 作为参数传递 file.py?
【发布时间】:2017-08-02 01:58:57
【问题描述】:

考虑一个简单的 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 的东西?

【问题讨论】:

  • Algo for doing it ,,, let x = base url of the server and y = x+pythonfile .. 只需从 y 中删除 x 部分即可获得文件名 e..
  • 您的意思是仅将localhost:5005/(根目录)重定向到文件吗?我不熟悉 micro 是什么,所以我不知道你到底要什么......
  • @TadhgMcDonald-Jensen 是的。使用命令行将localhost:5005/ 重定向到特定文件。
  • 嗯,我会挖掘相关的源代码,我知道如果有index.html它会自动重定向到那个。

标签: python python-3.x localhost httpserver


【解决方案1】:

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 分配给您要重定向到的文件。

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

【讨论】:

  • 我认为是一个很好的解决方案。我会检查这个替代方案。感谢您的帮助。
猜你喜欢
  • 2013-07-15
  • 2016-02-22
  • 2020-02-22
  • 2018-04-29
  • 2021-10-10
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多