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

Dfd7b9492f5c5e49dca373bfdd7a3b1a?s=128

Elias Dorneles

January 20, 2016
Tweet

More Decks by Elias Dorneles

Other Decks in Programming

Transcript

  1. None
  2. None
  3. X

  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/
  5. None
  6. >>> from json import <TAB> JSONDecoder _default_encoder dumps loads JSONEncoder

    decoder encoder scanner _default_decoder dump load tool >>> from json import dump<TAB> dump dumps >>> from xml.<TAB> xml.dom xml.etree xml.parsers xml.sax >>> from xml.dom.<TAB> xml.dom.NodeFilter xml.dom.expatbuilder xml.dom.minidom xml.dom.xmlbuilder xml.dom.domreg xml.dom.minicompat xml.dom.pulldom
  7. >>> d = { 'url': 'http://news.ycombinator.com', 'title': 'Hacker News', 'last_visit':

    '2016-01-17' } >>> d[<TAB> d['last_visit'] d['title'] d['url'] >>> d['ur<TAB>l'] 'http://news.ycombinator.com'
  8. >>> l = ["hello", [1, 2, 3]] >>> l[0].<TAB> 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].<TAB> 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(',').<TAB> '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
  9. None
  10. >>> import os >>> os.path.join? Type: function String form: <function

    join at 0x7f8bb58a4f50> 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. >>>
  11. >>> os.path.join?? Type: function String form: <function join at 0x7f8bb58a4f50>

    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 ...>
  12. None
  13. >>> 12 + 22 34 >>> 13 + 9 +

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

    4 26 >>> _ + __ 60 >>> result = _ # no need to re-run code =) >>> _1 34 >>> _2 26
  15. c.TerminalInteractiveShell.cache_size = 0 The above setting disables _<NUMBER> _, __

    and ___ will still work Ref: https://ipython.org/ipython-doc/3/interactive/reference.html#output-caching-system
  16. None
  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)
  18. None
  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
  20. ◦ ◦ ◦ ◦ ◦

  21. None
  22. >>> def double_loop(collection): ...: for e in collection: ...: print(e)

    ...: for e in collection: ...: print(e) ...: File "<ipython-input-8-17a426f52fc3>", 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. >>>
  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
  24. >>> %autoindent Automatic indentation is: OFF >>> def double_loop(collection): ....:

    for e in collection: ....: print(e) ....: for e in collection: ....: print(e) ....: >>>
  25. >>> %cpaste Pasting code; enter '--' alone on the line

    to stop or use Ctrl-D. :
  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) : :<EOF> >>>
  27. None
  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
  29. None
  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!
  31. None
  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']
  33. None
  34. from IPython import embed; embed()

  35. Questions?