gregsexton / ob-ipython

org-babel integration with Jupyter for evaluation of (Python by default) code blocks
737 stars 111 forks source link

Mention to install the tabulate module in README.org #198

Open NahsiN opened 5 years ago

NahsiN commented 5 years ago

Hello, I suggest mentioning to install the tabulate module when reading the Tip and Tricks section of the README. Just copy pasting the code snippet in a startup file and then trying to execute a code block using ob-ipython results in a cryptic json-read error which does not hint at the fact that the tabulate module might not be installed on the user's machine. Hence I suggest the following small change

" ob-ipython will display anything back from ipython with the mime type 'text/org' verbatim. This allows you and others to create [[https://www.safaribooksonline.com/blog/2014/02/11/altering-display-existing-classes-ipython/][formatters]] that output raw org. For example, drop this in your ipython startup file to have arrays and dataframes rendered as org tables (make sure the [[https://pypi.org/project/tabulate/][tabulate]] module is installed via pip or any package manager of your choice): "

digash commented 5 years ago

I've ran into this couple of times so I've wrapped it into try/except, so I do not have to stare at stack trace.

try:
    import IPython
    from tabulate import tabulate

    class OrgFormatter(IPython.core.formatters.BaseFormatter):
        def __call__(self, obj):
            try:
                if(isinstance(obj, str)):
                    return obj;
                try:                # python2 compatibility
                    if(isinstance(obj, basestring)):
                        return obj;
                except NameError:
                    pass;

                return tabulate(obj, headers='keys',
                                tablefmt='orgtbl',
                                showindex='always')
            except:
                return None

    ip = get_ipython()
    ip.display_formatter.formatters['text/org'] = OrgFormatter()

except Exception as e:
    print("ERROR: Failed to load OrgFormatter: " + str(e))

So now I just get a one line error message.

Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 11:27:44) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
ERROR: Failed to load OrgFormatter: No module named 'tabulate'

In [1]: