特定格式的HTML代码

时间:2013-11-05 07:00:18

标签: python html

我有HTMl代码@ http://pastie.org/8456333作为参考,我也有以下代码,我正在构建HTML代码到电子邮件..我需要输入或建议需要对下面的代码进行什么修改让桌子看起来像 HTML代码@ http://pastie.org/8456333

import re
import os
import sys
import time
from email.mime.text import MIMEText
import subprocess
from subprocess import check_call,Popen,PIPE

def email (body,subject,to=None):
    msg = MIMEText("%s" % body)
    msg["Content-Type"] = "text/html"
    msg["From"] = "cdit@company.com"
    #msg["From"] = "test@company.com"
    if to!=None:
        to=to.strip()
        #msg["To"] = "test@company.com"
        msg["To"] = to
    else:
        msg["To"] = to
    msg["Subject"] = '%s' % subject
    p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
    p.communicate(msg.as_string())

def  manifest_table(project,branch):
    global table_items
    global tableProperties
    table_items = table_items + "<tr><td>%s</td><td>%s</td></tr>"%(project,branch)
    tableBody = """\
                <style type="text/css">
                %s
                </style>
                <table id="tfhover" class="tftable" border="1">
                %s
                </table>
            """%(tableProperties, table_items)
    return tableBody

def main ():
    i=0
    global table_items
    table_items = "<tr><th>Project</th><th>Branch</th></tr>"
    global tableProperties
    tableProperties = r"table.tftable {font-size:12px;color:#333333;width:10%;border-width: 1px;border-color: #729ea5;border-collapse: collapse;} table.tftable th {font-size:12px;background-color:#ded0b0;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;text-align:left;} table.tftable tr {background-color:#ffffff;} table.tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;}"
    project_list=['data','modem','1x','umts']
    branch_list=['jb','fr','kk','choc']
    for proj in project_list:
        branch = branch_list[i]
        mft = manifest_table(proj,branch)
        i=i+1
    email_body = """\
            <html>
              <head></head>
              <body>
                <p>Please find the table for the gerrits you provided:- <br>
                </p>
                %s
              </body>
            </html>
            """%(mft)
    print "Emailing..."
    email(email_body,"Manifest table","test@company.com")

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

为了制作你的表我建议使用string.Template: 这是一个简单的例子:

from string import Template
a = Template("$name is my friend")
b=a.substitute(name="Sara")
print b
#output: Sara is my friend

关于代码的一部分:

table_items = table_items + "<tr><td>%s</td><td>%s</td></tr>"%(project,branch)

你可以做得更好:

table_items += "<tr><td>%(p)s</td><td>%(b)s</td></tr>" % {'p':project,'b':branch}

或通过string.Template:

table_items = Template("<tr><td>$p</td><td>$b</td></tr>")
table_items += table_items.substitute(p=project,b=branch)