From c426c773ee36d2872f79ff01d3bed615245e61b3 2013-07-09 16:40:18 From: MinRK Date: 2013-07-09 16:40:18 Subject: [PATCH] add nbconvert.utils.pandoc single entry point for calling pandoc for transforms. --- diff --git a/IPython/nbconvert/utils/pandoc.py b/IPython/nbconvert/utils/pandoc.py new file mode 100644 index 0000000..c914cee --- /dev/null +++ b/IPython/nbconvert/utils/pandoc.py @@ -0,0 +1,53 @@ +"""Utility for calling pandoc""" +#----------------------------------------------------------------------------- +# Copyright (c) 2013 the IPython Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +from __future__ import print_function + +# Stdlib imports +import sys +import subprocess + +# IPython imports +from IPython.utils.py3compat import cast_bytes + +#----------------------------------------------------------------------------- +# Classes and functions +#----------------------------------------------------------------------------- + +def pandoc(source, fmt, to, encoding='utf-8'): + """Convert an input string in format `from` to format `to` via pandoc. + + This function will raise an error if pandoc is not installed. + Any error messages generated by pandoc are printed to stderr. + + Parameters + ---------- + source : string + Input string, assumed to be valid format `from`. + fmt : string + The name of the input format (markdown, etc.) + to : string + The name of the output format (html, etc.) + + Returns + ------- + out : unicode + Output as returned by pandoc. + """ + p = subprocess.Popen(['pandoc', '-f', fmt, '-t', to], + stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) + out, _ = p.communicate(cast_bytes(source, encoding)) + out = out.decode(encoding, 'replace') + return out[:-1] +