python - 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.join
with 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
例如截断users/name/desktop
cwd。
推荐阅读
- reactjs - 使动作创建者不分派动作
- java - Python 到 Java 转换问题
- php - 如何在 Laravel 5.5 中保护 DB::statement() 免受 SQL 注入?
- c++ - 范围内的 C++ 变量重定义
- python - 如何收集相关文章取决于Django Python中的标题
- javascript - javascript中列表的选定索引
- java - java内部catch中的异常
- c# - 带有 PushNotificationChannel 的桌面桥应用程序找不到文件“System.Runtime.WindowsRuntime”
- javascript - 加载后是否可以读取脚本或图像标签的内容?
- ssas - ssas 维度仅在使用名称值时重复