gpt4 book ai didi

python - 使 python SimpleHTTPServer 在顶部列出子目录

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:56 25 4
gpt4 key购买 nike

我使用以下方式启动服务器:

python -m SimpleHTTPServer

在浏览器中,我可以通过转到“localhost”来查看当前目录列表。但是,它按字母顺序列出它们。

我可以采用 Windows shell 样式,在文件之前列出子目录,但两个组都按字母顺序单独排序吗?

最佳答案

我们需要在 SimpleHTTPServer.py 文件中进行更改。我对下面的函数做了一些更改。您可以更换并检查

def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).

Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().

"""
lst1=[]
lst2=[]
try:
list = os.listdir(path)
for i in list:
if os.path.isdir(os.path.join(path,i)):
lst1.append(i)
elif os.path.isfile(os.path.join(path,i)):
lst2.append(i)
except os.error:
self.send_error(404, "No permission to list directory")
return None
lst1.sort(key=lambda a: a.lower())
#print lst1
#print list
lst2.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
f.write("<hr>\n<ul>\n")
for name in lst1:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
f.write('<li><a href="%s">%s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname)))
for name in lst2:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname)))

f.write("</ul>\n<hr>\n</body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f

关于python - 使 python SimpleHTTPServer 在顶部列出子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com