├── IPython ├── core │ ├── __init__.py │ ├── tests │ │ ├── __init__.py │ │ ├── print_argv.py │ │ ├── 2x2.jpg │ │ ├── 2x2.png │ │ ├── nonascii.py │ │ ├── nonascii2.py │ │ ├── bad_all.py │ │ ├── daft_extension │ │ │ └── daft_extension.py │ │ ├── simpleerr.py │ │ ├── test_page.py │ │ ├── test_logger.py │ │ ├── test_prompts.py │ │ ├── tclass.py │ │ ├── test_imports.py │ │ ├── test_splitinput.py │ │ ├── refbug.py │ │ ├── test_events.py │ │ ├── test_autocall.py │ │ ├── test_alias.py │ │ └── test_shellapp.py │ ├── profile │ │ └── README_STARTUP │ ├── prompts.py │ ├── getipython.py │ ├── payloadpage.py │ ├── magics │ │ └── __init__.py │ ├── macro.py │ ├── error.py │ ├── payload.py │ ├── autocall.py │ └── display_trap.py ├── terminal │ ├── __init__.py │ ├── tests │ │ ├── __init__.py │ │ └── test_help.py │ ├── pt_inputhooks │ │ ├── gtk3.py │ │ ├── __init__.py │ │ └── qt.py │ ├── ptshell.py │ └── console.py ├── utils │ ├── __init__.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_decorators.py │ │ ├── test_shimmodule.py │ │ ├── test_sysinfo.py │ │ ├── test_imports.py │ │ ├── test_tempdir.py │ │ ├── test_importstring.py │ │ ├── test_openpy.py │ │ ├── test_dir2.py │ │ └── test_pycolorize.py │ ├── _sysinfo.py │ ├── log.py │ ├── eventful.py │ ├── jsonutil.py │ ├── pickleutil.py │ ├── traitlets.py │ ├── daemonize.py │ ├── localinterfaces.py │ ├── signatures.py │ ├── sentinel.py │ ├── ulinecache.py │ ├── colorable.py │ ├── generics.py │ ├── importstring.py │ ├── data.py │ ├── version.py │ ├── tz.py │ ├── syspathcontext.py │ ├── tempdir.py │ ├── strdispatch.py │ ├── process.py │ ├── contexts.py │ ├── decorators.py │ └── dir2.py ├── lib │ ├── tests │ │ ├── __init__.py │ │ ├── test.wav │ │ ├── test_imports.py │ │ ├── test_clipboard.py │ │ ├── test_security.py │ │ ├── test_editorhooks.py │ │ └── test_deepreload.py │ ├── kernel.py │ ├── __init__.py │ ├── inputhookgtk3.py │ ├── inputhookgtk.py │ └── clipboard.py ├── sphinxext │ ├── __init__.py │ └── ipython_console_highlighting.py ├── extensions │ ├── tests │ │ ├── __init__.py │ │ └── test_storemagic.py │ ├── __init__.py │ ├── rmagic.py │ ├── cythonmagic.py │ └── sympyprinting.py ├── testing │ ├── plugin │ │ ├── __init__.py │ │ ├── simplevars.py │ │ ├── show_refs.py │ │ ├── iptest.py │ │ ├── setup.py │ │ ├── simple.py │ │ ├── test_example.txt │ │ ├── test_exampleip.txt │ │ ├── test_refs.py │ │ ├── test_combo.txt │ │ ├── README.txt │ │ ├── Makefile │ │ └── test_ipdoctest.py │ ├── __main__.py │ ├── tests │ │ └── __init__.py │ ├── skipdoctest.py │ └── __init__.py ├── kernel │ ├── adapter.py │ ├── channels.py │ ├── client.py │ ├── launcher.py │ ├── manager.py │ ├── threaded.py │ ├── clientabc.py │ ├── kernelspec.py │ ├── managerabc.py │ ├── restarter.py │ ├── channelsabc.py │ ├── kernelspecapp.py │ ├── multikernelmanager.py │ ├── connect.py │ ├── __main__.py │ └── __init__.py ├── external │ ├── __init__.py │ ├── decorators │ │ ├── __init__.py │ │ └── _numpy_testing_noseclasses.py │ └── mathjax.py ├── consoleapp.py ├── __main__.py ├── display.py ├── config.py ├── nbformat.py ├── nbconvert.py ├── parallel.py ├── qt.py ├── html.py └── frontend.py ├── docs ├── source │ ├── whatsnew │ │ ├── pr │ │ │ ├── antigravity-feature.rst │ │ │ ├── incompat-switching-to-perl.rst │ │ │ ├── magic-run-bug-fix.md │ │ │ ├── jedi-signature.rst │ │ │ ├── env-config.rst │ │ │ ├── interactive_assignment.rst │ │ │ └── README.md │ │ ├── development.rst │ │ ├── version0.8.rst │ │ ├── index.rst │ │ └── github-stats-6.rst │ ├── _static │ │ ├── logo.png │ │ └── favicon.ico │ ├── _images │ │ ├── qtconsole.png │ │ ├── 2.0 │ │ │ ├── running.png │ │ │ ├── treeview.png │ │ │ ├── widgets.png │ │ │ ├── running-crop.png │ │ │ └── user-interface.png │ │ ├── ipy_013_par_tb.png │ │ ├── ipy_013_dashboard.png │ │ ├── ms_visual_studio.png │ │ ├── notebook_specgram.png │ │ ├── ptshell_features.png │ │ ├── qtconsole_tabbed.png │ │ ├── ipython-6-screenshot.png │ │ ├── unicode_completion.png │ │ ├── jedi_type_inference_60.png │ │ ├── ipy_013_dashboard_cluster.png │ │ ├── ipy_013_notebook_long_out.png │ │ ├── ipy_013_notebook_rmagic.png │ │ ├── ipy_013_notebook_tooltip.png │ │ ├── ipy_013_qtconsole_baboon.png │ │ ├── ipy_013_qtconsole_completer.png │ │ ├── kernel_selector_screenshot.png │ │ ├── ipy_013_notebook_cythonmagic.png │ │ ├── ipy_013_notebook_octavemagic.png │ │ ├── ipy_013_notebook_script_cells.png │ │ └── ipy_013_notebook_spectrogram.png │ ├── interactive │ │ ├── figs │ │ │ ├── besselj.png │ │ │ └── colors_dark.png │ │ ├── index.rst │ │ └── magics.rst │ ├── development │ │ ├── figs │ │ │ ├── other_kernels.png │ │ │ └── ipy_kernel_and_terminal.png │ │ ├── messaging.rst │ │ ├── kernels.rst │ │ ├── parallel_messages.rst │ │ ├── parallel_connections.rst │ │ ├── index.rst │ │ ├── pycompat.rst │ │ └── inputhook_app.rst │ ├── config │ │ ├── extensions │ │ │ ├── autoreload.rst │ │ │ └── storemagic.rst │ │ ├── options │ │ │ └── index.rst │ │ ├── index.rst │ │ ├── shortcuts │ │ │ └── index.rst │ │ └── integrating.rst │ ├── about │ │ ├── index.rst │ │ └── history.rst │ ├── api │ │ └── index.rst │ ├── parallel │ │ └── index.rst │ ├── _templates │ │ └── notebook_redirect.html │ └── install │ │ └── index.rst ├── requirements.txt ├── autogen_config.py ├── README.rst ├── sphinxext │ └── magics.py ├── autogen_magics.py └── man │ └── ipython.1 ├── examples ├── IPython Kernel │ ├── nbpackage │ │ ├── __init__.py │ │ ├── nbs │ │ │ ├── __init__.py │ │ │ └── other.ipynb │ │ └── mynotebook.ipynb │ ├── ipython.desktop │ ├── gui │ │ ├── gui-tk.py │ │ ├── gui-pyglet.py │ │ ├── gui-gtk3.py │ │ ├── gui-gtk.py │ │ ├── gui-qt.py │ │ └── gui-glut.py │ ├── ipython-get-history.py │ └── example-demo.py ├── images │ ├── animation.m4v │ ├── FrontendKernel.png │ ├── ipython_logo.png │ └── FrontendKernel.graffle │ │ └── image1.png ├── utils │ ├── list_pyfiles.ipy │ ├── list_subdirs.ipy │ └── cwd_prompt.py ├── Embedding │ ├── embed_function.py │ └── embed_class_short.py └── Index.ipynb ├── scripts ├── ipython.ico └── ipython_nb.ico ├── setupext └── __init__.py ├── .gitattributes ├── codecov.yml ├── setupegg.py ├── tools ├── tests │ ├── embed │ │ ├── embed2.py │ │ ├── embed1.py │ │ ├── embed_flufl.py │ │ ├── embed_no_flufl.py │ │ └── embed3.py │ ├── inline_figshow.py │ └── heartbeat │ │ ├── hb_gil.py │ │ └── gilsleep.ipynb ├── testupload ├── build_release ├── make_tarball.py ├── alldeps │ └── pkginstall.cfg ├── mknbindex.py ├── check_sources.py └── toollib.py ├── .gitignore ├── MANIFEST.in ├── appveyor.yml ├── tox.ini ├── .travis.yml └── CONTRIBUTING.md /IPython/core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/terminal/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/core/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/lib/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/sphinxext/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/utils/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/extensions/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/terminal/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/testing/plugin/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/antigravity-feature.rst: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/IPython Kernel/nbpackage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/IPython Kernel/nbpackage/nbs/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/incompat-switching-to-perl.rst: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /IPython/kernel/adapter.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.adapter import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/channels.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.channels import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/client.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.client import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/launcher.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.launcher import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/manager.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.manager import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/threaded.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.threaded import * 2 | -------------------------------------------------------------------------------- /IPython/testing/plugin/simplevars.py: -------------------------------------------------------------------------------- 1 | x = 1 2 | print('x is:',x) 3 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | ipykernel 3 | setuptools>=18.5 4 | -------------------------------------------------------------------------------- /IPython/core/tests/print_argv.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print(sys.argv[1:]) 3 | -------------------------------------------------------------------------------- /IPython/kernel/clientabc.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.clientabc import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/kernelspec.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.kernelspec import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/managerabc.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.managerabc import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/restarter.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.restarter import * 2 | -------------------------------------------------------------------------------- /IPython/utils/_sysinfo.py: -------------------------------------------------------------------------------- 1 | # GENERATED BY setup.py 2 | commit = u"" 3 | -------------------------------------------------------------------------------- /IPython/kernel/channelsabc.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.channelsabc import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/kernelspecapp.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.kernelspecapp import * 2 | -------------------------------------------------------------------------------- /IPython/kernel/multikernelmanager.py: -------------------------------------------------------------------------------- 1 | from jupyter_client.multikernelmanager import * 2 | -------------------------------------------------------------------------------- /scripts/ipython.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/scripts/ipython.ico -------------------------------------------------------------------------------- /IPython/kernel/connect.py: -------------------------------------------------------------------------------- 1 | from ipykernel.connect import * 2 | from jupyter_client.connect import * 3 | -------------------------------------------------------------------------------- /scripts/ipython_nb.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/scripts/ipython_nb.ico -------------------------------------------------------------------------------- /IPython/core/tests/2x2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/IPython/core/tests/2x2.jpg -------------------------------------------------------------------------------- /IPython/core/tests/2x2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/IPython/core/tests/2x2.png -------------------------------------------------------------------------------- /IPython/lib/tests/test.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/IPython/lib/tests/test.wav -------------------------------------------------------------------------------- /docs/source/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_static/logo.png -------------------------------------------------------------------------------- /examples/images/animation.m4v: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/examples/images/animation.m4v -------------------------------------------------------------------------------- /IPython/core/tests/nonascii.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/IPython/core/tests/nonascii.py -------------------------------------------------------------------------------- /IPython/extensions/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """This directory is meant for IPython extensions.""" 3 | -------------------------------------------------------------------------------- /docs/source/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_static/favicon.ico -------------------------------------------------------------------------------- /docs/source/_images/qtconsole.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/qtconsole.png -------------------------------------------------------------------------------- /examples/images/FrontendKernel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/examples/images/FrontendKernel.png -------------------------------------------------------------------------------- /examples/images/ipython_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/examples/images/ipython_logo.png -------------------------------------------------------------------------------- /setupext/__init__.py: -------------------------------------------------------------------------------- 1 | # load extended setup modules for distuils 2 | 3 | from .install_data_ext import install_data_ext 4 | -------------------------------------------------------------------------------- /docs/source/_images/2.0/running.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/2.0/running.png -------------------------------------------------------------------------------- /docs/source/_images/2.0/treeview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/2.0/treeview.png -------------------------------------------------------------------------------- /docs/source/_images/2.0/widgets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/2.0/widgets.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_par_tb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_par_tb.png -------------------------------------------------------------------------------- /IPython/kernel/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | from ipykernel import kernelapp as app 3 | app.launch_new_instance() 4 | -------------------------------------------------------------------------------- /docs/source/_images/2.0/running-crop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/2.0/running-crop.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_dashboard.png -------------------------------------------------------------------------------- /docs/source/_images/ms_visual_studio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ms_visual_studio.png -------------------------------------------------------------------------------- /docs/source/_images/notebook_specgram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/notebook_specgram.png -------------------------------------------------------------------------------- /docs/source/_images/ptshell_features.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ptshell_features.png -------------------------------------------------------------------------------- /docs/source/_images/qtconsole_tabbed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/qtconsole_tabbed.png -------------------------------------------------------------------------------- /docs/source/interactive/figs/besselj.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/interactive/figs/besselj.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | IPython/.git_commit_info.ini export-subst 2 | * text=auto 3 | *.py diff=python 4 | *.js diff=javascript 5 | *.html diff=html 6 | -------------------------------------------------------------------------------- /IPython/testing/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | from IPython.testing import iptestcontroller 3 | iptestcontroller.main() 4 | -------------------------------------------------------------------------------- /docs/source/_images/2.0/user-interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/2.0/user-interface.png -------------------------------------------------------------------------------- /docs/source/_images/ipython-6-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipython-6-screenshot.png -------------------------------------------------------------------------------- /docs/source/_images/unicode_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/unicode_completion.png -------------------------------------------------------------------------------- /docs/source/interactive/figs/colors_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/interactive/figs/colors_dark.png -------------------------------------------------------------------------------- /docs/source/_images/jedi_type_inference_60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/jedi_type_inference_60.png -------------------------------------------------------------------------------- /docs/source/development/figs/other_kernels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/development/figs/other_kernels.png -------------------------------------------------------------------------------- /IPython/external/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This package contains all third-party modules bundled with IPython. 3 | """ 4 | 5 | __all__ = ["simplegeneric"] 6 | -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_dashboard_cluster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_dashboard_cluster.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_long_out.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_long_out.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_rmagic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_rmagic.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_tooltip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_tooltip.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_qtconsole_baboon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_qtconsole_baboon.png -------------------------------------------------------------------------------- /examples/images/FrontendKernel.graffle/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/examples/images/FrontendKernel.graffle/image1.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_qtconsole_completer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_qtconsole_completer.png -------------------------------------------------------------------------------- /docs/source/_images/kernel_selector_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/kernel_selector_screenshot.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_cythonmagic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_cythonmagic.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_octavemagic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_octavemagic.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_script_cells.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_script_cells.png -------------------------------------------------------------------------------- /docs/source/_images/ipy_013_notebook_spectrogram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/_images/ipy_013_notebook_spectrogram.png -------------------------------------------------------------------------------- /IPython/utils/log.py: -------------------------------------------------------------------------------- 1 | 2 | from warnings import warn 3 | 4 | warn("IPython.utils.log has moved to traitlets.log", stacklevel=2) 5 | 6 | from traitlets.log import * 7 | -------------------------------------------------------------------------------- /docs/source/development/figs/ipy_kernel_and_terminal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drdarshan/ipython/master/docs/source/development/figs/ipy_kernel_and_terminal.png -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/magic-run-bug-fix.md: -------------------------------------------------------------------------------- 1 | Make ``%run -n -i ...`` work correctly. Earlier, if ``%run`` was passed both arguments, ``-n`` would be silently ignored. 2 | -------------------------------------------------------------------------------- /IPython/core/tests/nonascii2.py: -------------------------------------------------------------------------------- 1 | # coding: iso-8859-5 2 | # (Unlikely to be the default encoding for most testers.) 3 | # БЖџрстуфхцчшщъыьэюя <- Cyrillic characters 4 | 'Ўт№Ф' 5 | -------------------------------------------------------------------------------- /docs/source/config/extensions/autoreload.rst: -------------------------------------------------------------------------------- 1 | .. _extensions_autoreload: 2 | 3 | ========== 4 | autoreload 5 | ========== 6 | 7 | .. automodule:: IPython.extensions.autoreload 8 | -------------------------------------------------------------------------------- /IPython/utils/eventful.py: -------------------------------------------------------------------------------- 1 | 2 | from warnings import warn 3 | 4 | warn("IPython.utils.eventful has moved to traitlets.eventful", stacklevel=2) 5 | 6 | from traitlets.eventful import * 7 | -------------------------------------------------------------------------------- /IPython/utils/jsonutil.py: -------------------------------------------------------------------------------- 1 | from warnings import warn 2 | 3 | warn("IPython.utils.jsonutil has moved to jupyter_client.jsonutil", stacklevel=2) 4 | 5 | from jupyter_client.jsonutil import * 6 | -------------------------------------------------------------------------------- /IPython/utils/pickleutil.py: -------------------------------------------------------------------------------- 1 | from warnings import warn 2 | 3 | warn("IPython.utils.pickleutil has moved to ipykernel.pickleutil", stacklevel=2) 4 | 5 | from ipykernel.pickleutil import * 6 | -------------------------------------------------------------------------------- /IPython/utils/traitlets.py: -------------------------------------------------------------------------------- 1 | 2 | from warnings import warn 3 | 4 | warn("IPython.utils.traitlets has moved to a top-level traitlets package.", stacklevel=2) 5 | 6 | from traitlets import * 7 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: 5 | target: auto 6 | threshold: 10 7 | patch: 8 | default: 9 | target: 0% 10 | -------------------------------------------------------------------------------- /IPython/utils/daemonize.py: -------------------------------------------------------------------------------- 1 | from warnings import warn 2 | 3 | warn("IPython.utils.daemonize has moved to ipyparallel.apps.daemonize", stacklevel=2) 4 | from ipyparallel.apps.daemonize import daemonize 5 | -------------------------------------------------------------------------------- /docs/source/about/index.rst: -------------------------------------------------------------------------------- 1 | .. _about_index: 2 | 3 | ============= 4 | About IPython 5 | ============= 6 | 7 | .. toctree:: 8 | :maxdepth: 1 9 | 10 | history 11 | license_and_copyright 12 | 13 | -------------------------------------------------------------------------------- /IPython/utils/localinterfaces.py: -------------------------------------------------------------------------------- 1 | from warnings import warn 2 | 3 | warn("IPython.utils.localinterfaces has moved to jupyter_client.localinterfaces", stacklevel=2) 4 | 5 | from jupyter_client.localinterfaces import * 6 | -------------------------------------------------------------------------------- /docs/source/development/messaging.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | Messaging in IPython 4 | ==================== 5 | 6 | The message specification is now part of Jupyter - see 7 | :ref:`jupyterclient:messaging` for the documentation. 8 | -------------------------------------------------------------------------------- /docs/source/config/extensions/storemagic.rst: -------------------------------------------------------------------------------- 1 | .. _extensions_storemagic: 2 | 3 | ========== 4 | storemagic 5 | ========== 6 | 7 | .. automodule:: IPython.extensions.storemagic 8 | 9 | .. automethod:: StoreMagics.store 10 | -------------------------------------------------------------------------------- /examples/utils/list_pyfiles.ipy: -------------------------------------------------------------------------------- 1 | # A simple IPython script that provides Notebook links to .py files in the cwd 2 | 3 | from IPython.display import FileLink, display 4 | files =!ls *.py 5 | for f in files: 6 | display(FileLink(f)) -------------------------------------------------------------------------------- /docs/source/api/index.rst: -------------------------------------------------------------------------------- 1 | .. _api-index: 2 | 3 | ################### 4 | The IPython API 5 | ################### 6 | 7 | .. only:: html 8 | 9 | :Release: |version| 10 | :Date: |today| 11 | 12 | .. include:: generated/gen.txt 13 | -------------------------------------------------------------------------------- /docs/source/development/kernels.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | ========================== 4 | Making kernels for IPython 5 | ========================== 6 | 7 | Kernels are now part of Jupyter - see 8 | :ref:`jupyterclient:kernels` for the documentation. 9 | -------------------------------------------------------------------------------- /examples/utils/list_subdirs.ipy: -------------------------------------------------------------------------------- 1 | # A simple IPython script that lists files in all subdirs 2 | 3 | from IPython.display import FileLinks, display 4 | dirs =!ls -d */ 5 | for d in dirs: 6 | if d != '__pycache__/': 7 | display(FileLinks(d)) -------------------------------------------------------------------------------- /IPython/utils/tests/test_decorators.py: -------------------------------------------------------------------------------- 1 | from IPython.utils import decorators 2 | 3 | def test_flag_calls(): 4 | @decorators.flag_calls 5 | def f(): 6 | pass 7 | 8 | assert not f.called 9 | f() 10 | assert f.called -------------------------------------------------------------------------------- /setupegg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Wrapper to run setup.py using setuptools.""" 3 | 4 | # Import setuptools and call the actual setup 5 | import setuptools 6 | with open('setup.py', 'rb') as f: 7 | exec(compile(f.read(), 'setup.py', 'exec')) 8 | -------------------------------------------------------------------------------- /tools/tests/embed/embed2.py: -------------------------------------------------------------------------------- 1 | """This tests passing a dict for the user_ns at shell instantiation.""" 2 | from IPython import embed 3 | 4 | user_ns = dict(cookie='monster') 5 | embed(user_ns=user_ns, banner1="check 'cookie' present, locals and globals equivalent") 6 | -------------------------------------------------------------------------------- /docs/source/development/parallel_messages.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | ================================ 4 | Messaging for Parallel Computing 5 | ================================ 6 | 7 | IPython parallel has moved to ipyparallel - 8 | see :ref:`ipyparallel:parallel_messages` for the documentation. 9 | -------------------------------------------------------------------------------- /tools/tests/embed/embed1.py: -------------------------------------------------------------------------------- 1 | """This tests standard embedding, automatically detecting the module and 2 | local namespaces.""" 3 | 4 | f = set([1,2,3,4,5]) 5 | 6 | def bar(foo): 7 | import IPython 8 | IPython.embed(banner1='check f in globals, foo in locals') 9 | 10 | bar(f) 11 | -------------------------------------------------------------------------------- /IPython/core/tests/bad_all.py: -------------------------------------------------------------------------------- 1 | """Module with bad __all__ 2 | 3 | To test https://github.com/ipython/ipython/issues/9678 4 | """ 5 | 6 | def evil(): 7 | pass 8 | 9 | def puppies(): 10 | pass 11 | 12 | __all__ = [evil, # Bad 13 | 'puppies', # Good 14 | ] 15 | -------------------------------------------------------------------------------- /docs/source/parallel/index.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | .. _parallel_index: 4 | 5 | ==================================== 6 | Using IPython for parallel computing 7 | ==================================== 8 | 9 | IPython.parallel has moved to `ipyparallel `_. 10 | -------------------------------------------------------------------------------- /tools/tests/embed/embed_flufl.py: -------------------------------------------------------------------------------- 1 | """This tests that future compiler flags are passed to the embedded IPython.""" 2 | from __future__ import barry_as_FLUFL 3 | from IPython import embed 4 | embed(banner1='', header='check 1 <> 2 == True') 5 | embed(banner1='', header='check 1 <> 2 cause SyntaxError', compile_flags=0) 6 | -------------------------------------------------------------------------------- /docs/source/config/options/index.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | IPython options 3 | =============== 4 | 5 | Any of the options listed here can be set in config files, at the 6 | command line, or from inside IPython. See :ref:`setting_config` for 7 | details. 8 | 9 | .. toctree:: 10 | 11 | terminal 12 | kernel 13 | -------------------------------------------------------------------------------- /docs/source/development/parallel_connections.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | ============================================== 4 | Connection Diagrams of The IPython ZMQ Cluster 5 | ============================================== 6 | 7 | IPython parallel has moved to ipyparallel - 8 | see :ref:`ipyparallel:parallel_connections` for the documentation. 9 | -------------------------------------------------------------------------------- /IPython/external/decorators/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | from numpy.testing.decorators import * 3 | from numpy.testing.noseclasses import KnownFailure 4 | except ImportError: 5 | from ._decorators import * 6 | try: 7 | from ._numpy_testing_noseclasses import KnownFailure 8 | except ImportError: 9 | pass 10 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/jedi-signature.rst: -------------------------------------------------------------------------------- 1 | Terminal IPython will now show the signature of the function while completing. 2 | Only the currently highlighted function will show its signature on the line 3 | below the completer by default. The functionality is recent so might be 4 | limited, we welcome bug report and enhancement request on it. 5 | -------------------------------------------------------------------------------- /tools/tests/embed/embed_no_flufl.py: -------------------------------------------------------------------------------- 1 | """This tests that future compiler flags are passed to the embedded IPython.""" 2 | from IPython import embed 3 | import __future__ 4 | embed(banner1='', header='check 1 <> 2 cause SyntaxError') 5 | embed(banner1='', header='check 1 <> 2 == True', 6 | compile_flags=__future__.barry_as_FLUFL.compiler_flag) 7 | -------------------------------------------------------------------------------- /IPython/terminal/pt_inputhooks/gtk3.py: -------------------------------------------------------------------------------- 1 | """prompt_toolkit input hook for GTK 3 2 | """ 3 | 4 | from gi.repository import Gtk, GLib 5 | 6 | def _main_quit(*args, **kwargs): 7 | Gtk.main_quit() 8 | return False 9 | 10 | def inputhook(context): 11 | GLib.io_add_watch(context.fileno(), GLib.IO_IN, _main_quit) 12 | Gtk.main() 13 | -------------------------------------------------------------------------------- /IPython/terminal/ptshell.py: -------------------------------------------------------------------------------- 1 | raise DeprecationWarning("""DEPRECATED: 2 | 3 | After Popular request and decision from the BDFL: 4 | `IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell` 5 | during the beta cycle (after IPython 5.0.beta3) Sorry about that. 6 | 7 | This file will be removed in 5.0 rc or final. 8 | """) 9 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/env-config.rst: -------------------------------------------------------------------------------- 1 | 2 | - IPython now looks for config files in ``{sys.prefix}/etc/ipython`` 3 | for environment-specific configuration. 4 | - Startup files can be found in ``/etc/ipython/startup`` or ``{sys.prefix}/etc/ipython/startup`` 5 | in addition to the profile directory, for system-wide or env-specific startup files. 6 | -------------------------------------------------------------------------------- /IPython/lib/tests/test_imports.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | from IPython.testing import decorators as dec 3 | 4 | def test_import_backgroundjobs(): 5 | from IPython.lib import backgroundjobs 6 | 7 | def test_import_deepreload(): 8 | from IPython.lib import deepreload 9 | 10 | def test_import_demo(): 11 | from IPython.lib import demo 12 | -------------------------------------------------------------------------------- /docs/source/_templates/notebook_redirect.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Notebook docs have moved 5 | 6 | 7 |

The notebook docs have moved here.

8 | 9 | 10 | -------------------------------------------------------------------------------- /examples/Embedding/embed_function.py: -------------------------------------------------------------------------------- 1 | """Embed IPython using the simple embed function rather than the class API.""" 2 | 3 | from IPython import embed 4 | 5 | a = 10 6 | b = 20 7 | 8 | embed(header='First time', banner1='') 9 | 10 | c = 30 11 | d = 40 12 | 13 | try: 14 | raise Exception('adsfasdf') 15 | except: 16 | embed(header='The second time') 17 | -------------------------------------------------------------------------------- /tools/tests/embed/embed3.py: -------------------------------------------------------------------------------- 1 | """This tests passing local_ns and global_ns (for backwards compatibility only) 2 | at activation of an embedded shell.""" 3 | from IPython.terminal.embed import InteractiveShellEmbed 4 | 5 | user_ns = dict(cookie='monster') 6 | ISE = InteractiveShellEmbed(banner1='check cookie in locals, and globals empty') 7 | ISE(local_ns=user_ns, global_ns={}) 8 | -------------------------------------------------------------------------------- /IPython/lib/kernel.py: -------------------------------------------------------------------------------- 1 | """[DEPRECATED] Utilities for connecting to kernels 2 | 3 | Moved to IPython.kernel.connect 4 | """ 5 | 6 | import warnings 7 | warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0," 8 | " and will be removed in IPython 6.0.", 9 | DeprecationWarning 10 | ) 11 | 12 | from ipykernel.connect import * 13 | 14 | -------------------------------------------------------------------------------- /IPython/core/tests/daft_extension/daft_extension.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Useless IPython extension to test installing and loading extensions. 4 | """ 5 | some_vars = {'arq': 185} 6 | 7 | def load_ipython_extension(ip): 8 | # set up simplified quantity input 9 | ip.push(some_vars) 10 | 11 | def unload_ipython_extension(ip): 12 | ip.drop_by_id(some_vars) 13 | -------------------------------------------------------------------------------- /IPython/external/mathjax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | `IPython.external.mathjax` is deprecated with IPython 4.0+ 4 | 5 | mathjax is now install by default with the notebook package 6 | 7 | """ 8 | 9 | import sys 10 | 11 | if __name__ == '__main__' : 12 | sys.exit("IPython.external.mathjax is deprecated, Mathjax is now installed by default with the notebook package") 13 | 14 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_shimmodule.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import warnings 3 | 4 | from IPython.utils.shimmodule import ShimWarning 5 | 6 | 7 | def test_shim_warning(): 8 | sys.modules.pop('IPython.config', None) 9 | with warnings.catch_warnings(record=True) as w: 10 | warnings.simplefilter("always") 11 | import IPython.config 12 | assert len(w) == 1 13 | assert issubclass(w[-1].category, ShimWarning) 14 | -------------------------------------------------------------------------------- /IPython/core/profile/README_STARTUP: -------------------------------------------------------------------------------- 1 | This is the IPython startup directory 2 | 3 | .py and .ipy files in this directory will be run *prior* to any code or files specified 4 | via the exec_lines or exec_files configurables whenever you load this profile. 5 | 6 | Files will be run in lexicographical order, so you can control the execution order of files 7 | with a prefix, e.g.:: 8 | 9 | 00-first.py 10 | 50-middle.py 11 | 99-last.ipy 12 | -------------------------------------------------------------------------------- /IPython/consoleapp.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.consoleapp imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | from warnings import warn 8 | 9 | warn("The `IPython.consoleapp` package has been deprecated. " 10 | "You should import from jupyter_client.consoleapp instead.") 11 | 12 | from jupyter_client.consoleapp import * 13 | -------------------------------------------------------------------------------- /IPython/testing/plugin/show_refs.py: -------------------------------------------------------------------------------- 1 | """Simple script to show reference holding behavior. 2 | 3 | This is used by a companion test case. 4 | """ 5 | 6 | import gc 7 | 8 | class C(object): 9 | def __del__(self): 10 | pass 11 | #print 'deleting object...' # dbg 12 | 13 | if __name__ == '__main__': 14 | c = C() 15 | 16 | c_refs = gc.get_referrers(c) 17 | ref_ids = list(map(id,c_refs)) 18 | 19 | print('c referrers:',list(map(type,c_refs))) 20 | -------------------------------------------------------------------------------- /IPython/utils/signatures.py: -------------------------------------------------------------------------------- 1 | """DEPRECATED: Function signature objects for callables. 2 | 3 | Use the standard library version if available, as it is more up to date. 4 | Fallback on backport otherwise. 5 | """ 6 | 7 | import warnings 8 | warnings.warn("{} backport for Python 2 is deprecated in IPython 6, which only supports Python 3".format(__name__), 9 | DeprecationWarning, stacklevel=2) 10 | 11 | from inspect import BoundArguments, Parameter, Signature, signature 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | MANIFEST 2 | build 3 | dist 4 | _build 5 | docs/man/*.gz 6 | docs/source/api/generated 7 | docs/source/config/options 8 | docs/source/interactive/magics-generated.txt 9 | docs/source/config/shortcuts/*.csv 10 | docs/gh-pages 11 | jupyter_notebook/notebook/static/mathjax 12 | jupyter_notebook/static/style/*.map 13 | *.py[co] 14 | __pycache__ 15 | *.egg-info 16 | *~ 17 | *.bak 18 | .ipynb_checkpoints 19 | .tox 20 | .DS_Store 21 | \#*# 22 | .#* 23 | .coverage 24 | *.swp 25 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_sysinfo.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """Test suite for our sysinfo utilities.""" 3 | 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import json 8 | import nose.tools as nt 9 | 10 | from IPython.utils import sysinfo 11 | 12 | 13 | def test_json_getsysinfo(): 14 | """ 15 | test that it is easily jsonable and don't return bytes somewhere. 16 | """ 17 | json.dumps(sysinfo.get_sys_info()) 18 | -------------------------------------------------------------------------------- /examples/IPython Kernel/ipython.desktop: -------------------------------------------------------------------------------- 1 | # If you want ipython to appear in a linux app launcher ("start menu"), install this by doing: 2 | # sudo desktop-file-install ipython.desktop 3 | 4 | [Desktop Entry] 5 | Comment=Enhanced interactive Python shell 6 | Exec=ipython 7 | GenericName[en_US]=IPython 8 | GenericName=IPython 9 | Icon=gnome-netstatus-idle 10 | Name[en_US]=ipython 11 | Name=ipython 12 | Categories=Development;Utility; 13 | StartupNotify=false 14 | Terminal=true 15 | Type=Application 16 | -------------------------------------------------------------------------------- /IPython/utils/sentinel.py: -------------------------------------------------------------------------------- 1 | """Sentinel class for constants with useful reprs""" 2 | 3 | # Copyright (c) IPython Development Team. 4 | # Distributed under the terms of the Modified BSD License. 5 | 6 | class Sentinel(object): 7 | 8 | def __init__(self, name, module, docstring=None): 9 | self.name = name 10 | self.module = module 11 | if docstring: 12 | self.__doc__ = docstring 13 | 14 | 15 | def __repr__(self): 16 | return str(self.module)+'.'+self.name 17 | 18 | -------------------------------------------------------------------------------- /IPython/extensions/rmagic.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | #----------------------------------------------------------------------------- 4 | # Copyright (C) 2012 The IPython Development Team 5 | #----------------------------------------------------------------------------- 6 | 7 | import warnings 8 | 9 | def load_ipython_extension(ip): 10 | """Load the extension in IPython.""" 11 | warnings.warn("The rmagic extension in IPython has moved to " 12 | "`rpy2.ipython`, please see `rpy2` documentation.") 13 | -------------------------------------------------------------------------------- /IPython/__main__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Terminal-based IPython entry point. 3 | """ 4 | #----------------------------------------------------------------------------- 5 | # Copyright (c) 2012, IPython Development Team. 6 | # 7 | # Distributed under the terms of the Modified BSD License. 8 | # 9 | # The full license is in the file COPYING.txt, distributed with this software. 10 | #----------------------------------------------------------------------------- 11 | 12 | from IPython import start_ipython 13 | 14 | start_ipython() 15 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_imports.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | def test_import_coloransi(): 4 | from IPython.utils import coloransi 5 | 6 | def test_import_generics(): 7 | from IPython.utils import generics 8 | 9 | def test_import_ipstruct(): 10 | from IPython.utils import ipstruct 11 | 12 | def test_import_PyColorize(): 13 | from IPython.utils import PyColorize 14 | 15 | def test_import_strdispatch(): 16 | from IPython.utils import strdispatch 17 | 18 | def test_import_wildcard(): 19 | from IPython.utils import wildcard 20 | 21 | -------------------------------------------------------------------------------- /IPython/testing/plugin/iptest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Nose-based test runner. 3 | """ 4 | 5 | from nose.core import main 6 | from nose.plugins.builtin import plugins 7 | from nose.plugins.doctests import Doctest 8 | 9 | from . import ipdoctest 10 | from .ipdoctest import IPDocTestRunner 11 | 12 | if __name__ == '__main__': 13 | print('WARNING: this code is incomplete!') 14 | print() 15 | 16 | pp = [x() for x in plugins] # activate all builtin plugins first 17 | main(testRunner=IPDocTestRunner(), 18 | plugins=pp+[ipdoctest.IPythonDoctest(),Doctest()]) 19 | -------------------------------------------------------------------------------- /IPython/testing/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | __docformat__ = "restructuredtext en" 3 | #------------------------------------------------------------------------------- 4 | # Copyright (C) 2005 Fernando Perez 5 | # Brian E Granger 6 | # Benjamin Ragan-Kelley 7 | # 8 | # Distributed under the terms of the BSD License. The full license is in 9 | # the file COPYING, distributed as part of this software. 10 | #------------------------------------------------------------------------------- 11 | -------------------------------------------------------------------------------- /IPython/testing/plugin/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """A Nose plugin to support IPython doctests. 3 | """ 4 | 5 | from setuptools import setup 6 | 7 | setup(name='IPython doctest plugin', 8 | version='0.1', 9 | author='The IPython Team', 10 | description = 'Nose plugin to load IPython-extended doctests', 11 | license = 'LGPL', 12 | py_modules = ['ipdoctest'], 13 | entry_points = { 14 | 'nose.plugins.0.10': ['ipdoctest = ipdoctest:IPythonDoctest', 15 | 'extdoctest = ipdoctest:ExtensionDoctest', 16 | ], 17 | }, 18 | ) 19 | -------------------------------------------------------------------------------- /docs/source/whatsnew/development.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | Development version 3 | ===================== 4 | 5 | This document describes in-flight development work. 6 | 7 | .. warning:: 8 | 9 | Please do not edit this file by hand (doing so will likely cause merge 10 | conflicts for other Pull Requests). Instead, create a new file in the 11 | `docs/source/whatsnew/pr` folder 12 | 13 | 14 | 15 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. FEATURE INSERTION POINT. 16 | 17 | 18 | Backwards incompatible changes 19 | ------------------------------ 20 | 21 | .. DO NOT EDIT THIS LINE BEFORE RELEASE. INCOMPAT INSERTION POINT. 22 | -------------------------------------------------------------------------------- /docs/source/development/index.rst: -------------------------------------------------------------------------------- 1 | .. _developer_guide: 2 | 3 | ===================================================== 4 | Developer's guide for third party tools and libraries 5 | ===================================================== 6 | 7 | .. important:: 8 | 9 | This guide contains information for developers of third party tools and 10 | libraries that use IPython. Alternatively, documentation for core 11 | **IPython** development can be found in the :doc:`../coredev/index`. 12 | 13 | .. toctree:: 14 | :maxdepth: 1 15 | 16 | how_ipython_works 17 | wrapperkernels 18 | execution 19 | lexer 20 | config 21 | inputhook_app 22 | -------------------------------------------------------------------------------- /IPython/testing/plugin/simple.py: -------------------------------------------------------------------------------- 1 | """Simple example using doctests. 2 | 3 | This file just contains doctests both using plain python and IPython prompts. 4 | All tests should be loaded by nose. 5 | """ 6 | 7 | def pyfunc(): 8 | """Some pure python tests... 9 | 10 | >>> pyfunc() 11 | 'pyfunc' 12 | 13 | >>> import os 14 | 15 | >>> 2+3 16 | 5 17 | 18 | >>> for i in range(3): 19 | ... print(i, end=' ') 20 | ... print(i+1, end=' ') 21 | ... 22 | 0 1 1 2 2 3 23 | """ 24 | return 'pyfunc' 25 | 26 | 27 | def ipyfunc2(): 28 | """Some pure python tests... 29 | 30 | >>> 1+1 31 | 2 32 | """ 33 | return 'pyfunc2' 34 | -------------------------------------------------------------------------------- /tools/tests/inline_figshow.py: -------------------------------------------------------------------------------- 1 | """Manual test for figure.show() in the inline matplotlib backend. 2 | 3 | This script should be loaded for interactive use (via %load) into a qtconsole 4 | or notebook initialized with the inline backend. 5 | 6 | Expected behavior: only *one* copy of the figure is shown. 7 | 8 | 9 | For further details: 10 | https://github.com/ipython/ipython/issues/1612 11 | https://github.com/matplotlib/matplotlib/issues/835 12 | """ 13 | 14 | import numpy as np 15 | import matplotlib.pyplot as plt 16 | 17 | plt.ioff() 18 | x = np.random.uniform(-5, 5, size=(100)) 19 | y = np.random.uniform(-5, 5, size=(100)) 20 | f = plt.figure() 21 | plt.scatter(x, y) 22 | plt.plot(y) 23 | f.show() 24 | -------------------------------------------------------------------------------- /IPython/core/prompts.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Being removed 3 | """ 4 | 5 | class LazyEvaluate(object): 6 | """This is used for formatting strings with values that need to be updated 7 | at that time, such as the current time or working directory.""" 8 | def __init__(self, func, *args, **kwargs): 9 | self.func = func 10 | self.args = args 11 | self.kwargs = kwargs 12 | 13 | def __call__(self, **kwargs): 14 | self.kwargs.update(kwargs) 15 | return self.func(*self.args, **self.kwargs) 16 | 17 | def __str__(self): 18 | return str(self()) 19 | 20 | def __format__(self, format_spec): 21 | return format(self(), format_spec) 22 | -------------------------------------------------------------------------------- /IPython/display.py: -------------------------------------------------------------------------------- 1 | """Public API for display tools in IPython. 2 | """ 3 | 4 | #----------------------------------------------------------------------------- 5 | # Copyright (C) 2012 The IPython Development Team 6 | # 7 | # Distributed under the terms of the BSD License. The full license is in 8 | # the file COPYING, distributed as part of this software. 9 | #----------------------------------------------------------------------------- 10 | 11 | #----------------------------------------------------------------------------- 12 | # Imports 13 | #----------------------------------------------------------------------------- 14 | 15 | from IPython.core.display import * 16 | from IPython.lib.display import * 17 | -------------------------------------------------------------------------------- /docs/source/config/index.rst: -------------------------------------------------------------------------------- 1 | .. _config_index: 2 | 3 | =============================== 4 | Configuration and customization 5 | =============================== 6 | 7 | Configuring IPython 8 | ------------------- 9 | 10 | .. toctree:: 11 | :maxdepth: 2 12 | 13 | intro 14 | options/index 15 | shortcuts/index 16 | details 17 | 18 | .. seealso:: 19 | 20 | :doc:`/development/config` 21 | Technical details of the config system. 22 | 23 | Extending and integrating with IPython 24 | -------------------------------------- 25 | 26 | .. toctree:: 27 | :maxdepth: 2 28 | 29 | extensions/index 30 | integrating 31 | custommagics 32 | inputtransforms 33 | callbacks 34 | eventloops 35 | -------------------------------------------------------------------------------- /tools/testupload: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple upload script to push up into the testing directory a local build 3 | """ 4 | from __future__ import print_function 5 | 6 | from toollib import * 7 | 8 | # Get main ipython dir, this will raise if it doesn't pass some checks 9 | ipdir = get_ipdir() 10 | distdir = pjoin(ipdir, 'dist') 11 | 12 | # Load release info 13 | execfile(pjoin(ipdir, 'IPython','core','release.py')) 14 | 15 | # Build site addresses for file uploads 16 | testing_site = '%s/testing/%s' % (archive, version) 17 | 18 | cd(distdir) 19 | 20 | # Create remote path if it doesn't exist. 21 | sh('ssh %s "mkdir -p %s/testing/%s" ' % (archive_user, archive_dir, version)) 22 | sh('scp * %s' % testing_site) 23 | -------------------------------------------------------------------------------- /IPython/config.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.config imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.config` package has been deprecated since IPython 4.0. " 13 | "You should import from traitlets.config instead.", ShimWarning) 14 | 15 | 16 | # Unconditionally insert the shim into sys.modules so that further import calls 17 | # trigger the custom attribute access above 18 | 19 | sys.modules['IPython.config'] = ShimModule(src='IPython.config', mirror='traitlets.config') 20 | -------------------------------------------------------------------------------- /IPython/nbformat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.nbformat imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.nbformat` package has been deprecated since IPython 4.0. " 13 | "You should import from nbformat instead.", ShimWarning) 14 | 15 | # Unconditionally insert the shim into sys.modules so that further import calls 16 | # trigger the custom attribute access above 17 | 18 | sys.modules['IPython.nbformat'] = ShimModule( 19 | src='IPython.nbformat', mirror='nbformat') 20 | -------------------------------------------------------------------------------- /tools/tests/heartbeat/hb_gil.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run this script in the qtconsole with one of: 3 | 4 | %load hb_gil.py 5 | 6 | or 7 | %run hb_gil.py 8 | 9 | Holding the GIL for too long could disrupt the heartbeat. 10 | 11 | See Issue #1260: https://github.com/ipython/ipython/issues/1260 12 | 13 | """ 14 | 15 | import sys 16 | import time 17 | 18 | from cython import inline 19 | 20 | def gilsleep(t): 21 | """gil-holding sleep with cython.inline""" 22 | code = '\n'.join([ 23 | 'from posix cimport unistd', 24 | 'unistd.sleep(t)', 25 | ]) 26 | while True: 27 | inline(code, quiet=True, t=t) 28 | print(time.time()) 29 | sys.stdout.flush() # this is important 30 | 31 | gilsleep(5) 32 | -------------------------------------------------------------------------------- /IPython/nbconvert.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.nbconvert imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.nbconvert` package has been deprecated since IPython 4.0. " 13 | "You should import from nbconvert instead.", ShimWarning) 14 | 15 | # Unconditionally insert the shim into sys.modules so that further import calls 16 | # trigger the custom attribute access above 17 | 18 | sys.modules['IPython.nbconvert'] = ShimModule( 19 | src='IPython.nbconvert', mirror='nbconvert') 20 | -------------------------------------------------------------------------------- /IPython/parallel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.parallel imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.parallel` package has been deprecated since IPython 4.0. " 13 | "You should import from ipyparallel instead.", ShimWarning) 14 | 15 | # Unconditionally insert the shim into sys.modules so that further import calls 16 | # trigger the custom attribute access above 17 | 18 | sys.modules['IPython.parallel'] = ShimModule( 19 | src='IPython.parallel', mirror='ipyparallel') 20 | 21 | -------------------------------------------------------------------------------- /IPython/core/tests/simpleerr.py: -------------------------------------------------------------------------------- 1 | """Error script. DO NOT EDIT FURTHER! It will break exception doctests!!!""" 2 | import sys 3 | 4 | def div0(): 5 | "foo" 6 | x = 1 7 | y = 0 8 | x/y 9 | 10 | def sysexit(stat, mode): 11 | raise SystemExit(stat, 'Mode = %s' % mode) 12 | 13 | def bar(mode): 14 | "bar" 15 | if mode=='div': 16 | div0() 17 | elif mode=='exit': 18 | try: 19 | stat = int(sys.argv[2]) 20 | except: 21 | stat = 1 22 | sysexit(stat, mode) 23 | else: 24 | raise ValueError('Unknown mode') 25 | 26 | if __name__ == '__main__': 27 | try: 28 | mode = sys.argv[1] 29 | except IndexError: 30 | mode = 'div' 31 | 32 | bar(mode) 33 | -------------------------------------------------------------------------------- /examples/utils/cwd_prompt.py: -------------------------------------------------------------------------------- 1 | """This is an example that shows how to create new prompts for IPython 2 | """ 3 | 4 | from IPython.terminal.prompts import Prompts, Token 5 | import os 6 | 7 | class MyPrompt(Prompts): 8 | 9 | def in_prompt_tokens(self, cli=None): 10 | return [(Token, os.getcwd()), 11 | (Token.Prompt, '>>>')] 12 | 13 | def load_ipython_extension(shell): 14 | new_prompts = MyPrompt(shell) 15 | new_prompts.old_prompts = shell.prompts 16 | shell.prompts = new_prompts 17 | 18 | def unload_ipython_extension(shell): 19 | if not hasattr(shell.prompts, 'old_prompts'): 20 | print("cannot unload") 21 | else: 22 | shell.prompts = shell.prompts.old_prompts 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /IPython/lib/tests/test_clipboard.py: -------------------------------------------------------------------------------- 1 | import nose.tools as nt 2 | 3 | from IPython.core.error import TryNext 4 | from IPython.lib.clipboard import ClipboardEmpty 5 | from IPython.testing.decorators import skip_if_no_x11 6 | 7 | @skip_if_no_x11 8 | def test_clipboard_get(): 9 | # Smoketest for clipboard access - we can't easily guarantee that the 10 | # clipboard is accessible and has something on it, but this tries to 11 | # exercise the relevant code anyway. 12 | try: 13 | a = get_ipython().hooks.clipboard_get() 14 | except ClipboardEmpty: 15 | # Nothing in clipboard to get 16 | pass 17 | except TryNext: 18 | # No clipboard access API available 19 | pass 20 | else: 21 | nt.assert_is_instance(a, str) 22 | -------------------------------------------------------------------------------- /IPython/terminal/console.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.terminal.console imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " 13 | "You should import from jupyter_console instead.", ShimWarning) 14 | 15 | # Unconditionally insert the shim into sys.modules so that further import calls 16 | # trigger the custom attribute access above 17 | 18 | sys.modules['IPython.terminal.console'] = ShimModule( 19 | src='IPython.terminal.console', mirror='jupyter_console') 20 | -------------------------------------------------------------------------------- /IPython/utils/ulinecache.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module has been deprecated since IPython 6.0. 3 | 4 | Wrapper around linecache which decodes files to unicode according to PEP 263. 5 | """ 6 | import functools 7 | import linecache 8 | from warnings import warn 9 | 10 | getline = linecache.getline 11 | 12 | # getlines has to be looked up at runtime, because doctests monkeypatch it. 13 | @functools.wraps(linecache.getlines) 14 | def getlines(filename, module_globals=None): 15 | """ 16 | Deprecated since IPython 6.0 17 | """ 18 | warn(("`IPython.utils.ulinecache.getlines` is deprecated since" 19 | " IPython 6.0 and will be removed in future versions."), 20 | DeprecationWarning, stacklevel=2) 21 | return linecache.getlines(filename, module_globals=module_globals) 22 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-tk.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple Tk example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [5]: %gui tk 7 | 8 | In [6]: %run gui-tk.py 9 | """ 10 | 11 | from tkinter import * 12 | 13 | 14 | class MyApp: 15 | 16 | def __init__(self, root): 17 | frame = Frame(root) 18 | frame.pack() 19 | 20 | self.button = Button(frame, text="Hello", command=self.hello_world) 21 | self.button.pack(side=LEFT) 22 | 23 | def hello_world(self): 24 | print("Hello World!") 25 | 26 | root = Tk() 27 | 28 | app = MyApp(root) 29 | 30 | try: 31 | from IPython.lib.inputhook import enable_gui 32 | enable_gui('tk', root) 33 | except ImportError: 34 | root.mainloop() 35 | -------------------------------------------------------------------------------- /IPython/extensions/cythonmagic.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | **DEPRECATED** 4 | 5 | The cython magic has been integrated into Cython itself, 6 | which is now released in version 0.21. 7 | 8 | cf github `Cython` organisation, `Cython` repo, under the 9 | file `Cython/Build/IpythonMagic.py` 10 | """ 11 | #----------------------------------------------------------------------------- 12 | # Copyright (C) 2010-2011, IPython Development Team. 13 | #----------------------------------------------------------------------------- 14 | 15 | import warnings 16 | 17 | ## still load the magic in IPython 3.x, remove completely in future versions. 18 | def load_ipython_extension(ip): 19 | """Load the extension in IPython.""" 20 | 21 | warnings.warn("""The Cython magic has been moved to the Cython package""") 22 | -------------------------------------------------------------------------------- /IPython/testing/skipdoctest.py: -------------------------------------------------------------------------------- 1 | """Decorators marks that a doctest should be skipped. 2 | 3 | The IPython.testing.decorators module triggers various extra imports, including 4 | numpy and sympy if they're present. Since this decorator is used in core parts 5 | of IPython, it's in a separate module so that running IPython doesn't trigger 6 | those imports.""" 7 | 8 | # Copyright (C) IPython Development Team 9 | # Distributed under the terms of the Modified BSD License. 10 | 11 | 12 | def skip_doctest(f): 13 | """Decorator - mark a function or method for skipping its doctest. 14 | 15 | This decorator allows you to mark a function whose docstring you wish to 16 | omit from testing, while preserving the docstring for introspection, help, 17 | etc.""" 18 | f.skip_doctest = True 19 | return f 20 | -------------------------------------------------------------------------------- /IPython/terminal/tests/test_help.py: -------------------------------------------------------------------------------- 1 | """Test help output of various IPython entry points""" 2 | 3 | # Copyright (c) IPython Development Team. 4 | # Distributed under the terms of the Modified BSD License. 5 | 6 | import IPython.testing.tools as tt 7 | 8 | 9 | def test_ipython_help(): 10 | tt.help_all_output_test() 11 | 12 | def test_profile_help(): 13 | tt.help_all_output_test("profile") 14 | 15 | def test_profile_list_help(): 16 | tt.help_all_output_test("profile list") 17 | 18 | def test_profile_create_help(): 19 | tt.help_all_output_test("profile create") 20 | 21 | def test_locate_help(): 22 | tt.help_all_output_test("locate") 23 | 24 | def test_locate_profile_help(): 25 | tt.help_all_output_test("locate profile") 26 | 27 | def test_trust_help(): 28 | tt.help_all_output_test("trust") 29 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include COPYING.rst 3 | include setupbase.py 4 | include setupegg.py 5 | 6 | graft setupext 7 | 8 | graft scripts 9 | 10 | # Load main dir but exclude things we don't want in the distro 11 | graft IPython 12 | 13 | # Include some specific files and data resources we need 14 | include IPython/.git_commit_info.ini 15 | 16 | # Documentation 17 | graft docs 18 | exclude docs/\#* 19 | exclude docs/man/*.1.gz 20 | 21 | # Examples 22 | graft examples 23 | 24 | # docs subdirs we want to skip 25 | prune docs/build 26 | prune docs/gh-pages 27 | prune docs/dist 28 | 29 | # Patterns to exclude from any directory 30 | global-exclude *~ 31 | global-exclude *.flc 32 | global-exclude *.pyc 33 | global-exclude *.pyo 34 | global-exclude .dircopy.log 35 | global-exclude .git 36 | global-exclude .ipynb_checkpoints 37 | -------------------------------------------------------------------------------- /docs/source/config/shortcuts/index.rst: -------------------------------------------------------------------------------- 1 | ================= 2 | IPython shortcuts 3 | ================= 4 | 5 | Available shortcut in IPython terminal. 6 | 7 | .. warning:: 8 | 9 | This list is automatically generated, and may not hold all the available 10 | shortcut. In particular, it may depends on the version of ``prompt_toolkit`` 11 | installed during the generation of this page. 12 | 13 | 14 | Single Filtered shortcuts 15 | ========================= 16 | 17 | .. csv-table:: 18 | :header: Shortcut,Filter,Description 19 | :widths: 30, 30, 100 20 | :delim: tab 21 | :file: single_filtered.csv 22 | 23 | 24 | Multi Filtered shortcuts 25 | ========================= 26 | 27 | .. csv-table:: 28 | :header: Shortcut,Filter,Description 29 | :widths: 30, 30, 100 30 | :delim: tab 31 | :file: multi_filtered.csv 32 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/interactive_assignment.rst: -------------------------------------------------------------------------------- 1 | IPython can now trigger the display hook on last assignment of cells. 2 | Up until 6.0 the following code wouldn't show the value of the assigned 3 | variable:: 4 | 5 | In[1]: xyz = "something" 6 | # nothing shown 7 | 8 | You would have to actually make it the last statement:: 9 | 10 | In [2]: xyz = "something else" 11 | ... : xyz 12 | Out[2]: "something else" 13 | 14 | With the option ``InteractiveShell.ast_node_interactivity='last_expr_or_assign'`` 15 | you can now do:: 16 | 17 | In [2]: xyz = "something else" 18 | Out[2]: "something else" 19 | 20 | This option can be toggled at runtime with the ``%config`` magic, and will 21 | trigger on assignment ``a = 1``, augmented assignment ``+=``, ``-=``, ``|=`` ... 22 | as well as type annotated assignments: ``a:int = 2``. 23 | -------------------------------------------------------------------------------- /tools/build_release: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """IPython release build script. 3 | """ 4 | import os 5 | from shutil import rmtree 6 | 7 | from toollib import sh, pjoin, get_ipdir, cd, execfile, sdists, buildwheels 8 | 9 | def build_release(): 10 | 11 | # Get main ipython dir, this will raise if it doesn't pass some checks 12 | ipdir = get_ipdir() 13 | cd(ipdir) 14 | 15 | # Load release info 16 | execfile(pjoin('IPython', 'core', 'release.py'), globals()) 17 | 18 | # Cleanup 19 | for d in ['build', 'dist', pjoin('docs', 'build'), pjoin('docs', 'dist'), 20 | pjoin('docs', 'source', 'api', 'generated')]: 21 | if os.path.isdir(d): 22 | rmtree(d) 23 | 24 | # Build source and binary distros 25 | sh(sdists) 26 | buildwheels() 27 | 28 | if __name__ == '__main__': 29 | build_release() 30 | -------------------------------------------------------------------------------- /tools/make_tarball.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple script to create a tarball with proper git info. 3 | """ 4 | 5 | import subprocess 6 | import os 7 | 8 | from toollib import cd, sh 9 | 10 | tag = subprocess.check_output('git describe --tags', shell=True).decode('utf8', 'replace').strip() 11 | base_name = 'ipython-%s' % tag 12 | tar_name = '%s.tgz' % base_name 13 | 14 | # git archive is weird: Even if I give it a specific path, it still won't 15 | # archive the whole tree. It seems the only way to get the whole tree is to cd 16 | # to the top of the tree. There are long threads (since 2007) on the git list 17 | # about this and it still doesn't work in a sensible way... 18 | 19 | cd('..') 20 | git_tpl = 'git archive --format=tar --prefix={0}/ HEAD | gzip > {1}' 21 | sh(git_tpl.format(base_name, tar_name)) 22 | sh('mv {0} tools/'.format(tar_name)) 23 | -------------------------------------------------------------------------------- /IPython/testing/plugin/test_example.txt: -------------------------------------------------------------------------------- 1 | ===================================== 2 | Tests in example form - pure python 3 | ===================================== 4 | 5 | This file contains doctest examples embedded as code blocks, using normal 6 | Python prompts. See the accompanying file for similar examples using IPython 7 | prompts (you can't mix both types within one file). The following will be run 8 | as a test:: 9 | 10 | >>> 1+1 11 | 2 12 | >>> print ("hello") 13 | hello 14 | 15 | More than one example works:: 16 | 17 | >>> s="Hello World" 18 | 19 | >>> s.upper() 20 | 'HELLO WORLD' 21 | 22 | but you should note that the *entire* test file is considered to be a single 23 | test. Individual code blocks that fail are printed separately as ``example 24 | failures``, but the whole file is still counted and reported as one test. 25 | -------------------------------------------------------------------------------- /IPython/qt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.qt imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.qt` package has been deprecated since IPython 4.0. " 13 | "You should import from qtconsole instead.", ShimWarning) 14 | 15 | # Unconditionally insert the shim into sys.modules so that further import calls 16 | # trigger the custom attribute access above 17 | 18 | _console = sys.modules['IPython.qt.console'] = ShimModule( 19 | src='IPython.qt.console', mirror='qtconsole') 20 | 21 | _qt = ShimModule(src='IPython.qt', mirror='qtconsole') 22 | 23 | _qt.console = _console 24 | sys.modules['IPython.qt'] = _qt 25 | -------------------------------------------------------------------------------- /IPython/core/tests/test_page.py: -------------------------------------------------------------------------------- 1 | #----------------------------------------------------------------------------- 2 | # Copyright (C) 2010-2011 The IPython Development Team. 3 | # 4 | # Distributed under the terms of the BSD License. 5 | # 6 | # The full license is in the file COPYING.txt, distributed with this software. 7 | #----------------------------------------------------------------------------- 8 | import io 9 | 10 | # N.B. For the test suite, page.page is overridden (see IPython.testing.globalipapp) 11 | from IPython.core import page 12 | 13 | def test_detect_screen_size(): 14 | """Simple smoketest for page._detect_screen_size.""" 15 | try: 16 | page._detect_screen_size(True, 25) 17 | except (TypeError, io.UnsupportedOperation): 18 | # This can happen in the test suite, because stdout may not have a 19 | # fileno. 20 | pass 21 | -------------------------------------------------------------------------------- /IPython/lib/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Extra capabilities for IPython 4 | """ 5 | 6 | #----------------------------------------------------------------------------- 7 | # Copyright (C) 2008-2011 The IPython Development Team 8 | # 9 | # Distributed under the terms of the BSD License. The full license is in 10 | # the file COPYING, distributed as part of this software. 11 | #----------------------------------------------------------------------------- 12 | 13 | #----------------------------------------------------------------------------- 14 | # Imports 15 | #----------------------------------------------------------------------------- 16 | 17 | from IPython.lib.security import passwd 18 | 19 | #----------------------------------------------------------------------------- 20 | # Code 21 | #----------------------------------------------------------------------------- 22 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | build: false 2 | matrix: 3 | fast_finish: true # immediately finish build once one of the jobs fails. 4 | 5 | environment: 6 | matrix: 7 | - PYTHON: "C:\\Python36" 8 | PYTHON_VERSION: "3.6.x" 9 | PYTHON_ARCH: "32" 10 | 11 | - PYTHON: "C:\\Python33-x64" 12 | PYTHON_VERSION: "3.3.x" 13 | PYTHON_ARCH: "64" 14 | 15 | - PYTHON: "C:\\Python36-x64" 16 | PYTHON_VERSION: "3.6.x" 17 | PYTHON_ARCH: "64" 18 | 19 | init: 20 | - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" 21 | 22 | install: 23 | - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" 24 | - "%CMD_IN_ENV% pip install setuptools>=18.5 --upgrade" 25 | - "%CMD_IN_ENV% pip install nose coverage" 26 | - "%CMD_IN_ENV% pip install .[test]" 27 | - "%CMD_IN_ENV% mkdir results" 28 | - "%CMD_IN_ENV% cd results" 29 | test_script: 30 | - "%CMD_IN_ENV% iptest --coverage xml" 31 | 32 | -------------------------------------------------------------------------------- /IPython/utils/colorable.py: -------------------------------------------------------------------------------- 1 | #***************************************************************************** 2 | # Copyright (C) 2016 The IPython Team 3 | # 4 | # Distributed under the terms of the BSD License. The full license is in 5 | # the file COPYING, distributed as part of this software. 6 | #***************************************************************************** 7 | 8 | """ 9 | Color managing related utilities 10 | """ 11 | 12 | import pygments 13 | 14 | from traitlets.config import Configurable 15 | from traitlets import Unicode 16 | 17 | 18 | available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral'] 19 | 20 | class Colorable(Configurable): 21 | """ 22 | A subclass of configurable for all the classes that have a `default_scheme` 23 | """ 24 | default_style=Unicode('LightBG').tag(config=True) 25 | 26 | -------------------------------------------------------------------------------- /IPython/utils/generics.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Generic functions for extending IPython. 3 | 4 | See http://pypi.python.org/pypi/simplegeneric. 5 | """ 6 | 7 | from IPython.core.error import TryNext 8 | from simplegeneric import generic 9 | 10 | 11 | @generic 12 | def inspect_object(obj): 13 | """Called when you do obj?""" 14 | raise TryNext 15 | 16 | 17 | @generic 18 | def complete_object(obj, prev_completions): 19 | """Custom completer dispatching for python objects. 20 | 21 | Parameters 22 | ---------- 23 | obj : object 24 | The object to complete. 25 | prev_completions : list 26 | List of attributes discovered so far. 27 | 28 | This should return the list of attributes in obj. If you only wish to 29 | add to the attributes already discovered normally, return 30 | own_attrs + prev_completions. 31 | """ 32 | raise TryNext 33 | 34 | 35 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-pyglet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple pyglet example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [5]: %gui pyglet 7 | 8 | In [6]: %run gui-pyglet.py 9 | """ 10 | 11 | import pyglet 12 | 13 | 14 | window = pyglet.window.Window() 15 | label = pyglet.text.Label('Hello, world', 16 | font_name='Times New Roman', 17 | font_size=36, 18 | x=window.width//2, y=window.height//2, 19 | anchor_x='center', anchor_y='center') 20 | @window.event 21 | def on_close(): 22 | window.close() 23 | 24 | @window.event 25 | def on_draw(): 26 | window.clear() 27 | label.draw() 28 | 29 | try: 30 | from IPython.lib.inputhook import enable_gui 31 | enable_gui('pyglet') 32 | except ImportError: 33 | pyglet.app.run() 34 | -------------------------------------------------------------------------------- /IPython/lib/tests/test_security.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from IPython.lib import passwd 3 | from IPython.lib.security import passwd_check, salt_len 4 | import nose.tools as nt 5 | 6 | def test_passwd_structure(): 7 | p = passwd('passphrase') 8 | algorithm, salt, hashed = p.split(':') 9 | nt.assert_equal(algorithm, 'sha1') 10 | nt.assert_equal(len(salt), salt_len) 11 | nt.assert_equal(len(hashed), 40) 12 | 13 | def test_roundtrip(): 14 | p = passwd('passphrase') 15 | nt.assert_equal(passwd_check(p, 'passphrase'), True) 16 | 17 | def test_bad(): 18 | p = passwd('passphrase') 19 | nt.assert_equal(passwd_check(p, p), False) 20 | nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) 21 | nt.assert_equal(passwd_check(p, 'a:b'), False) 22 | 23 | def test_passwd_check_unicode(): 24 | # GH issue #4524 25 | phash = u'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f' 26 | assert passwd_check(phash, u"łe¶ŧ←↓→") -------------------------------------------------------------------------------- /docs/source/interactive/index.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Tutorial 3 | ======== 4 | 5 | This section of IPython documentation will walk you through most of the IPython 6 | functionality. You do not need to have any deep knowledge of Python to read this 7 | tutorial, though some sections might make slightly more sense if you have already 8 | done some work in the classic Python REPL. 9 | 10 | .. note:: 11 | 12 | Some part of this documentation are more than a decade old so might be out 13 | of date, we welcome any report of inaccuracy, and Pull Requests that make 14 | that up to date. 15 | 16 | .. toctree:: 17 | :maxdepth: 2 18 | :hidden: 19 | 20 | tutorial 21 | plotting 22 | reference 23 | shell 24 | tips 25 | python-ipython-diff 26 | magics 27 | 28 | .. seealso:: 29 | 30 | `A Qt Console for Jupyter `__ 31 | `The Jupyter Notebook `__ 32 | -------------------------------------------------------------------------------- /IPython/html.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.html imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.html` package has been deprecated since IPython 4.0. " 13 | "You should import from `notebook` instead. " 14 | "`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning) 15 | 16 | _widgets = sys.modules['IPython.html.widgets'] = ShimModule( 17 | src='IPython.html.widgets', mirror='ipywidgets') 18 | 19 | _html = ShimModule( 20 | src='IPython.html', mirror='notebook') 21 | 22 | # hook up widgets 23 | _html.widgets = _widgets 24 | sys.modules['IPython.html'] = _html 25 | 26 | if __name__ == '__main__': 27 | from notebook import notebookapp as app 28 | app.launch_new_instance() 29 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-gtk3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple Gtk example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [1]: %gui gtk3 7 | 8 | In [2]: %run gui-gtk3.py 9 | """ 10 | 11 | from gi.repository import Gtk 12 | 13 | 14 | def hello_world(wigdet, data=None): 15 | print("Hello World") 16 | 17 | def delete_event(widget, event, data=None): 18 | return False 19 | 20 | def destroy(widget, data=None): 21 | Gtk.main_quit() 22 | 23 | window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL) 24 | window.connect("delete_event", delete_event) 25 | window.connect("destroy", destroy) 26 | button = Gtk.Button(label="Hello World") 27 | button.connect("clicked", hello_world, None) 28 | 29 | window.add(button) 30 | button.show() 31 | window.show() 32 | 33 | try: 34 | from IPython.lib.inputhook import enable_gui 35 | enable_gui('gtk3') 36 | except ImportError: 37 | Gtk.main() 38 | -------------------------------------------------------------------------------- /IPython/testing/plugin/test_exampleip.txt: -------------------------------------------------------------------------------- 1 | ================================= 2 | Tests in example form - IPython 3 | ================================= 4 | 5 | You can write text files with examples that use IPython prompts (as long as you 6 | use the nose ipython doctest plugin), but you can not mix and match prompt 7 | styles in a single file. That is, you either use all ``>>>`` prompts or all 8 | IPython-style prompts. Your test suite *can* have both types, you just need to 9 | put each type of example in a separate. Using IPython prompts, you can paste 10 | directly from your session:: 11 | 12 | In [5]: s="Hello World" 13 | 14 | In [6]: s.upper() 15 | Out[6]: 'HELLO WORLD' 16 | 17 | Another example:: 18 | 19 | In [8]: 1+3 20 | Out[8]: 4 21 | 22 | Just like in IPython docstrings, you can use all IPython syntax and features:: 23 | 24 | In [9]: !echo "hello" 25 | hello 26 | 27 | In [10]: a='hi' 28 | 29 | In [11]: !echo $a 30 | hi 31 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-gtk.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple GTK example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [5]: %gui gtk 7 | 8 | In [6]: %run gui-gtk.py 9 | """ 10 | 11 | import pygtk 12 | pygtk.require('2.0') 13 | import gtk 14 | 15 | 16 | def hello_world(wigdet, data=None): 17 | print("Hello World") 18 | 19 | def delete_event(widget, event, data=None): 20 | return False 21 | 22 | def destroy(widget, data=None): 23 | gtk.main_quit() 24 | 25 | window = gtk.Window(gtk.WINDOW_TOPLEVEL) 26 | window.connect("delete_event", delete_event) 27 | window.connect("destroy", destroy) 28 | button = gtk.Button("Hello World") 29 | button.connect("clicked", hello_world, None) 30 | 31 | window.add(button) 32 | button.show() 33 | window.show() 34 | 35 | try: 36 | from IPython.lib.inputhook import enable_gui 37 | enable_gui('gtk') 38 | except ImportError: 39 | gtk.main() 40 | -------------------------------------------------------------------------------- /examples/IPython Kernel/nbpackage/nbs/other.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "This notebook just defines `bar`" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": { 14 | "collapsed": false 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "def bar(x):\n", 19 | " return \"bar\" * x" 20 | ] 21 | } 22 | ], 23 | "metadata": { 24 | "kernelspec": { 25 | "display_name": "Python 3", 26 | "language": "python", 27 | "name": "python3" 28 | }, 29 | "language_info": { 30 | "codemirror_mode": { 31 | "name": "ipython", 32 | "version": 3 33 | }, 34 | "file_extension": ".py", 35 | "mimetype": "text/x-python", 36 | "name": "python", 37 | "nbconvert_exporter": "python", 38 | "pygments_lexer": "ipython3", 39 | "version": "3.4.2" 40 | } 41 | }, 42 | "nbformat": 4, 43 | "nbformat_minor": 0 44 | } 45 | -------------------------------------------------------------------------------- /IPython/core/getipython.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Simple function to call to get the current InteractiveShell instance 3 | """ 4 | 5 | #----------------------------------------------------------------------------- 6 | # Copyright (C) 2013 The IPython Development Team 7 | # 8 | # Distributed under the terms of the BSD License. The full license is in 9 | # the file COPYING, distributed as part of this software. 10 | #----------------------------------------------------------------------------- 11 | 12 | #----------------------------------------------------------------------------- 13 | # Classes and functions 14 | #----------------------------------------------------------------------------- 15 | 16 | 17 | def get_ipython(): 18 | """Get the global InteractiveShell instance. 19 | 20 | Returns None if no InteractiveShell instance is registered. 21 | """ 22 | from IPython.core.interactiveshell import InteractiveShell 23 | if InteractiveShell.initialized(): 24 | return InteractiveShell.instance() 25 | -------------------------------------------------------------------------------- /docs/source/interactive/magics.rst: -------------------------------------------------------------------------------- 1 | ======================= 2 | Built-in magic commands 3 | ======================= 4 | 5 | .. note:: 6 | 7 | To Jupyter users: Magics are specific to and provided by the IPython kernel. 8 | Whether magics are available on a kernel is a decision that is made by 9 | the kernel developer on a per-kernel basis. To work properly, Magics must 10 | use a syntax element which is not valid in the underlying language. For 11 | example, the IPython kernel uses the `%` syntax element for magics as `%` 12 | is not a valid unary operator in Python. While, the syntax element has 13 | meaning in other languages. 14 | 15 | Here is the help auto generated from the docstrings of all the available magics 16 | function that IPython ships with. 17 | 18 | You can create an register your own magics with IPython. You can find many user 19 | defined magics on `PyPI `_. Feel free to publish your own and 20 | use the ``Framework :: IPython`` trove classifier. 21 | 22 | 23 | .. include:: magics-generated.txt 24 | -------------------------------------------------------------------------------- /IPython/core/tests/test_logger.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Test IPython.core.logger""" 3 | 4 | import os.path 5 | 6 | import nose.tools as nt 7 | from IPython.utils.tempdir import TemporaryDirectory 8 | 9 | _ip = get_ipython() 10 | 11 | def test_logstart_inaccessible_file(): 12 | try: 13 | _ip.logger.logstart(logfname="/") # Opening that filename will fail. 14 | except IOError: 15 | pass 16 | else: 17 | nt.assert_true(False) # The try block should never pass. 18 | 19 | try: 20 | _ip.run_cell("a=1") # Check it doesn't try to log this 21 | finally: 22 | _ip.logger.log_active = False # If this fails, don't let later tests fail 23 | 24 | def test_logstart_unicode(): 25 | with TemporaryDirectory() as tdir: 26 | logfname = os.path.join(tdir, "test_unicode.log") 27 | _ip.run_cell("'abc€'") 28 | try: 29 | _ip.magic("logstart -to %s" % logfname) 30 | _ip.run_cell("'abc€'") 31 | finally: 32 | _ip.logger.logstop() 33 | -------------------------------------------------------------------------------- /tools/alldeps/pkginstall.cfg: -------------------------------------------------------------------------------- 1 | # -*- sh -*- 2 | # 3 | # Configuration for the pkginstall script. 4 | # This script uses bash syntax, as it will be sourced by a bash script. 5 | 6 | # Uncomment and set the variables you want, otherwise pkginstall has sensible 7 | # defaults predefined. These can also be declared either as environment 8 | # variables (which can be done by the makefile calling this script). 9 | 10 | #----------------------------------------------------------------------------- 11 | # 12 | # Executable for Python. 13 | # 14 | # You can set this to an explicit full path if you don't want the default 15 | # (simply 'python') to be the version used to install this package. 16 | 17 | #PYTHON=python 18 | 19 | #----------------------------------------------------------------------------- 20 | # 21 | # Default prefix. 22 | # 23 | # This should be a valid input the setup.py script as the --prefix argument. 24 | # That is, your $PYTHONPATH should contain $PREFIX/lib/pythonX.Y/site-packages, 25 | # your $PATH should contain $PREFIX/bin, etc. 26 | 27 | #PREFIX=$HOME/usr/local 28 | -------------------------------------------------------------------------------- /IPython/core/tests/test_prompts.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 2 | """Tests for prompt generation.""" 3 | 4 | import unittest 5 | 6 | from IPython.core.prompts import LazyEvaluate 7 | from IPython.testing.globalipapp import get_ipython 8 | 9 | ip = get_ipython() 10 | 11 | 12 | class PromptTests(unittest.TestCase): 13 | def test_lazy_eval_unicode(self): 14 | u = u'ünicødé' 15 | lz = LazyEvaluate(lambda : u) 16 | self.assertEqual(str(lz), u) 17 | self.assertEqual(format(lz), u) 18 | 19 | def test_lazy_eval_nonascii_bytes(self): 20 | u = u'ünicødé' 21 | b = u.encode('utf8') 22 | lz = LazyEvaluate(lambda : b) 23 | # unicode(lz) would fail 24 | self.assertEqual(str(lz), str(b)) 25 | self.assertEqual(format(lz), str(b)) 26 | 27 | def test_lazy_eval_float(self): 28 | f = 0.503 29 | lz = LazyEvaluate(lambda : f) 30 | 31 | self.assertEqual(str(lz), str(f)) 32 | self.assertEqual(format(lz), str(f)) 33 | self.assertEqual(format(lz, '.1'), '0.5') 34 | 35 | -------------------------------------------------------------------------------- /docs/source/whatsnew/version0.8.rst: -------------------------------------------------------------------------------- 1 | ======================================== 2 | 0.8 series 3 | ======================================== 4 | 5 | Release 0.8.4 6 | ============= 7 | 8 | This was a quick release to fix an unfortunate bug that slipped into the 0.8.3 9 | release. The ``--twisted`` option was disabled, as it turned out to be broken 10 | across several platforms. 11 | 12 | 13 | Release 0.8.3 14 | ============= 15 | 16 | * pydb is now disabled by default (due to %run -d problems). You can enable 17 | it by passing -pydb command line argument to IPython. Note that setting 18 | it in config file won't work. 19 | 20 | 21 | Release 0.8.2 22 | ============= 23 | 24 | * %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory 25 | and jumps to /foo. The current behaviour is closer to the documented 26 | behaviour, and should not trip anyone. 27 | 28 | 29 | Older releases 30 | ============== 31 | 32 | Changes in earlier releases of IPython are described in the older file 33 | ``ChangeLog``. Please refer to this document for details. 34 | 35 | -------------------------------------------------------------------------------- /IPython/core/tests/tclass.py: -------------------------------------------------------------------------------- 1 | """Simple script to be run *twice*, to check reference counting bugs. 2 | 3 | See test_run for details.""" 4 | 5 | 6 | import sys 7 | 8 | # We want to ensure that while objects remain available for immediate access, 9 | # objects from *previous* runs of the same script get collected, to avoid 10 | # accumulating massive amounts of old references. 11 | class C(object): 12 | def __init__(self,name): 13 | self.name = name 14 | self.p = print 15 | self.flush_stdout = sys.stdout.flush 16 | 17 | def __del__(self): 18 | self.p('tclass.py: deleting object:',self.name) 19 | self.flush_stdout() 20 | 21 | try: 22 | name = sys.argv[1] 23 | except IndexError: 24 | pass 25 | else: 26 | if name.startswith('C'): 27 | c = C(name) 28 | 29 | #print >> sys.stderr, "ARGV:", sys.argv # dbg 30 | 31 | # This next print statement is NOT debugging, we're making the check on a 32 | # completely separate process so we verify by capturing stdout: 33 | print('ARGV 1-:', sys.argv[1:]) 34 | sys.stdout.flush() 35 | -------------------------------------------------------------------------------- /IPython/testing/plugin/test_refs.py: -------------------------------------------------------------------------------- 1 | """Some simple tests for the plugin while running scripts. 2 | """ 3 | # Module imports 4 | # Std lib 5 | import inspect 6 | 7 | # Our own 8 | 9 | #----------------------------------------------------------------------------- 10 | # Testing functions 11 | 12 | def test_trivial(): 13 | """A trivial passing test.""" 14 | pass 15 | 16 | def doctest_run(): 17 | """Test running a trivial script. 18 | 19 | In [13]: run simplevars.py 20 | x is: 1 21 | """ 22 | 23 | def doctest_runvars(): 24 | """Test that variables defined in scripts get loaded correcly via %run. 25 | 26 | In [13]: run simplevars.py 27 | x is: 1 28 | 29 | In [14]: x 30 | Out[14]: 1 31 | """ 32 | 33 | def doctest_ivars(): 34 | """Test that variables defined interactively are picked up. 35 | In [5]: zz=1 36 | 37 | In [6]: zz 38 | Out[6]: 1 39 | """ 40 | 41 | def doctest_refs(): 42 | """DocTest reference holding issues when running scripts. 43 | 44 | In [32]: run show_refs.py 45 | c referrers: [<... 'dict'>] 46 | """ 47 | -------------------------------------------------------------------------------- /IPython/testing/plugin/test_combo.txt: -------------------------------------------------------------------------------- 1 | ======================= 2 | Combo testing example 3 | ======================= 4 | 5 | This is a simple example that mixes ipython doctests:: 6 | 7 | In [1]: import code 8 | 9 | In [2]: 2**12 10 | Out[2]: 4096 11 | 12 | with command-line example information that does *not* get executed:: 13 | 14 | $ mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0 15 | 16 | and with literal examples of Python source code:: 17 | 18 | controller = dict(host='myhost', 19 | engine_port=None, # default is 10105 20 | control_port=None, 21 | ) 22 | 23 | # keys are hostnames, values are the number of engine on that host 24 | engines = dict(node1=2, 25 | node2=2, 26 | node3=2, 27 | node3=2, 28 | ) 29 | 30 | # Force failure to detect that this test is being run. 31 | 1/0 32 | 33 | These source code examples are executed but no output is compared at all. An 34 | error or failure is reported only if an exception is raised. 35 | 36 | NOTE: the execution of pure python blocks is not yet working! 37 | -------------------------------------------------------------------------------- /IPython/lib/tests/test_editorhooks.py: -------------------------------------------------------------------------------- 1 | """Test installing editor hooks""" 2 | import sys 3 | from unittest import mock 4 | 5 | import nose.tools as nt 6 | 7 | from IPython import get_ipython 8 | from IPython.lib import editorhooks 9 | 10 | def test_install_editor(): 11 | called = [] 12 | def fake_popen(*args, **kwargs): 13 | called.append({ 14 | 'args': args, 15 | 'kwargs': kwargs, 16 | }) 17 | return mock.MagicMock(**{'wait.return_value': 0}) 18 | editorhooks.install_editor('foo -l {line} -f {filename}', wait=False) 19 | 20 | with mock.patch('subprocess.Popen', fake_popen): 21 | get_ipython().hooks.editor('the file', 64) 22 | 23 | nt.assert_equal(len(called), 1) 24 | args = called[0]['args'] 25 | kwargs = called[0]['kwargs'] 26 | 27 | nt.assert_equal(kwargs, {'shell': True}) 28 | 29 | if sys.platform.startswith('win'): 30 | expected = ['foo', '-l', '64', '-f', 'the file'] 31 | else: 32 | expected = "foo -l 64 -f 'the file'" 33 | cmd = args[0] 34 | nt.assert_equal(cmd, expected) 35 | -------------------------------------------------------------------------------- /IPython/sphinxext/ipython_console_highlighting.py: -------------------------------------------------------------------------------- 1 | """ 2 | reST directive for syntax-highlighting ipython interactive sessions. 3 | 4 | """ 5 | 6 | from sphinx import highlighting 7 | from IPython.lib.lexers import IPyLexer 8 | 9 | def setup(app): 10 | """Setup as a sphinx extension.""" 11 | 12 | # This is only a lexer, so adding it below to pygments appears sufficient. 13 | # But if somebody knows what the right API usage should be to do that via 14 | # sphinx, by all means fix it here. At least having this setup.py 15 | # suppresses the sphinx warning we'd get without it. 16 | metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} 17 | return metadata 18 | 19 | # Register the extension as a valid pygments lexer. 20 | # Alternatively, we could register the lexer with pygments instead. This would 21 | # require using setuptools entrypoints: http://pygments.org/docs/plugins 22 | 23 | ipy2 = IPyLexer(python3=False) 24 | ipy3 = IPyLexer(python3=True) 25 | 26 | highlighting.lexers['ipython'] = ipy2 27 | highlighting.lexers['ipython2'] = ipy2 28 | highlighting.lexers['ipython3'] = ipy3 29 | -------------------------------------------------------------------------------- /docs/source/whatsnew/pr/README.md: -------------------------------------------------------------------------------- 1 | Documenting What's New 2 | ---------------------- 3 | 4 | When making a new pull request that either adds a new feature, or makes a 5 | backwards-incompatible change to IPython, please add a new `.rst` file in this 6 | directory documenting this change as a part of your Pull Request. 7 | 8 | This will allow multiple Pull Requests to do the same without conflicting with 9 | one another. Periodically, IPython developers with commit rights will run a 10 | script and populate [development.rst](../development.rst) 11 | with the contents of this directory, and clean it up. 12 | 13 | Files which describe new features can have any name, such as 14 | `antigravity-feature.rst`, whereas backwards incompatible changes **must have** 15 | have a filename starting with `incompat-`, such as 16 | `incompat-switching-to-perl.rst`. Our "What's new" files always have two 17 | sections, and this prefix scheme will make sure that the backwards incompatible 18 | changes get routed to their proper section. 19 | 20 | To merge these files into :file:`whatsnew/development.rst`, run the script :file:`tools/update_whatsnew.py`. 21 | -------------------------------------------------------------------------------- /IPython/lib/inputhookgtk3.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Enable Gtk3 to be used interacive by IPython. 4 | 5 | Authors: Thomi Richards 6 | """ 7 | #----------------------------------------------------------------------------- 8 | # Copyright (c) 2012, the IPython Development Team. 9 | # 10 | # Distributed under the terms of the Modified BSD License. 11 | # 12 | # The full license is in the file COPYING.txt, distributed with this software. 13 | #----------------------------------------------------------------------------- 14 | 15 | #----------------------------------------------------------------------------- 16 | # Imports 17 | #----------------------------------------------------------------------------- 18 | 19 | import sys 20 | from gi.repository import Gtk, GLib 21 | 22 | #----------------------------------------------------------------------------- 23 | # Code 24 | #----------------------------------------------------------------------------- 25 | 26 | def _main_quit(*args, **kwargs): 27 | Gtk.main_quit() 28 | return False 29 | 30 | 31 | def inputhook_gtk3(): 32 | GLib.io_add_watch(sys.stdin, GLib.IO_IN, _main_quit) 33 | Gtk.main() 34 | return 0 35 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_tempdir.py: -------------------------------------------------------------------------------- 1 | #----------------------------------------------------------------------------- 2 | # Copyright (C) 2012- The IPython Development Team 3 | # 4 | # Distributed under the terms of the BSD License. The full license is in 5 | # the file COPYING, distributed as part of this software. 6 | #----------------------------------------------------------------------------- 7 | 8 | import os 9 | 10 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory 11 | from IPython.utils.tempdir import TemporaryWorkingDirectory 12 | 13 | 14 | def test_named_file_in_temporary_directory(): 15 | with NamedFileInTemporaryDirectory('filename') as file: 16 | name = file.name 17 | assert not file.closed 18 | assert os.path.exists(name) 19 | file.write(b'test') 20 | assert file.closed 21 | assert not os.path.exists(name) 22 | 23 | def test_temporary_working_directory(): 24 | with TemporaryWorkingDirectory() as dir: 25 | assert os.path.exists(dir) 26 | assert os.path.realpath(os.curdir) == os.path.realpath(dir) 27 | assert not os.path.exists(dir) 28 | assert os.path.abspath(os.curdir) != dir 29 | -------------------------------------------------------------------------------- /IPython/lib/inputhookgtk.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Enable pygtk to be used interacive by setting PyOS_InputHook. 4 | 5 | Authors: Brian Granger 6 | """ 7 | 8 | #----------------------------------------------------------------------------- 9 | # Copyright (C) 2008-2011 The IPython Development Team 10 | # 11 | # Distributed under the terms of the BSD License. The full license is in 12 | # the file COPYING, distributed as part of this software. 13 | #----------------------------------------------------------------------------- 14 | 15 | #----------------------------------------------------------------------------- 16 | # Imports 17 | #----------------------------------------------------------------------------- 18 | 19 | import sys 20 | import gtk, gobject 21 | 22 | #----------------------------------------------------------------------------- 23 | # Code 24 | #----------------------------------------------------------------------------- 25 | 26 | 27 | def _main_quit(*args, **kwargs): 28 | gtk.main_quit() 29 | return False 30 | 31 | def inputhook_gtk(): 32 | gobject.io_add_watch(sys.stdin, gobject.IO_IN, _main_quit) 33 | gtk.main() 34 | return 0 35 | 36 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | ; Tox (http://tox.testrun.org/) is a virtualenv manager for running tests in 2 | ; multiple environments. This configuration file gets the requirements from 3 | ; setup.py like a "pip install ipython[test]". To create the environments, it 4 | ; requires every interpreter available/installed. 5 | ; -- Commands -- 6 | ; pip install tox # Installs tox 7 | ; tox # Runs the tests (call from the directory with tox.ini) 8 | ; tox -r # Ditto, but forcing the virtual environments to be rebuilt 9 | ; tox -e py35,pypy # Runs only in the selected environments 10 | ; tox -- --all -j # Runs "iptest --all -j" in every environment 11 | 12 | [tox] 13 | envlist = py{36,35,34,33,27,py} 14 | skip_missing_interpreters = True 15 | toxworkdir = /tmp/tox_ipython 16 | 17 | [testenv] 18 | ; PyPy requires its Numpy fork instead of "pip install numpy" 19 | ; Other IPython/testing dependencies should be in setup.py, not here 20 | deps = 21 | pypy: https://bitbucket.org/pypy/numpy/get/master.zip 22 | py{36,35,34,33,27}: matplotlib 23 | .[test] 24 | 25 | ; It's just to avoid loading the IPython package in the current directory 26 | changedir = {envtmpdir} 27 | 28 | commands = iptest {posargs} 29 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-qt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple Qt4 example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [5]: %gui qt 7 | 8 | In [6]: %run gui-qt.py 9 | 10 | Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/ 11 | """ 12 | 13 | from PyQt4 import QtGui, QtCore 14 | 15 | class SimpleWindow(QtGui.QWidget): 16 | def __init__(self, parent=None): 17 | QtGui.QWidget.__init__(self, parent) 18 | 19 | self.setGeometry(300, 300, 200, 80) 20 | self.setWindowTitle('Hello World') 21 | 22 | quit = QtGui.QPushButton('Close', self) 23 | quit.setGeometry(10, 10, 60, 35) 24 | 25 | self.connect(quit, QtCore.SIGNAL('clicked()'), 26 | self, QtCore.SLOT('close()')) 27 | 28 | if __name__ == '__main__': 29 | app = QtCore.QCoreApplication.instance() 30 | if app is None: 31 | app = QtGui.QApplication([]) 32 | 33 | sw = SimpleWindow() 34 | sw.show() 35 | 36 | try: 37 | from IPython.lib.guisupport import start_event_loop_qt4 38 | start_event_loop_qt4(app) 39 | except ImportError: 40 | app.exec_() 41 | -------------------------------------------------------------------------------- /IPython/utils/importstring.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | A simple utility to import something by its string name. 4 | """ 5 | 6 | # Copyright (c) IPython Development Team. 7 | # Distributed under the terms of the Modified BSD License. 8 | 9 | 10 | def import_item(name): 11 | """Import and return ``bar`` given the string ``foo.bar``. 12 | 13 | Calling ``bar = import_item("foo.bar")`` is the functional equivalent of 14 | executing the code ``from foo import bar``. 15 | 16 | Parameters 17 | ---------- 18 | name : string 19 | The fully qualified name of the module/package being imported. 20 | 21 | Returns 22 | ------- 23 | mod : module object 24 | The module that was imported. 25 | """ 26 | 27 | parts = name.rsplit('.', 1) 28 | if len(parts) == 2: 29 | # called with 'foo.bar....' 30 | package, obj = parts 31 | module = __import__(package, fromlist=[obj]) 32 | try: 33 | pak = getattr(module, obj) 34 | except AttributeError: 35 | raise ImportError('No module named %s' % obj) 36 | return pak 37 | else: 38 | # called with un-dotted string 39 | return __import__(parts[0]) 40 | -------------------------------------------------------------------------------- /docs/autogen_config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os.path import join, dirname, abspath 4 | 5 | from IPython.terminal.ipapp import TerminalIPythonApp 6 | from ipykernel.kernelapp import IPKernelApp 7 | 8 | here = abspath(dirname(__file__)) 9 | options = join(here, 'source', 'config', 'options') 10 | generated = join(options, 'config-generated.txt') 11 | 12 | 13 | def write_doc(name, title, app, preamble=None): 14 | filename = join(options, name+'.rst') 15 | with open(filename, 'w') as f: 16 | f.write(title + '\n') 17 | f.write(('=' * len(title)) + '\n') 18 | f.write('\n') 19 | if preamble is not None: 20 | f.write(preamble + '\n\n') 21 | f.write(app.document_config_options()) 22 | 23 | 24 | if __name__ == '__main__': 25 | # Touch this file for the make target 26 | with open(generated, 'w'): 27 | pass 28 | 29 | write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) 30 | write_doc('kernel', 'IPython kernel options', IPKernelApp(), 31 | preamble=("These options can be used in :file:`ipython_kernel_config.py`. " 32 | "The kernel also respects any options in `ipython_config.py`"), 33 | ) 34 | -------------------------------------------------------------------------------- /IPython/extensions/sympyprinting.py: -------------------------------------------------------------------------------- 1 | """ 2 | **DEPRECATED** 3 | 4 | A print function that pretty prints sympy Basic objects. 5 | 6 | :moduleauthor: Brian Granger 7 | 8 | Usage 9 | ===== 10 | 11 | Once the extension is loaded, Sympy Basic objects are automatically 12 | pretty-printed. 13 | 14 | As of SymPy 0.7.2, maintenance of this extension has moved to SymPy under 15 | sympy.interactive.ipythonprinting, any modifications to account for changes to 16 | SymPy should be submitted to SymPy rather than changed here. This module is 17 | maintained here for backwards compatablitiy with old SymPy versions. 18 | 19 | """ 20 | #----------------------------------------------------------------------------- 21 | # Copyright (C) 2008 The IPython Development Team 22 | #----------------------------------------------------------------------------- 23 | 24 | #----------------------------------------------------------------------------- 25 | # Imports 26 | #----------------------------------------------------------------------------- 27 | 28 | import warnings 29 | 30 | def load_ipython_extension(ip): 31 | warnings.warn("The sympyprinting extension has moved to `sympy`, " 32 | "use `from sympy import init_printing; init_printing()`") 33 | -------------------------------------------------------------------------------- /IPython/frontend.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old frontend imports. 3 | 4 | We have moved all contents of the old `frontend` subpackage into top-level 5 | subpackages (`html`, `qt` and `terminal`), and flattened the notebook into 6 | just `IPython.html`, formerly `IPython.frontend.html.notebook`. 7 | 8 | This will let code that was making `from IPython.frontend...` calls continue 9 | working, though a warning will be printed. 10 | """ 11 | 12 | # Copyright (c) IPython Development Team. 13 | # Distributed under the terms of the Modified BSD License. 14 | 15 | import sys 16 | from warnings import warn 17 | 18 | from IPython.utils.shimmodule import ShimModule, ShimWarning 19 | 20 | warn("The top-level `frontend` package has been deprecated since IPython 1.0. " 21 | "All its subpackages have been moved to the top `IPython` level.", ShimWarning) 22 | 23 | # Unconditionally insert the shim into sys.modules so that further import calls 24 | # trigger the custom attribute access above 25 | 26 | sys.modules['IPython.frontend.html.notebook'] = ShimModule( 27 | src='IPython.frontend.html.notebook', mirror='IPython.html') 28 | sys.modules['IPython.frontend'] = ShimModule( 29 | src='IPython.frontend', mirror='IPython') 30 | -------------------------------------------------------------------------------- /docs/README.rst: -------------------------------------------------------------------------------- 1 | IPython Documentation 2 | --------------------- 3 | 4 | This directory contains the majority of the documentation for IPython. 5 | 6 | Deploy docs 7 | ----------- 8 | 9 | Documentation is automatically deployed on ReadTheDocs on every push or merged 10 | Pull requests. 11 | 12 | 13 | Requirements 14 | ------------ 15 | The following tools are needed to build the documentation: 16 | 17 | - sphinx 18 | 19 | On Debian-based systems, you should be able to run:: 20 | 21 | sudo apt-get install python-sphinx 22 | 23 | The documentation gets built using ``make``, and comes in several flavors. 24 | 25 | ``make html`` - build the API and narrative documentation web pages, this is 26 | the default ``make`` target, so running just ``make`` is equivalent to ``make 27 | html``. 28 | 29 | ``make html_noapi`` - same as above, but without running the auto-generated API 30 | docs. When you are working on the narrative documentation, the most time 31 | consuming portion of the build process is the processing and rending of the 32 | API documentation. This build target skips that. 33 | 34 | ``make pdf`` will compile a pdf from the documentation. 35 | 36 | You can run ``make help`` to see information on all possible make targets. 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /examples/IPython Kernel/ipython-get-history.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Extract a session from the IPython input history. 3 | 4 | Usage: 5 | ipython-get-history.py sessionnumber [outputfile] 6 | 7 | If outputfile is not given, the relevant history is written to stdout. If 8 | outputfile has a .py extension, the translated history (without IPython's 9 | special syntax) will be extracted. 10 | 11 | Example: 12 | ./ipython-get-history.py 57 record.ipy 13 | 14 | 15 | This script is a simple demonstration of HistoryAccessor. It should be possible 16 | to build much more flexible and powerful tools to browse and pull from the 17 | history database. 18 | """ 19 | import sys 20 | 21 | from IPython.core.history import HistoryAccessor 22 | 23 | session_number = int(sys.argv[1]) 24 | if len(sys.argv) > 2: 25 | dest = open(sys.argv[2], "w") 26 | raw = not sys.argv[2].endswith('.py') 27 | else: 28 | dest = sys.stdout 29 | raw = True 30 | dest.write("# coding: utf-8\n") 31 | 32 | # Profiles other than 'default' can be specified here with a profile= argument: 33 | hist = HistoryAccessor() 34 | 35 | for session, lineno, cell in hist.get_range(session=session_number, raw=raw): 36 | cell = cell.encode('utf-8') # This line is only needed on Python 2. 37 | dest.write(cell + '\n') 38 | -------------------------------------------------------------------------------- /IPython/lib/tests/test_deepreload.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Test suite for the deepreload module.""" 3 | 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import os 8 | 9 | import nose.tools as nt 10 | 11 | from IPython.utils.syspathcontext import prepended_to_syspath 12 | from IPython.utils.tempdir import TemporaryDirectory 13 | from IPython.lib.deepreload import reload as dreload 14 | 15 | def test_deepreload(): 16 | "Test that dreload does deep reloads and skips excluded modules." 17 | with TemporaryDirectory() as tmpdir: 18 | with prepended_to_syspath(tmpdir): 19 | with open(os.path.join(tmpdir, 'A.py'), 'w') as f: 20 | f.write("class Object(object):\n pass\n") 21 | with open(os.path.join(tmpdir, 'B.py'), 'w') as f: 22 | f.write("import A\n") 23 | import A 24 | import B 25 | 26 | # Test that A is not reloaded. 27 | obj = A.Object() 28 | dreload(B, exclude=['A']) 29 | nt.assert_true(isinstance(obj, A.Object)) 30 | 31 | # Test that A is reloaded. 32 | obj = A.Object() 33 | dreload(B) 34 | nt.assert_false(isinstance(obj, A.Object)) 35 | -------------------------------------------------------------------------------- /IPython/utils/data.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Utilities for working with data structures like lists, dicts and tuples. 3 | """ 4 | 5 | #----------------------------------------------------------------------------- 6 | # Copyright (C) 2008-2011 The IPython Development Team 7 | # 8 | # Distributed under the terms of the BSD License. The full license is in 9 | # the file COPYING, distributed as part of this software. 10 | #----------------------------------------------------------------------------- 11 | 12 | 13 | def uniq_stable(elems): 14 | """uniq_stable(elems) -> list 15 | 16 | Return from an iterable, a list of all the unique elements in the input, 17 | but maintaining the order in which they first appear. 18 | 19 | Note: All elements in the input must be hashable for this routine 20 | to work, as it internally uses a set for efficiency reasons. 21 | """ 22 | seen = set() 23 | return [x for x in elems if x not in seen and not seen.add(x)] 24 | 25 | 26 | def flatten(seq): 27 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" 28 | 29 | return [x for subseq in seq for x in subseq] 30 | 31 | 32 | def chop(seq, size): 33 | """Chop a sequence into chunks of the given size.""" 34 | return [seq[i:i+size] for i in range(0,len(seq),size)] 35 | 36 | 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # http://travis-ci.org/#!/ipython/ipython 2 | language: python 3 | python: 4 | - "nightly" 5 | - 3.6 6 | - 3.5 7 | - 3.4 8 | - 3.3 9 | sudo: false 10 | before_install: 11 | - 'if [[ $GROUP != js* ]]; then COVERAGE=""; fi' 12 | install: 13 | - pip install setuptools pip --upgrade 14 | - pip install -e file://$PWD#egg=ipython[test] --upgrade 15 | - pip install codecov --upgrade 16 | script: 17 | - cd /tmp && iptest --coverage xml && cd - 18 | after_success: 19 | - cp /tmp/ipy_coverage.xml ./ 20 | - cp /tmp/.coverage ./ 21 | - codecov 22 | 23 | matrix: 24 | allow_failures: 25 | - python: nightly 26 | 27 | before_deploy: 28 | - rm -rf dist/ 29 | - python setup.py sdist 30 | - python setup.py bdist_wheel 31 | 32 | deploy: 33 | provider: releases 34 | api_key: 35 | secure: Y/Ae9tYs5aoBU8bDjN2YrwGG6tCbezj/h3Lcmtx8HQavSbBgXnhnZVRb2snOKD7auqnqjfT/7QMm4ZyKvaOEgyggGktKqEKYHC8KOZ7yp8I5/UMDtk6j9TnXpSqqBxPiud4MDV76SfRYEQiaDoG4tGGvSfPJ9KcNjKrNvSyyxns= 36 | file: dist/* 37 | file_glob: true 38 | skip_cleanup: true 39 | on: 40 | repo: ipython/ipython 41 | all_branches: true # Backports are released from e.g. 5.x branch 42 | tags: true 43 | python: 3.6 # Any version should work, but we only need one 44 | -------------------------------------------------------------------------------- /IPython/kernel/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shim to maintain backwards compatibility with old IPython.kernel imports. 3 | """ 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import sys 8 | from warnings import warn 9 | 10 | from IPython.utils.shimmodule import ShimModule, ShimWarning 11 | 12 | warn("The `IPython.kernel` package has been deprecated since IPython 4.0." 13 | "You should import from ipykernel or jupyter_client instead.", ShimWarning) 14 | 15 | 16 | # zmq subdir is gone 17 | sys.modules['IPython.kernel.zmq.session'] = ShimModule( 18 | src='IPython.kernel.zmq.session', mirror='jupyter_client.session') 19 | sys.modules['IPython.kernel.zmq'] = ShimModule( 20 | src='IPython.kernel.zmq', mirror='ipykernel') 21 | 22 | for pkg in ('comm', 'inprocess'): 23 | src = 'IPython.kernel.%s' % pkg 24 | sys.modules[src] = ShimModule(src=src, mirror='ipykernel.%s' % pkg) 25 | 26 | for pkg in ('ioloop', 'blocking'): 27 | src = 'IPython.kernel.%s' % pkg 28 | sys.modules[src] = ShimModule(src=src, mirror='jupyter_client.%s' % pkg) 29 | 30 | # required for `from IPython.kernel import PKG` 31 | from ipykernel import comm, inprocess 32 | from jupyter_client import ioloop, blocking 33 | # public API 34 | from ipykernel.connect import * 35 | from jupyter_client import * 36 | -------------------------------------------------------------------------------- /docs/source/development/pycompat.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | Writing code for Python 2 and 3 4 | =============================== 5 | 6 | .. module:: IPython.utils.py3compat 7 | :synopsis: Python 2 & 3 compatibility helpers 8 | 9 | 10 | IPython 6 requires Python 3, so our compatibility module 11 | ``IPython.utils.py3compat`` is deprecated. In most cases, we recommend you use 12 | the `six module `__ to support compatible code. 13 | This is widely used by other projects, so it is familiar to many developers and 14 | thoroughly battle-tested. 15 | 16 | Our ``py3compat`` module provided some more specific unicode conversions than 17 | those offered by ``six``. If you want to use these, copy them into your own code 18 | from IPython 5.x. Do not rely on importing them from IPython, as the module may 19 | be removed in the future. 20 | 21 | .. seealso:: 22 | 23 | `Porting Python 2 code to Python 3 `_ 24 | Official information in the Python docs. 25 | 26 | `Python-Modernize `_ 27 | A tool which helps make code compatible with Python 3. 28 | 29 | `Python-Future `_ 30 | Another compatibility tool, which focuses on writing code for Python 3 and 31 | making it work on Python 2. 32 | -------------------------------------------------------------------------------- /IPython/terminal/pt_inputhooks/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | aliases = { 5 | 'qt4': 'qt', 6 | 'gtk2': 'gtk', 7 | } 8 | 9 | backends = [ 10 | 'qt', 'qt4', 'qt5', 11 | 'gtk', 'gtk2', 'gtk3', 12 | 'tk', 13 | 'wx', 14 | 'pyglet', 'glut', 15 | 'osx', 16 | ] 17 | 18 | registered = {} 19 | 20 | def register(name, inputhook): 21 | """Register the function *inputhook* as an event loop integration.""" 22 | registered[name] = inputhook 23 | 24 | class UnknownBackend(KeyError): 25 | def __init__(self, name): 26 | self.name = name 27 | 28 | def __str__(self): 29 | return ("No event loop integration for {!r}. " 30 | "Supported event loops are: {}").format(self.name, 31 | ', '.join(backends + sorted(registered))) 32 | 33 | def get_inputhook_name_and_func(gui): 34 | if gui in registered: 35 | return gui, registered[gui] 36 | 37 | if gui not in backends: 38 | raise UnknownBackend(gui) 39 | 40 | if gui in aliases: 41 | return get_inputhook_name_and_func(aliases[gui]) 42 | 43 | gui_mod = gui 44 | if gui == 'qt5': 45 | os.environ['QT_API'] = 'pyqt5' 46 | gui_mod = 'qt' 47 | 48 | mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) 49 | return gui, mod.inputhook 50 | -------------------------------------------------------------------------------- /IPython/utils/version.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Utilities for version comparison 4 | 5 | It is a bit ridiculous that we need these. 6 | """ 7 | 8 | #----------------------------------------------------------------------------- 9 | # Copyright (C) 2013 The IPython Development Team 10 | # 11 | # Distributed under the terms of the BSD License. The full license is in 12 | # the file COPYING, distributed as part of this software. 13 | #----------------------------------------------------------------------------- 14 | 15 | #----------------------------------------------------------------------------- 16 | # Imports 17 | #----------------------------------------------------------------------------- 18 | 19 | from distutils.version import LooseVersion 20 | 21 | #----------------------------------------------------------------------------- 22 | # Code 23 | #----------------------------------------------------------------------------- 24 | 25 | def check_version(v, check): 26 | """check version string v >= check 27 | 28 | If dev/prerelease tags result in TypeError for string-number comparison, 29 | it is assumed that the dependency is satisfied. 30 | Users on dev branches are responsible for keeping their own packages up to date. 31 | """ 32 | try: 33 | return LooseVersion(v) >= LooseVersion(check) 34 | except TypeError: 35 | return True 36 | 37 | -------------------------------------------------------------------------------- /examples/IPython Kernel/example-demo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """A simple interactive demo to illustrate the use of IPython's Demo class. 3 | 4 | Any python script can be run as a demo, but that does little more than showing 5 | it on-screen, syntax-highlighted in one shot. If you add a little simple 6 | markup, you can stop at specified intervals and return to the ipython prompt, 7 | resuming execution later. 8 | 9 | This is a unicode test, åäö 10 | """ 11 | 12 | print('Hello, welcome to an interactive IPython demo.') 13 | print('Executing this block should require confirmation before proceeding,') 14 | print('unless auto_all has been set to true in the demo object') 15 | 16 | # The mark below defines a block boundary, which is a point where IPython will 17 | # stop execution and return to the interactive prompt. 18 | # --- stop --- 19 | 20 | x = 1 21 | y = 2 22 | 23 | # --- stop --- 24 | 25 | # the mark below makes this block as silent 26 | # silent 27 | 28 | print('This is a silent block, which gets executed but not printed.') 29 | 30 | # --- stop --- 31 | # auto 32 | print('This is an automatic block.') 33 | print('It is executed without asking for confirmation, but printed.') 34 | z = x+y 35 | 36 | print('z=',x) 37 | 38 | # --- stop --- 39 | # This is just another normal block. 40 | print('z is now:', z) 41 | 42 | print('bye!') 43 | -------------------------------------------------------------------------------- /IPython/core/tests/test_imports.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | def test_import_completer(): 4 | from IPython.core import completer 5 | 6 | def test_import_crashhandler(): 7 | from IPython.core import crashhandler 8 | 9 | def test_import_debugger(): 10 | from IPython.core import debugger 11 | 12 | def test_import_excolors(): 13 | from IPython.core import excolors 14 | 15 | def test_import_history(): 16 | from IPython.core import history 17 | 18 | def test_import_hooks(): 19 | from IPython.core import hooks 20 | 21 | def test_import_getipython(): 22 | from IPython.core import getipython 23 | 24 | def test_import_interactiveshell(): 25 | from IPython.core import interactiveshell 26 | 27 | def test_import_logger(): 28 | from IPython.core import logger 29 | 30 | def test_import_macro(): 31 | from IPython.core import macro 32 | 33 | def test_import_magic(): 34 | from IPython.core import magic 35 | 36 | def test_import_oinspect(): 37 | from IPython.core import oinspect 38 | 39 | def test_import_prefilter(): 40 | from IPython.core import prefilter 41 | 42 | def test_import_prompts(): 43 | from IPython.core import prompts 44 | 45 | def test_import_release(): 46 | from IPython.core import release 47 | 48 | def test_import_ultratb(): 49 | from IPython.core import ultratb 50 | 51 | def test_import_usage(): 52 | from IPython.core import usage 53 | -------------------------------------------------------------------------------- /IPython/testing/plugin/README.txt: -------------------------------------------------------------------------------- 1 | ======================================================= 2 | Nose plugin with IPython and extension module support 3 | ======================================================= 4 | 5 | This directory provides the key functionality for test support that IPython 6 | needs as a nose plugin, which can be installed for use in projects other than 7 | IPython. 8 | 9 | The presence of a Makefile here is mostly for development and debugging 10 | purposes as it only provides a few shorthand commands. You can manually 11 | install the plugin by using standard Python procedures (``setup.py install`` 12 | with appropriate arguments). 13 | 14 | To install the plugin using the Makefile, edit its first line to reflect where 15 | you'd like the installation. If you want it system-wide, you may want to edit 16 | the install line in the plugin target to use sudo and no prefix:: 17 | 18 | sudo python setup.py install 19 | 20 | instead of the code using `--prefix` that's in there. 21 | 22 | Once you've set the prefix, simply build/install the plugin with:: 23 | 24 | make 25 | 26 | and run the tests with:: 27 | 28 | make test 29 | 30 | You should see output similar to:: 31 | 32 | maqroll[plugin]> make test 33 | nosetests -s --with-ipdoctest --doctest-tests dtexample.py 34 | .. 35 | ---------------------------------------------------------------------- 36 | Ran 2 tests in 0.016s 37 | 38 | OK 39 | 40 | -------------------------------------------------------------------------------- /docs/source/install/index.rst: -------------------------------------------------------------------------------- 1 | .. _install_index: 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | .. toctree:: 8 | :maxdepth: 3 9 | :hidden: 10 | 11 | 12 | install 13 | kernel_install 14 | 15 | 16 | 17 | This sections will guide you through :ref:`installing IPython itself `, and 18 | installing :ref:`kernels for Jupyter ` if you wish to work with 19 | multiple version of Python, or multiple environments. 20 | 21 | 22 | Quick install reminder 23 | ~~~~~~~~~~~~~~~~~~~~~~ 24 | 25 | Here is a quick reminder of the commands needed for installation if you are 26 | already familiar with IPython and are just searching to refresh your memory: 27 | 28 | Install IPython: 29 | 30 | .. code-block:: bash 31 | 32 | $ pip install ipython 33 | 34 | 35 | Install and register an IPython kernel with Jupyter: 36 | 37 | 38 | .. code-block:: bash 39 | 40 | $ python -m pip install ipykernel 41 | 42 | $ python -m ipykernel install [--user] [--name ] [--display-name <"User Friendly Name">] 43 | 44 | for more help see 45 | 46 | .. code-block:: bash 47 | 48 | $ python -m ipykernel install --help 49 | 50 | 51 | 52 | .. seealso:: 53 | 54 | `Installing Jupyter `__ 55 | The Notebook, nbconvert, and many other former pieces of IPython are now 56 | part of Project Jupyter. 57 | 58 | 59 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_importstring.py: -------------------------------------------------------------------------------- 1 | """Tests for IPython.utils.importstring.""" 2 | 3 | #----------------------------------------------------------------------------- 4 | # Copyright (C) 2013 The IPython Development Team 5 | # 6 | # Distributed under the terms of the BSD License. The full license is in 7 | # the file COPYING, distributed as part of this software. 8 | #----------------------------------------------------------------------------- 9 | 10 | #----------------------------------------------------------------------------- 11 | # Imports 12 | #----------------------------------------------------------------------------- 13 | 14 | import nose.tools as nt 15 | 16 | from IPython.utils.importstring import import_item 17 | 18 | #----------------------------------------------------------------------------- 19 | # Tests 20 | #----------------------------------------------------------------------------- 21 | 22 | def test_import_plain(): 23 | "Test simple imports" 24 | import os 25 | os2 = import_item('os') 26 | nt.assert_true(os is os2) 27 | 28 | 29 | def test_import_nested(): 30 | "Test nested imports from the stdlib" 31 | from os import path 32 | path2 = import_item('os.path') 33 | nt.assert_true(path is path2) 34 | 35 | 36 | def test_import_raises(): 37 | "Test that failing imports raise the right exception" 38 | nt.assert_raises(ImportError, import_item, 'IPython.foobar') 39 | 40 | -------------------------------------------------------------------------------- /IPython/terminal/pt_inputhooks/qt.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from IPython.external.qt_for_kernel import QtCore, QtGui 3 | 4 | # If we create a QApplication, keep a reference to it so that it doesn't get 5 | # garbage collected. 6 | _appref = None 7 | 8 | 9 | def inputhook(context): 10 | global _appref 11 | app = QtCore.QCoreApplication.instance() 12 | if not app: 13 | _appref = app = QtGui.QApplication([" "]) 14 | event_loop = QtCore.QEventLoop(app) 15 | 16 | if sys.platform == 'win32': 17 | # The QSocketNotifier method doesn't appear to work on Windows. 18 | # Use polling instead. 19 | timer = QtCore.QTimer() 20 | timer.timeout.connect(event_loop.quit) 21 | while not context.input_is_ready(): 22 | timer.start(50) # 50 ms 23 | event_loop.exec_() 24 | timer.stop() 25 | else: 26 | # On POSIX platforms, we can use a file descriptor to quit the event 27 | # loop when there is input ready to read. 28 | notifier = QtCore.QSocketNotifier(context.fileno(), 29 | QtCore.QSocketNotifier.Read) 30 | # connect the callback we care about before we turn it on 31 | notifier.activated.connect(event_loop.exit) 32 | notifier.setEnabled(True) 33 | # only start the event loop we are not already flipped 34 | if not context.input_is_ready(): 35 | event_loop.exec_() 36 | -------------------------------------------------------------------------------- /docs/source/whatsnew/index.rst: -------------------------------------------------------------------------------- 1 | .. Developers should add in this file, during each release cycle, information 2 | .. about important changes they've made, in a summary format that's meant for 3 | .. end users. For each release we normally have three sections: features, bug 4 | .. fixes and api breakage. 5 | .. Please remember to credit the authors of the contributions by name, 6 | .. especially when they are new users or developers who do not regularly 7 | .. participate in IPython's development. 8 | 9 | .. _whatsnew_index: 10 | 11 | ===================== 12 | What's new in IPython 13 | ===================== 14 | 15 | This section documents the changes that have been made in various versions of 16 | IPython. Users should consult these pages to learn about new features, bug 17 | fixes and backwards incompatibilities. Developers should summarize the 18 | development work they do here in a user friendly format. 19 | 20 | .. toctree:: 21 | :maxdepth: 1 22 | 23 | developement 24 | version6 25 | github-stats-6 26 | version5 27 | github-stats-5 28 | version4 29 | github-stats-4 30 | version3 31 | github-stats-3 32 | version3_widget_migration 33 | version2.0 34 | github-stats-2.0 35 | version1.0 36 | github-stats-1.0 37 | version0.13 38 | github-stats-0.13 39 | version0.12 40 | github-stats-0.12 41 | version0.11 42 | github-stats-0.11 43 | version0.10 44 | version0.9 45 | version0.8 46 | 47 | 48 | -------------------------------------------------------------------------------- /tools/mknbindex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple script to auto-generate the index of notebooks in a given directory. 3 | """ 4 | 5 | import glob 6 | import urllib 7 | 8 | notebooks = sorted(glob.glob('*.ipynb')) 9 | 10 | tpl = ( '* [{0}](http://nbviewer.ipython.org/url/github.com/ipython/ipython/' 11 | 'raw/master/examples/notebooks/{1})' ) 12 | 13 | idx = [ 14 | """# A collection of Notebooks for using IPython effectively 15 | 16 | The following notebooks showcase multiple aspects of IPython, from its basic 17 | use to more advanced scenarios. They introduce you to the use of the Notebook 18 | and also cover aspects of IPython that are available in other clients, such as 19 | the cell magics for multi-language integration or our extended display 20 | protocol. 21 | 22 | For beginners, we recommend that you start with the 5-part series that 23 | introduces the system, and later read others as the topics interest you. 24 | 25 | Once you are familiar with the notebook system, we encourage you to visit our 26 | [gallery](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks) 27 | where you will find many more examples that cover areas from basic Python 28 | programming to advanced topics in scientific computing. 29 | """] 30 | 31 | idx.extend(tpl.format(nb.replace('.ipynb',''), urllib.quote(nb)) 32 | for nb in notebooks) 33 | 34 | with open('README.md', 'w') as f: 35 | f.write('\n'.join(idx)) 36 | f.write('\n') 37 | -------------------------------------------------------------------------------- /IPython/core/tests/test_splitinput.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import nose.tools as nt 3 | 4 | from IPython.core.splitinput import split_user_input, LineInfo 5 | from IPython.testing import tools as tt 6 | from IPython.utils import py3compat 7 | 8 | tests = [ 9 | ('x=1', ('', '', 'x', '=1')), 10 | ('?', ('', '?', '', '')), 11 | ('??', ('', '??', '', '')), 12 | (' ?', (' ', '?', '', '')), 13 | (' ??', (' ', '??', '', '')), 14 | ('??x', ('', '??', 'x', '')), 15 | ('?x=1', ('', '?', 'x', '=1')), 16 | ('!ls', ('', '!', 'ls', '')), 17 | (' !ls', (' ', '!', 'ls', '')), 18 | ('!!ls', ('', '!!', 'ls', '')), 19 | (' !!ls', (' ', '!!', 'ls', '')), 20 | (',ls', ('', ',', 'ls', '')), 21 | (';ls', ('', ';', 'ls', '')), 22 | (' ;ls', (' ', ';', 'ls', '')), 23 | ('f.g(x)', ('', '', 'f.g', '(x)')), 24 | ('f.g (x)', ('', '', 'f.g', '(x)')), 25 | ('?%hist1', ('', '?', '%hist1', '')), 26 | ('?%%hist2', ('', '?', '%%hist2', '')), 27 | ('??%hist3', ('', '??', '%hist3', '')), 28 | ('??%%hist4', ('', '??', '%%hist4', '')), 29 | ('?x*', ('', '?', 'x*', '')), 30 | ] 31 | tests.append((u"Pérez Fernando", (u'', u'', u'Pérez', u'Fernando'))) 32 | 33 | def test_split_user_input(): 34 | return tt.check_pairs(split_user_input, tests) 35 | 36 | def test_LineInfo(): 37 | """Simple test for LineInfo construction and str()""" 38 | linfo = LineInfo(' %cd /home') 39 | nt.assert_equal(str(linfo), 'LineInfo [ |%|cd|/home]') 40 | -------------------------------------------------------------------------------- /examples/IPython Kernel/nbpackage/mynotebook.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# My Notebook" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": false 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "def foo():\n", 19 | " return \"foo\"" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 2, 25 | "metadata": { 26 | "collapsed": false 27 | }, 28 | "outputs": [], 29 | "source": [ 30 | "def has_ip_syntax():\n", 31 | " listing = !ls\n", 32 | " return listing" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 4, 38 | "metadata": { 39 | "collapsed": false 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "def whatsmyname():\n", 44 | " return __name__" 45 | ] 46 | } 47 | ], 48 | "metadata": { 49 | "kernelspec": { 50 | "display_name": "Python 3", 51 | "language": "python", 52 | "name": "python3" 53 | }, 54 | "language_info": { 55 | "codemirror_mode": { 56 | "name": "ipython", 57 | "version": 3 58 | }, 59 | "file_extension": ".py", 60 | "mimetype": "text/x-python", 61 | "name": "python", 62 | "nbconvert_exporter": "python", 63 | "pygments_lexer": "ipython3", 64 | "version": "3.4.2" 65 | } 66 | }, 67 | "nbformat": 4, 68 | "nbformat_minor": 0 69 | } 70 | -------------------------------------------------------------------------------- /IPython/testing/__init__.py: -------------------------------------------------------------------------------- 1 | """Testing support (tools to test IPython itself). 2 | """ 3 | 4 | #----------------------------------------------------------------------------- 5 | # Copyright (C) 2009-2011 The IPython Development Team 6 | # 7 | # Distributed under the terms of the BSD License. The full license is in 8 | # the file COPYING, distributed as part of this software. 9 | #----------------------------------------------------------------------------- 10 | 11 | #----------------------------------------------------------------------------- 12 | # Functions 13 | #----------------------------------------------------------------------------- 14 | 15 | # User-level entry point for testing 16 | def test(**kwargs): 17 | """Run the entire IPython test suite. 18 | 19 | Any of the options for run_iptestall() may be passed as keyword arguments. 20 | 21 | For example:: 22 | 23 | IPython.test(testgroups=['lib', 'config', 'utils'], fast=2) 24 | 25 | will run those three sections of the test suite, using two processes. 26 | """ 27 | 28 | # Do the import internally, so that this function doesn't increase total 29 | # import time 30 | from .iptestcontroller import run_iptestall, default_options 31 | options = default_options() 32 | for name, val in kwargs.items(): 33 | setattr(options, name, val) 34 | run_iptestall(options) 35 | 36 | # So nose doesn't try to run this as a test itself and we end up with an 37 | # infinite test loop 38 | test.__test__ = False 39 | -------------------------------------------------------------------------------- /examples/IPython Kernel/gui/gui-glut.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Simple GLUT example to manually test event loop integration. 3 | 4 | This is meant to run tests manually in ipython as: 5 | 6 | In [5]: %gui glut 7 | 8 | In [6]: %run gui-glut.py 9 | 10 | In [7]: gl.glClearColor(1,1,1,1) 11 | """ 12 | 13 | #!/usr/bin/env python 14 | import sys 15 | import OpenGL.GL as gl 16 | import OpenGL.GLUT as glut 17 | 18 | def close(): 19 | glut.glutDestroyWindow(glut.glutGetWindow()) 20 | 21 | def display(): 22 | gl.glClear (gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) 23 | glut.glutSwapBuffers() 24 | 25 | def resize(width,height): 26 | gl.glViewport(0, 0, width, height+4) 27 | gl.glMatrixMode(gl.GL_PROJECTION) 28 | gl.glLoadIdentity() 29 | gl.glOrtho(0, width, 0, height+4, -1, 1) 30 | gl.glMatrixMode(gl.GL_MODELVIEW) 31 | 32 | if glut.glutGetWindow() > 0: 33 | interactive = True 34 | glut.glutInit(sys.argv) 35 | glut.glutInitDisplayMode(glut.GLUT_DOUBLE | 36 | glut.GLUT_RGBA | 37 | glut.GLUT_DEPTH) 38 | else: 39 | interactive = False 40 | 41 | glut.glutCreateWindow(b'gui-glut') 42 | glut.glutDisplayFunc(display) 43 | glut.glutReshapeFunc(resize) 44 | # This is necessary on osx to be able to close the window 45 | # (else the close button is disabled) 46 | if sys.platform == 'darwin' and not bool(glut.HAVE_FREEGLUT): 47 | glut.glutWMCloseFunc(close) 48 | gl.glClearColor(0,0,0,1) 49 | 50 | if not interactive: 51 | glut.glutMainLoop() 52 | -------------------------------------------------------------------------------- /IPython/utils/tz.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Timezone utilities 4 | 5 | Just UTC-awareness right now 6 | """ 7 | 8 | #----------------------------------------------------------------------------- 9 | # Copyright (C) 2013 The IPython Development Team 10 | # 11 | # Distributed under the terms of the BSD License. The full license is in 12 | # the file COPYING, distributed as part of this software. 13 | #----------------------------------------------------------------------------- 14 | 15 | #----------------------------------------------------------------------------- 16 | # Imports 17 | #----------------------------------------------------------------------------- 18 | 19 | from datetime import tzinfo, timedelta, datetime 20 | 21 | #----------------------------------------------------------------------------- 22 | # Code 23 | #----------------------------------------------------------------------------- 24 | # constant for zero offset 25 | ZERO = timedelta(0) 26 | 27 | class tzUTC(tzinfo): 28 | """tzinfo object for UTC (zero offset)""" 29 | 30 | def utcoffset(self, d): 31 | return ZERO 32 | 33 | def dst(self, d): 34 | return ZERO 35 | 36 | UTC = tzUTC() 37 | 38 | def utc_aware(unaware): 39 | """decorator for adding UTC tzinfo to datetime's utcfoo methods""" 40 | def utc_method(*args, **kwargs): 41 | dt = unaware(*args, **kwargs) 42 | return dt.replace(tzinfo=UTC) 43 | return utc_method 44 | 45 | utcfromtimestamp = utc_aware(datetime.utcfromtimestamp) 46 | utcnow = utc_aware(datetime.utcnow) 47 | -------------------------------------------------------------------------------- /docs/source/about/history.rst: -------------------------------------------------------------------------------- 1 | .. _history: 2 | 3 | ======= 4 | History 5 | ======= 6 | 7 | Origins 8 | ======= 9 | 10 | IPython was starting in 2001 by Fernando Perez while he was a graduate student 11 | at the University of Colorado, Boulder. IPython as we know it today grew out 12 | of the following three projects: 13 | 14 | * ipython by Fernando Pérez. Fernando began using Python and ipython began as 15 | an outgrowth of his desire for things like Mathematica-style prompts, access 16 | to previous output (again like Mathematica's % syntax) and a flexible 17 | configuration system (something better than :envvar:`PYTHONSTARTUP`). 18 | * IPP by Janko Hauser. Very well organized, great usability. Had 19 | an old help system. IPP was used as the "container" code into 20 | which Fernando added the functionality from ipython and LazyPython. 21 | * LazyPython by Nathan Gray. Simple but very powerful. The quick 22 | syntax (auto parens, auto quotes) and verbose/colored tracebacks 23 | were all taken from here. 24 | 25 | Here is how Fernando describes the early history of IPython: 26 | 27 | When I found out about IPP and LazyPython I tried to join all three 28 | into a unified system. I thought this could provide a very nice 29 | working environment, both for regular programming and scientific 30 | computing: shell-like features, IDL/Matlab numerics, Mathematica-type 31 | prompt history and great object introspection and help facilities. I 32 | think it worked reasonably well, though it was a lot more work than I 33 | had initially planned. 34 | 35 | -------------------------------------------------------------------------------- /IPython/extensions/tests/test_storemagic.py: -------------------------------------------------------------------------------- 1 | import tempfile, os 2 | 3 | from traitlets.config.loader import Config 4 | import nose.tools as nt 5 | 6 | ip = get_ipython() 7 | ip.magic('load_ext storemagic') 8 | 9 | def test_store_restore(): 10 | ip.user_ns['foo'] = 78 11 | ip.magic('alias bar echo "hello"') 12 | tmpd = tempfile.mkdtemp() 13 | ip.magic('cd ' + tmpd) 14 | ip.magic('store foo') 15 | ip.magic('store bar') 16 | 17 | # Check storing 18 | nt.assert_equal(ip.db['autorestore/foo'], 78) 19 | nt.assert_in('bar', ip.db['stored_aliases']) 20 | 21 | # Remove those items 22 | ip.user_ns.pop('foo', None) 23 | ip.alias_manager.undefine_alias('bar') 24 | ip.magic('cd -') 25 | ip.user_ns['_dh'][:] = [] 26 | 27 | # Check restoring 28 | ip.magic('store -r') 29 | nt.assert_equal(ip.user_ns['foo'], 78) 30 | assert ip.alias_manager.is_alias('bar') 31 | nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) 32 | 33 | os.rmdir(tmpd) 34 | 35 | def test_autorestore(): 36 | ip.user_ns['foo'] = 95 37 | ip.magic('store foo') 38 | del ip.user_ns['foo'] 39 | c = Config() 40 | c.StoreMagics.autorestore = False 41 | orig_config = ip.config 42 | try: 43 | ip.config = c 44 | ip.extension_manager.reload_extension('storemagic') 45 | nt.assert_not_in('foo', ip.user_ns) 46 | c.StoreMagics.autorestore = True 47 | ip.extension_manager.reload_extension('storemagic') 48 | nt.assert_equal(ip.user_ns['foo'], 95) 49 | finally: 50 | ip.config = orig_config 51 | -------------------------------------------------------------------------------- /tools/check_sources.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Utility to look for hard tabs and \r characters in all sources. 3 | 4 | Usage: 5 | 6 | ./check_sources.py 7 | 8 | It prints summaries and if chosen, line-by-line info of where \\t or \\r 9 | characters can be found in our source tree. 10 | """ 11 | 12 | # Config 13 | # If true, all lines that have tabs are printed, with line number 14 | full_report_tabs = True 15 | # If true, all lines that have tabs are printed, with line number 16 | full_report_rets = False 17 | 18 | # Code begins 19 | from IPython.external.path import path 20 | 21 | rets = [] 22 | tabs = [] 23 | 24 | for f in path('..').walkfiles('*.py'): 25 | errs = '' 26 | cont = f.bytes() 27 | if '\t' in cont: 28 | errs+='t' 29 | tabs.append(f) 30 | 31 | if '\r' in cont: 32 | errs+='r' 33 | rets.append(f) 34 | 35 | if errs: 36 | print("%3s" % errs, f) 37 | 38 | if 't' in errs and full_report_tabs: 39 | for ln,line in enumerate(f.lines()): 40 | if '\t' in line: 41 | print('TAB:',ln,':',line, end=' ') 42 | 43 | if 'r' in errs and full_report_rets: 44 | for ln,line in enumerate(open(f.abspath(),'rb')): 45 | if '\r' in line: 46 | print('RET:',ln,':',line, end=' ') 47 | 48 | # Summary at the end, to call cleanup tools if necessary 49 | if tabs: 50 | print('Hard tabs found. These can be cleaned with untabify:') 51 | for f in tabs: print(f, end=' ') 52 | if rets: 53 | print('Carriage returns (\\r) found in:') 54 | for f in rets: print(f, end=' ') 55 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_openpy.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os.path 3 | import nose.tools as nt 4 | 5 | from IPython.utils import openpy 6 | 7 | mydir = os.path.dirname(__file__) 8 | nonascii_path = os.path.join(mydir, '../../core/tests/nonascii.py') 9 | 10 | def test_detect_encoding(): 11 | f = open(nonascii_path, 'rb') 12 | enc, lines = openpy.detect_encoding(f.readline) 13 | nt.assert_equal(enc, 'iso-8859-5') 14 | 15 | def test_read_file(): 16 | read_specified_enc = io.open(nonascii_path, encoding='iso-8859-5').read() 17 | read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False) 18 | nt.assert_equal(read_detected_enc, read_specified_enc) 19 | assert u'coding: iso-8859-5' in read_detected_enc 20 | 21 | read_strip_enc_cookie = openpy.read_py_file(nonascii_path, skip_encoding_cookie=True) 22 | assert u'coding: iso-8859-5' not in read_strip_enc_cookie 23 | 24 | def test_source_to_unicode(): 25 | with io.open(nonascii_path, 'rb') as f: 26 | source_bytes = f.read() 27 | nt.assert_equal(openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines(), 28 | source_bytes.decode('iso-8859-5').splitlines()) 29 | 30 | source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True) 31 | nt.assert_not_in(u'coding: iso-8859-5', source_no_cookie) 32 | 33 | def test_list_readline(): 34 | l = ['a', 'b'] 35 | readline = openpy._list_readline(l) 36 | nt.assert_equal(readline(), 'a') 37 | nt.assert_equal(readline(), 'b') 38 | with nt.assert_raises(StopIteration): 39 | readline() -------------------------------------------------------------------------------- /IPython/utils/tests/test_dir2.py: -------------------------------------------------------------------------------- 1 | import nose.tools as nt 2 | from IPython.utils.dir2 import dir2 3 | 4 | 5 | class Base(object): 6 | x = 1 7 | z = 23 8 | 9 | 10 | def test_base(): 11 | res = dir2(Base()) 12 | assert ('x' in res) 13 | assert ('z' in res) 14 | assert ('y' not in res) 15 | assert ('__class__' in res) 16 | nt.assert_equal(res.count('x'), 1) 17 | nt.assert_equal(res.count('__class__'), 1) 18 | 19 | def test_SubClass(): 20 | 21 | class SubClass(Base): 22 | y = 2 23 | 24 | res = dir2(SubClass()) 25 | assert ('y' in res) 26 | nt.assert_equal(res.count('y'), 1) 27 | nt.assert_equal(res.count('x'), 1) 28 | 29 | 30 | def test_SubClass_with_trait_names_attr(): 31 | # usecase: trait_names is used in a class describing psychological classification 32 | 33 | class SubClass(Base): 34 | y = 2 35 | trait_names = 44 36 | 37 | res = dir2(SubClass()) 38 | assert('trait_names' in res) 39 | 40 | 41 | def test_misbehaving_object_without_trait_names(): 42 | # dir2 shouldn't raise even when objects are dumb and raise 43 | # something other than AttribteErrors on bad getattr. 44 | 45 | class MisbehavingGetattr(object): 46 | def __getattr__(self): 47 | raise KeyError("I should be caught") 48 | 49 | def some_method(self): 50 | pass 51 | 52 | class SillierWithDir(MisbehavingGetattr): 53 | def __dir__(self): 54 | return ['some_method'] 55 | 56 | for bad_klass in (MisbehavingGetattr, SillierWithDir): 57 | res = dir2(bad_klass()) 58 | assert('some_method' in res) 59 | -------------------------------------------------------------------------------- /docs/sphinxext/magics.py: -------------------------------------------------------------------------------- 1 | import re 2 | from sphinx import addnodes 3 | from sphinx.domains.std import StandardDomain 4 | from sphinx.roles import XRefRole 5 | 6 | name_re = re.compile(r"[\w_]+") 7 | 8 | def parse_magic(env, sig, signode): 9 | m = name_re.match(sig) 10 | if not m: 11 | raise Exception("Invalid magic command: %s" % sig) 12 | name = "%" + sig 13 | signode += addnodes.desc_name(name, name) 14 | return m.group(0) 15 | 16 | class LineMagicRole(XRefRole): 17 | """Cross reference role displayed with a % prefix""" 18 | prefix = "%" 19 | 20 | def process_link(self, env, refnode, has_explicit_title, title, target): 21 | if not has_explicit_title: 22 | title = self.prefix + title.lstrip("%") 23 | target = target.lstrip("%") 24 | return title, target 25 | 26 | def parse_cell_magic(env, sig, signode): 27 | m = name_re.match(sig) 28 | if not m: 29 | raise ValueError("Invalid cell magic: %s" % sig) 30 | name = "%%" + sig 31 | signode += addnodes.desc_name(name, name) 32 | return m.group(0) 33 | 34 | class CellMagicRole(LineMagicRole): 35 | """Cross reference role displayed with a %% prefix""" 36 | prefix = "%%" 37 | 38 | def setup(app): 39 | app.add_object_type('magic', 'magic', 'pair: %s; magic command', parse_magic) 40 | StandardDomain.roles['magic'] = LineMagicRole() 41 | app.add_object_type('cellmagic', 'cellmagic', 'pair: %s; cell magic', parse_cell_magic) 42 | StandardDomain.roles['cellmagic'] = CellMagicRole() 43 | 44 | metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} 45 | return metadata 46 | -------------------------------------------------------------------------------- /IPython/core/payloadpage.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """A payload based version of page.""" 3 | 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import warnings 8 | from IPython.core.getipython import get_ipython 9 | 10 | 11 | def page(strng, start=0, screen_lines=0, pager_cmd=None): 12 | """Print a string, piping through a pager. 13 | 14 | This version ignores the screen_lines and pager_cmd arguments and uses 15 | IPython's payload system instead. 16 | 17 | Parameters 18 | ---------- 19 | strng : str or mime-dict 20 | Text to page, or a mime-type keyed dict of already formatted data. 21 | 22 | start : int 23 | Starting line at which to place the display. 24 | """ 25 | 26 | # Some routines may auto-compute start offsets incorrectly and pass a 27 | # negative value. Offset to 0 for robustness. 28 | start = max(0, start) 29 | shell = get_ipython() 30 | 31 | if isinstance(strng, dict): 32 | data = strng 33 | else: 34 | data = {'text/plain' : strng} 35 | payload = dict( 36 | source='page', 37 | data=data, 38 | start=start, 39 | ) 40 | shell.payload_manager.write_payload(payload) 41 | 42 | 43 | def install_payload_page(): 44 | """DEPRECATED, use show_in_pager hook 45 | 46 | Install this version of page as IPython.core.page.page. 47 | """ 48 | warnings.warn("""install_payload_page is deprecated. 49 | Use `ip.set_hook('show_in_pager, page.as_hook(payloadpage.page))` 50 | """) 51 | from IPython.core import page as corepage 52 | corepage.page = page 53 | -------------------------------------------------------------------------------- /tools/toollib.py: -------------------------------------------------------------------------------- 1 | """Various utilities common to IPython release and maintenance tools. 2 | """ 3 | 4 | # Library imports 5 | import os 6 | 7 | # Useful shorthands 8 | pjoin = os.path.join 9 | cd = os.chdir 10 | 11 | # Constants 12 | 13 | # SSH root address of the archive site 14 | archive_user = 'ipython@archive.ipython.org' 15 | archive_dir = 'archive.ipython.org' 16 | archive = '%s:%s' % (archive_user, archive_dir) 17 | 18 | # Build commands 19 | # Source dists 20 | sdists = './setup.py sdist --formats=gztar' 21 | # Binary dists 22 | def buildwheels(): 23 | sh('python3 setupegg.py bdist_wheel') 24 | 25 | # Utility functions 26 | def sh(cmd): 27 | """Run system command in shell, raise SystemExit if it returns an error.""" 28 | print("$", cmd) 29 | stat = os.system(cmd) 30 | #stat = 0 # Uncomment this and comment previous to run in debug mode 31 | if stat: 32 | raise SystemExit("Command %s failed with code: %s" % (cmd, stat)) 33 | 34 | # Backwards compatibility 35 | c = sh 36 | 37 | def get_ipdir(): 38 | """Get IPython directory from command line, or assume it's the one above.""" 39 | 40 | # Initialize arguments and check location 41 | ipdir = pjoin(os.path.dirname(__file__), os.pardir) 42 | 43 | ipdir = os.path.abspath(ipdir) 44 | 45 | cd(ipdir) 46 | if not os.path.isdir('IPython') and os.path.isfile('setup.py'): 47 | raise SystemExit('Invalid ipython directory: %s' % ipdir) 48 | return ipdir 49 | 50 | try: 51 | execfile = execfile 52 | except NameError: 53 | def execfile(fname, globs, locs=None): 54 | locs = locs or globs 55 | exec(compile(open(fname).read(), fname, "exec"), globs, locs) 56 | -------------------------------------------------------------------------------- /IPython/external/decorators/_numpy_testing_noseclasses.py: -------------------------------------------------------------------------------- 1 | # IPython: modified copy of numpy.testing.noseclasses, so 2 | # IPython.external._decorators works without numpy being installed. 3 | 4 | # These classes implement a "known failure" error class. 5 | 6 | import os 7 | 8 | from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin 9 | 10 | class KnownFailureTest(Exception): 11 | '''Raise this exception to mark a test as a known failing test.''' 12 | pass 13 | 14 | 15 | class KnownFailure(ErrorClassPlugin): 16 | '''Plugin that installs a KNOWNFAIL error class for the 17 | KnownFailureClass exception. When KnownFailureTest is raised, 18 | the exception will be logged in the knownfail attribute of the 19 | result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the 20 | exception will not be counted as an error or failure.''' 21 | enabled = True 22 | knownfail = ErrorClass(KnownFailureTest, 23 | label='KNOWNFAIL', 24 | isfailure=False) 25 | 26 | def options(self, parser, env=os.environ): 27 | env_opt = 'NOSE_WITHOUT_KNOWNFAIL' 28 | parser.add_option('--no-knownfail', action='store_true', 29 | dest='noKnownFail', default=env.get(env_opt, False), 30 | help='Disable special handling of KnownFailureTest ' 31 | 'exceptions') 32 | 33 | def configure(self, options, conf): 34 | if not self.can_configure: 35 | return 36 | self.conf = conf 37 | disable = getattr(options, 'noKnownFail', False) 38 | if disable: 39 | self.enabled = False 40 | 41 | 42 | -------------------------------------------------------------------------------- /IPython/core/tests/refbug.py: -------------------------------------------------------------------------------- 1 | """Minimal script to reproduce our nasty reference counting bug. 2 | 3 | The problem is related to https://github.com/ipython/ipython/issues/141 4 | 5 | The original fix for that appeared to work, but John D. Hunter found a 6 | matplotlib example which, when run twice in a row, would break. The problem 7 | were references held by open figures to internals of Tkinter. 8 | 9 | This code reproduces the problem that John saw, without matplotlib. 10 | 11 | This script is meant to be called by other parts of the test suite that call it 12 | via %run as if it were executed interactively by the user. As of 2011-05-29, 13 | test_run.py calls it. 14 | """ 15 | 16 | #----------------------------------------------------------------------------- 17 | # Module imports 18 | #----------------------------------------------------------------------------- 19 | import sys 20 | 21 | from IPython import get_ipython 22 | 23 | #----------------------------------------------------------------------------- 24 | # Globals 25 | #----------------------------------------------------------------------------- 26 | 27 | # This needs to be here because nose and other test runners will import 28 | # this module. Importing this module has potential side effects that we 29 | # want to prevent. 30 | if __name__ == '__main__': 31 | 32 | ip = get_ipython() 33 | 34 | if not '_refbug_cache' in ip.user_ns: 35 | ip.user_ns['_refbug_cache'] = [] 36 | 37 | 38 | aglobal = 'Hello' 39 | def f(): 40 | return aglobal 41 | 42 | cache = ip.user_ns['_refbug_cache'] 43 | cache.append(f) 44 | 45 | def call_f(): 46 | for func in cache: 47 | print('lowercased:',func().lower()) 48 | -------------------------------------------------------------------------------- /examples/Index.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "# IPython Documentation" 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": {}, 20 | "source": [ 21 | "This directory contains IPython's notebook-based documentation. This augments our [Sphinx-based documentation](http://ipython.org/ipython-doc/stable/index.html) with notebooks that contain interactive tutorials and examples. Over time, more of our documentation will be pulled into this format." 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "## Topics" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "* [IPython Kernel](IPython Kernel/Index.ipynb): IPython's core syntax and command line features available in all frontends\n", 36 | "* [Embedding](Embedding/Index.ipynb): Embedding and reusing IPython's components into other applications\n" 37 | ] 38 | } 39 | ], 40 | "metadata": { 41 | "kernelspec": { 42 | "display_name": "Python 3", 43 | "language": "python", 44 | "name": "python3" 45 | }, 46 | "language_info": { 47 | "codemirror_mode": { 48 | "name": "ipython", 49 | "version": 3 50 | }, 51 | "file_extension": ".py", 52 | "mimetype": "text/x-python", 53 | "name": "python", 54 | "nbconvert_exporter": "python", 55 | "pygments_lexer": "ipython3", 56 | "version": "3.4.3" 57 | } 58 | }, 59 | "nbformat": 4, 60 | "nbformat_minor": 0 61 | } 62 | -------------------------------------------------------------------------------- /IPython/core/magics/__init__.py: -------------------------------------------------------------------------------- 1 | """Implementation of all the magic functions built into IPython. 2 | """ 3 | #----------------------------------------------------------------------------- 4 | # Copyright (c) 2012 The IPython Development Team. 5 | # 6 | # Distributed under the terms of the Modified BSD License. 7 | # 8 | # The full license is in the file COPYING.txt, distributed with this software. 9 | #----------------------------------------------------------------------------- 10 | 11 | #----------------------------------------------------------------------------- 12 | # Imports 13 | #----------------------------------------------------------------------------- 14 | 15 | from ..magic import Magics, magics_class 16 | from .auto import AutoMagics 17 | from .basic import BasicMagics 18 | from .code import CodeMagics, MacroToEdit 19 | from .config import ConfigMagics 20 | from .display import DisplayMagics 21 | from .execution import ExecutionMagics 22 | from .extension import ExtensionMagics 23 | from .history import HistoryMagics 24 | from .logging import LoggingMagics 25 | from .namespace import NamespaceMagics 26 | from .osm import OSMagics 27 | from .pylab import PylabMagics 28 | from .script import ScriptMagics 29 | 30 | #----------------------------------------------------------------------------- 31 | # Magic implementation classes 32 | #----------------------------------------------------------------------------- 33 | 34 | @magics_class 35 | class UserMagics(Magics): 36 | """Placeholder for user-defined magics to be added at runtime. 37 | 38 | All magics are eventually merged into a single namespace at runtime, but we 39 | use this class to isolate the magics defined dynamically by the user into 40 | their own class. 41 | """ 42 | -------------------------------------------------------------------------------- /IPython/core/tests/test_events.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import Mock 3 | 4 | from IPython.core import events 5 | import IPython.testing.tools as tt 6 | 7 | def ping_received(): 8 | pass 9 | 10 | class CallbackTests(unittest.TestCase): 11 | def setUp(self): 12 | self.em = events.EventManager(get_ipython(), {'ping_received': ping_received}) 13 | 14 | def test_register_unregister(self): 15 | cb = Mock() 16 | 17 | self.em.register('ping_received', cb) 18 | self.em.trigger('ping_received') 19 | self.assertEqual(cb.call_count, 1) 20 | 21 | self.em.unregister('ping_received', cb) 22 | self.em.trigger('ping_received') 23 | self.assertEqual(cb.call_count, 1) 24 | 25 | def test_cb_error(self): 26 | cb = Mock(side_effect=ValueError) 27 | self.em.register('ping_received', cb) 28 | with tt.AssertPrints("Error in callback"): 29 | self.em.trigger('ping_received') 30 | 31 | def test_unregister_during_callback(self): 32 | invoked = [False] * 3 33 | 34 | def func1(*_): 35 | invoked[0] = True 36 | self.em.unregister('ping_received', func1) 37 | self.em.register('ping_received', func3) 38 | 39 | def func2(*_): 40 | invoked[1] = True 41 | self.em.unregister('ping_received', func2) 42 | 43 | def func3(*_): 44 | invoked[2] = True 45 | 46 | self.em.register('ping_received', func1) 47 | self.em.register('ping_received', func2) 48 | 49 | self.em.trigger('ping_received') 50 | self.assertEqual([True, True, False], invoked) 51 | self.assertEqual([func3], self.em.callbacks['ping_received']) 52 | -------------------------------------------------------------------------------- /IPython/testing/plugin/Makefile: -------------------------------------------------------------------------------- 1 | # Set this prefix to where you want to install the plugin 2 | PREFIX=/usr/local 3 | 4 | NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors 5 | NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt \ 6 | --detailed-errors 7 | 8 | SRC=ipdoctest.py setup.py ../decorators.py 9 | 10 | # Default target for clean 'make' 11 | default: interactiveshell 12 | 13 | # The actual plugin installation 14 | plugin: IPython_doctest_plugin.egg-info 15 | 16 | # Simple targets that test one thing 17 | simple: plugin simple.py 18 | $(NOSE) simple.py 19 | 20 | dtest: plugin dtexample.py 21 | $(NOSE) dtexample.py 22 | 23 | rtest: plugin test_refs.py 24 | $(NOSE) test_refs.py 25 | 26 | test: plugin dtexample.py 27 | $(NOSE) dtexample.py test*.py test*.txt 28 | 29 | deb: plugin dtexample.py 30 | $(NOSE) test_combo.txt 31 | 32 | # IPython tests 33 | deco: 34 | $(NOSE0) IPython.testing.decorators 35 | 36 | magic: plugin 37 | $(NOSE) IPython.core.magic 38 | 39 | excolors: plugin 40 | $(NOSE) IPython.core.excolors 41 | 42 | interactiveshell: plugin 43 | $(NOSE) IPython.core.interactiveshell 44 | 45 | strd: plugin 46 | $(NOSE) IPython.core.strdispatch 47 | 48 | engine: plugin 49 | $(NOSE) IPython.kernel 50 | 51 | tf: plugin 52 | $(NOSE) IPython.config.traitlets 53 | 54 | # All of ipython itself 55 | ipython: plugin 56 | $(NOSE) IPython 57 | 58 | 59 | # Combined targets 60 | sr: rtest strd 61 | 62 | base: dtest rtest test strd deco 63 | 64 | quick: base interactiveshell ipipe 65 | 66 | all: base ipython 67 | 68 | # Main plugin and cleanup 69 | IPython_doctest_plugin.egg-info: $(SRC) 70 | python setup.py install --prefix=$(PREFIX) 71 | touch $@ 72 | 73 | clean: 74 | rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/ 75 | -------------------------------------------------------------------------------- /examples/Embedding/embed_class_short.py: -------------------------------------------------------------------------------- 1 | """Quick code snippets for embedding IPython into other programs. 2 | 3 | See embed_class_long.py for full details, this file has the bare minimum code for 4 | cut and paste use once you understand how to use the system.""" 5 | 6 | #--------------------------------------------------------------------------- 7 | # This code loads IPython but modifies a few things if it detects it's running 8 | # embedded in another IPython session (helps avoid confusion) 9 | 10 | try: 11 | get_ipython 12 | except NameError: 13 | banner=exit_msg='' 14 | else: 15 | banner = '*** Nested interpreter ***' 16 | exit_msg = '*** Back in main IPython ***' 17 | 18 | # First import the embed function 19 | from IPython.terminal.embed import InteractiveShellEmbed 20 | # Now create the IPython shell instance. Put ipshell() anywhere in your code 21 | # where you want it to open. 22 | ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg) 23 | 24 | #--------------------------------------------------------------------------- 25 | # This code will load an embeddable IPython shell always with no changes for 26 | # nested embededings. 27 | 28 | from IPython import embed 29 | # Now embed() will open IPython anywhere in the code. 30 | 31 | #--------------------------------------------------------------------------- 32 | # This code loads an embeddable shell only if NOT running inside 33 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a 34 | # dummy function. 35 | 36 | try: 37 | get_ipython 38 | except NameError: 39 | from IPython.terminal.embed import InteractiveShellEmbed 40 | ipshell = InteractiveShellEmbed() 41 | # Now ipshell() will open IPython anywhere in the code 42 | else: 43 | # Define a dummy ipshell() so the same code doesn't crash inside an 44 | # interactive IPython 45 | def ipshell(): pass 46 | -------------------------------------------------------------------------------- /IPython/core/tests/test_autocall.py: -------------------------------------------------------------------------------- 1 | """These kinds of tests are less than ideal, but at least they run. 2 | 3 | This was an old test that was being run interactively in the top-level tests/ 4 | directory, which we are removing. For now putting this here ensures at least 5 | we do run the test, though ultimately this functionality should all be tested 6 | with better-isolated tests that don't rely on the global instance in iptest. 7 | """ 8 | from IPython.core.splitinput import LineInfo 9 | from IPython.core.prefilter import AutocallChecker 10 | from IPython.utils import py3compat 11 | from IPython.testing.globalipapp import get_ipython 12 | 13 | 14 | ip = get_ipython() 15 | 16 | 17 | @py3compat.doctest_refactor_print 18 | def doctest_autocall(): 19 | """ 20 | In [1]: def f1(a,b,c): 21 | ...: return a+b+c 22 | ...: 23 | 24 | In [2]: def f2(a): 25 | ...: return a + a 26 | ...: 27 | 28 | In [3]: def r(x): 29 | ...: return True 30 | ...: 31 | 32 | In [4]: ;f2 a b c 33 | Out[4]: 'a b ca b c' 34 | 35 | In [5]: assert _ == "a b ca b c" 36 | 37 | In [6]: ,f1 a b c 38 | Out[6]: 'abc' 39 | 40 | In [7]: assert _ == 'abc' 41 | 42 | In [8]: print _ 43 | abc 44 | 45 | In [9]: /f1 1,2,3 46 | Out[9]: 6 47 | 48 | In [10]: assert _ == 6 49 | 50 | In [11]: /f2 4 51 | Out[11]: 8 52 | 53 | In [12]: assert _ == 8 54 | 55 | In [12]: del f1, f2 56 | 57 | In [13]: ,r a 58 | Out[13]: True 59 | 60 | In [14]: assert _ == True 61 | 62 | In [15]: r'a' 63 | Out[15]: 'a' 64 | 65 | In [16]: assert _ == 'a' 66 | """ 67 | 68 | 69 | def test_autocall_should_ignore_raw_strings(): 70 | line_info = LineInfo("r'a'") 71 | pm = ip.prefilter_manager 72 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) 73 | assert ac.check(line_info) is None 74 | -------------------------------------------------------------------------------- /IPython/core/macro.py: -------------------------------------------------------------------------------- 1 | """Support for interactive macros in IPython""" 2 | 3 | #***************************************************************************** 4 | # Copyright (C) 2001-2005 Fernando Perez 5 | # 6 | # Distributed under the terms of the BSD License. The full license is in 7 | # the file COPYING, distributed as part of this software. 8 | #***************************************************************************** 9 | 10 | import re 11 | 12 | from IPython.utils.encoding import DEFAULT_ENCODING 13 | 14 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") 15 | 16 | class Macro(object): 17 | """Simple class to store the value of macros as strings. 18 | 19 | Macro is just a callable that executes a string of IPython 20 | input when called. 21 | """ 22 | 23 | def __init__(self,code): 24 | """store the macro value, as a single string which can be executed""" 25 | lines = [] 26 | enc = None 27 | for line in code.splitlines(): 28 | coding_match = coding_declaration.match(line) 29 | if coding_match: 30 | enc = coding_match.group(1) 31 | else: 32 | lines.append(line) 33 | code = "\n".join(lines) 34 | if isinstance(code, bytes): 35 | code = code.decode(enc or DEFAULT_ENCODING) 36 | self.value = code + '\n' 37 | 38 | def __str__(self): 39 | return self.value 40 | 41 | def __repr__(self): 42 | return 'IPython.macro.Macro(%s)' % repr(self.value) 43 | 44 | def __getstate__(self): 45 | """ needed for safe pickling via %store """ 46 | return {'value': self.value} 47 | 48 | def __add__(self, other): 49 | if isinstance(other, Macro): 50 | return Macro(self.value + other.value) 51 | elif isinstance(other, str): 52 | return Macro(self.value + other) 53 | raise TypeError 54 | -------------------------------------------------------------------------------- /IPython/utils/syspathcontext.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Context managers for adding things to sys.path temporarily. 4 | 5 | Authors: 6 | 7 | * Brian Granger 8 | """ 9 | 10 | #----------------------------------------------------------------------------- 11 | # Copyright (C) 2008-2011 The IPython Development Team 12 | # 13 | # Distributed under the terms of the BSD License. The full license is in 14 | # the file COPYING, distributed as part of this software. 15 | #----------------------------------------------------------------------------- 16 | 17 | import sys 18 | 19 | 20 | class appended_to_syspath(object): 21 | """A context for appending a directory to sys.path for a second.""" 22 | 23 | def __init__(self, dir): 24 | self.dir = dir 25 | 26 | def __enter__(self): 27 | if self.dir not in sys.path: 28 | sys.path.append(self.dir) 29 | self.added = True 30 | else: 31 | self.added = False 32 | 33 | def __exit__(self, type, value, traceback): 34 | if self.added: 35 | try: 36 | sys.path.remove(self.dir) 37 | except ValueError: 38 | pass 39 | # Returning False causes any exceptions to be re-raised. 40 | return False 41 | 42 | class prepended_to_syspath(object): 43 | """A context for prepending a directory to sys.path for a second.""" 44 | 45 | def __init__(self, dir): 46 | self.dir = dir 47 | 48 | def __enter__(self): 49 | if self.dir not in sys.path: 50 | sys.path.insert(0,self.dir) 51 | self.added = True 52 | else: 53 | self.added = False 54 | 55 | def __exit__(self, type, value, traceback): 56 | if self.added: 57 | try: 58 | sys.path.remove(self.dir) 59 | except ValueError: 60 | pass 61 | # Returning False causes any exceptions to be re-raised. 62 | return False 63 | -------------------------------------------------------------------------------- /tools/tests/heartbeat/gilsleep.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Holding the GIL for too long could disrupt the heartbeat due to non-copying sends.\n", 8 | "\n", 9 | "The following cell repeatedly calls a function that holds the GIL for five seconds.\n", 10 | "\n", 11 | "The heartbeat will fail after a few iterations prior to fixing Issue [#1260](https://github.com/ipython/ipython/issues/1260)." 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 1, 17 | "metadata": { 18 | "collapsed": false 19 | }, 20 | "outputs": [], 21 | "source": [ 22 | "import sys\n", 23 | "import time\n", 24 | "\n", 25 | "from cython import inline\n", 26 | "\n", 27 | "def gilsleep(t):\n", 28 | " \"\"\"gil-holding sleep with cython.inline\"\"\"\n", 29 | " code = '\\n'.join([\n", 30 | " 'from posix cimport unistd',\n", 31 | " 'unistd.sleep(t)',\n", 32 | " ])\n", 33 | " while True:\n", 34 | " inline(code, quiet=True, t=t)\n", 35 | " print time.time()\n", 36 | " sys.stdout.flush() # this is important\n", 37 | "\n", 38 | "gilsleep(5)" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": { 45 | "collapsed": true 46 | }, 47 | "outputs": [], 48 | "source": [] 49 | } 50 | ], 51 | "metadata": { 52 | "kernelspec": { 53 | "display_name": "Python 3", 54 | "language": "python", 55 | "name": "python3" 56 | }, 57 | "language_info": { 58 | "codemirror_mode": { 59 | "name": "ipython", 60 | "version": 3 61 | }, 62 | "file_extension": ".py", 63 | "mimetype": "text/x-python", 64 | "name": "python", 65 | "nbconvert_exporter": "python", 66 | "pygments_lexer": "ipython3", 67 | "version": "3.4.2" 68 | } 69 | }, 70 | "nbformat": 4, 71 | "nbformat_minor": 0 72 | } 73 | -------------------------------------------------------------------------------- /IPython/core/error.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Global exception classes for IPython.core. 4 | 5 | Authors: 6 | 7 | * Brian Granger 8 | * Fernando Perez 9 | * Min Ragan-Kelley 10 | 11 | Notes 12 | ----- 13 | """ 14 | 15 | #----------------------------------------------------------------------------- 16 | # Copyright (C) 2008 The IPython Development Team 17 | # 18 | # Distributed under the terms of the BSD License. The full license is in 19 | # the file COPYING, distributed as part of this software. 20 | #----------------------------------------------------------------------------- 21 | 22 | #----------------------------------------------------------------------------- 23 | # Imports 24 | #----------------------------------------------------------------------------- 25 | 26 | #----------------------------------------------------------------------------- 27 | # Exception classes 28 | #----------------------------------------------------------------------------- 29 | 30 | class IPythonCoreError(Exception): 31 | pass 32 | 33 | 34 | class TryNext(IPythonCoreError): 35 | """Try next hook exception. 36 | 37 | Raise this in your hook function to indicate that the next hook handler 38 | should be used to handle the operation. 39 | """ 40 | 41 | class UsageError(IPythonCoreError): 42 | """Error in magic function arguments, etc. 43 | 44 | Something that probably won't warrant a full traceback, but should 45 | nevertheless interrupt a macro / batch file. 46 | """ 47 | 48 | class StdinNotImplementedError(IPythonCoreError, NotImplementedError): 49 | """raw_input was requested in a context where it is not supported 50 | 51 | For use in IPython kernels, where only some frontends may support 52 | stdin requests. 53 | """ 54 | 55 | class InputRejected(Exception): 56 | """Input rejected by ast transformer. 57 | 58 | Raise this in your NodeTransformer to indicate that InteractiveShell should 59 | not execute the supplied input. 60 | """ 61 | -------------------------------------------------------------------------------- /IPython/core/payload.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Payload system for IPython. 3 | 4 | Authors: 5 | 6 | * Fernando Perez 7 | * Brian Granger 8 | """ 9 | 10 | #----------------------------------------------------------------------------- 11 | # Copyright (C) 2008-2011 The IPython Development Team 12 | # 13 | # Distributed under the terms of the BSD License. The full license is in 14 | # the file COPYING, distributed as part of this software. 15 | #----------------------------------------------------------------------------- 16 | 17 | #----------------------------------------------------------------------------- 18 | # Imports 19 | #----------------------------------------------------------------------------- 20 | 21 | from traitlets.config.configurable import Configurable 22 | from traitlets import List 23 | 24 | #----------------------------------------------------------------------------- 25 | # Main payload class 26 | #----------------------------------------------------------------------------- 27 | 28 | class PayloadManager(Configurable): 29 | 30 | _payload = List([]) 31 | 32 | def write_payload(self, data, single=True): 33 | """Include or update the specified `data` payload in the PayloadManager. 34 | 35 | If a previous payload with the same source exists and `single` is True, 36 | it will be overwritten with the new one. 37 | """ 38 | 39 | if not isinstance(data, dict): 40 | raise TypeError('Each payload write must be a dict, got: %r' % data) 41 | 42 | if single and 'source' in data: 43 | source = data['source'] 44 | for i, pl in enumerate(self._payload): 45 | if 'source' in pl and pl['source'] == source: 46 | self._payload[i] = data 47 | return 48 | 49 | self._payload.append(data) 50 | 51 | def read_payload(self): 52 | return self._payload 53 | 54 | def clear_payload(self): 55 | self._payload = [] 56 | -------------------------------------------------------------------------------- /IPython/utils/tempdir.py: -------------------------------------------------------------------------------- 1 | """ This module contains classes - NamedFileInTemporaryDirectory, TemporaryWorkingDirectory. 2 | 3 | These classes add extra features such as creating a named file in temporary directory and 4 | creating a context manager for the working directory which is also temporary. 5 | """ 6 | 7 | import os as _os 8 | from tempfile import TemporaryDirectory 9 | 10 | 11 | class NamedFileInTemporaryDirectory(object): 12 | 13 | def __init__(self, filename, mode='w+b', bufsize=-1, **kwds): 14 | """ 15 | Open a file named `filename` in a temporary directory. 16 | 17 | This context manager is preferred over `NamedTemporaryFile` in 18 | stdlib `tempfile` when one needs to reopen the file. 19 | 20 | Arguments `mode` and `bufsize` are passed to `open`. 21 | Rest of the arguments are passed to `TemporaryDirectory`. 22 | 23 | """ 24 | self._tmpdir = TemporaryDirectory(**kwds) 25 | path = _os.path.join(self._tmpdir.name, filename) 26 | self.file = open(path, mode, bufsize) 27 | 28 | def cleanup(self): 29 | self.file.close() 30 | self._tmpdir.cleanup() 31 | 32 | __del__ = cleanup 33 | 34 | def __enter__(self): 35 | return self.file 36 | 37 | def __exit__(self, type, value, traceback): 38 | self.cleanup() 39 | 40 | 41 | class TemporaryWorkingDirectory(TemporaryDirectory): 42 | """ 43 | Creates a temporary directory and sets the cwd to that directory. 44 | Automatically reverts to previous cwd upon cleanup. 45 | Usage example: 46 | 47 | with TemporaryWorkingDirectory() as tmpdir: 48 | ... 49 | """ 50 | def __enter__(self): 51 | self.old_wd = _os.getcwd() 52 | _os.chdir(self.name) 53 | return super(TemporaryWorkingDirectory, self).__enter__() 54 | 55 | def __exit__(self, exc, value, tb): 56 | _os.chdir(self.old_wd) 57 | return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb) 58 | -------------------------------------------------------------------------------- /IPython/testing/plugin/test_ipdoctest.py: -------------------------------------------------------------------------------- 1 | """Tests for the ipdoctest machinery itself. 2 | 3 | Note: in a file named test_X, functions whose only test is their docstring (as 4 | a doctest) and which have no test functionality of their own, should be called 5 | 'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the 6 | empty function call is counted as a test, which just inflates tests numbers 7 | artificially). 8 | """ 9 | from IPython.utils.py3compat import doctest_refactor_print 10 | 11 | @doctest_refactor_print 12 | def doctest_simple(): 13 | """ipdoctest must handle simple inputs 14 | 15 | In [1]: 1 16 | Out[1]: 1 17 | 18 | In [2]: print 1 19 | 1 20 | """ 21 | 22 | @doctest_refactor_print 23 | def doctest_multiline1(): 24 | """The ipdoctest machinery must handle multiline examples gracefully. 25 | 26 | In [2]: for i in range(4): 27 | ...: print i 28 | ...: 29 | 0 30 | 1 31 | 2 32 | 3 33 | """ 34 | 35 | @doctest_refactor_print 36 | def doctest_multiline2(): 37 | """Multiline examples that define functions and print output. 38 | 39 | In [7]: def f(x): 40 | ...: return x+1 41 | ...: 42 | 43 | In [8]: f(1) 44 | Out[8]: 2 45 | 46 | In [9]: def g(x): 47 | ...: print 'x is:',x 48 | ...: 49 | 50 | In [10]: g(1) 51 | x is: 1 52 | 53 | In [11]: g('hello') 54 | x is: hello 55 | """ 56 | 57 | 58 | def doctest_multiline3(): 59 | """Multiline examples with blank lines. 60 | 61 | In [12]: def h(x): 62 | ....: if x>1: 63 | ....: return x**2 64 | ....: # To leave a blank line in the input, you must mark it 65 | ....: # with a comment character: 66 | ....: # 67 | ....: # otherwise the doctest parser gets confused. 68 | ....: else: 69 | ....: return -1 70 | ....: 71 | 72 | In [13]: h(5) 73 | Out[13]: 25 74 | 75 | In [14]: h(1) 76 | Out[14]: -1 77 | 78 | In [15]: h(0) 79 | Out[15]: -1 80 | """ 81 | -------------------------------------------------------------------------------- /IPython/utils/strdispatch.py: -------------------------------------------------------------------------------- 1 | """String dispatch class to match regexps and dispatch commands. 2 | """ 3 | 4 | # Stdlib imports 5 | import re 6 | 7 | # Our own modules 8 | from IPython.core.hooks import CommandChainDispatcher 9 | 10 | # Code begins 11 | class StrDispatch(object): 12 | """Dispatch (lookup) a set of strings / regexps for match. 13 | 14 | Example: 15 | 16 | >>> dis = StrDispatch() 17 | >>> dis.add_s('hei',34, priority = 4) 18 | >>> dis.add_s('hei',123, priority = 2) 19 | >>> dis.add_re('h.i', 686) 20 | >>> print(list(dis.flat_matches('hei'))) 21 | [123, 34, 686] 22 | """ 23 | 24 | def __init__(self): 25 | self.strs = {} 26 | self.regexs = {} 27 | 28 | def add_s(self, s, obj, priority= 0 ): 29 | """ Adds a target 'string' for dispatching """ 30 | 31 | chain = self.strs.get(s, CommandChainDispatcher()) 32 | chain.add(obj,priority) 33 | self.strs[s] = chain 34 | 35 | def add_re(self, regex, obj, priority= 0 ): 36 | """ Adds a target regexp for dispatching """ 37 | 38 | chain = self.regexs.get(regex, CommandChainDispatcher()) 39 | chain.add(obj,priority) 40 | self.regexs[regex] = chain 41 | 42 | def dispatch(self, key): 43 | """ Get a seq of Commandchain objects that match key """ 44 | if key in self.strs: 45 | yield self.strs[key] 46 | 47 | for r, obj in self.regexs.items(): 48 | if re.match(r, key): 49 | yield obj 50 | else: 51 | #print "nomatch",key # dbg 52 | pass 53 | 54 | def __repr__(self): 55 | return "" % (self.strs, self.regexs) 56 | 57 | def s_matches(self, key): 58 | if key not in self.strs: 59 | return 60 | for el in self.strs[key]: 61 | yield el[1] 62 | 63 | def flat_matches(self, key): 64 | """ Yield all 'value' targets, without priority """ 65 | for val in self.dispatch(key): 66 | for el in val: 67 | yield el[1] # only value, no priority 68 | return 69 | -------------------------------------------------------------------------------- /IPython/core/tests/test_alias.py: -------------------------------------------------------------------------------- 1 | from IPython.utils.capture import capture_output 2 | 3 | import nose.tools as nt 4 | 5 | def test_alias_lifecycle(): 6 | name = 'test_alias1' 7 | cmd = 'echo "Hello"' 8 | am = _ip.alias_manager 9 | am.clear_aliases() 10 | am.define_alias(name, cmd) 11 | assert am.is_alias(name) 12 | nt.assert_equal(am.retrieve_alias(name), cmd) 13 | nt.assert_in((name, cmd), am.aliases) 14 | 15 | # Test running the alias 16 | orig_system = _ip.system 17 | result = [] 18 | _ip.system = result.append 19 | try: 20 | _ip.run_cell('%{}'.format(name)) 21 | result = [c.strip() for c in result] 22 | nt.assert_equal(result, [cmd]) 23 | finally: 24 | _ip.system = orig_system 25 | 26 | # Test removing the alias 27 | am.undefine_alias(name) 28 | assert not am.is_alias(name) 29 | with nt.assert_raises(ValueError): 30 | am.retrieve_alias(name) 31 | nt.assert_not_in((name, cmd), am.aliases) 32 | 33 | 34 | def test_alias_args_error(): 35 | """Error expanding with wrong number of arguments""" 36 | _ip.alias_manager.define_alias('parts', 'echo first %s second %s') 37 | # capture stderr: 38 | with capture_output() as cap: 39 | _ip.run_cell('parts 1') 40 | 41 | nt.assert_equal(cap.stderr.split(':')[0], 'UsageError') 42 | 43 | def test_alias_args_commented(): 44 | """Check that alias correctly ignores 'commented out' args""" 45 | _ip.magic('alias commetarg echo this is %%s a commented out arg') 46 | 47 | with capture_output() as cap: 48 | _ip.run_cell('commetarg') 49 | 50 | nt.assert_equal(cap.stdout, 'this is %s a commented out arg') 51 | 52 | def test_alias_args_commented_nargs(): 53 | """Check that alias correctly counts args, excluding those commented out""" 54 | am = _ip.alias_manager 55 | alias_name = 'comargcount' 56 | cmd = 'echo this is %%s a commented out arg and this is not %s' 57 | 58 | am.define_alias(alias_name, cmd) 59 | assert am.is_alias(alias_name) 60 | 61 | thealias = am.get_alias(alias_name) 62 | nt.assert_equal(thealias.nargs, 1) -------------------------------------------------------------------------------- /IPython/utils/process.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Utilities for working with external processes. 4 | """ 5 | 6 | # Copyright (c) IPython Development Team. 7 | # Distributed under the terms of the Modified BSD License. 8 | 9 | 10 | import os 11 | import sys 12 | 13 | if sys.platform == 'win32': 14 | from ._process_win32 import system, getoutput, arg_split, check_pid 15 | elif sys.platform == 'cli': 16 | from ._process_cli import system, getoutput, arg_split, check_pid 17 | else: 18 | from ._process_posix import system, getoutput, arg_split, check_pid 19 | 20 | from ._process_common import getoutputerror, get_output_error_code, process_handler 21 | from . import py3compat 22 | 23 | 24 | class FindCmdError(Exception): 25 | pass 26 | 27 | 28 | def find_cmd(cmd): 29 | """Find absolute path to executable cmd in a cross platform manner. 30 | 31 | This function tries to determine the full path to a command line program 32 | using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the 33 | time it will use the version that is first on the users `PATH`. 34 | 35 | Warning, don't use this to find IPython command line programs as there 36 | is a risk you will find the wrong one. Instead find those using the 37 | following code and looking for the application itself:: 38 | 39 | import sys 40 | argv = [sys.executable, '-m', 'IPython'] 41 | 42 | Parameters 43 | ---------- 44 | cmd : str 45 | The command line program to look for. 46 | """ 47 | path = py3compat.which(cmd) 48 | if path is None: 49 | raise FindCmdError('command could not be found: %s' % cmd) 50 | return path 51 | 52 | 53 | def abbrev_cwd(): 54 | """ Return abbreviated version of cwd, e.g. d:mydir """ 55 | cwd = os.getcwd().replace('\\','/') 56 | drivepart = '' 57 | tail = cwd 58 | if sys.platform == 'win32': 59 | if len(cwd) < 4: 60 | return cwd 61 | drivepart,tail = os.path.splitdrive(cwd) 62 | 63 | 64 | parts = tail.split('/') 65 | if len(parts) > 2: 66 | tail = '/'.join(parts[-2:]) 67 | 68 | return (drivepart + ( 69 | cwd == '/' and '/' or tail)) 70 | -------------------------------------------------------------------------------- /docs/source/config/integrating.rst: -------------------------------------------------------------------------------- 1 | .. _integrating: 2 | 3 | ===================================== 4 | Integrating your objects with IPython 5 | ===================================== 6 | 7 | Tab completion 8 | ============== 9 | 10 | To change the attributes displayed by tab-completing your object, define a 11 | ``__dir__(self)`` method for it. For more details, see the documentation of the 12 | built-in `dir() function `_. 13 | 14 | You can also customise key completions for your objects, e.g. pressing tab after 15 | ``obj["a``. To do so, define a method ``_ipython_key_completions_()``, which 16 | returns a list of objects which are possible keys in a subscript expression 17 | ``obj[key]``. 18 | 19 | .. versionadded:: 5.0 20 | Custom key completions 21 | 22 | Rich display 23 | ============ 24 | 25 | The notebook and the Qt console can display richer representations of objects. 26 | To use this, you can define any of a number of ``_repr_*_()`` methods. Note that 27 | these are surrounded by single, not double underscores. 28 | 29 | Both the notebook and the Qt console can display ``svg``, ``png`` and ``jpeg`` 30 | representations. The notebook can also display ``html``, ``javascript``, 31 | and ``latex``. If the methods don't exist, or return ``None``, it falls 32 | back to a standard ``repr()``. 33 | 34 | For example:: 35 | 36 | class Shout(object): 37 | def __init__(self, text): 38 | self.text = text 39 | 40 | def _repr_html_(self): 41 | return "

" + self.text + "

" 42 | 43 | Custom exception tracebacks 44 | =========================== 45 | 46 | Rarely, you might want to display a custom traceback when reporting an 47 | exception. To do this, define the custom traceback using 48 | `_render_traceback_(self)` method which returns a list of strings, one string 49 | for each line of the traceback. For example, the `ipyparallel 50 | `__ a parallel computing framework for 51 | IPython, does this to display errors from multiple engines. 52 | 53 | Please be conservative in using this feature; by replacing the default traceback 54 | you may hide important information from the user. 55 | -------------------------------------------------------------------------------- /docs/autogen_magics.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from IPython.core.alias import Alias 4 | from IPython.core.interactiveshell import InteractiveShell 5 | from IPython.core.magic import MagicAlias 6 | from IPython.utils.text import dedent, indent 7 | 8 | shell = InteractiveShell.instance() 9 | magics = shell.magics_manager.magics 10 | 11 | def _strip_underline(line): 12 | chars = set(line.strip()) 13 | if len(chars) == 1 and ('-' in chars or '=' in chars): 14 | return "" 15 | else: 16 | return line 17 | 18 | def format_docstring(func): 19 | docstring = (func.__doc__ or "Undocumented").rstrip() 20 | docstring = indent(dedent(docstring)) 21 | # Sphinx complains if indented bits have rst headings in, so strip out 22 | # any underlines in the docstring. 23 | lines = [_strip_underline(l) for l in docstring.splitlines()] 24 | return "\n".join(lines) 25 | 26 | output = [ 27 | "Line magics", 28 | "===========", 29 | "", 30 | ] 31 | 32 | # Case insensitive sort by name 33 | def sortkey(s): return s[0].lower() 34 | 35 | for name, func in sorted(magics['line'].items(), key=sortkey): 36 | if isinstance(func, Alias) or isinstance(func, MagicAlias): 37 | # Aliases are magics, but shouldn't be documented here 38 | # Also skip aliases to other magics 39 | continue 40 | output.extend([".. magic:: {}".format(name), 41 | "", 42 | format_docstring(func), 43 | ""]) 44 | 45 | output.extend([ 46 | "Cell magics", 47 | "===========", 48 | "", 49 | ]) 50 | 51 | for name, func in sorted(magics['cell'].items(), key=sortkey): 52 | if name == "!": 53 | # Special case - don't encourage people to use %%! 54 | continue 55 | if func == magics['line'].get(name, 'QQQP'): 56 | # Don't redocument line magics that double as cell magics 57 | continue 58 | if isinstance(func, MagicAlias): 59 | continue 60 | output.extend([".. cellmagic:: {}".format(name), 61 | "", 62 | format_docstring(func), 63 | ""]) 64 | 65 | here = os.path.dirname(__file__) 66 | dest = os.path.join(here, 'source', 'interactive', 'magics-generated.txt') 67 | with open(dest, "w") as f: 68 | f.write("\n".join(output)) 69 | -------------------------------------------------------------------------------- /docs/source/whatsnew/github-stats-6.rst: -------------------------------------------------------------------------------- 1 | Issues closed in the 6.x development cycle 2 | ========================================== 3 | 4 | Issues closed in 6.1 5 | -------------------- 6 | 7 | GitHub stats for 2017/04/19 - 2017/05/30 (tag: 6.0.0) 8 | 9 | These lists are automatically generated, and may be incomplete or contain duplicates. 10 | 11 | We closed 10 issues and merged 43 pull requests. 12 | The full list can be seen `on GitHub `__ 13 | 14 | The following 26 authors contributed 116 commits. 15 | 16 | * Alex Alekseyev 17 | * Benjamin Ragan-Kelley 18 | * Brian E. Granger 19 | * Christopher C. Aycock 20 | * Dave Willmer 21 | * David Bradway 22 | * ICanWaitAndFishAllDay 23 | * Ignat Shining 24 | * Jarrod Janssen 25 | * Joshua Storck 26 | * Luke Pfister 27 | * Matthias Bussonnier 28 | * Matti Remes 29 | * meeseeksdev[bot] 30 | * memeplex 31 | * Ming Zhang 32 | * Nick Weseman 33 | * Paul Ivanov 34 | * Piotr Zielinski 35 | * ryan thielke 36 | * sagnak 37 | * Sang Min Park 38 | * Srinivas Reddy Thatiparthy 39 | * Steve Bartz 40 | * Thomas Kluyver 41 | * Tory Haavik 42 | 43 | 44 | Issues closed in 6.0 45 | -------------------- 46 | 47 | GitHub stats for 2017/04/10 - 2017/04/19 (milestone: 6.0) 48 | 49 | These lists are automatically generated, and may be incomplete or contain duplicates. 50 | 51 | We closed 49 issues and merged 145 pull requests. 52 | The full list can be seen `on GitHub `__ 53 | 54 | The following 34 authors contributed 176 commits. 55 | 56 | * Adam Eury 57 | * anantkaushik89 58 | * Antonino Ingargiola 59 | * Benjamin Ragan-Kelley 60 | * Carol Willing 61 | * Chilaka Ramakrishna 62 | * chillaranand 63 | * Denis S. Tereshchenko 64 | * Diego Garcia 65 | * fatData 66 | * Fermi paradox 67 | * fuho 68 | * Grant Nestor 69 | * Ian Rose 70 | * Jeroen Demeyer 71 | * kaushikanant 72 | * Keshav Ramaswamy 73 | * Matteo 74 | * Matthias Bussonnier 75 | * mbyt 76 | * Michael Käufl 77 | * michaelpacer 78 | * Moez Bouhlel 79 | * Pablo Galindo 80 | * Paul Ivanov 81 | * Piotr Przetacznik 82 | * Rounak Banik 83 | * sachet-mittal 84 | * Srinivas Reddy Thatiparthy 85 | * Tamir Bahar 86 | * Thomas Hisch 87 | * Thomas Kluyver 88 | * Utkarsh Upadhyay 89 | * Yuri Numerov 90 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Opening an Issue 2 | 3 | When opening a new Issue, please take the following steps: 4 | 5 | 1. Search GitHub and/or Google for your issue to avoid duplicate reports. 6 | Keyword searches for your error messages are most helpful. 7 | 2. If possible, try updating to master and reproducing your issue, 8 | because we may have already fixed it. 9 | 3. Try to include a minimal reproducible test case 10 | 4. Include relevant system information. Start with the output of: 11 | 12 | python -c "import IPython; print(IPython.sys_info())" 13 | 14 | And include any relevant package versions, depending on the issue, 15 | such as matplotlib, numpy, Qt, Qt bindings (PyQt/PySide), tornado, web browser, etc. 16 | 17 | ## Pull Requests 18 | 19 | Some guidelines on contributing to IPython: 20 | 21 | * All work is submitted via Pull Requests. 22 | * Pull Requests can be submitted as soon as there is code worth discussing. 23 | Pull Requests track the branch, so you can continue to work after the PR is submitted. 24 | Review and discussion can begin well before the work is complete, 25 | and the more discussion the better. 26 | The worst case is that the PR is closed. 27 | * Pull Requests should generally be made against master 28 | * Pull Requests should be tested, if feasible: 29 | - bugfixes should include regression tests 30 | - new behavior should at least get minimal exercise 31 | * New features and backwards-incompatible changes should be documented by adding 32 | a new file to the [pr](docs/source/whatsnew/pr) directory, see [the README.md 33 | there](docs/source/whatsnew/pr/README.md) for details. 34 | * Don't make 'cleanup' pull requests just to change code style. 35 | We don't follow any style guide strictly, and we consider formatting changes 36 | unnecessary noise. 37 | If you're making functional changes, you can clean up the specific pieces of 38 | code you're working on. 39 | 40 | [Travis](http://travis-ci.org/#!/ipython/ipython) does a pretty good job testing 41 | IPython and Pull Requests, but it may make sense to manually perform tests, 42 | particularly for PRs that affect `IPython.parallel` or Windows. 43 | 44 | For more detailed information, see our [GitHub Workflow](https://github.com/ipython/ipython/wiki/Dev:-GitHub-workflow). 45 | 46 | -------------------------------------------------------------------------------- /IPython/utils/contexts.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Miscellaneous context managers. 3 | """ 4 | 5 | import warnings 6 | 7 | # Copyright (c) IPython Development Team. 8 | # Distributed under the terms of the Modified BSD License. 9 | 10 | class preserve_keys(object): 11 | """Preserve a set of keys in a dictionary. 12 | 13 | Upon entering the context manager the current values of the keys 14 | will be saved. Upon exiting, the dictionary will be updated to 15 | restore the original value of the preserved keys. Preserved keys 16 | which did not exist when entering the context manager will be 17 | deleted. 18 | 19 | Examples 20 | -------- 21 | 22 | >>> d = {'a': 1, 'b': 2, 'c': 3} 23 | >>> with preserve_keys(d, 'b', 'c', 'd'): 24 | ... del d['a'] 25 | ... del d['b'] # will be reset to 2 26 | ... d['c'] = None # will be reset to 3 27 | ... d['d'] = 4 # will be deleted 28 | ... d['e'] = 5 29 | ... print(sorted(d.items())) 30 | ... 31 | [('c', None), ('d', 4), ('e', 5)] 32 | >>> print(sorted(d.items())) 33 | [('b', 2), ('c', 3), ('e', 5)] 34 | """ 35 | 36 | def __init__(self, dictionary, *keys): 37 | self.dictionary = dictionary 38 | self.keys = keys 39 | 40 | def __enter__(self): 41 | # Actions to perform upon exiting. 42 | to_delete = [] 43 | to_update = {} 44 | 45 | d = self.dictionary 46 | for k in self.keys: 47 | if k in d: 48 | to_update[k] = d[k] 49 | else: 50 | to_delete.append(k) 51 | 52 | self.to_delete = to_delete 53 | self.to_update = to_update 54 | 55 | def __exit__(self, *exc_info): 56 | d = self.dictionary 57 | 58 | for k in self.to_delete: 59 | d.pop(k, None) 60 | d.update(self.to_update) 61 | 62 | 63 | class NoOpContext(object): 64 | """ 65 | Deprecated 66 | 67 | Context manager that does nothing.""" 68 | 69 | def __init__(self): 70 | warnings.warn("""NoOpContext is deprecated since IPython 5.0 """, 71 | DeprecationWarning, stacklevel=2) 72 | 73 | def __enter__(self): pass 74 | def __exit__(self, type, value, traceback): pass 75 | -------------------------------------------------------------------------------- /docs/man/ipython.1: -------------------------------------------------------------------------------- 1 | .\" Hey, EMACS: -*- nroff -*- 2 | .\" First parameter, NAME, should be all caps 3 | .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection 4 | .\" other parameters are allowed: see man(7), man(1) 5 | .TH IPYTHON 1 "July 15, 2011" 6 | .\" Please adjust this date whenever revising the manpage. 7 | .\" 8 | .\" Some roff macros, for reference: 9 | .\" .nh disable hyphenation 10 | .\" .hy enable hyphenation 11 | .\" .ad l left justify 12 | .\" .ad b justify to both left and right margins 13 | .\" .nf disable filling 14 | .\" .fi enable filling 15 | .\" .br insert line break 16 | .\" .sp insert n+1 empty lines 17 | .\" for manpage-specific macros, see man(7) and groff_man(7) 18 | .\" .SH section heading 19 | .\" .SS secondary section heading 20 | .\" 21 | .\" 22 | .\" To preview this page as plain text: nroff -man ipython.1 23 | .\" 24 | .SH NAME 25 | ipython \- Tools for Interactive Computing in Python. 26 | .SH SYNOPSIS 27 | .B ipython 28 | .RI [ options ] " files" ... 29 | 30 | .B ipython subcommand 31 | .RI [ options ] ... 32 | 33 | .SH DESCRIPTION 34 | An interactive Python shell with automatic history (input and output), dynamic 35 | object introspection, easier configuration, command completion, access to the 36 | system shell, integration with numerical and scientific computing tools, 37 | web notebook, Qt console, and more. 38 | 39 | For more information on how to use IPython, see 'ipython \-\-help', 40 | or 'ipython \-\-help\-all' for all available command\(hyline options. 41 | 42 | .SH "ENVIRONMENT VARIABLES" 43 | .sp 44 | .PP 45 | \fIIPYTHONDIR\fR 46 | .RS 4 47 | This is the location where IPython stores all its configuration files. The default 48 | is $HOME/.ipython if IPYTHONDIR is not defined. 49 | 50 | You can see the computed value of IPYTHONDIR with `ipython locate`. 51 | 52 | .SH FILES 53 | 54 | IPython uses various configuration files stored in profiles within IPYTHONDIR. 55 | To generate the default configuration files and start configuring IPython, 56 | do 'ipython profile create', and edit '*_config.py' files located in 57 | IPYTHONDIR/profile_default. 58 | 59 | .SH AUTHORS 60 | IPython is written by the IPython Development Team . 61 | -------------------------------------------------------------------------------- /IPython/core/autocall.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Autocall capabilities for IPython.core. 4 | 5 | Authors: 6 | 7 | * Brian Granger 8 | * Fernando Perez 9 | * Thomas Kluyver 10 | 11 | Notes 12 | ----- 13 | """ 14 | 15 | #----------------------------------------------------------------------------- 16 | # Copyright (C) 2008-2011 The IPython Development Team 17 | # 18 | # Distributed under the terms of the BSD License. The full license is in 19 | # the file COPYING, distributed as part of this software. 20 | #----------------------------------------------------------------------------- 21 | 22 | #----------------------------------------------------------------------------- 23 | # Imports 24 | #----------------------------------------------------------------------------- 25 | 26 | 27 | #----------------------------------------------------------------------------- 28 | # Code 29 | #----------------------------------------------------------------------------- 30 | 31 | class IPyAutocall(object): 32 | """ Instances of this class are always autocalled 33 | 34 | This happens regardless of 'autocall' variable state. Use this to 35 | develop macro-like mechanisms. 36 | """ 37 | _ip = None 38 | rewrite = True 39 | def __init__(self, ip=None): 40 | self._ip = ip 41 | 42 | def set_ip(self, ip): 43 | """ Will be used to set _ip point to current ipython instance b/f call 44 | 45 | Override this method if you don't want this to happen. 46 | 47 | """ 48 | self._ip = ip 49 | 50 | 51 | class ExitAutocall(IPyAutocall): 52 | """An autocallable object which will be added to the user namespace so that 53 | exit, exit(), quit or quit() are all valid ways to close the shell.""" 54 | rewrite = False 55 | 56 | def __call__(self): 57 | self._ip.ask_exit() 58 | 59 | class ZMQExitAutocall(ExitAutocall): 60 | """Exit IPython. Autocallable, so it needn't be explicitly called. 61 | 62 | Parameters 63 | ---------- 64 | keep_kernel : bool 65 | If True, leave the kernel alive. Otherwise, tell the kernel to exit too 66 | (default). 67 | """ 68 | def __call__(self, keep_kernel=False): 69 | self._ip.keepkernel_on_exit = keep_kernel 70 | self._ip.ask_exit() 71 | -------------------------------------------------------------------------------- /IPython/utils/decorators.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Decorators that don't go anywhere else. 3 | 4 | This module contains misc. decorators that don't really go with another module 5 | in :mod:`IPython.utils`. Beore putting something here please see if it should 6 | go into another topical module in :mod:`IPython.utils`. 7 | """ 8 | 9 | #----------------------------------------------------------------------------- 10 | # Copyright (C) 2008-2011 The IPython Development Team 11 | # 12 | # Distributed under the terms of the BSD License. The full license is in 13 | # the file COPYING, distributed as part of this software. 14 | #----------------------------------------------------------------------------- 15 | 16 | #----------------------------------------------------------------------------- 17 | # Imports 18 | #----------------------------------------------------------------------------- 19 | 20 | #----------------------------------------------------------------------------- 21 | # Code 22 | #----------------------------------------------------------------------------- 23 | 24 | def flag_calls(func): 25 | """Wrap a function to detect and flag when it gets called. 26 | 27 | This is a decorator which takes a function and wraps it in a function with 28 | a 'called' attribute. wrapper.called is initialized to False. 29 | 30 | The wrapper.called attribute is set to False right before each call to the 31 | wrapped function, so if the call fails it remains False. After the call 32 | completes, wrapper.called is set to True and the output is returned. 33 | 34 | Testing for truth in wrapper.called allows you to determine if a call to 35 | func() was attempted and succeeded.""" 36 | 37 | # don't wrap twice 38 | if hasattr(func, 'called'): 39 | return func 40 | 41 | def wrapper(*args,**kw): 42 | wrapper.called = False 43 | out = func(*args,**kw) 44 | wrapper.called = True 45 | return out 46 | 47 | wrapper.called = False 48 | wrapper.__doc__ = func.__doc__ 49 | return wrapper 50 | 51 | def undoc(func): 52 | """Mark a function or class as undocumented. 53 | 54 | This is found by inspecting the AST, so for now it must be used directly 55 | as @undoc, not as e.g. @decorators.undoc 56 | """ 57 | return func 58 | 59 | -------------------------------------------------------------------------------- /IPython/core/tests/test_shellapp.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Tests for shellapp module. 3 | 4 | Authors 5 | ------- 6 | * Bradley Froehle 7 | """ 8 | #----------------------------------------------------------------------------- 9 | # Copyright (C) 2012 The IPython Development Team 10 | # 11 | # Distributed under the terms of the BSD License. The full license is in 12 | # the file COPYING, distributed as part of this software. 13 | #----------------------------------------------------------------------------- 14 | 15 | #----------------------------------------------------------------------------- 16 | # Imports 17 | #----------------------------------------------------------------------------- 18 | import unittest 19 | 20 | from IPython.testing import decorators as dec 21 | from IPython.testing import tools as tt 22 | 23 | sqlite_err_maybe = dec.module_not_available('sqlite3') 24 | SQLITE_NOT_AVAILABLE_ERROR = ('WARNING: IPython History requires SQLite,' 25 | ' your history will not be saved\n') 26 | 27 | class TestFileToRun(unittest.TestCase, tt.TempFileMixin): 28 | """Test the behavior of the file_to_run parameter.""" 29 | 30 | def test_py_script_file_attribute(self): 31 | """Test that `__file__` is set when running `ipython file.py`""" 32 | src = "print(__file__)\n" 33 | self.mktmp(src) 34 | 35 | err = SQLITE_NOT_AVAILABLE_ERROR if sqlite_err_maybe else None 36 | tt.ipexec_validate(self.fname, self.fname, err) 37 | 38 | def test_ipy_script_file_attribute(self): 39 | """Test that `__file__` is set when running `ipython file.ipy`""" 40 | src = "print(__file__)\n" 41 | self.mktmp(src, ext='.ipy') 42 | 43 | err = SQLITE_NOT_AVAILABLE_ERROR if sqlite_err_maybe else None 44 | tt.ipexec_validate(self.fname, self.fname, err) 45 | 46 | # The commands option to ipexec_validate doesn't work on Windows, and it 47 | # doesn't seem worth fixing 48 | @dec.skip_win32 49 | def test_py_script_file_attribute_interactively(self): 50 | """Test that `__file__` is not set after `ipython -i file.py`""" 51 | src = "True\n" 52 | self.mktmp(src) 53 | 54 | out, err = tt.ipexec(self.fname, options=['-i'], 55 | commands=['"__file__" in globals()', 'exit()']) 56 | self.assertIn("False", out) 57 | -------------------------------------------------------------------------------- /IPython/core/display_trap.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | A context manager for handling sys.displayhook. 4 | 5 | Authors: 6 | 7 | * Robert Kern 8 | * Brian Granger 9 | """ 10 | 11 | #----------------------------------------------------------------------------- 12 | # Copyright (C) 2008-2011 The IPython Development Team 13 | # 14 | # Distributed under the terms of the BSD License. The full license is in 15 | # the file COPYING, distributed as part of this software. 16 | #----------------------------------------------------------------------------- 17 | 18 | #----------------------------------------------------------------------------- 19 | # Imports 20 | #----------------------------------------------------------------------------- 21 | 22 | import sys 23 | 24 | from traitlets.config.configurable import Configurable 25 | from traitlets import Any 26 | 27 | #----------------------------------------------------------------------------- 28 | # Classes and functions 29 | #----------------------------------------------------------------------------- 30 | 31 | 32 | class DisplayTrap(Configurable): 33 | """Object to manage sys.displayhook. 34 | 35 | This came from IPython.core.kernel.display_hook, but is simplified 36 | (no callbacks or formatters) until more of the core is refactored. 37 | """ 38 | 39 | hook = Any() 40 | 41 | def __init__(self, hook=None): 42 | super(DisplayTrap, self).__init__(hook=hook, config=None) 43 | self.old_hook = None 44 | # We define this to track if a single BuiltinTrap is nested. 45 | # Only turn off the trap when the outermost call to __exit__ is made. 46 | self._nested_level = 0 47 | 48 | def __enter__(self): 49 | if self._nested_level == 0: 50 | self.set() 51 | self._nested_level += 1 52 | return self 53 | 54 | def __exit__(self, type, value, traceback): 55 | if self._nested_level == 1: 56 | self.unset() 57 | self._nested_level -= 1 58 | # Returning False will cause exceptions to propagate 59 | return False 60 | 61 | def set(self): 62 | """Set the hook.""" 63 | if sys.displayhook is not self.hook: 64 | self.old_hook = sys.displayhook 65 | sys.displayhook = self.hook 66 | 67 | def unset(self): 68 | """Unset the hook.""" 69 | sys.displayhook = self.old_hook 70 | 71 | -------------------------------------------------------------------------------- /IPython/utils/tests/test_pycolorize.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | """Test suite for our color utilities. 3 | 4 | Authors 5 | ------- 6 | 7 | * Min RK 8 | """ 9 | #----------------------------------------------------------------------------- 10 | # Copyright (C) 2011 The IPython Development Team 11 | # 12 | # Distributed under the terms of the BSD License. The full license is in 13 | # the file COPYING.txt, distributed as part of this software. 14 | #----------------------------------------------------------------------------- 15 | 16 | #----------------------------------------------------------------------------- 17 | # Imports 18 | #----------------------------------------------------------------------------- 19 | 20 | # third party 21 | import nose.tools as nt 22 | 23 | # our own 24 | from IPython.utils.PyColorize import Parser 25 | import io 26 | 27 | #----------------------------------------------------------------------------- 28 | # Test functions 29 | #----------------------------------------------------------------------------- 30 | 31 | sample = u""" 32 | def function(arg, *args, kwarg=True, **kwargs): 33 | ''' 34 | this is docs 35 | ''' 36 | pass is True 37 | False == None 38 | 39 | with io.open(ru'unicode'): 40 | raise ValueError("\n escape \r sequence") 41 | 42 | print("wěird ünicoðe") 43 | 44 | class Bar(Super): 45 | 46 | def __init__(self): 47 | super(Bar, self).__init__(1**2, 3^4, 5 or 6) 48 | """ 49 | 50 | def test_loop_colors(): 51 | 52 | for style in ('Linux', 'NoColor','LightBG', 'Neutral'): 53 | 54 | def test_unicode_colorize(): 55 | p = Parser(style=style) 56 | f1 = p.format('1/0', 'str') 57 | f2 = p.format(u'1/0', 'str') 58 | nt.assert_equal(f1, f2) 59 | 60 | def test_parse_sample(): 61 | """and test writing to a buffer""" 62 | buf = io.StringIO() 63 | p = Parser(style=style) 64 | p.format(sample, buf) 65 | buf.seek(0) 66 | f1 = buf.read() 67 | 68 | nt.assert_not_in('ERROR', f1) 69 | 70 | def test_parse_error(): 71 | p = Parser(style=style) 72 | f1 = p.format(')', 'str') 73 | if style != 'NoColor': 74 | nt.assert_in('ERROR', f1) 75 | 76 | yield test_unicode_colorize 77 | yield test_parse_sample 78 | yield test_parse_error 79 | -------------------------------------------------------------------------------- /IPython/lib/clipboard.py: -------------------------------------------------------------------------------- 1 | """ Utilities for accessing the platform's clipboard. 2 | """ 3 | 4 | import subprocess 5 | 6 | from IPython.core.error import TryNext 7 | import IPython.utils.py3compat as py3compat 8 | 9 | class ClipboardEmpty(ValueError): 10 | pass 11 | 12 | def win32_clipboard_get(): 13 | """ Get the current clipboard's text on Windows. 14 | 15 | Requires Mark Hammond's pywin32 extensions. 16 | """ 17 | try: 18 | import win32clipboard 19 | except ImportError: 20 | raise TryNext("Getting text from the clipboard requires the pywin32 " 21 | "extensions: http://sourceforge.net/projects/pywin32/") 22 | win32clipboard.OpenClipboard() 23 | try: 24 | text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) 25 | except (TypeError, win32clipboard.error): 26 | try: 27 | text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) 28 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) 29 | except (TypeError, win32clipboard.error): 30 | raise ClipboardEmpty 31 | finally: 32 | win32clipboard.CloseClipboard() 33 | return text 34 | 35 | def osx_clipboard_get(): 36 | """ Get the clipboard's text on OS X. 37 | """ 38 | p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], 39 | stdout=subprocess.PIPE) 40 | text, stderr = p.communicate() 41 | # Text comes in with old Mac \r line endings. Change them to \n. 42 | text = text.replace(b'\r', b'\n') 43 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) 44 | return text 45 | 46 | def tkinter_clipboard_get(): 47 | """ Get the clipboard's text using Tkinter. 48 | 49 | This is the default on systems that are not Windows or OS X. It may 50 | interfere with other UI toolkits and should be replaced with an 51 | implementation that uses that toolkit. 52 | """ 53 | try: 54 | from tkinter import Tk, TclError 55 | except ImportError: 56 | raise TryNext("Getting text from the clipboard on this platform requires tkinter.") 57 | 58 | root = Tk() 59 | root.withdraw() 60 | try: 61 | text = root.clipboard_get() 62 | except TclError: 63 | raise ClipboardEmpty 64 | finally: 65 | root.destroy() 66 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) 67 | return text 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/source/development/inputhook_app.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | IPython GUI Support Notes 3 | ========================= 4 | 5 | IPython allows GUI event loops to be run in an interactive IPython session. 6 | This is done using Python's PyOS_InputHook hook which Python calls 7 | when the :func:`raw_input` function is called and waiting for user input. 8 | IPython has versions of this hook for wx, pyqt4 and pygtk. 9 | 10 | When a GUI program is used interactively within IPython, the event loop of 11 | the GUI should *not* be started. This is because, the PyOS_Inputhook itself 12 | is responsible for iterating the GUI event loop. 13 | 14 | IPython has facilities for installing the needed input hook for each GUI 15 | toolkit and for creating the needed main GUI application object. Usually, 16 | these main application objects should be created only once and for some 17 | GUI toolkits, special options have to be passed to the application object 18 | to enable it to function properly in IPython. 19 | 20 | We need to answer the following questions: 21 | 22 | * Who is responsible for creating the main GUI application object, IPython 23 | or third parties (matplotlib, enthought.traits, etc.)? 24 | 25 | * What is the proper way for third party code to detect if a GUI application 26 | object has already been created? If one has been created, how should 27 | the existing instance be retrieved? 28 | 29 | * In a GUI application object has been created, how should third party code 30 | detect if the GUI event loop is running. It is not sufficient to call the 31 | relevant function methods in the GUI toolkits (like ``IsMainLoopRunning``) 32 | because those don't know if the GUI event loop is running through the 33 | input hook. 34 | 35 | * We might need a way for third party code to determine if it is running 36 | in IPython or not. Currently, the only way of running GUI code in IPython 37 | is by using the input hook, but eventually, GUI based versions of IPython 38 | will allow the GUI event loop in the more traditional manner. We will need 39 | a way for third party code to distinguish between these two cases. 40 | 41 | Here is some sample code I have been using to debug this issue:: 42 | 43 | from matplotlib import pyplot as plt 44 | 45 | from enthought.traits import api as traits 46 | 47 | class Foo(traits.HasTraits): 48 | a = traits.Float() 49 | 50 | f = Foo() 51 | f.configure_traits() 52 | 53 | plt.plot(range(10)) 54 | 55 | 56 | -------------------------------------------------------------------------------- /IPython/utils/dir2.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """A fancy version of Python's builtin :func:`dir` function. 3 | """ 4 | 5 | # Copyright (c) IPython Development Team. 6 | # Distributed under the terms of the Modified BSD License. 7 | 8 | import inspect 9 | 10 | 11 | def safe_hasattr(obj, attr): 12 | """In recent versions of Python, hasattr() only catches AttributeError. 13 | This catches all errors. 14 | """ 15 | try: 16 | getattr(obj, attr) 17 | return True 18 | except: 19 | return False 20 | 21 | 22 | def dir2(obj): 23 | """dir2(obj) -> list of strings 24 | 25 | Extended version of the Python builtin dir(), which does a few extra 26 | checks. 27 | 28 | This version is guaranteed to return only a list of true strings, whereas 29 | dir() returns anything that objects inject into themselves, even if they 30 | are later not really valid for attribute access (many extension libraries 31 | have such bugs). 32 | """ 33 | 34 | # Start building the attribute list via dir(), and then complete it 35 | # with a few extra special-purpose calls. 36 | 37 | try: 38 | words = set(dir(obj)) 39 | except Exception: 40 | # TypeError: dir(obj) does not return a list 41 | words = set() 42 | 43 | if safe_hasattr(obj, '__class__'): 44 | words |= set(dir(obj.__class__)) 45 | 46 | # filter out non-string attributes which may be stuffed by dir() calls 47 | # and poor coding in third-party modules 48 | 49 | words = [w for w in words if isinstance(w, str)] 50 | return sorted(words) 51 | 52 | 53 | def get_real_method(obj, name): 54 | """Like getattr, but with a few extra sanity checks: 55 | 56 | - If obj is a class, ignore its methods 57 | - Check if obj is a proxy that claims to have all attributes 58 | - Catch attribute access failing with any exception 59 | - Check that the attribute is a callable object 60 | 61 | Returns the method or None. 62 | """ 63 | if inspect.isclass(obj): 64 | return None 65 | 66 | try: 67 | canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None) 68 | except Exception: 69 | return None 70 | 71 | if canary is not None: 72 | # It claimed to have an attribute it should never have 73 | return None 74 | 75 | try: 76 | m = getattr(obj, name, None) 77 | except Exception: 78 | return None 79 | 80 | if callable(m): 81 | return m 82 | 83 | return None 84 | --------------------------------------------------------------------------------