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

时间:2017-03-11 20:16:57

标签: 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?

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

1 个答案:

答案 0 :(得分:1)

它似乎重定向到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) (或文件列表)以外的任何内容the base code不支持:

("index.html", "index.htm")

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

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