[英]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()
Hello, I'm trying to manipulate a file using a BaseHTTPRequestHandler and a local HTTP server. 您好,我正在尝试使用BaseHTTPRequestHandler和本地HTTP服务器来处理文件。 I can't get the absolute path, really weird stuff.
我无法走绝对的道路,真的很奇怪。 I'm using
os.path.join
with os.getcwd
, and it will always return this kind of directory : c:\\\\path.ext
instead of c:\\\\user\\\\name\\\\blabla\\\\path.ext
I'm working on windows. 我将
os.path.join
与os.getcwd
一起使用,它将始终返回这种目录: c:\\\\path.ext
而不是c:\\\\user\\\\name\\\\blabla\\\\path.ext
我在Windows上工作。
Hope someone can help, it seem that the server directory is always at the base root of 'C:'. 希望有人可以提供帮助,看来服务器目录始终位于“ C:”的基本根目录下。
Thanks 谢谢
Actually, the cwd directory didn't change at all : printing os.getcwd() in my function do_GET or just after if __name__ == '__main__'
give the same result. 实际上,cwd目录根本没有改变:在我的函数do_GET中打印os.getcwd(),或者在
__name__ == '__main__'
给出相同结果之后。
The real problem was about usage of os.path.join
, or simply when using something like open(self.path)
. 真正的问题是关于
os.path.join
使用,或者仅仅是在使用诸如open(self.path)
类的东西时。 self.path
give a string with this format /path.ext
, and I needed to remove slash... self.path
提供一个格式为/path.ext
的字符串,我需要删除斜杠...
os.path.join(os.getcwd(), '/a_second_path')
will return a string with format like c:/a_second_path
, with truncating for example users/name/desktop
of cwd. os.path.join(os.getcwd(), '/a_second_path')
将返回格式为c:/a_second_path
的字符串,例如截断cwd的users/name/desktop
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.