Using click library in jupyter laptop cell

Is there a way to use the click library in a cell in a Jupyter laptop? I would like to pass the checkboxes into my Jupyter laptop code, in notepad, to make it more smooth transition to a stand-alone script. For example, using OptionParser from a Jupyter laptop 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()

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

Using the click library, I get an error string. I ran this code from Jupyter's laptop 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()

Output (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
+4
source share
2 answers

You can use the magic command %%pythonto launch the new Python propeller:

%%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()

Conclusion:

Hello Max!
Hello Max!
Hello Max!
+1
source

Jupyter stdout/stderr/stdin. , import sys; type(sys.stdin), ipykernel.iostream.OutStream. , jupyter click , - sys.stdout .

def monkey_patch_jupyter_click_sreams():
    """see https://stackoverflow.com/a/49595790/221742 ."""
    import sys
    import ipykernel
    import click  
    if not click._compat.PY2 and isinstance(sys.stdout, ipykernel.iostream.OutStream):
        click._compat._force_correct_text_writer = lambda stream, encoding, errors: stream

monkey_patch_jupyter_click_sreams()
# your code here
hello()

, stdout stdout._buffer. , stdout ipythons ipykernel.iostream.OutStream.

+1

Source: https://habr.com/ru/post/1690804/


All Articles