【问题标题】:python BaseHTTPRequestHandler and local http server directory for opening filepython BaseHTTPRequestHandler 和用于打开文件的本地http服务器目录
【发布时间】:2018-06-16 21:49:37
【问题描述】:
from http.server import BaseHTTPRequestHandler, HTTPServer

class S(BaseHTTPRequestHandler):

    def do_GET(self):
        #path = os.path.join(os.getcwd(), self.path)   --> Not work !
        with open(self.path, 'r', encoding='utf8') as File:
            content = File.read()


def run(server_class=HTTPServer, handler_class=S, port=8085):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print ('Starting httpd...')
    httpd.serve_forever()


if __name__ == "__main__":
    run()

你好, 我正在尝试使用 BaseHTTPRequestHandler 和本地 HTTP 服务器来操作文件。 我无法获得绝对路径,真的很奇怪。我正在使用os.path.joinos.getcwd,它总是会返回这种目录:c:\\path.ext 而不是c:\\user\\name\\blabla\\path.ext 我在 Windows 上工作。

希望有人能提供帮助,似乎服务器目录始终位于“C:”的根目录。
谢谢

【问题讨论】:

  • 进程的cwd是继承的。如果您的 cmd 位于 C:\ 并且您像 python c:\user\name\blabla\serv.py 一样启动服务器,则 cwd 为 C:\。 Ether 在 cmd (cd c:\user\name\blabla\ ) 中更改 cwd,硬编码 c:\\user\\name\\blabla\\ 作为应用程序中的路径,或查看 __file__ 并计算相对于当前 python 文件位置的路径。
  • 感谢您对继承的解释,它将让我继续前进。

标签: python directory httpserver basehttprequesthandler


【解决方案1】:

实际上,cwd 目录根本没有改变:在我的函数 do_GET 中打印 os.getcwd() 或在 __name__ == '__main__' 之后打印相同的结果。

真正的问题在于os.path.join 的使用,或者只是在使用open(self.path) 之类的东西时。 self.path 给出一个格式为/path.ext 的字符串,我需要删除斜线...

os.path.join(os.getcwd(), '/a_second_path') 将返回格式类似于 c:/a_second_path 的字符串,并截断例如 cwd 的 users/name/desktop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 2017-06-23
    • 2012-11-17
    • 2018-09-05
    • 2013-10-16
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    相关资源
    最近更新 更多