[英]python BaseHTTPRequestHandler and local http server directory for opening file
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目录根本没有改变:在我的函数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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.