#!/usr/bin/env python"""CLI interface to markdown-it-pyParse one or more markdown files, convert each to HTML, and print to stdout."""importargparseimportsysfromtypingimportIterable,Optional,Sequencefrommarkdown_itimport__version__frommarkdown_it.mainimportMarkdownItversion_str="markdown-it-py [version {}]".format(__version__)
[文档]defconvert_file(filename:str)->None:""" Parse a Markdown file and dump the output to stdout. """try:withopen(filename,"r")asfin:rendered=MarkdownIt().render(fin.read())print(rendered,end="")exceptOSError:sys.stderr.write(f'Cannot open file "{filename}".\n')sys.exit(1)
[文档]definteractive()->None:""" Parse user input, dump to stdout, rinse and repeat. Python REPL style. """print_heading()contents=[]more=FalsewhileTrue:try:prompt,more=("... ",True)ifmoreelse(">>> ",True)contents.append(input(prompt)+"\n")exceptEOFError:print("\n"+MarkdownIt().render("\n".join(contents)),end="")more=Falsecontents=[]exceptKeyboardInterrupt:print("\nExiting.")break
[文档]defparse_args(args:Optional[Sequence[str]])->argparse.Namespace:"""Parse input CLI arguments."""parser=argparse.ArgumentParser(description="Parse one or more markdown files, ""convert each to HTML, and print to stdout",# NOTE: Remember to update README.md w/ the output of `markdown-it -h`epilog=(f"""Interactive: $ markdown-it markdown-it-py [version {__version__}] (interactive) Type Ctrl-D to complete input, or Ctrl-C to exit. >>> # Example ... > markdown *input* ... <h1>Example</h1> <blockquote> <p>markdown <em>input</em></p> </blockquote>Batch: $ markdown-it README.md README.footer.md > index.html"""),formatter_class=argparse.RawDescriptionHelpFormatter,)parser.add_argument("-v","--version",action="version",version=version_str)parser.add_argument("filenames",nargs="*",help="specify an optional list of files to convert")returnparser.parse_args(args)
[文档]defprint_heading()->None:print("{} (interactive)".format(version_str))print("Type Ctrl-D to complete input, or Ctrl-C to exit.")