Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using click library in jupyter notebook cell

Is there a way to use the click library in a Jupyter notebook cell? I would like to pass flags to my Jupyter notebook code, within the notebook, to make it smoother transiting to a stand alone script. For instance, using OptionParser from a Jupyter notebook cell:

from optparse import OptionParser
import sys


def main():
    parser = OptionParser()
    parser.add_option('-f', '--fake',
                    default='False',
                help='Fake data')
    (options,args) = parser.parse_args()
    print('options:{} args: {}'.format(options, args))
    if options.fake:
        print('Fake detected')

def test_args():

    print('hello')

if __name__ == '__main__':

    sys.argv = ['--fake', 'True' '--help']
    main()

output: options:{'fake': 'False'} args: ['True--help'] Fake detected

Using the click library, I get a string of errors. I ran this code from a Jupyter notebook cell:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
            help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

Ouput (truncated):

UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-6-ad31be7bf0fe> in <module>()
    12 if __name__ == '__main__':
    13     sys.argv = ['--count', '3']
---> 14     hello()

~/.local/lib/python3.6/site-packages/click/core.py in __call__(self, *args, **kwargs)
    720     def __call__(self, *args, **kwargs):
    721         """Alias for :meth:`main`."""
--> 722         return self.main(*args, **kwargs)
    723 
    724 
...
257 
    258     if message:
--> 259         file.write(message)
    260     file.flush()
    261 

UnsupportedOperation: not writable
like image 645
Oppy Avatar asked Dec 14 '17 18:12

Oppy


People also ask

How do you select specific cells in a Jupyter Notebook?

Select Multiple Cells: Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up . Once cells are selected, you can then delete / copy / cut / paste / run them as a batch.

What does %% do in Jupyter Notebook?

Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.

What is %% capture in Python?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. from __future__ import print_function import sys. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.


1 Answers

You can use the %%python magic command to start a new Python propcess:

%%python

import sys
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
            help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    with open('echo.txt', 'w') as fobj:
        for x in range(count):
            click.echo('Hello %s!' % name)

if __name__ == '__main__':
    # first element is the script name, use empty string instead
    sys.argv = ['', '--name', 'Max', '--count', '3']
    hello()

Output:

Hello Max!
Hello Max!
Hello Max!
like image 143
Mike Müller Avatar answered Sep 29 '22 15:09

Mike Müller