【发布时间】: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.join 和os.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