使用同步写入,并且加上文件验证,文件延时0.5秒

This commit is contained in:
liuwei
2025-06-23 17:33:41 +08:00
parent 82a9ca361a
commit 4db938df0b

View File

@@ -155,14 +155,39 @@ async def md_str_to_html(md_content, output_html):
</style>
"""
# 异步写入 HTML 文件
async with aiofiles.open(output_html, 'w', encoding='utf-8') as f:
await f.write('<html><head>')
await f.write('<meta charset="UTF-8">') # 确保 UTF-8 编码
await f.write(css)
await f.write('</head><body>')
await f.write(html_content)
await f.write('</body></html>')
# 构建完整的 HTML 内容
full_html = f'''<html>
<head>
<meta charset="UTF-8">
{css}
</head>
<body>
{html_content}
</body>
</html>'''
# 使用普通的文件写入,确保文件完全写入
try:
with open(output_html, 'w', encoding='utf-8') as f:
f.write(full_html)
f.flush() # 强制刷新缓冲区
os.fsync(f.fileno()) # 确保写入磁盘
except Exception as e:
logger.error(f"写入HTML文件失败: {e}")
raise
# 验证文件是否成功写入
try:
with open(output_html, 'r', encoding='utf-8') as f:
content = f.read()
if not content:
raise ValueError("HTML文件写入后为空")
except Exception as e:
logger.error(f"验证HTML文件失败: {e}")
raise
# 添加小延时确保文件系统同步
await asyncio.sleep(0.5)
def check_chromium_installed(path):