【问题标题】:Python SimpleHTTPServer serve a subdirectoryPython SimpleHTTPServer 提供一个子目录
【发布时间】:2016-11-16 15:49:23
【问题描述】:

是否可以使用 SimpleHTTPServer 提供子目录而不是当前目录?

我像这样从命令行使用它:

python -m SimpleHTTPServer 5002

我想使用它的原因是我有一个target 文件夹,我不时删除它,并由我的工具重新生成。但是,当我这样做时,我还需要重新启动 SimpleHTTPServer。我认为从父存储库提供它可以让我不重新启动它。

【问题讨论】:

    标签: python simplehttpserver


    【解决方案1】:

    好吧,要为父目录提供服务,只需在运行 Python 脚本 (python -m SimpleHTTPServer 5002) 之前更改当前工作目录。

    您可以编写自己的脚本,例如:'my_server.py':

    import SimpleHTTPServer
    import os
    
    
    def main():
        pwd = os.getcwd()
        try:
            os.chdir("..")  # or any path you like
            SimpleHTTPServer.test()
        finally:
            os.chdir(pwd)
    
    
    if __name__ == "__main__":
        main()
    

    然后运行'my_server.py':

    python -m my_server 5002
    

    【讨论】:

      【解决方案2】:

      如果你是从 shell 调用它,你可以只使用 shell 功能并执行以下操作:

      对于 Python 2:

      pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd
      

      对于 Python 3.6,您甚至不需要这样做。
      http.server 有一个目录参数,所以这样做:

      python3 -m http.server -d /path/you/want/to/serve
      

      但是,如果您想以编程方式调用它,Andy Hayden 在“How to run a http server which serves a specific path?”上提出的解决方案似乎更合适。
      (它不那么“hacky”/依赖于副作用,而是使用类构造函数。)

      是这样的:

      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 >= 3.6
      对于 3.5 及以下的 Python,没有可用于 TCPServer 基类的 contextmanager 协议,但这仅意味着您需要更改 with 语句并将其转换为简单的赋值:

      httpd = socketserver.TCPServer(("", PORT), Handler)
      

      last detail 归功于Anthony Sottile

      【讨论】:

        猜你喜欢
        • 2011-02-04
        • 1970-01-01
        • 2012-01-04
        • 2015-09-23
        • 2013-06-29
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多