Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 'master' into htmlnotebook

Conflicts:
	setupbase.py
  • Loading branch information...
commit fd892df5cf2ce725fc5d7f8195dd459d0bbd0640 2 parents ddb901b + 8de5e11
@ellisonbg ellisonbg authored
Showing with 3,051 additions and 1,410 deletions.
  1. +3 −4 IPython/__init__.py
  2. +15 −5 IPython/config/application.py
  3. +3 −2 IPython/core/crashhandler.py
  4. +4 −1 IPython/core/formatters.py
  5. +7 −5 IPython/core/history.py
  6. +0 −14 IPython/core/magic.py
  7. +14 −12 IPython/core/release.py
  8. +10 −2 IPython/core/tests/test_interactiveshell.py
  9. +5 −2 IPython/core/usage.py
  10. +0 −290 IPython/deathrow/Itpl.py
  11. +4 −2 IPython/frontend/qt/console/console_widget.py
  12. +18 −10 IPython/frontend/qt/console/history_console_widget.py
  13. +5 −1 IPython/frontend/qt/console/ipython_widget.py
  14. +17 −4 IPython/frontend/terminal/ipapp.py
  15. 0  IPython/lib/guisupport.py
  16. +39 −33 IPython/lib/inputhook.py
  17. +7 −5 IPython/lib/irunner.py
  18. +4 −25 IPython/parallel/apps/baseapp.py
  19. +1 −1  IPython/parallel/apps/ipclusterapp.py
  20. +5 −1 IPython/parallel/client/client.py
  21. +10 −1 IPython/parallel/tests/test_client.py
  22. +3 −1 IPython/parallel/util.py
  23. +2 −2 IPython/utils/io.py
  24. +8 −4 IPython/zmq/heartbeat.py
  25. +3 −0  IPython/zmq/iostream.py
  26. +11 −4 IPython/zmq/kernelmanager.py
  27. +13 −2 IPython/zmq/zmqshell.py
  28. +11 −11 README.rst
  29. +9 −6 docs/Makefile
  30. +0 −143 docs/examples/core/ipy.vim
  31. +15 −0 docs/examples/core/ipython-qtconsole.desktop
  32. +1 −8 docs/examples/core/ipython-sh.desktop
  33. +0 −7 docs/examples/core/ipython.desktop
  34. +40 −0 docs/examples/lib/example-demo.py
  35. +0 −4 docs/examples/lib/gui-gtk.py
  36. +0 −54 docs/examples/lib/gui-mpl.py
  37. +2 −1  docs/examples/lib/gui-qt.py
  38. +1 −1  docs/examples/lib/gui-tk.py
  39. +21 −9 docs/examples/lib/gui-wx.py
  40. +65 −0 docs/examples/lib/internal_ipkernel.py
  41. +75 −0 docs/examples/lib/ipkernel_qtapp.py
  42. +119 −0 docs/examples/lib/ipkernel_wxapp.py
  43. +107 −0 docs/examples/vim/README.rst
  44. +343 −0 docs/examples/vim/ipy.vim
  45. +3 −1 docs/man/ipcluster.1
  46. +5 −3 docs/man/ipcontroller.1
  47. +98 −0 docs/man/iplogger.1
  48. +2 −2 docs/man/ipython.1
  49. +3 −1 docs/man/irunner.1
  50. BIN  docs/source/_static/logo.png
  51. BIN  docs/source/_static/ms_visual_studio.png
  52. BIN  docs/source/_static/qtconsole.png
  53. +4 −3 docs/source/about/credits.txt
  54. +1 −1  docs/source/attic/parallel_task_old.txt
  55. 0  docs/source/development/{ → figs}/frontend-kernel.png
  56. 0  docs/source/development/{ → figs}/frontend-kernel.svg
  57. +1 −1  docs/source/development/messaging.txt
  58. +173 −103 docs/source/interactive/qtconsole.txt
  59. +152 −227 docs/source/interactive/reference.txt
  60. +11 −1 docs/source/parallel/parallel_intro.txt
  61. +1 −1  docs/source/parallel/parallel_multiengine.txt
  62. +1 −1  docs/source/parallel/parallel_task.txt
  63. +528 −0 docs/source/whatsnew/github-stats-0.11.txt
  64. +1 −0  docs/source/whatsnew/index.txt
  65. +506 −132 docs/source/whatsnew/version0.11.txt
  66. +338 −160 docs/sphinxext/ipython_directive.py
  67. +4 −5 scripts/ipython_win_post_install.py
  68. +12 −7 setup.py
  69. +15 −54 setupbase.py
  70. +4 −4 tools/build_release
  71. +109 −0 tools/github_stats.py
  72. +31 −20 tools/release
  73. +20 −5 tools/testupload
  74. +8 −1 tools/toollib.py
View
7 IPython/__init__.py
@@ -1,11 +1,11 @@
# encoding: utf-8
"""
-IPython.
+IPython: tools for interactive and parallel computing in Python.
-IPython is a set of tools for interactive and exploratory computing in Python.
+http://ipython.org
"""
#-----------------------------------------------------------------------------
-# Copyright (c) 2008-2010, IPython Development Team.
+# Copyright (c) 2008-2011, IPython Development Team.
# Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
@@ -31,7 +31,6 @@
if sys.version[0:3] < '2.6':
raise ImportError('Python Version 2.6 or above is required for IPython.')
-
# Make it easy to import extensions - they are always directly on pythonpath.
# Therefore, non-IPython modules can be added to extensions directory.
# This should probably be in ipapp.py.
View
20 IPython/config/application.py
@@ -143,9 +143,10 @@ def _flags_changed(self, name, old, new):
def __init__(self, **kwargs):
SingletonConfigurable.__init__(self, **kwargs)
- # Add my class to self.classes so my attributes appear in command line
- # options.
- self.classes.insert(0, self.__class__)
+ # Ensure my class is in self.classes, so my attributes appear in command line
+ # options and config files.
+ if self.__class__ not in self.classes:
+ self.classes.insert(0, self.__class__)
self.init_logging()
@@ -366,8 +367,17 @@ def parse_command_line(self, argv=None):
def load_config_file(self, filename, path=None):
"""Load a .py based config file by filename and path."""
loader = PyFileConfigLoader(filename, path=path)
- config = loader.load_config()
- self.update_config(config)
+ try:
+ config = loader.load_config()
+ except IOError:
+ # problem with the file (probably doesn't exist), raise
+ raise
+ except Exception:
+ # problem while running the file
+ self.log.error("Exception while loading config file %s [path=%s]"%
+ (filename, path), exc_info=True)
+ else:
+ self.update_config(config)
def generate_config_file(self):
"""generate default config file from Configurables"""
View
5 IPython/core/crashhandler.py
@@ -37,14 +37,14 @@
A crash report was automatically generated with the following information:
- A verbatim copy of the crash traceback.
- A copy of your input history during this session.
- - Data on your current $self.app_name configuration.
+ - Data on your current {app_name} configuration.
It was left in the file named:
\t'{crash_report_fname}'
If you can email this file to the developers, the information in it will help
them in understanding and correcting the problem.
-You can mail it to: $self.contact_name at {contact_email}
+You can mail it to: {contact_name} at {contact_email}
with the subject '{app_name} Crash Report'.
If you want to do it now, the following command will work (under Unix):
@@ -126,6 +126,7 @@ def __call__(self, etype, evalue, etb):
# write the report filename into the instance dict so it can get
# properly expanded out in the user message template
self.crash_report_fname = report_name
+ self.info['crash_report_fname'] = report_name
TBhandler = ultratb.VerboseTB(
color_scheme=color_scheme,
long_header=1,
View
5 IPython/core/formatters.py
@@ -432,8 +432,11 @@ def __call__(self, obj):
else:
# This uses use StringIO, as cStringIO doesn't handle unicode.
stream = StringIO()
+ # self.newline.encode() is a quick fix for issue gh-597. We need to
+ # ensure that stream does not get a mix of unicode and bytestrings,
+ # or it will cause trouble.
printer = pretty.RepresentationPrinter(stream, self.verbose,
- self.max_width, self.newline,
+ self.max_width, self.newline.encode(),
singleton_pprinters=self.singleton_printers,
type_pprinters=self.type_printers,
deferred_pprinters=self.deferred_printers)
View
12 IPython/core/history.py
@@ -650,6 +650,7 @@ def _format_lineno(session, line):
if 'g' in opts: # Glob search
pattern = "*" + args + "*" if args else "*"
hist = history_manager.search(pattern, raw=raw, output=get_output)
+ print_nums = True
elif 'l' in opts: # Get 'tail'
try:
n = int(args)
@@ -692,9 +693,10 @@ def _format_lineno(session, line):
def magic_rep(self, arg):
- r""" Repeat a command, or get command to input line for editing
+ r"""Repeat a command, or get command to input line for editing. %recall and
+ %rep are equivalent.
- - %rep (no arguments):
+ - %recall (no arguments):
Place a string version of last computation result (stored in the special '_'
variable) to the next input prompt. Allows you to create elaborate command
@@ -706,17 +708,17 @@ def magic_rep(self, arg):
In[3]: %rep
In[4]: heivaan_ <== cursor blinking
- %rep 45
+ %recall 45
Place history line 45 on the next input prompt. Use %hist to find
out the number.
- %rep 1-4
+ %recall 1-4
Combine the specified lines into one cell, and place it on the next
input prompt. See %history for the slice syntax.
- %rep foo+bar
+ %recall foo+bar
If foo+bar can be evaluated in the user namespace, the result is
placed at the next input prompt. Otherwise, the history is searched
View
14 IPython/core/magic.py
@@ -385,20 +385,6 @@ def magic_magic(self, parameter_s = ''):
Example: typing '%cd mydir' (without the quotes) changes you working directory
to 'mydir', if it exists.
-You can define your own magic functions to extend the system. See the supplied
-ipythonrc and example-magic.py files for details (in your ipython
-configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
-
-You can also define your own aliased names for magic functions. In your
-ipythonrc file, placing a line like:
-
- execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
-
-will define %pf as a new name for %profile.
-
-You can also call magics in code using the magic() function, which IPython
-automatically adds to the builtin namespace. Type 'magic?' for details.
-
For a list of the available magic functions, use %lsmagic. For a description
of any of them, type %magic_name?, e.g. '%cd?'.
View
26 IPython/core/release.py
@@ -2,7 +2,7 @@
"""Release data for the IPython project."""
#-----------------------------------------------------------------------------
-# Copyright (c) 2008-2010, IPython Development Team.
+# Copyright (c) 2008-2011, IPython Development Team.
# Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
@@ -20,7 +20,7 @@
# release. 'dev' as a _version_extra string means this is a development
# version
_version_major = 0
-_version_minor = 11
+_version_minor = 12
_version_micro = '' # use '' for first of series, number for 1 and above
_version_extra = 'dev'
#_version_extra = '' # Uncomment this for full releases
@@ -36,19 +36,19 @@
version = __version__ # backwards compatibility name
-description = "An interactive computing environment for Python"
+description = "IPython: Productive Interactive Computing"
long_description = \
"""
-The goal of IPython is to create a comprehensive environment for
-interactive and exploratory computing. To support this goal, IPython
-has two main components:
+IPython provides a rich toolkit to help you make the most out of using Python
+interactively. Its main components are:
-* An enhanced interactive Python shell.
+* Powerful interactive Python shells (terminal- and Qt-based).
+* Support for interactive data visualization and use of GUI toolkits.
+* Flexible, embeddable interpreters to load into your own projects.
+* Tools for high level and interactive parallel computing.
-* An architecture for interactive parallel computing.
-
-The enhanced interactive Python shell has the following main features:
+The enhanced interactive Python shells have the following main features:
* Comprehensive object introspection.
@@ -116,8 +116,10 @@
url = 'http://ipython.org'
-download_url = 'http://ipython.scipy.org/dist'
+# This will only be valid for actual releases sent to PyPI, but that's OK since
+# those are the ones we want pip/easy_install to be able to find.
+download_url = 'http://archive.ipython.org/release/%s' % version
-platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
+platforms = ['Linux','Mac OSX','Windows XP/2000/NT']
keywords = ['Interactive','Interpreter','Shell','Parallel','Distributed']
View
12 IPython/core/tests/test_interactiveshell.py
@@ -112,5 +112,13 @@ def test_trailing_newline(self):
ip = get_ipython()
ip.run_cell('!(true)\n', False)
ip.run_cell('!(true)\n\n\n', False)
-
-
+
+ def test_gh_597(self):
+ """Pretty-printing lists of objects with non-ascii reprs may cause
+ problems."""
+ class Spam(object):
+ def __repr__(self):
+ return "\xe9"*50
+ import IPython.core.formatters
+ f = IPython.core.formatters.PlainTextFormatter()
+ f([Spam(),Spam()])
View
7 IPython/core/usage.py
@@ -26,7 +26,6 @@
Usage
------
ipython [subcommand] [options] [files]
@@ -388,8 +387,12 @@
The keybindings themselves are:
- ``Enter``: insert new line (may cause execution, see above).
-- ``C-Enter``: force new line, *never* causes execution.
+- ``C-Enter``: *force* new line, *never* causes execution.
- ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
+- ``Up``: step backwards through the history.
+- ``Down``: step forwards through the history.
+- ``S-Up``: search backwards through the history (like ``C-r`` in bash).
+- ``S-Down``: search forwards through the history.
- ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
- ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
- ``C-v``: paste text from clipboard.
View
290 IPython/deathrow/Itpl.py
@@ -1,290 +0,0 @@
-# -*- coding: utf-8 -*-
-"""String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
-
-This module lets you quickly and conveniently interpolate values into
-strings (in the flavour of Perl or Tcl, but with less extraneous
-punctuation). You get a bit more power than in the other languages,
-because this module allows subscripting, slicing, function calls,
-attribute lookup, or arbitrary expressions. Variables and expressions
-are evaluated in the namespace of the caller.
-
-The itpl() function returns the result of interpolating a string, and
-printpl() prints out an interpolated string. Here are some examples:
-
- from Itpl import printpl
- printpl("Here is a $string.")
- printpl("Here is a $module.member.")
- printpl("Here is an $object.member.")
- printpl("Here is a $functioncall(with, arguments).")
- printpl("Here is an ${arbitrary + expression}.")
- printpl("Here is an $array[3] member.")
- printpl("Here is a $dictionary['member'].")
-
-The filter() function filters a file object so that output through it
-is interpolated. This lets you produce the illusion that Python knows
-how to do interpolation:
-
- import Itpl
- sys.stdout = Itpl.filter()
- f = "fancy"
- print "Is this not $f?"
- print "Standard output has been replaced with a $sys.stdout object."
- sys.stdout = Itpl.unfilter()
- print "Okay, back $to $normal."
-
-Under the hood, the Itpl class represents a string that knows how to
-interpolate values. An instance of the class parses the string once
-upon initialization; the evaluation and substitution can then be done
-each time the instance is evaluated with str(instance). For example:
-
- from Itpl import Itpl
- s = Itpl("Here is $foo.")
- foo = 5
- print str(s)
- foo = "bar"
- print str(s)
-"""
-
-#*****************************************************************************
-#
-# Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
-#
-#
-# Published under the terms of the MIT license, hereby reproduced:
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-# IN THE SOFTWARE.
-#
-#*****************************************************************************
-
-__author__ = 'Ka-Ping Yee <ping@lfw.org>'
-__license__ = 'MIT'
-
-import string
-import sys
-from tokenize import tokenprog
-from types import StringType
-
-class ItplError(ValueError):
- def __init__(self, text, pos):
- self.text = text
- self.pos = pos
- def __str__(self):
- return "unfinished expression in %s at char %d" % (
- repr(self.text), self.pos)
-
-def matchorfail(text, pos):
- match = tokenprog.match(text, pos)
- if match is None:
- raise ItplError(text, pos)
-
- return match, match.end()
-
-try:
- itpl_encoding = sys.stdin.encoding or 'ascii'
-except AttributeError:
- itpl_encoding = 'ascii'
-
-
-
-class Itpl:
- """Class representing a string with interpolation abilities.
-
- Upon creation, an instance works out what parts of the format
- string are literal and what parts need to be evaluated. The
- evaluation and substitution happens in the namespace of the
- caller when str(instance) is called."""
-
- def __init__(self, format,codec=itpl_encoding,encoding_errors='backslashreplace'):
- """The single mandatory argument to this constructor is a format
- string.
-
- The format string is parsed according to the following rules:
-
- 1. A dollar sign and a name, possibly followed by any of:
- - an open-paren, and anything up to the matching paren
- - an open-bracket, and anything up to the matching bracket
- - a period and a name
- any number of times, is evaluated as a Python expression.
-
- 2. A dollar sign immediately followed by an open-brace, and
- anything up to the matching close-brace, is evaluated as
- a Python expression.
-
- 3. Outside of the expressions described in the above two rules,
- two dollar signs in a row give you one literal dollar sign.
-
- Optional arguments:
-
- - codec('utf_8'): a string containing the name of a valid Python
- codec.
-
- - encoding_errors('backslashreplace'): a string with a valid error handling
- policy. See the codecs module documentation for details.
-
- These are used to encode the format string if a call to str() fails on
- the expanded result."""
-
- if not isinstance(format,basestring):
- raise TypeError, "needs string initializer"
- self.format = format
- self.codec = codec
- self.encoding_errors = encoding_errors
-
- namechars = "abcdefghijklmnopqrstuvwxyz" \
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
- chunks = []
- pos = 0
-
- while 1:
- dollar = string.find(format, "$", pos)
- if dollar < 0: break
- nextchar = format[dollar+1]
-
- if nextchar == "{":
- chunks.append((0, format[pos:dollar]))
- pos, level = dollar+2, 1
- while level:
- match, pos = matchorfail(format, pos)
- tstart, tend = match.regs[3]
- token = format[tstart:tend]
- if token == "{": level = level+1
- elif token == "}": level = level-1
- chunks.append((1, format[dollar+2:pos-1]))
-
- elif nextchar in namechars:
- chunks.append((0, format[pos:dollar]))
- match, pos = matchorfail(format, dollar+1)
- while pos < len(format):
- if format[pos] == "." and \
- pos+1 < len(format) and format[pos+1] in namechars:
- match, pos = matchorfail(format, pos+1)
- elif format[pos] in "([":
- pos, level = pos+1, 1
- while level:
- match, pos = matchorfail(format, pos)
- tstart, tend = match.regs[3]
- token = format[tstart:tend]
- if token[0] in "([": level = level+1
- elif token[0] in ")]": level = level-1
- else: break
- chunks.append((1, format[dollar+1:pos]))
-
- else:
- chunks.append((0, format[pos:dollar+1]))
- pos = dollar + 1 + (nextchar == "$")
-
- if pos < len(format): chunks.append((0, format[pos:]))
- self.chunks = chunks
-
- def __repr__(self):
- return "<Itpl %s >" % repr(self.format)
-
- def _str(self,glob,loc):
- """Evaluate to a string in the given globals/locals.
-
- The final output is built by calling str(), but if this fails, the
- result is encoded with the instance's codec and error handling policy,
- via a call to out.encode(self.codec,self.encoding_errors)"""
- result = []
- app = result.append
- for live, chunk in self.chunks:
- if live:
- val = eval(chunk,glob,loc)
- try:
- app(str(val))
- except UnicodeEncodeError:
- app(unicode(val))
-
- else: app(chunk)
- out = ''.join(result)
- try:
- return str(out)
- except UnicodeError:
- return out.encode(self.codec,self.encoding_errors)
-
- def __str__(self):
- """Evaluate and substitute the appropriate parts of the string."""
-
- # We need to skip enough frames to get to the actual caller outside of
- # Itpl.
- frame = sys._getframe(1)
- while frame.f_globals["__name__"] == __name__: frame = frame.f_back
- loc, glob = frame.f_locals, frame.f_globals
-
- return self._str(glob,loc)
-
-class ItplNS(Itpl):
- """Class representing a string with interpolation abilities.
-
- This inherits from Itpl, but at creation time a namespace is provided
- where the evaluation will occur. The interpolation becomes a bit more
- efficient, as no traceback needs to be extracte. It also allows the
- caller to supply a different namespace for the interpolation to occur than
- its own."""
-
- def __init__(self, format,globals,locals=None,
- codec='utf_8',encoding_errors='backslashreplace'):
- """ItplNS(format,globals[,locals]) -> interpolating string instance.
-
- This constructor, besides a format string, takes a globals dictionary
- and optionally a locals (which defaults to globals if not provided).
-
- For further details, see the Itpl constructor."""
-
- if locals is None:
- locals = globals
- self.globals = globals
- self.locals = locals
- Itpl.__init__(self,format,codec,encoding_errors)
-
- def __str__(self):
- """Evaluate and substitute the appropriate parts of the string."""
- return self._str(self.globals,self.locals)
-
- def __repr__(self):
- return "<ItplNS %s >" % repr(self.format)
-
-# utilities for fast printing
-def itpl(text): return str(Itpl(text))
-def printpl(text): print itpl(text)
-# versions with namespace
-def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
-def printplns(text,globals,locals=None): print itplns(text,globals,locals)
-
-class ItplFile:
- """A file object that filters each write() through an interpolator."""
- def __init__(self, file): self.file = file
- def __repr__(self): return "<interpolated " + repr(self.file) + ">"
- def __getattr__(self, attr): return getattr(self.file, attr)
- def write(self, text): self.file.write(str(Itpl(text)))
-
-def filter(file=sys.stdout):
- """Return an ItplFile that filters writes to the given file object.
-
- 'file = filter(file)' replaces 'file' with a filtered object that
- has a write() method. When called with no argument, this creates
- a filter to sys.stdout."""
- return ItplFile(file)
-
-def unfilter(ifile=None):
- """Return the original file that corresponds to the given ItplFile.
-
- 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
- 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
- return ifile and ifile.file or sys.stdout.file
View
6 IPython/frontend/qt/console/console_widget.py
@@ -1220,8 +1220,10 @@ def _event_filter_console_keypress(self, event):
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
- # using the keyboard in any part of the buffer.
- if not self._control_key_down(event.modifiers(), include_command=True):
+ # using the keyboard in any part of the buffer. Also, permit scrolling
+ # with Page Up/Down keys.
+ if not (self._control_key_down(event.modifiers(), include_command=True)
+ or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)):
self._keep_cursor_in_buffer()
return intercepted
View
28 IPython/frontend/qt/console/history_console_widget.py
@@ -82,7 +82,8 @@ def _up_pressed(self, shift_modifier):
self._history_prefix = input_buffer[:col]
# Perform the search.
- self.history_previous(self._history_prefix)
+ self.history_previous(self._history_prefix,
+ as_prefix=not shift_modifier)
# Go to the first line of the prompt for seemless history scrolling.
# Emulate readline: keep the cursor position fixed for a prefix
@@ -110,7 +111,8 @@ def _down_pressed(self, shift_modifier):
return False
# Perform the search.
- replaced = self.history_next(self._history_prefix)
+ replaced = self.history_next(self._history_prefix,
+ as_prefix=not shift_modifier)
# Emulate readline: keep the cursor position fixed for a prefix
# search. (We don't need to move the cursor to the end of the buffer
@@ -130,13 +132,15 @@ def _down_pressed(self, shift_modifier):
# 'HistoryConsoleWidget' public interface
#---------------------------------------------------------------------------
- def history_previous(self, prefix=''):
+ def history_previous(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a previous history item.
Parameters:
-----------
- prefix : str, optional
- If specified, search for an item with this prefix.
+ substring : str, optional
+ If specified, search for an item with this substring.
+ as_prefix : bool, optional
+ If True, the substring must match at the beginning (default).
Returns:
--------
@@ -147,7 +151,8 @@ def history_previous(self, prefix=''):
while index > 0:
index -= 1
history = self._get_edited_history(index)
- if history.startswith(prefix):
+ if (as_prefix and history.startswith(substring)) \
+ or (not as_prefix and substring in history):
replace = True
break
@@ -158,13 +163,15 @@ def history_previous(self, prefix=''):
return replace
- def history_next(self, prefix=''):
+ def history_next(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a subsequent history item.
Parameters:
-----------
- prefix : str, optional
- If specified, search for an item with this prefix.
+ substring : str, optional
+ If specified, search for an item with this substring.
+ as_prefix : bool, optional
+ If True, the substring must match at the beginning (default).
Returns:
--------
@@ -175,7 +182,8 @@ def history_next(self, prefix=''):
while self._history_index < len(self._history):
index += 1
history = self._get_edited_history(index)
- if history.startswith(prefix):
+ if (as_prefix and history.startswith(substring)) \
+ or (not as_prefix and substring in history):
replace = True
break
View
6 IPython/frontend/qt/console/ipython_widget.py
@@ -440,7 +440,11 @@ def _edit(self, filename, line=None):
def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
- body = self.in_prompt % number
+ try:
+ body = self.in_prompt % number
+ except TypeError:
+ # allow in_prompt to leave out number, e.g. '>>> '
+ body = self.in_prompt
return '<span class="in-prompt">%s</span>' % body
def _make_continuation_prompt(self, prompt):
View
21 IPython/frontend/terminal/ipapp.py
@@ -48,7 +48,7 @@
from IPython.utils import warn
from IPython.utils.path import get_ipython_dir, check_for_old_config
from IPython.utils.traitlets import (
- Bool, Dict, CaselessStrEnum
+ Bool, List, Dict, CaselessStrEnum
)
#-----------------------------------------------------------------------------
@@ -189,8 +189,17 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
flags = Dict(flags)
aliases = Dict(aliases)
- classes = [InteractiveShellApp, TerminalInteractiveShell, ProfileDir,
- PlainTextFormatter]
+ classes = List()
+ def _classes_default(self):
+ """This has to be in a method, for TerminalIPythonApp to be available."""
+ return [
+ InteractiveShellApp, # ShellApp comes before TerminalApp, because
+ self.__class__, # it will also affect subclasses (e.g. QtConsole)
+ TerminalInteractiveShell,
+ ProfileDir,
+ PlainTextFormatter,
+ ]
+
subcommands = Dict(dict(
qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
"""Launch the IPython Qt Console."""
@@ -199,7 +208,11 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
"""Launch the IPython HTML Notebook Server"""
),
profile = ("IPython.core.profileapp.ProfileApp",
- "Create and manage IPython profiles.")
+ "Create and manage IPython profiles."
+ ),
+ kernel = ("IPython.zmq.ipkernel.IPKernelApp",
+ "Start a kernel without an attached frontend."
+ ),
))
# *do* autocreate requested profile, but don't create the config file.
View
0  IPython/lib/guisupport.py 100644 → 100755
File mode changed
View
72 IPython/lib/inputhook.py
@@ -115,13 +115,14 @@ def clear_app_refs(self, gui=None):
elif self._apps.has_key(gui):
del self._apps[gui]
- def enable_wx(self):
+ def enable_wx(self, app=None):
"""Enable event loop integration with wxPython.
Parameters
----------
- app : bool
- Create a running application object or not.
+ app : WX Application, optional.
+ Running application to use. If not given, we probe WX for an
+ existing application object, and create a new one if none is found.
Notes
-----
@@ -129,22 +130,19 @@ def enable_wx(self):
the wxPython to integrate with terminal based applications like
IPython.
- If ``app`` is True, we create an :class:`wx.App` as follows::
+ If ``app`` is not given we probe for an existing one, and return it if
+ found. If no existing app is found, we create an :class:`wx.App` as
+ follows::
import wx
app = wx.App(redirect=False, clearSigInt=False)
-
- Both options this constructor are important for things to work
- properly in an interactive context.
-
- But, we first check to see if an application has already been
- created. If so, we simply return that instance.
"""
from IPython.lib.inputhookwx import inputhook_wx
self.set_inputhook(inputhook_wx)
self._current_gui = GUI_WX
import wx
- app = wx.GetApp()
+ if app is None:
+ app = wx.GetApp()
if app is None:
app = wx.App(redirect=False, clearSigInt=False)
app._in_event_loop = True
@@ -160,13 +158,14 @@ def disable_wx(self):
self._apps[GUI_WX]._in_event_loop = False
self.clear_inputhook()
- def enable_qt4(self):
+ def enable_qt4(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
- app : bool
- Create a running application object or not.
+ app : Qt Application, optional.
+ Running application to use. If not given, we probe Qt for an
+ existing application object, and create a new one if none is found.
Notes
-----
@@ -174,13 +173,12 @@ def enable_qt4(self):
the PyQt4 to integrate with terminal based applications like
IPython.
- If ``app`` is True, we create an :class:`QApplication` as follows::
+ If ``app`` is not given we probe for an existing one, and return it if
+ found. If no existing app is found, we create an :class:`QApplication`
+ as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
-
- But, we first check to see if an application has already been
- created. If so, we simply return that instance.
"""
from IPython.external.qt_for_kernel import QtCore, QtGui
@@ -205,7 +203,8 @@ def enable_qt4(self):
pass
self._current_gui = GUI_QT4
- app = QtCore.QCoreApplication.instance()
+ if app is None:
+ app = QtCore.QCoreApplication.instance()
if app is None:
app = QtGui.QApplication([" "])
app._in_event_loop = True
@@ -221,14 +220,15 @@ def disable_qt4(self):
self._apps[GUI_QT4]._in_event_loop = False
self.clear_inputhook()
- def enable_gtk(self, app=False):
+ def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
- app : bool
- Create a running application object or not. Because gtk does't
- have an app class, this does nothing.
+ app : ignored
+ Ignored, it's only a placeholder to keep the call signature of all
+ gui activation methods consistent, which simplifies the logic of
+ supporting magics.
Notes
-----
@@ -253,21 +253,24 @@ def disable_gtk(self):
"""
self.clear_inputhook()
- def enable_tk(self, app=False):
+ def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
- app : bool
- Create a running application object or not.
+ app : toplevel :class:`Tkinter.Tk` widget, optional.
+ Running toplevel widget to use. If not given, we probe Tk for an
+ existing one, and create a new one if none is found.
Notes
-----
- Currently this is a no-op as creating a :class:`Tkinter.Tk` object
+ If you have already created a :class:`Tkinter.Tk` object, the only
+ thing done by this method is to register with the
+ :class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
- if app:
+ if app is None:
import Tkinter
app = Tkinter.Tk()
app.withdraw()
@@ -302,7 +305,7 @@ def current_gui(self):
# Convenience function to switch amongst them
-def enable_gui(gui=None):
+def enable_gui(gui=None, app=None):
"""Switch amongst GUI input hooks by name.
This is just a utility wrapper around the methods of the InputHookManager
@@ -314,8 +317,11 @@ def enable_gui(gui=None):
If None, clears input hook, otherwise it must be one of the recognized
GUI names (see ``GUI_*`` constants in module).
- app : optional, bool
- If true, create an app object and return it.
+ app : optional, existing application object.
+ For toolkits that have the concept of a global app, you can supply an
+ existing one. If not given, the toolkit will be probed for one, and if
+ none is found, a new one will be created. Note that GTK does not have
+ this concept, and passing an app if `gui`=="GTK" will raise an error.
Returns
-------
@@ -333,7 +339,7 @@ def enable_gui(gui=None):
try:
gui_hook = guis[gui]
except KeyError:
- e="Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
+ e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
raise ValueError(e)
- return gui_hook()
+ return gui_hook(app)
View
12 IPython/lib/irunner.py
@@ -16,7 +16,7 @@
This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
contributed on the ipython-user list:
-http://scipy.net/pipermail/ipython-user/2006-May/001705.html
+http://mail.scipy.org/pipermail/ipython-user/2006-May/003539.html
NOTES:
@@ -35,8 +35,9 @@
import os
import sys
-# Third-party modules.
-import pexpect
+# Third-party modules: we carry a copy of pexpect to reduce the need for
+# external dependencies, but our import checks for a system version first.
+from IPython.external import pexpect
# Global usage strings, to avoid indentation issues when typing it below.
USAGE = """
@@ -410,7 +411,6 @@ def main():
parser = optparse.OptionParser(usage=MAIN_USAGE)
newopt = parser.add_option
- parser.set_defaults(mode='ipython')
newopt('--ipython',action='store_const',dest='mode',const='ipython',
help='IPython interactive runner (default).')
newopt('--python',action='store_const',dest='mode',const='python',
@@ -430,7 +430,9 @@ def main():
modes = {'.ipy':'ipython',
'.py':'python',
'.sage':'sage'}
- mode = modes.get(ext,opts.mode)
+ mode = modes.get(ext,"ipython")
+ if opts.mode:
+ mode = opts.mode
runners[mode]().main(args)
if __name__ == '__main__':
View
29 IPython/parallel/apps/baseapp.py
@@ -53,34 +53,9 @@ class PIDFileError(Exception):
# Crash handler for this application
#-----------------------------------------------------------------------------
-
-_message_template = """\
-Oops, $self.app_name crashed. We do our best to make it stable, but...
-
-A crash report was automatically generated with the following information:
- - A verbatim copy of the crash traceback.
- - Data on your current $self.app_name configuration.
-
-It was left in the file named:
-\t'$self.crash_report_fname'
-If you can email this file to the developers, the information in it will help
-them in understanding and correcting the problem.
-
-You can mail it to: $self.contact_name at $self.contact_email
-with the subject '$self.app_name Crash Report'.
-
-If you want to do it now, the following command will work (under Unix):
-mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
-
-To ensure accurate tracking of this issue, please file a report about it at:
-$self.bug_tracker
-"""
-
class ParallelCrashHandler(CrashHandler):
"""sys.excepthook for IPython itself, leaves a detailed report on disk."""
- message_template = _message_template
-
def __init__(self, app):
contact_name = release.authors['Min'][0]
contact_email = release.authors['Min'][1]
@@ -187,6 +162,10 @@ def reinit_logging(self):
self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
self._log_handler.setFormatter(self._log_formatter)
self.log.addHandler(self._log_handler)
+ # do not propagate log messages to root logger
+ # ipcluster app will sometimes print duplicate messages during shutdown
+ # if this is 1 (default):
+ self.log.propagate = False
def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
View
2  IPython/parallel/apps/ipclusterapp.py
@@ -63,7 +63,7 @@
range of startup methods (SSH, local processes, PBS, mpiexec,
Windows HPC Server 2008). To start a cluster with 4 engines on your
local host simply do 'ipcluster start --n=4'. For more complex usage
-you will typically do 'ipython create mycluster --parallel', then edit
+you will typically do 'ipython profile create mycluster --parallel', then edit
configuration files, followed by 'ipcluster start --profile=mycluster --n=4'.
"""
View
6 IPython/parallel/client/client.py
@@ -1024,6 +1024,8 @@ def load_balanced_view(self, targets=None):
targets: list,slice,int,etc. [default: use all engines]
The subset of engines across which to load-balance
"""
+ if targets == 'all':
+ targets = None
if targets is not None:
targets = self._build_targets(targets)[1]
return LoadBalancedView(client=self, socket=self._task_socket, targets=targets)
@@ -1041,7 +1043,9 @@ def direct_view(self, targets='all'):
The engines to use for the View
"""
single = isinstance(targets, int)
- targets = self._build_targets(targets)[1]
+ # allow 'all' to be lazily evaluated at each execution
+ if targets != 'all':
+ targets = self._build_targets(targets)[1]
if single:
targets = targets[0]
return DirectView(client=self, socket=self._mux_socket, targets=targets)
View
11 IPython/parallel/tests/test_client.py
@@ -76,7 +76,16 @@ def test_lbview_targets(self):
v = self.client.load_balanced_view(-1)
self.assertEquals(v.targets, [self.client.ids[-1]])
v = self.client.load_balanced_view('all')
- self.assertEquals(v.targets, self.client.ids)
+ self.assertEquals(v.targets, None)
+
+ def test_dview_targets(self):
+ """test load_balanced_view targets"""
+ v = self.client.direct_view()
+ self.assertEquals(v.targets, 'all')
+ v = self.client.direct_view('all')
+ self.assertEquals(v.targets, 'all')
+ v = self.client.direct_view(-1)
+ self.assertEquals(v.targets, self.client.ids[-1])
def test_targets(self):
"""test various valid targets arguments"""
View
4 IPython/parallel/util.py
@@ -40,6 +40,7 @@
from zmq.log import handlers
# IPython imports
+from IPython.config.application import Application
from IPython.utils.pickleutil import can, uncan, canSequence, uncanSequence
from IPython.utils.newserialized import serialize, unserialize
from IPython.zmq.log import EnginePUBHandler
@@ -391,7 +392,8 @@ def select_random_ports(n):
def signal_children(children):
"""Relay interupt/term signals to children, for more solid process cleanup."""
def terminate_children(sig, frame):
- logging.critical("Got signal %i, terminating children..."%sig)
+ log = Application.instance().log
+ log.critical("Got signal %i, terminating children..."%sig)
for child in children:
child.terminate()
View
4 IPython/utils/io.py
@@ -196,7 +196,7 @@ def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
return lines[:-1] # don't return the termination command
except EOFError:
- print
+ print()
return lines
@@ -232,7 +232,7 @@ def ask_yes_no(prompt,default=None):
except EOFError:
if default in answers.keys():
ans = default
- print
+ print()
else:
raise
View
12 IPython/zmq/heartbeat.py
@@ -12,6 +12,7 @@
# Imports
#-----------------------------------------------------------------------------
+import socket
import sys
from threading import Thread
@@ -33,13 +34,16 @@ def __init__(self, context, addr=(LOCALHOST, 0)):
self.addr = addr
self.ip = addr[0]
self.port = addr[1]
+ if self.port == 0:
+ s = socket.socket()
+ s.bind(self.addr)
+ self.port = s.getsockname()[1]
+ s.close()
+ self.addr = (self.ip, self.port)
self.daemon = True
def run(self):
self.socket = self.context.socket(zmq.REP)
- if self.port == 0:
- self.port = self.socket.bind_to_random_port('tcp://%s' % self.ip)
- else:
- self.socket.bind('tcp://%s:%i' % self.addr)
+ self.socket.bind('tcp://%s:%i' % self.addr)
zmq.device(zmq.FORWARDER, self.socket, self.socket)
View
3  IPython/zmq/iostream.py
@@ -45,6 +45,9 @@ def flush(self):
msg = self.session.send(self.pub_socket, u'stream', content=content,
parent=self.parent_header, ident=self.topic)
+ if hasattr(self.pub_socket, 'flush'):
+ # socket itself has flush (presumably ZMQStream)
+ self.pub_socket.flush()
self._buffer.close()
self._new_buffer()
View
15 IPython/zmq/kernelmanager.py
@@ -771,6 +771,11 @@ def start_kernel(self, **kw):
ipython : bool, optional (default True)
Whether to use an IPython kernel instead of a plain Python kernel.
+ launcher : callable, optional (default None)
+ A custom function for launching the kernel process (generally a
+ wrapper around ``entry_point.base_launch_kernel``). In most cases,
+ it should not be necessary to use this parameter.
+
**kw : optional
See respective options for IPython and Python kernels.
"""
@@ -785,10 +790,12 @@ def start_kernel(self, **kw):
)
self._launch_args = kw.copy()
- if kw.pop('ipython', True):
- from ipkernel import launch_kernel
- else:
- from pykernel import launch_kernel
+ launch_kernel = kw.pop('launcher', None)
+ if launch_kernel is None:
+ if kw.pop('ipython', True):
+ from ipkernel import launch_kernel
+ else:
+ from pykernel import launch_kernel
self.kernel, xrep, pub, req, _hb = launch_kernel(
shell_port=shell[1], iopub_port=sub[1],
stdin_port=stdin[1], hb_port=hb[1], **kw)
View
15 IPython/zmq/zmqshell.py
@@ -31,7 +31,7 @@
from IPython.core.payloadpage import install_payload_page
from IPython.utils import io
from IPython.utils.path import get_py_filename
-from IPython.utils.traitlets import Instance, Type, Dict
+from IPython.utils.traitlets import Instance, Type, Dict, CBool
from IPython.utils.warn import warn
from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_png
from IPython.zmq.session import extract_header
@@ -80,6 +80,17 @@ class ZMQInteractiveShell(InteractiveShell):
displayhook_class = Type(ZMQShellDisplayHook)
display_pub_class = Type(ZMQDisplayPublisher)
+ # Override the traitlet in the parent class, because there's no point using
+ # readline for the kernel. Can be removed when the readline code is moved
+ # to the terminal frontend.
+
+ # FIXME. This is disabled for now, even though it may cause problems under
+ # Windows, because it breaks %run in the Qt console. See gh-617 for more
+ # details. Re-enable once we've fully tested that %run works in the Qt
+ # console with syntax highlighting in tracebacks.
+ # readline_use = CBool(False)
+ # /FIXME
+
exiter = Instance(ZMQExitAutocall)
def _exiter_default(self):
return ZMQExitAutocall(self)
@@ -385,7 +396,7 @@ def magic_edit(self,parameter_s='',last_call=['','']):
def magic_gui(self, *args, **kwargs):
raise NotImplementedError(
- 'GUI support must be enabled in command line options.')
+ 'Kernel GUI support is not implemented yet, except for --pylab.')
def magic_pylab(self, *args, **kwargs):
raise NotImplementedError(
View
22 README.rst
@@ -1,14 +1,15 @@
-==============
-IPython README
-==============
+===========================================
+ IPython: Productive Interactive Computing
+===========================================
Overview
========
-Welcome to IPython. Our full documentation can be found in the ``docs/dist``
-subdirectory in ``.html`` and ``.pdf`` formats, also available online at our
-`docs repo <http://ipython.github.com/ipython-doc>`_. The ``docs/source`` directory
-contains the plaintext version of these manuals.
+Welcome to IPython. Our full documentation, including PDF versions of our
+manual, is available on `our website <http://ipython.org/documentation.html>`_;
+if you downloaded a built source distribution the ``docs/html`` directory
+contains an HTML version of the manual. The ``docs/source`` directory contains
+the plaintext version of these manuals.
Dependencies and supported Python versions
@@ -18,9 +19,9 @@ For full details, see the installation section of the manual. The basic parts
of IPython only need the Python standard library, but much of its more advanced
functionality requires extra packages.
-Officially, IPython requires Python version 2.6 or 2.7. An experimental port
-of IPython to Python 3.x is being developed at
-http://github.com/ipython/ipython-py3k.
+Officially, IPython requires Python version 2.6 or 2.7. A separate repository
+contains our Python 3 version, as explained `in our wiki
+<http://wiki.ipython.org/Python_3>`_.
Instant running
@@ -30,4 +31,3 @@ You can run IPython from this directory without even installing it system-wide
by typing at the terminal::
$ python ipython.py
-
View
15 docs/Makefile
@@ -39,12 +39,15 @@ pdf: latex
all: html pdf
-dist: all
- mkdir -p dist
- rm -rf dist/*
- ln build/latex/ipython.pdf dist/
- cp -al build/html dist/
- @echo "Build finished. Final docs are in dist/"
+# For final distribution, only build HTML (our pdf is now so large as to be
+# unusable, takes forever to build and just bloats the downloads). We leave
+# them hardlinked at the top-level so users find them easily, though the
+# original build/html dir is left in-place (useful to reload builds while
+# testing).
+dist: html
+ rm -rf html
+ cp -al build/html .
+ @echo "Build finished. Final docs are in html/"
html: api
mkdir -p build/html build/doctrees
View
143 docs/examples/core/ipy.vim
@@ -1,143 +0,0 @@
-if !exists("$IPY_SESSION")
- finish
-endif
-
-" set up the python interpreter within vim, to have all the right modules
-" imported, as well as certain useful globals set
-python import socket
-python import os
-python import vim
-python from IPython.core.debugger import Pdb
-python IPYSERVER = None
-python reselect = True
-
-python << EOF
-# do we have a connection to the ipython instance?
-def check_server():
- global IPYSERVER
- if IPYSERVER:
- return True
- else:
- return False
-
-# connect to the ipython server, if we need to
-def connect():
- global IPYSERVER
- if check_server():
- return
- try:
- IPYSERVER = socket.socket(socket.AF_UNIX)
- IPYSERVER.connect(os.environ.get('IPY_SERVER'))
- except:
- IPYSERVER = None
-
-def disconnect():
- if IPYSERVER:
- IPYSERVER.close()
-
-def send(cmd):
- x = 0
- while True:
- x += IPYSERVER.send(cmd)
- if x < len(cmd):
- cmd = cmd[x:]
- else:
- break
-
-def run_this_file():
- if check_server():
- send('run %s' % (vim.current.buffer.name,))
- else:
- raise Exception, "Not connected to an IPython server"
- print "\'run %s\' sent to ipython" % vim.current.buffer.name
-
-def run_this_line():
- if check_server():
- send(vim.current.line)
- print "line \'%s\' sent to ipython"% vim.current.line
- else:
- raise Exception, "Not connected to an IPython server"
-
-def run_these_lines():
- r = vim.current.range
- if check_server():
- #send(str((vim.current.range.start,vim.current.range.end)))
- for l in vim.current.buffer[r.start:r.end+1]:
- send(str(l)+'\n')
- #send(str(vim.current.buffer[vim.current.range.start:vim.current.range.end]).join("\n"))
- #print "lines %d-%d sent to ipython"% (r.start,r.end)
- else:
- raise Exception, "Not connected to an IPython server"
-
- #reselect the previously highlighted block
- if reselect:
- vim.command("normal gv")
- #vim lines start with 1
- print "lines %d-%d sent to ipython"% (r.start+1,r.end+1)
-
-def toggle_reselect():
- global reselect
- reselect=not reselect
- print "F9 will%sreselect lines after sending to ipython"% (reselect and " " or " not ")
-
-def set_breakpoint():
- if check_server():
- send("__IP.InteractiveTB.pdb.set_break('%s',%d)" % (vim.current.buffer.name,
- vim.current.window.cursor[0]))
- print "set breakpoint in %s:%d"% (vim.current.buffer.name,
- vim.current.window.cursor[0])
- else:
- raise Exception, "Not connected to an IPython server"
-
-def clear_breakpoint():
- if check_server():
- send("__IP.InteractiveTB.pdb.clear_break('%s',%d)" % (vim.current.buffer.name,
- vim.current.window.cursor[0]))
- print "clearing breakpoint in %s:%d" % (vim.current.buffer.name,
- vim.current.window.cursor[0])
- else:
- raise Exception, "Not connected to an IPython server"
-
-def clear_all_breakpoints():
- if check_server():
- send("__IP.InteractiveTB.pdb.clear_all_breaks()");
- print "clearing all breakpoints"
- else:
- raise Exception, "Not connected to an IPython server"
-
-def run_this_file_pdb():
- if check_server():
- send(' __IP.InteractiveTB.pdb.run(\'execfile("%s")\')' % (vim.current.buffer.name,))
- else:
- raise Exception, "Not connected to an IPython server"
- print "\'run %s\' using pdb sent to ipython" % vim.current.buffer.name
-
- #XXX: have IPYSERVER print the prompt (look at Leo example)
-EOF
-
-fun! <SID>toggle_send_on_save()
- if exists("s:ssos") && s:ssos == 1
- let s:ssos = 0
- au! BufWritePost *.py :py run_this_file()
- echo "Autosend Off"
- else
- let s:ssos = 1
- au BufWritePost *.py :py run_this_file()
- echo "Autowsend On"
- endif
-endfun
-
-map <silent> <F5> :python run_this_file()<CR>
-map <silent> <S-F5> :python run_this_line()<CR>
-map <silent> <F9> :python run_these_lines()<CR>
-map <silent> <S-F9> :python toggle_reselect()<CR>
-map <silent> <C-F6> :python send('%pdb')<CR>
-map <silent> <F6> :python set_breakpoint()<CR>
-map <silent> <s-F6> :python clear_breakpoint()<CR>
-map <silent> <F7> :python run_this_file_pdb()<CR>
-map <silent> <s-F7> :python clear_all_breaks()<CR>
-imap <C-F5> <ESC><F5>a
-imap <S-F5> <ESC><S-F5>a
-imap <silent> <F5> <ESC><F5>a
-map <C-F5> :call <SID>toggle_send_on_save()<CR>
-py connect()
View
15 docs/examples/core/ipython-qtconsole.desktop
@@ -0,0 +1,15 @@
+# If you want ipython to appear in a linux app launcher ("start menu"), install this by doing:
+# sudo desktop-file-install ipython-qtconsole.desktop
+
+[Desktop Entry]
+Comment=Enhanced interactive Python qtconsole
+Exec=ipython qtconsole
+GenericName[en_US]=IPython qtconsole
+GenericName=IPython qtconsole
+Icon=gnome-netstatus-idle
+Name[en_US]=ipython qtconsole
+Name=ipython qtconsole
+Categories=Development;Utility;
+StartupNotify=false
+Terminal=false
+Type=Application
View
9 docs/examples/core/ipython-sh.desktop
@@ -3,20 +3,13 @@
[Desktop Entry]
Comment=Perform shell-like tasks in interactive ipython session
-Exec=ipython -p sh
+Exec=ipython --profile=pysh
GenericName[en_US]=IPython shell mode
GenericName=IPython shell mode
Icon=gnome-netstatus-idle
-MimeType=
Name[en_US]=ipython-sh
Name=ipython-sh
-Path=
Categories=Development;Utility;
StartupNotify=false
Terminal=true
-TerminalOptions=
Type=Application
-X-DBUS-ServiceName=
-X-DBUS-StartupType=none
-X-KDE-SubstituteUID=false
-X-KDE-Username=
View
7 docs/examples/core/ipython.desktop
@@ -7,16 +7,9 @@ Exec=ipython
GenericName[en_US]=IPython
GenericName=IPython
Icon=gnome-netstatus-idle
-MimeType=
Name[en_US]=ipython
Name=ipython
-Path=
Categories=Development;Utility;
StartupNotify=false
Terminal=true
-TerminalOptions=
Type=Application
-X-DBUS-ServiceName=
-X-DBUS-StartupType=none
-X-KDE-SubstituteUID=false
-X-KDE-Username=
View
40 docs/examples/lib/example-demo.py
@@ -0,0 +1,40 @@
+"""A simple interactive demo to illustrate the use of IPython's Demo class.
+
+Any python script can be run as a demo, but that does little more than showing
+it on-screen, syntax-highlighted in one shot. If you add a little simple
+markup, you can stop at specified intervals and return to the ipython prompt,
+resuming execution later.
+"""
+
+print 'Hello, welcome to an interactive IPython demo.'
+print 'Executing this block should require confirmation before proceeding,'
+print 'unless auto_all has been set to true in the demo object'
+
+# The mark below defines a block boundary, which is a point where IPython will
+# stop execution and return to the interactive prompt.
+# Note that in actual interactive execution,
+# <demo> --- stop ---
+
+x = 1
+y = 2
+
+# <demo> --- stop ---
+
+# the mark below makes this block as silent
+# <demo> silent
+
+print 'This is a silent block, which gets executed but not printed.'
+
+# <demo> --- stop ---
+# <demo> auto
+print 'This is an automatic block.'
+print 'It is executed without asking for confirmation, but printed.'
+z = x+y
+
+print 'z=',x
+
+# <demo> --- stop ---
+# This is just another normal block.
+print 'z is now:', z
+
+print 'bye!'
View
4 docs/examples/lib/gui-gtk.py
@@ -8,7 +8,6 @@
In [6]: %run gui-gtk.py
"""
-
import pygtk
pygtk.require('2.0')
import gtk
@@ -38,6 +37,3 @@ def destroy(widget, data=None):
enable_gtk()
except ImportError:
gtk.main()
-
-
-
View
54 docs/examples/lib/gui-mpl.py
@@ -1,54 +0,0 @@
-"""Test the new %gui command. Run this in ipython as
-
-In [1]: %gui [backend]
-
-In [2]: %run switchgui [backend]
-
-where the optional backend can be one of: qt4, gtk, tk, wx.
-
-Because of subtle difference in how Matplotlib handles the different GUI
-toolkits (in things like draw and show), minor modifications to this script
-have to be made for Tk to get it to work with the 0.99 and below releases
-of Matplotlib. However, in the future, Matplotlib should be able to have
-similar logic for all the toolkits, as they are all now using PyOS_InputHook.
-"""
-
-import sys
-import time
-
-from IPython.lib import inputhook
-
-gui = inputhook.current_gui()
-if gui is None:
- gui = 'qt4'
- inputhook.enable_qt4(app=True)
-
-backends = dict(wx='wxagg', qt4='qt4agg', gtk='gtkagg', tk='tkagg')
-
-import matplotlib
-matplotlib.use(backends[gui])
-matplotlib.interactive(True)
-
-import matplotlib
-from matplotlib import pyplot as plt, mlab, pylab
-import numpy as np
-
-from numpy import *
-from matplotlib.pyplot import *
-
-x = np.linspace(0,pi,500)
-
-print "A plot has been created"
-line, = plot(x,sin(2*x))
-inputhook.spin() # This has to be removed for Tk
-
-
-print "Now, we will update the plot..."
-print
-for i in range(1,51):
- print i,
- sys.stdout.flush()
- line.set_data(x,sin(x*i))
- plt.title('i=%d' % i)
- plt.draw()
- inputhook.spin() # This has to be removed for Tk
View
3  docs/examples/lib/gui-qt.py
@@ -35,6 +35,7 @@ def __init__(self, parent=None):
sw.show()
try:
- from IPython import enable_qt4; enable_qt4(app)
+ from IPython.lib.guisupport import start_event_loop_qt4
+ start_event_loop_qt4(app)
except ImportError:
app.exec_()
View
2  docs/examples/lib/gui-tk.py 100644 → 100755
@@ -27,6 +27,6 @@ def hello_world(self):
app = MyApp(root)
try:
- from IPython import enable_tk; enable_tk(root)
+ from IPython.lib.inputhook import enable_tk; enable_tk(root)
except ImportError:
root.mainloop()
View
30 docs/examples/lib/gui-wx.py 100644 → 100755
@@ -1,4 +1,10 @@
-"""A Simple wx example to test IPython's event loop integration.
+#!/usr/bin/env python
+"""
+WARNING: This example is currently broken, see
+https://github.com/ipython/ipython/issues/645 for details on our progress on
+this issue.
+
+A Simple wx example to test IPython's event loop integration.
To run this do:
@@ -97,13 +103,19 @@ def OnInit(self):
frame.Show(True)
return True
-app = wx.GetApp()
-if app is None:
- app = MyApp(redirect=False, clearSigInt=False)
-try:
- from IPython.lib.inputhook import enable_wx
- enable_wx(app)
-except ImportError:
- app.MainLoop()
+if __name__ == '__main__':
+ raise NotImplementedError(
+ 'Standalone WX GUI support is currently broken. '
+ 'See https://github.com/ipython/ipython/issues/645 for details')
+
+ app = wx.GetApp()
+ if app is None:
+ app = MyApp(redirect=False, clearSigInt=False)
+
+ try:
+ from IPython.lib.inputhook import enable_wx
+ enable_wx(app)
+ except ImportError:
+ app.MainLoop()
View
65 docs/examples/lib/internal_ipkernel.py
@@ -0,0 +1,65 @@
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+import subprocess
+import sys
+
+from IPython.zmq.ipkernel import IPKernelApp
+
+#-----------------------------------------------------------------------------
+# Functions and classes
+#-----------------------------------------------------------------------------
+def pylab_kernel(gui):
+ """Launch and return an IPython kernel with pylab support for the desired gui
+ """
+ kernel = IPKernelApp()
+ kernel.initialize(['python', '--pylab=%s' % gui,
+ #'--log-level=10'
+ ])
+ return kernel
+
+
+def qtconsole_cmd(kernel):
+ """Compute the command to connect a qt console to an already running kernel
+ """
+ ports = ['--%s=%d' % (name, port) for name, port in kernel.ports.items()]
+ return ['ipython', 'qtconsole', '--existing'] + ports
+
+
+class InternalIPKernel(object):
+
+ def init_ipkernel(self, backend):
+ # Start IPython kernel with GUI event loop and pylab support
+ self.ipkernel = pylab_kernel(backend)
+ # To create and track active qt consoles
+ self._qtconsole_cmd = qtconsole_cmd(self.ipkernel)
+ self.consoles = []
+
+ # This application will also act on the shell user namespace
+ self.namespace = self.ipkernel.shell.user_ns
+ # Keys present at startup so we don't print the entire pylab/numpy
+ # namespace when the user clicks the 'namespace' button
+ self._init_keys = set(self.namespace.keys())
+
+ # Example: a variable that will be seen by the user in the shell, and
+ # that the GUI modifies (the 'Counter++' button increments it):
+ self.namespace['app_counter'] = 0
+ #self.namespace['ipkernel'] = self.ipkernel # dbg
+
+ def print_namespace(self, evt=None):
+ print "\n***Variables in User namespace***"
+ for k, v in self.namespace.iteritems():
+ if k not in self._init_keys and not k.startswith('_'):
+ print '%s -> %r' % (k, v)
+ sys.stdout.flush()
+
+ def new_qt_console(self, evt=None):
+ self.consoles.append(subprocess.Popen(self._qtconsole_cmd))
+
+ def count(self, evt=None):
+ self.namespace['app_counter'] += 1
+
+ def cleanup_consoles(self, evt=None):
+ for c in self.consoles:
+ c.kill()
View
75 docs/examples/lib/ipkernel_qtapp.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+"""Example integrating an IPython kernel into a GUI App.
+
+This trivial GUI application internally starts an IPython kernel, to which Qt
+consoles can be connected either by the user at the command line or started
+from the GUI itself, via a button. The GUI can also manipulate one variable in
+the kernel's namespace, and print the namespace to the console.
+
+Play with it by running the script and then opening one or more consoles, and
+pushing the 'Counter++' and 'Namespace' buttons.
+
+Upon exit, it should automatically close all consoles opened from the GUI.
+
+Consoles attached separately from a terminal will not be terminated, though
+they will notice that their kernel died.
+"""
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from PyQt4 import Qt
+
+from internal_ipkernel import InternalIPKernel
+
+#-----------------------------------------------------------------------------
+# Functions and classes
+#-----------------------------------------------------------------------------
+class SimpleWindow(Qt.QWidget, InternalIPKernel):
+
+ def __init__(self, app):
+ Qt.QWidget.__init__(self)
+ self.app = app
+ self.add_widgets()
+ self.init_ipkernel('qt')
+
+ def add_widgets(self):
+ self.setGeometry(300, 300, 400, 70)
+ self.setWindowTitle('IPython in your app')
+
+ # Add simple buttons:
+ console = Qt.QPushButton('Qt Console', self)
+ console.setGeometry(10, 10, 100, 35)
+ self.connect(console, Qt.SIGNAL('clicked()'), self.new_qt_console)
+
+ namespace = Qt.QPushButton('Namespace', self)
+ namespace.setGeometry(120, 10, 100, 35)
+ self.connect(namespace, Qt.SIGNAL('clicked()'), self.print_namespace)
+
+ count = Qt.QPushButton('Count++', self)
+ count.setGeometry(230, 10, 80, 35)
+ self.connect(count, Qt.SIGNAL('clicked()'), self.count)
+
+ # Quit and cleanup
+ quit = Qt.QPushButton('Quit', self)
+ quit.setGeometry(320, 10, 60, 35)
+ self.connect(quit, Qt.SIGNAL('clicked()'), Qt.qApp, Qt.SLOT('quit()'))
+
+ self.app.connect(self.app, Qt.SIGNAL("lastWindowClosed()"),
+ self.app, Qt.SLOT("quit()"))
+
+ self.app.aboutToQuit.connect(self.cleanup_consoles)
+
+#-----------------------------------------------------------------------------
+# Main script
+#-----------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ app = Qt.QApplication([])
+ # Create our window
+ win = SimpleWindow(app)
+ win.show()
+
+ # Very important, IPython-specific step: this gets GUI event loop
+ # integration going, and it replaces calling app.exec_()
+ win.ipkernel.start()
View
119 docs/examples/lib/ipkernel_wxapp.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python
+"""Example integrating an IPython kernel into a GUI App.
+
+This trivial GUI application internally starts an IPython kernel, to which Qt
+consoles can be connected either by the user at the command line or started
+from the GUI itself, via a button. The GUI can also manipulate one variable in
+the kernel's namespace, and print the namespace to the console.
+
+Play with it by running the script and then opening one or more consoles, and
+pushing the 'Counter++' and 'Namespace' buttons.
+
+Upon exit, it should automatically close all consoles opened from the GUI.
+
+Consoles attached separately from a terminal will not be terminated, though
+they will notice that their kernel died.
+
+Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
+"""
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+import sys
+
+import wx
+
+from internal_ipkernel import InternalIPKernel
+
+#-----------------------------------------------------------------------------
+# Functions and classes
+#-----------------------------------------------------------------------------
+
+class MyFrame(wx.Frame, InternalIPKernel):
+ """
+ This is MyFrame. It just shows a few controls on a wxPanel,
+ and has a simple menu.
+ """
+
+ def __init__(self, parent, title):
+ wx.Frame.__init__(self, parent, -1, title,
+ pos=(150, 150), size=(350, 285))
+
+ # Create the menubar
+ menuBar = wx.MenuBar()
+
+ # and a menu
+ menu = wx.Menu()
+
+ # add an item to the menu, using \tKeyName automatically
+ # creates an accelerator, the third param is some help text
+ # that will show up in the statusbar
+ menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
+
+ # bind the menu event to an event handler
+ self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
+
+ # and put the menu on the menubar
+ menuBar.Append(menu, "&File")
+ self.SetMenuBar(menuBar)
+
+ self.CreateStatusBar()
+
+ # Now create the Panel to put the other controls on.
+ panel = wx.Panel(self)
+
+ # and a few controls
+ text = wx.StaticText(panel, -1, "Hello World!")
+ text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
+ text.SetSize(text.GetBestSize())
+ qtconsole_btn = wx.Button(panel, -1, "Qt Console")
+ ns_btn = wx.Button(panel, -1, "Namespace")
+ count_btn = wx.Button(panel, -1, "Count++")
+ close_btn = wx.Button(panel, -1, "Quit")
+
+ # bind the button events to handlers
+ self.Bind(wx.EVT_BUTTON, self.new_qt_console, qtconsole_btn)
+ self.Bind(wx.EVT_BUTTON, self.print_namespace, ns_btn)
+ self.Bind(wx.EVT_BUTTON, self.count, count_btn)
+ self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, close_btn)
+
+ # Use a sizer to layout the controls, stacked vertically and with
+ # a 10 pixel border around each
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ for ctrl in [text, qtconsole_btn, ns_btn, count_btn, close_btn]:
+ sizer.Add(ctrl, 0, wx.ALL, 10)
+ panel.SetSizer(sizer)
+ panel.Layout()
+
+ # Start the IPython kernel with gui support
+ self.init_ipkernel('wx')
+
+ def OnTimeToClose(self, evt):
+ """Event handler for the button click."""
+ print "See ya later!"
+ sys.stdout.flush()
+ self.cleanup_consoles(evt)
+ self.Close()
+ # Not sure why, but our IPython kernel seems to prevent normal WX
+ # shutdown, so an explicit exit() call is needed.
+ sys.exit()
+
+
+class MyApp(wx.App):
+ def OnInit(self):
+ frame = MyFrame(None, "Simple wxPython App")
+ self.SetTopWindow(frame)
+ frame.Show(True)
+ self.ipkernel = frame.ipkernel
+ return True
+
+#-----------------------------------------------------------------------------
+# Main script
+#-----------------------------------------------------------------------------
+
+if __name__ == '__main__':
+ app = MyApp(redirect=False, clearSigInt=False)
+
+ # Very important, IPython-specific step: this gets GUI event loop
+ # integration going, and it replaces calling app.MainLoop()
+ app.ipkernel.start()
View
107 docs/examples/vim/README.rst
@@ -0,0 +1,107 @@
+###########
+vim-ipython
+###########
+
+A two-way integration between Vim and IPython 0.11+
+
+author: Paul Ivanov (http://pirsquared.org)
+
+github: http://github.com/ivanov/vim-ipython
+
+demo: http://pirsquared.org/vim-ipython/
+
+Using this plugin, you can send lines or whole files for IPython to
+execute, and also get back object introspection and word completions in
+Vim, like what you get with: ``object?<enter>`` and ``object.<tab>`` in
+IPython.
+
+The big change from previous versions of ``ipy.vim`` is that it no longer
+requires the brittle ipy_vimserver.py instantiation, and since it uses
+just vim and python, it is platform independent (i.e. should work even
+on windows, unlike the previous \*nix only solution)
+
+
+-----------------
+Quickstart Guide:
+-----------------
+Start ``ipython qtconsole`` and copy the connection string.
+Source ``ipy.vim`` file, which provides new IPython command::
+
+ :source ipy.vim
+ (or copy it to ~/.vim/ftplugin/python to load automatically)
+
+ :IPythonClipboard
+ (or :IPythonXSelection if you're using X11 without having to copy)
+
+The :IPython command allows you to put the full string, e.g.::
+
+ :IPython --existing --shell=41882 --iopub=43286 --stdin=34987 --hb=36697
+
+The ``:IPythonClipboard`` command just uses the ``+`` register to get the
+connection string, whereas ``:IPythonXSelection`` uses the ``*`` register
+
+------------------------
+Sending lines to IPython
+------------------------
+Now type out a line and send it to IPython using ``<Ctrl-S>`` from Command mode::
+
+ import os
+
+You should see a notification message confirming the line was sent, along
+with the input number for the line, like so ``In[1]: import os``.
+
+``<Ctrl-S>`` also works from insert mode, but doesn't show notification
+
+It also works blockwise in Visual Mode. Strip the leading double quotes and
+send these lines using ``<Ctrl-S>``::
+
+ import this,math # secret decoder ring
+ a,b,c,d,e,f,g,h,i = range(1,10)
+ code =(c,a,d,a,e,i,)
+ msg = '...jrer nyy frag sebz Ivz.\nIvz+VClguba=%fyl '+this.s.split()[g]
+ decode=lambda x:"\n"+"".join([this.d.get(c,c) for c in x])+"!"
+ format=lambda x:'These lines:\n '+'\n '.join([l for l in x.splitlines()])
+ secret_decoder = lambda a,b: format(a)+decode(msg)%str(b)[:-1]
+ '%d'*len(code)%code == str(int(math.pi*1e5))
+
+Then, go to the qtconsole and run this line::
+
+ print secret_decoder(_i,_)
+
+You can also send whole files to IPython's ``%run`` magic using ``<F5>``.
+
+-------------------------------
+IPython's object? Functionality
+-------------------------------
+
+If you're using gvim, mouse-over a variable to see IPython's ? equivalent. If
+you're using vim from a terminal, or want to copy something from the
+docstring, type ``<leader>d``. ``<leader>`` is usually ``\`` (the backslash
+key). This will open a quickpreview window, which can be closed by hitting
+``q`` or ``<escape>``.
+
+--------------------------------------
+IPython's tab-completion Functionality
+--------------------------------------
+vim-ipython activates a 'completefunc' that queries IPython.
+A completefunc is activated using ``Ctrl-X Ctrl-U`` in Insert Mode (vim
+default). You can combine this functionality with SuperTab to get tab
+completion
+
+---------------
+Current issues:
+---------------
+For now, vim-ipython only connects to an ipython session in progress.
+
+ipy.vim takes a while to load, I'll eventually move the python code to its
+own file and do a lazy import (only when the IPython command is called)
+
+The ipdb integration is not yet re-implemented.
+
+Need to add more message handling for sub_channel messages from IPython
+(i.e. notification of changes which were not sent from vim).
+
+------
+Thanks
+------
+@MinRK for guiding me through the IPython kernel manager protocol.
View
343 docs/examples/vim/ipy.vim
@@ -0,0 +1,343 @@
+" Vim integration with IPython 0.11+
+"
+" A two-way integration between Vim and IPython.
+"
+" Using this plugin, you can send lines or whole files for IPython to execute,
+" and also get back object introspection and word completions in Vim, like
+" what you get with: object?<enter> object.<tab> in IPython
+"
+" -----------------
+" Quickstart Guide:
+" -----------------
+" Start ipython qtconsole and copy the connection string.
+" Source this file, which provides new IPython command
+" :source ipy.vim
+" :IPythonClipboard
+" (or :IPythonXSelection if you're using X11 without having to copy)
+"
+" written by Paul Ivanov (http://pirsquared.org)
+python << EOF
+import time
+import vim
+import sys
+
+try:
+ sys.stdout.flush
+except AttributeError:
+ # IPython complains if stderr and stdout don't have flush
+ # this is fixed in newer version of Vim
+ class WithFlush(object):