我在使用Python生成html文档时遇到了一些问题.我正在尝试创建目录树的HTML列表.这是我到目前为止:
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
if level <= 1:
print('<li>{}<ul>'.format(os.path.basename(root)))
else:
print('<li>{}'.format(os.path.basename(root)))
for f in files:
last_file = len(files)-1
if f == files[last_file]:
print('<li>{}</li></ul>'.format(f))
elif f == files[0] and level-1 > 0:
print('<ul><li>{}</li>'.format(f))
else:
print('<li>{}</li>'.format(f))
print('</li></ul>')
Run Code Online (Sandbox Code Playgroud)
如果只有根目录,一级子目录和文件,它似乎运行良好.但是,添加另一级别的子目录会导致出现问题(因为我认为close标签在结束时输入的次数不够多).但是我很难理解它.
如果不能这样做,有没有更简单的方法呢?我正在使用Flask,但我对模板缺乏经验,所以也许我错过了一些东西.
好吧,我设法让它按我想要的方式工作(虽然有些/大多数人可能不同意这种方法).我按照下面的建议使用了Flask.可能被视为"错误"的部分是404检查循环.这是不正确的设计,如果它持续太长时间,会导致某些浏览器出现"卡住脚本"错误.但是,我想运行的脚本不会持续很长时间才能成为问题.
感谢您的帮助,如果您有任何其他建议,请与我们联系.
烧瓶应用:
import threading
import subprocess
import os
import sys
from flask import Flask
from flask import render_template, abort
app = Flask(__name__)
app.debug = True
def run_script():
theproc = subprocess.Popen([sys.executable, "run_me.py"])
theproc.communicate()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate')
def generate():
threading.Thread(target=lambda: run_script()).start()
return render_template('processing.html')
@app.route('/is_done')
def is_done():
hfile = "templates\\itworked.html"
if os.path.isfile(hfile):
return render_template('itworked.html')
else:
abort(404)
if __name__ == "__main__":
app.run()
Run Code Online (Sandbox Code Playgroud)
processing.html:
<!DOCTYPE html>
<html>
<head>
<script src="/static/jquery.min.js"></script>
</head>
<body>
<p>Processing...</p>
<script>
setInterval(function()
{
var http = new XMLHttpRequest(); …Run Code Online (Sandbox Code Playgroud)