1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import sys import os
from bs4 import BeautifulSoup import markdown
class MarkdownToHtml:
headTag = '<head><meta charset="utf-8" /></head>'
def __init__(self, cssFilePath = None): if cssFilePath != None: self.genStyle(cssFilePath)
def genStyle(self,cssFilePath): with open(cssFilePath,'r') as f: cssString = f.read() self.headTag = self.headTag[:-7] + '<style type="text/css">{}</style>'.format(cssString) + self.headTag[-7:]
def markdownToHtml(self,**arguments): if 'sourceFilePath' in arguments: sourceFilePath = arguments['sourceFilePath'] else: return if 'destinationDirectory' in arguments: destinationDirectory = arguments['destinationDirectory'] else: destinationDirectory = os.path.dirname(os.path.abspath(sourceFilePath)) if 'outputFileName' in arguments: outputFileName = arguments['outputFileName'] else: outputFileName = os.path.splitext(os.path.basename(sourceFilePath))[0] + '.html' if destinationDirectory[-1] != '/': destinationDirectory += '/' with open(sourceFilePath,'r', encoding='utf8') as f: markdownText = f.read() rawHtml = self.headTag + markdown.markdown(markdownText,output_format='html5') beautifyHtml = BeautifulSoup(rawHtml,'html5lib').prettify() with open(destinationDirectory + outputFileName, 'w', encoding='utf8') as f: f.write(beautifyHtml)
if __name__ == "__main__": mth = MarkdownToHtml() argv = sys.argv[1:] if '-s' in argv: cssArgIndex = argv.index('-s') +1 cssFilePath = argv[cssArgIndex] if not os.path.isfile(cssFilePath): print('Invalid Path: ' + cssFilePath) sys.exit() mth.genStyle(cssFilePath) argv.pop(cssArgIndex) argv.pop(cssArgIndex-1) if '-o' in argv: dirArgIndex = argv.index('-o') +1 outputDirectory = argv[dirArgIndex] if not os.path.isdir(outputDirectory): print('Invalid Directory: ' + outputDirectory) sys.exit() argv.pop(dirArgIndex) argv.pop(dirArgIndex-1) argumentsList = [dict([('sourceFilePath',filePath), ('destinationDirectory',outputDirectory)]) for filePath in argv] else: argumentsList = [dict([('sourceFilePath',filePath)]) for filePath in argv] for argument in argumentsList: if os.path.isfile(argument['sourceFilePath']): mth.markdownToHtml(**argument) else: print('Invalid Path: '+argument['sourceFilePath'])
|