在Python 3.7中,
SimpleHTTPRequestHandler
支持使用
directory
参数。
import http.server
import socketserver
PORT = 8000
DIRECTORY = "web"
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
并且从命令行进行:
python -m http.server --directory web
要有些疯狂的想法...你可以为任意目录创建处理程序:
def handler_from(directory):
def _init(self, *args, **kwargs):
return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)
return type(f'HandlerFrom<{directory}>',
(http.server.SimpleHTTPRequestHandler,),
{'__init__': _init, 'directory': directory})
with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
python3 -m http.server -d /path/to/web/dir
来完成任务吗?感谢@kyle-barron在评论中提供了这个完美的解决方案。 - Akseli Palénserver.py: error: argument port: invalid int value: '/media/EHD/web_root'
错误。 - Lost Crotchet