使用python将c程序呈现为html

使用python将c程序呈现为html,python,jinja2,Python,Jinja2,任务是使用python将c程序呈现为HTML文件 这是我的密码 from jinja2 import Template html_template = ''' <html> <body> <div> {% for i in code %} {{i}}<br> {% endfor %} </div> </body>

任务是使用python将c程序呈现为HTML文件

这是我的密码

from jinja2 import Template

html_template = '''
    <html>
        <body>
            <div>
            {% for i in code %}  {{i}}<br> {% endfor %}
            </div>
        </body> 
    </html>'''

# reading c program file
file_content = open("prog.c",'r').readlines()
template = Template(html_template)
html_content = template.render(code = file_content)

with open('outp.html','w') as f:
    f.write(html_content)
来自jinja2导入模板的

html_模板=“”
{%for代码%}{{i}}
{%endfor%} ''' #读取c程序文件 文件内容=打开(“prog.c”,“r”).readlines() 模板=模板(html\U模板) html\u content=template.render(code=file\u content) 以open('outp.html','w')作为f: f、 编写(html_内容)
假设prog.c文件包含

#include <stdio.h>
int main(void) {
    printf("Hello World!");
    }
#包括
内部主(空){
printf(“你好,世界!”);
}
HTML输出应该是

#include <stdio.h> int main(void) { printf("Hello World!"); } #包括 内部主(空){ printf(“你好,世界!”); } 但我得到的是

#include int main(void) { printf("Hello World!"); } #包括 内部主(空){ printf(“你好,世界!”); } 我在这方面有两个问题:

  • “printf…”行之前的缩进也应反映在HTML中
  • c代码中的
    在渲染时被视为HTML标记,我需要它作为HTML中的文本
  • 注:限制条件

  • 不应更改prog.c文件,因为它始终是动态的
  • 您可以使用python字符串格式或jinja模板,这取决于您,我只需要一个解决方案


    你能给我一些建议吗?

    我使用
    django.template
    来实现它

    (我喜欢
    django模板
    样式。但别担心。它的样式与
    jinja
    非常相似。)

    从django.template导入模板、引擎、上下文
    文件内容=“”
    #包括
    内部主(空){
    printf(“你好,世界!”);
    }
    '''
    html_模板=“”
    {%for代码%}{{i}}
    {%endfor%} ''' t=模板(html_模板,engine=engine()) result=t.render(上下文(dict(代码=[[uu]表示文件中的u内容.split('\n'),如果!='])) result\u compress=''.join([\u.strip()表示result.split('\n')中的uu,如果u.strip()])) 将open('outp_compress.html','w')作为f: f、 写入(结果压缩) 打印(结果压缩) 以open('outp.html','w')作为f: f、 写入(结果) 打印(结果)
    在浏览器中查看 在浏览器中打开,如下所示

    <html><body><pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;Hello World!&quot;);<br>    }<br></pre></body></html>
    
    #包括
    内部主(空){
    printf(“你好,世界!”);
    }
    
    文本内容 outp_compress.html
    #include stdio.h
    intmain(void){
    printf(“helloworld!”);
    }
    outp.html
    
    #包括stdio.h
    intmain(void){
    printf(“helloworld!”);
    }

    是否可以使用
    标签?这应该保留缩进。谢谢你@carson。这就是我需要的解决方案。在Django模板中,您是如何知道这件事的?我在试的时候没有注意到。说来话长,过几天我会回复你的。TLDR,我阅读了Django模板源代码。
    #include <stdio.h>
    int main(void) {
        printf("Hello World!");
        }
    
    <html><body><pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;Hello World!&quot;);<br>    }<br></pre></body></html>
    
    
        <html>
            <body>
                <pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;Hello World!&quot;);<br>    }<br></pre>
            </body> 
        </html>