[英]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.