@会网络的老鼠

涂飞平的博客空间

一个转换Markdown为html的简易工具 [原]

4 年前 0

最近在忙着系统的产品化工作,其中的说明文档和开发文档都是采用Markdown格式来编写,然后通过pandoc输出为html格式,但由于其只输出文档部分,没有将html的头部和编码信息加入,所以为了简单,用python写了一个工具来完成这个工作,源代码如下:

#!/usr/bin/python
#code: utf-8

import sys, os, time

HEADER = '''<html>
<head>
<!-- %s -->
<title>%s</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
'''

FOOTER = '''
</body>
</html> '''

COMMANDSTR = "pandoc -thtml -fmarkdown %s -o /var/tmp/1.html"

def getComment():
return "Copyright(C)Beijing Aegean Software. build by sunny " + time.strftime("%Y-%m-%d %H:%M:%S")

def guessTitle(inf):
try:
f = open(inf, "r")
title = f.readline()
return title.rstrip().lstrip()
except (Exception, e):
print str(e)
return ''
finally:
if f != None:
f.close()

def processHeader(inf, outf):
try:
f = open(outf, "w")
header = HEADER % (getComment(), guessTitle(inf))
f.write(header)
except:
print "error [header]"
finally:
if f != None:
f.close()

def processFooter(outf):
try:
f = open(outf, "a")
f.write(FOOTER)
except:
print "error [footer]"
finally:
if f != None:
f.close()


def processContent(inf, outf):
try:
os.system(COMMANDSTR % inf)
f = open("/var/tmp/1.html", "r")
content = f.read()
fo = open(outf, "a+")
fo.write(content)
except:
print "error [content]"
finally:
if f != None:
f.close()
if fo != None:
fo.close()
if os.path.exists("/var/tmp/1.html"):
os.remove("/var/tmp/1.html")

if __name__=="__main__":
if len(sys.argv) != 3:
print "Usage: markdown input-file output-file"
sys.exit(1)

inputf = sys.argv[1]
outputf = sys.argv[2]
processHeader(inputf, outputf)
processContent(inputf, outputf)
processFooter(outputf)
print "Convert Finished!"

保存为markdown文件并设置为可执行属性,然后就可以简单调用了:
markdown ~/irpdir/allconfig.md ~/irpdir/configures.html

编写评论