Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Some IPython tricks

Some IPython tricks

English version of talk presented at local Python user group in Florianopolis

Elias Dorneles

January 20, 2016
Tweet

More Decks by Elias Dorneles

Other Decks in Programming

Transcript

  1. View Slide

  2. View Slide

  3. X

    View Slide

  4. $ ipython profile create
    [ProfileCreate] Generating default config file: u'~/.
    ipython/profile_default/ipython_config.py'
    $ vim ~/.ipython/profile_default/ipython_config.py
    c = get_config()
    c.TerminalIPythonApp.display_banner = False
    c.TerminalInteractiveShell.colors = 'Linux'
    c.TerminalInteractiveShell.separate_in = ''
    c.TerminalInteractiveShell.confirm_exit = False
    c.TerminalInteractiveShell.term_title = True
    c.PromptManager.out_template = ''
    c.PromptManager.in2_template = ' '
    c.PromptManager.in_template = '>>> '
    $ ipython
    >>> print '\o/'
    \o/

    View Slide

  5. View Slide

  6. >>> from json import
    JSONDecoder _default_encoder dumps loads
    JSONEncoder decoder encoder scanner
    _default_decoder dump load tool
    >>> from json import dump
    dump dumps
    >>> from xml.
    xml.dom xml.etree xml.parsers xml.sax
    >>> from xml.dom.
    xml.dom.NodeFilter xml.dom.expatbuilder xml.dom.minidom xml.dom.xmlbuilder
    xml.dom.domreg xml.dom.minicompat xml.dom.pulldom

    View Slide

  7. >>> d = {
    'url': 'http://news.ycombinator.com',
    'title': 'Hacker News',
    'last_visit': '2016-01-17'
    }
    >>> d[
    d['last_visit'] d['title'] d['url']
    >>> d['url']
    'http://news.ycombinator.com'

    View Slide

  8. >>> l = ["hello", [1, 2, 3]]
    >>> l[0].
    l[0].capitalize l[0].isalnum l[0].lstrip l[0].splitlines
    l[0].center l[0].isalpha l[0].partition l[0].startswith
    l[0].count l[0].isdigit l[0].replace l[0].strip
    l[0].decode l[0].islower l[0].rfind l[0].swapcase
    l[0].encode l[0].isspace l[0].rindex l[0].title
    ...
    >>> l[1].
    l[1].append l[1].extend l[1].insert l[1].remove l[1].sort
    l[1].count l[1].index l[1].pop l[1].reverse
    >>> '1,2,3'.split(',').
    '1,2,3'.split(',').append '1,2,3'.split(',').pop
    '1,2,3'.split(',').count '1,2,3'.split(',').remove
    '1,2,3'.split(',').extend '1,2,3'.split(',').reverse
    ...
    Enable greedy completion in profile:
    c.IPCompleter.greedy = True

    View Slide

  9. View Slide

  10. >>> import os
    >>> os.path.join?
    Type: function
    String form:
    File: /usr/lib/python2.7/posixpath.py
    Definition: os.path.join(a, *p)
    Docstring:
    Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded. An empty last part will result in a path that
    ends with a separator.
    >>>

    View Slide

  11. >>> os.path.join??
    Type: function
    String form:
    File: /usr/lib/python2.7/posixpath.py
    Definition: os.path.join(a, *p)
    Source:
    def join(a, *p):
    """Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded. An empty last part will result in a path that
    ends with a separator."""
    path = a
    for b in p:
    <... resto do código omitido ...>

    View Slide

  12. View Slide

  13. >>> 12 + 22
    34
    >>> 13 + 9 + 4
    26
    >>> _ + __
    60
    >>> result = _ # no need to re-run code =)

    View Slide

  14. >>> 12 + 22
    34
    >>> 13 + 9 + 4
    26
    >>> _ + __
    60
    >>> result = _ # no need to re-run code =)
    >>> _1
    34
    >>> _2
    26

    View Slide

  15. c.TerminalInteractiveShell.cache_size = 0
    The above setting disables _
    _, __ and ___ will still work
    Ref: https://ipython.org/ipython-doc/3/interactive/reference.html#output-caching-system

    View Slide

  16. View Slide

  17. >>> lista = list(range(1000))
    >>> %timeit map(str, lista)
    10000 loops, best of 3: 74.5 µs per
    loop
    >>> %timeit [str(l) for l in lista]
    10000 loops, best of 3: 121 µs per loop
    >>>
    >>> import math
    >>> %time math.sqrt(3.456)
    CPU times: user 0 ns, sys: 0 ns, total:
    0 ns
    Wall time: 13.1 µs
    1.85903200617956
    %time runs only once and shows
    the result
    (much like the Bash time builtin)

    View Slide

  18. View Slide

  19. >>> import os
    >>> bashrc = os.path.expanduser('~/.
    bashrc')
    >>> open(bashrc, 'w').write('echo
    muhaha')
    >>> %hist
    import os
    bashrc = os.path.expanduser('~/.
    bashrc')
    open(bashrc, 'w').write('echo muhaha')
    %hist
    >>> %hist -f arquivo.py
    >>> # or yet:
    >>> %save arquivo.py 1-3

    View Slide






  20. View Slide

  21. View Slide

  22. >>> def double_loop(collection):
    ...: for e in collection:
    ...: print(e)
    ...: for e in collection:
    ...: print(e)
    ...:
    File "", line 4
    for e in collection:
    ^
    IndentationError: unindent does not match any outer indentation level
    If you want to paste code into IPython, try the %paste and %cpaste magic functions.
    >>>

    View Slide

  23. >>> %paste
    def double_loop(collection):
    for e in collection:
    print(e)
    for e in collection:
    print(e)
    ## -- End pasted text --
    >>>
    Works like Ctrl-V or Cmd-
    V, but doesn’t always work
    -- it needs bindings to
    desktop libraries

    View Slide

  24. >>> %autoindent
    Automatic indentation is: OFF
    >>> def double_loop(collection):
    ....: for e in collection:
    ....: print(e)
    ....: for e in collection:
    ....: print(e)
    ....:
    >>>

    View Slide

  25. >>> %cpaste
    Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
    :

    View Slide

  26. >>> %cpaste
    Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
    :def loop_duplo(collection):
    : for e in collection:
    : print(e)
    : for e in collection:
    : print(e)
    :
    :
    >>>

    View Slide

  27. View Slide

  28. >>> >>> import math
    >>> >>> for n in [9, 6, 25]:
    ....: ...: print(math.sqrt(n))
    ....: ...:
    3.0
    2.44948974278
    5.0
    >>>
    Note how the extra markup got
    ignored

    View Slide

  29. View Slide

  30. (env)$ ipython
    WARNING: Attempting to work in a virtualenv. If
    you encounter problems, please install IPython
    inside the virtualenv.
    (env)$ pip install ipython
    (env)$ ipython
    WARNING: Attempting to work in a virtualenv. If
    you encounter problems, please install IPython
    inside the virtualenv.
    (env)$ hash -r
    (env)$ ipython
    >>> print "Yay!"
    Yay!

    View Slide

  31. View Slide

  32. >>> !ls
    a.out file1.txt file2.txt
    >>> files = !ls
    >>> files
    ['a.out', 'file1.txt', 'file2.txt']
    >>> files.s
    'a.out file1.txt file2.txt'
    >>> files.grep('\d')
    ['file1.txt', 'file2.txt']

    View Slide

  33. View Slide

  34. from IPython import embed; embed()

    View Slide

  35. Questions?

    View Slide