File: pandoc.py

package info (click to toggle)
ipython 1.2.1-2~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 22,884 kB
  • sloc: python: 67,305; makefile: 469; lisp: 272; sh: 251
file content (69 lines) | stat: -rw-r--r-- 2,256 bytes parent folder | download
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
"""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 subprocess
from io import TextIOWrapper, BytesIO

# IPython imports
from IPython.utils.py3compat import cast_bytes

from .exceptions import ConversionException

#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------

class PandocMissing(ConversionException):
    """Exception raised when Pandoc is missing. """
    pass


def pandoc(source, fmt, to, extra_args=None, 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.
    """
    command = ['pandoc', '-f', fmt, '-t', to]
    if extra_args:
        command.extend(extra_args)
    try:
        p = subprocess.Popen(command,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE
        )
    except OSError as e:
        raise PandocMissing(
            "The command '%s' returned an error: %s.\n" %(" ".join(command), e) +
            "Please check that pandoc package is installed."
        )
    out, _ = p.communicate(cast_bytes(source, encoding))
    out = TextIOWrapper(BytesIO(out), encoding, 'replace').read()
    return out.rstrip('\n')