首页 > 解决方案 > python BaseHTTPRequestHandler 和用于打开文件的本地 http 服务器目录

问题描述

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.joinwith os.getcwd,它总是会返回这种目录:c:\\path.ext而不是c:\\user\\name\\blabla\\path.ext 我在 windows 上工作。

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

标签: pythondirectoryhttpserverbasehttprequesthandler

解决方案


实际上,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例如截断users/name/desktopcwd。


推荐阅读