##// END OF EJS Templates
More work on componentizing everything....
Brian Granger -
Show More
@@ -0,0 +1,191 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 IPython's alias component
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 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 __builtin__
23 import keyword
24 import os
25 import sys
26
27 from IPython.core.component import Component
28
29 from IPython.utils.traitlets import CBool, List, Instance
30 from IPython.utils.genutils import error
31
32 #-----------------------------------------------------------------------------
33 # Functions and classes
34 #-----------------------------------------------------------------------------
35
36 def default_aliases():
37 # Make some aliases automatically
38 # Prepare list of shell aliases to auto-define
39 if os.name == 'posix':
40 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
41 'mv mv -i','rm rm -i','cp cp -i',
42 'cat cat','less less','clear clear',
43 # a better ls
44 'ls ls -F',
45 # long ls
46 'll ls -lF')
47 # Extra ls aliases with color, which need special treatment on BSD
48 # variants
49 ls_extra = ( # color ls
50 'lc ls -F -o --color',
51 # ls normal files only
52 'lf ls -F -o --color %l | grep ^-',
53 # ls symbolic links
54 'lk ls -F -o --color %l | grep ^l',
55 # directories or links to directories,
56 'ldir ls -F -o --color %l | grep /$',
57 # things which are executable
58 'lx ls -F -o --color %l | grep ^-..x',
59 )
60 # The BSDs don't ship GNU ls, so they don't understand the
61 # --color switch out of the box
62 if 'bsd' in sys.platform:
63 ls_extra = ( # ls normal files only
64 'lf ls -lF | grep ^-',
65 # ls symbolic links
66 'lk ls -lF | grep ^l',
67 # directories or links to directories,
68 'ldir ls -lF | grep /$',
69 # things which are executable
70 'lx ls -lF | grep ^-..x',
71 )
72 auto_alias = auto_alias + ls_extra
73 elif os.name in ['nt','dos']:
74 auto_alias = ('ls dir /on',
75 'ddir dir /ad /on', 'ldir dir /ad /on',
76 'mkdir mkdir','rmdir rmdir','echo echo',
77 'ren ren','cls cls','copy copy')
78 else:
79 auto_alias = ()
80 return [s.split(None,1) for s in auto_alias]
81
82
83 class AliasError(Exception):
84 pass
85
86
87 class InvalidAliasError(AliasError):
88 pass
89
90
91 class AliasManager(Component):
92
93 auto_alias = List(default_aliases())
94 user_alias = List(default_value=[], config_key='USER_ALIAS')
95
96 def __init__(self, parent, config=None):
97 super(AliasManager, self).__init__(parent, config=config)
98 self.shell = Component.get_instances(
99 root=self.root,
100 klass='IPython.core.iplib.InteractiveShell'
101 )[0]
102 self.alias_table = {}
103 self.exclude_aliases()
104 self.init_aliases()
105
106 def __contains__(self, name):
107 if name in self.alias_table:
108 return True
109 else:
110 return False
111
112 @property
113 def aliases(self):
114 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
115
116 def exclude_aliases(self):
117 # set of things NOT to alias (keywords, builtins and some magics)
118 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
119 no_alias.update(set(keyword.kwlist))
120 no_alias.update(set(__builtin__.__dict__.keys()))
121 self.no_alias = no_alias
122
123 def init_aliases(self):
124 # Load default aliases
125 for name, cmd in self.auto_alias:
126 self.soft_define_alias(name, cmd)
127
128 # Load user aliases
129 for name, cmd in self.user_alias:
130 self.soft_define_alias(name, cmd)
131
132 def soft_define_alias(self, name, cmd):
133 """Define an alias, but don't raise on an AliasError."""
134 try:
135 self.define_alias(name, cmd)
136 except AliasError, e:
137 error("Invalid alias: %s" % e)
138
139 def define_alias(self, name, cmd):
140 """Define a new alias after validating it.
141
142 This will raise an :exc:`AliasError` if there are validation
143 problems.
144 """
145 nargs = self.validate_alias(name, cmd)
146 self.alias_table[name] = (nargs, cmd)
147
148 def validate_alias(self, name, cmd):
149 """Validate an alias and return the its number of arguments."""
150 if name in self.no_alias:
151 raise InvalidAliasError("The name %s can't be aliased "
152 "because it is a keyword or builtin." % name)
153 if not (isinstance(cmd, basestring)):
154 raise InvalidAliasError("An alias command must be a string, "
155 "got: %r" % name)
156 nargs = cmd.count('%s')
157 if nargs>0 and cmd.find('%l')>=0:
158 raise InvalidAliasError('The %s and %l specifiers are mutually '
159 'exclusive in alias definitions.')
160 return nargs
161
162 def call_alias(self, alias, rest=''):
163 """Call an alias given its name and the rest of the line."""
164 cmd = self.transform_alias(alias, rest)
165 try:
166 self.shell.system(cmd)
167 except:
168 self.shell.showtraceback()
169
170 def transform_alias(self, alias,rest=''):
171 """Transform alias to system command string."""
172 nargs, cmd = self.alias_table[alias]
173
174 if ' ' in cmd and os.path.isfile(cmd):
175 cmd = '"%s"' % cmd
176
177 # Expand the %l special to be the user's input line
178 if cmd.find('%l') >= 0:
179 cmd = cmd.replace('%l', rest)
180 rest = ''
181 if nargs==0:
182 # Simple, argument-less aliases
183 cmd = '%s %s' % (cmd, rest)
184 else:
185 # Handle aliases with positional arguments
186 args = rest.split(None, nargs)
187 if len(args) < nargs:
188 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
189 (alias, nargs, len(args)))
190 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
191 return cmd
@@ -1,241 +1,242 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An application for IPython
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 import os
27 27 import sys
28 28 import traceback
29 29
30 30 from copy import deepcopy
31 31 from IPython.utils.ipstruct import Struct
32 32 from IPython.utils.genutils import get_ipython_dir, filefind
33 33 from IPython.config.loader import (
34 34 IPythonArgParseConfigLoader,
35 35 PyFileConfigLoader
36 36 )
37 37
38 38 #-----------------------------------------------------------------------------
39 39 # Classes and functions
40 40 #-----------------------------------------------------------------------------
41 41
42 42
43 43 class ApplicationError(Exception):
44 44 pass
45 45
46 46
47 47 class Application(object):
48 48 """Load a config, construct an app and run it.
49 49 """
50 50
51 51 config_file_name = 'ipython_config.py'
52 52 name = 'ipython'
53 53 debug = False
54 54
55 55 def __init__(self):
56 56 pass
57 57
58 58 def start(self):
59 59 """Start the application."""
60 60 self.attempt(self.create_default_config)
61 61 self.attempt(self.pre_load_command_line_config)
62 62 self.attempt(self.load_command_line_config, action='abort')
63 63 self.attempt(self.post_load_command_line_config)
64 64 self.attempt(self.find_ipythondir)
65 65 self.attempt(self.find_config_file_name)
66 66 self.attempt(self.find_config_file_paths)
67 67 self.attempt(self.pre_load_file_config)
68 68 self.attempt(self.load_file_config)
69 69 self.attempt(self.post_load_file_config)
70 70 self.attempt(self.merge_configs)
71 71 self.attempt(self.pre_construct)
72 72 self.attempt(self.construct)
73 73 self.attempt(self.post_construct)
74 74 self.attempt(self.start_app)
75 75
76 76 #-------------------------------------------------------------------------
77 77 # Various stages of Application creation
78 78 #-------------------------------------------------------------------------
79 79
80 80 def create_default_config(self):
81 81 """Create defaults that can't be set elsewhere."""
82 82 self.default_config = Struct()
83 83 self.default_config.IPYTHONDIR = get_ipython_dir()
84 84
85 85 def create_command_line_config(self):
86 86 """Create and return a command line config loader."""
87 87 return IPythonArgParseConfigLoader(description=self.name)
88 88
89 89 def pre_load_command_line_config(self):
90 90 """Do actions just before loading the command line config."""
91 91 pass
92 92
93 93 def load_command_line_config(self):
94 94 """Load the command line config.
95 95
96 96 This method also sets ``self.debug``.
97 97 """
98 98
99 99 loader = self.create_command_line_config()
100 100 self.command_line_config = loader.load_config()
101 101 try:
102 102 self.debug = self.command_line_config.DEBUG
103 103 except AttributeError:
104 104 pass # use class default
105 105 self.log("Default config loaded:", self.default_config)
106 106 self.log("Command line config loaded:", self.command_line_config)
107 107
108 108 def post_load_command_line_config(self):
109 109 """Do actions just after loading the command line config."""
110 110 pass
111 111
112 112 def find_ipythondir(self):
113 113 """Set the IPython directory.
114 114
115 115 This sets ``self.ipythondir``, but the actual value that is passed
116 116 to the application is kept in either ``self.default_config`` or
117 117 ``self.command_line_config``. This also added ``self.ipythondir`` to
118 118 ``sys.path`` so config files there can be references by other config
119 119 files.
120 120 """
121 121
122 122 try:
123 123 self.ipythondir = self.command_line_config.IPYTHONDIR
124 124 except AttributeError:
125 125 self.ipythondir = self.default_config.IPYTHONDIR
126 126 sys.path.append(os.path.abspath(self.ipythondir))
127 127 if not os.path.isdir(self.ipythondir):
128 128 os.makedirs(self.ipythondir, mode = 0777)
129 129 self.log("IPYTHONDIR set to: %s" % self.ipythondir)
130 130
131 131 def find_config_file_name(self):
132 132 """Find the config file name for this application.
133 133
134 134 If a profile has been set at the command line, this will resolve
135 135 it. The search paths for the config file are set in
136 136 :meth:`find_config_file_paths` and then passed to the config file
137 137 loader where they are resolved to an absolute path.
138 138 """
139 139
140 140 try:
141 141 self.config_file_name = self.command_line_config.CONFIG_FILE
142 142 except AttributeError:
143 143 pass
144 144
145 145 try:
146 146 self.profile_name = self.command_line_config.PROFILE
147 147 name_parts = self.config_file_name.split('.')
148 148 name_parts.insert(1, '_' + self.profile_name + '.')
149 149 self.config_file_name = ''.join(name_parts)
150 150 except AttributeError:
151 151 pass
152 152
153 153 def find_config_file_paths(self):
154 154 """Set the search paths for resolving the config file."""
155 155 self.config_file_paths = (os.getcwd(), self.ipythondir)
156 156
157 157 def pre_load_file_config(self):
158 158 """Do actions before the config file is loaded."""
159 159 pass
160 160
161 161 def load_file_config(self):
162 162 """Load the config file.
163 163
164 164 This tries to load the config file from disk. If successful, the
165 165 ``CONFIG_FILE`` config variable is set to the resolved config file
166 166 location. If not successful, an empty config is used.
167 167 """
168 168 loader = PyFileConfigLoader(self.config_file_name,
169 169 self.config_file_paths)
170 170 try:
171 171 self.file_config = loader.load_config()
172 172 self.file_config.CONFIG_FILE = loader.full_filename
173 173 except IOError:
174 174 self.log("Config file not found, skipping: %s" % \
175 175 self.config_file_name)
176 176 self.file_config = Struct()
177 177 else:
178 178 self.log("Config file loaded: %s" % loader.full_filename,
179 179 self.file_config)
180 180
181 181 def post_load_file_config(self):
182 182 """Do actions after the config file is loaded."""
183 183 pass
184 184
185 185 def merge_configs(self):
186 186 """Merge the default, command line and file config objects."""
187 187 config = Struct()
188 188 config.update(self.default_config)
189 189 config.update(self.file_config)
190 190 config.update(self.command_line_config)
191 191 self.master_config = config
192 192 self.log("Master config created:", self.master_config)
193 193
194 194 def pre_construct(self):
195 195 """Do actions after the config has been built, but before construct."""
196 196 pass
197 197
198 198 def construct(self):
199 199 """Construct the main components that make up this app."""
200 200 self.log("Constructing components for application...")
201 201
202 202 def post_construct(self):
203 203 """Do actions after construct, but before starting the app."""
204 204 pass
205 205
206 206 def start_app(self):
207 207 """Actually start the app."""
208 208 self.log("Starting application...")
209 209
210 210 #-------------------------------------------------------------------------
211 211 # Utility methods
212 212 #-------------------------------------------------------------------------
213 213
214 214 def abort(self):
215 215 """Abort the starting of the application."""
216 216 print "Aborting application: ", self.name
217 217 sys.exit(1)
218 218
219 219 def exit(self):
220 220 print "Exiting application: ", self.name
221 221 sys.exit(1)
222 222
223 223 def attempt(self, func, action='abort'):
224 224 try:
225 225 func()
226 226 except:
227 227 if action == 'abort':
228 228 self.print_traceback()
229 229 self.abort()
230 230 elif action == 'exit':
231 self.print_traceback()
231 232 self.exit()
232 233
233 234 def print_traceback(self):
234 235 print "Error in appliction startup: ", self.name
235 236 print
236 237 traceback.print_exc()
237 238
238 239 def log(self, *args):
239 240 if self.debug:
240 241 for arg in args:
241 242 print "[%s] %s" % (self.name, arg) No newline at end of file
@@ -1,107 +1,108 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A context manager for managing things injected into :mod:`__builtin__`.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import __builtin__
23 23
24 24 from IPython.core.component import Component
25 25 from IPython.core.quitter import Quitter
26 26
27 27 from IPython.utils.traitlets import Instance
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Classes and functions
31 31 #-----------------------------------------------------------------------------
32 32
33 33
34 34 class BuiltinUndefined(object): pass
35 35 BuiltinUndefined = BuiltinUndefined()
36 36
37 37
38 38 class BuiltinTrap(Component):
39 shell = Instance('IPython.core.iplib.InteractiveShell')
40 39
41 40 def __init__(self, parent):
42 41 super(BuiltinTrap, self).__init__(parent, None, None)
43 42 # Don't just grab parent!!!
44 self.shell = Component.get_instances(root=self.root,
45 klass='IPython.core.iplib.InteractiveShell')[0]
43 self.shell = Component.get_instances(
44 root=self.root,
45 klass='IPython.core.iplib.InteractiveShell'
46 )[0]
46 47 self._orig_builtins = {}
47 48
48 49 def __enter__(self):
49 50 self.set()
50 51 # I return self, so callers can use add_builtin in a with clause.
51 52 return self
52 53
53 54 def __exit__(self, type, value, traceback):
54 55 self.unset()
55 56 return True
56 57
57 58 def add_builtin(self, key, value):
58 59 """Add a builtin and save the original."""
59 60 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
60 61 self._orig_builtins[key] = orig
61 62 __builtin__.__dict__[key] = value
62 63
63 64 def remove_builtin(self, key):
64 65 """Remove an added builtin and re-set the original."""
65 66 try:
66 67 orig = self._orig_builtins.pop(key)
67 68 except KeyError:
68 69 pass
69 70 else:
70 71 if orig is BuiltinUndefined:
71 72 del __builtin__.__dict__[key]
72 73 else:
73 74 __builtin__.__dict__[key] = orig
74 75
75 76 def set(self):
76 77 """Store ipython references in the __builtin__ namespace."""
77 78 self.add_builtin('exit', Quitter(self.shell, 'exit'))
78 79 self.add_builtin('quit', Quitter(self.shell, 'quit'))
79 80
80 81 # Recursive reload function
81 82 try:
82 83 from IPython.lib import deepreload
83 84 if self.shell.deep_reload:
84 85 self.add_builtin('reload', deepreload.reload)
85 86 else:
86 87 self.add_builtin('dreload', deepreload.reload)
87 88 del deepreload
88 89 except ImportError:
89 90 pass
90 91
91 92 # Keep in the builtins a flag for when IPython is active. We set it
92 93 # with setdefault so that multiple nested IPythons don't clobber one
93 94 # another. Each will increase its value by one upon being activated,
94 95 # which also gives us a way to determine the nesting level.
95 96 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
96 97
97 98 def unset(self):
98 99 """Remove any builtins which might have been added by add_builtins, or
99 100 restore overwritten ones to their previous values."""
100 101 for key in self._orig_builtins.keys():
101 102 self.remove_builtin(key)
102 103 self._orig_builtins.clear()
103 104 self._builtins_added = False
104 105 try:
105 106 del __builtin__.__dict__['__IPYTHON__active']
106 107 except KeyError:
107 108 pass No newline at end of file
@@ -1,248 +1,305 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A lightweight component system for IPython.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2009 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from copy import deepcopy
24 24 import datetime
25 25 from weakref import WeakValueDictionary
26 26
27 27 from IPython.utils.importstring import import_item
28 28 from IPython.utils.ipstruct import Struct
29 29 from IPython.utils.traitlets import (
30 30 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
31 31 )
32 32
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Helper classes for Components
36 36 #-----------------------------------------------------------------------------
37 37
38 38
39 39 class ComponentError(Exception):
40 40 pass
41 41
42 42 class MetaComponentTracker(type):
43 43 """A metaclass that tracks instances of Components and its subclasses."""
44 44
45 45 def __init__(cls, name, bases, d):
46 46 super(MetaComponentTracker, cls).__init__(name, bases, d)
47 47 cls.__instance_refs = WeakValueDictionary()
48 48 cls.__numcreated = 0
49 49
50 50 def __call__(cls, *args, **kw):
51 """Called when *class* is called (instantiated)!!!
51 """Called when a class is called (instantiated)!!!
52 52
53 53 When a Component or subclass is instantiated, this is called and
54 54 the instance is saved in a WeakValueDictionary for tracking.
55 55 """
56 56 instance = cls.__new__(cls, *args, **kw)
57 # Do this before __init__ is called so get_instances works inside
58 # __init__ methods!
57
58 # Register the instance before __init__ is called so get_instances
59 # works inside __init__ methods!
60 indices = cls.register_instance(instance)
61
62 # This is in a try/except because of the __init__ method fails, the
63 # instance is discarded and shouldn't be tracked.
64 try:
65 if isinstance(instance, cls):
66 cls.__init__(instance, *args, **kw)
67 except:
68 # Unregister the instance because __init__ failed!
69 cls.unregister_instances(indices)
70 raise
71 else:
72 return instance
73
74 def register_instance(cls, instance):
75 """Register instance with cls and its subclasses."""
76 # indices is a list of the keys used to register the instance
77 # with. This list is needed if the instance needs to be unregistered.
78 indices = []
59 79 for c in cls.__mro__:
60 80 if issubclass(cls, c) and issubclass(c, Component):
61 81 c.__numcreated += 1
82 indices.append(c.__numcreated)
62 83 c.__instance_refs[c.__numcreated] = instance
63 if isinstance(instance, cls):
64 cls.__init__(instance, *args, **kw)
84 else:
85 break
86 return indices
87
88 def unregister_instances(cls, indices):
89 """Unregister instance with cls and its subclasses."""
90 for c, index in zip(cls.__mro__, indices):
91 try:
92 del c.__instance_refs[index]
93 except KeyError:
94 pass
65 95
66 return instance
96 def clear_instances(cls):
97 """Clear all instances tracked by cls."""
98 cls.__instance_refs.clear()
99 cls.__numcreated = 0
67 100
68 101 def get_instances(cls, name=None, root=None, klass=None):
69 102 """Get all instances of cls and its subclasses.
70 103
71 104 Parameters
72 105 ----------
73 106 name : str
74 107 Limit to components with this name.
75 108 root : Component or subclass
76 109 Limit to components having this root.
77 110 klass : class or str
78 111 Limits to instances of the class or its subclasses. If a str
79 112 is given ut must be in the form 'foo.bar.MyClass'. The str
80 113 form of this argument is useful for forward declarations.
81 114 """
82 115 if klass is not None:
83 116 if isinstance(klass, basestring):
84 117 klass = import_item(klass)
118 # Limit search to instances of klass for performance
119 if issubclass(klass, Component):
120 return klass.get_instances(name=name, root=root)
85 121 instances = cls.__instance_refs.values()
86 122 if name is not None:
87 123 instances = [i for i in instances if i.name == name]
88 124 if klass is not None:
89 125 instances = [i for i in instances if isinstance(i, klass)]
90 126 if root is not None:
91 127 instances = [i for i in instances if i.root == root]
92 128 return instances
93 129
94 130 def get_instances_by_condition(cls, call, name=None, root=None,
95 131 klass=None):
96 132 """Get all instances of cls, i such that call(i)==True.
97 133
98 134 This also takes the ``name`` and ``root`` and ``classname``
99 135 arguments of :meth:`get_instance`
100 136 """
101 137 return [i for i in cls.get_instances(name, root, klass) if call(i)]
102 138
103 139
140 def masquerade_as(instance, cls):
141 """Let instance masquerade as an instance of cls.
142
143 Sometimes, such as in testing code, it is useful to let a class
144 masquerade as another. Python, being duck typed, allows this by
145 default. But, instances of components are tracked by their class type.
146
147 After calling this, cls.get_instances() will return ``instance``. This
148 does not, however, cause isinstance(instance, cls) to return ``True``.
149
150 Parameters
151 ----------
152 instance : an instance of a Component or Component subclass
153 The instance that will pretend to be a cls.
154 cls : subclass of Component
155 The Component subclass that instance will pretend to be.
156 """
157 cls.register_instance(instance)
158
159
104 160 class ComponentNameGenerator(object):
105 161 """A Singleton to generate unique component names."""
106 162
107 163 def __init__(self, prefix):
108 164 self.prefix = prefix
109 165 self.i = 0
110 166
111 167 def __call__(self):
112 168 count = self.i
113 169 self.i += 1
114 170 return "%s%s" % (self.prefix, count)
115 171
116 172
117 173 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
118 174
119 175
120 176 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
121 177 pass
122 178
123 179
124 180 #-----------------------------------------------------------------------------
125 181 # Component implementation
126 182 #-----------------------------------------------------------------------------
127 183
128 184
129 185 class Component(HasTraitlets):
130 186
131 187 __metaclass__ = MetaComponent
132 188
133 189 # Traitlets are fun!
134 190 config = Instance(Struct,(),{})
135 191 parent = This()
136 192 root = This()
137 193 created = None
138 194
139 195 def __init__(self, parent, name=None, config=None):
140 196 """Create a component given a parent and possibly and name and config.
141 197
142 198 Parameters
143 199 ----------
144 200 parent : Component subclass
145 201 The parent in the component graph. The parent is used
146 202 to get the root of the component graph.
147 203 name : str
148 204 The unique name of the component. If empty, then a unique
149 205 one will be autogenerated.
150 206 config : Struct
151 207 If this is empty, self.config = parent.config, otherwise
152 208 self.config = config and root.config is ignored. This argument
153 209 should only be used to *override* the automatic inheritance of
154 210 parent.config. If a caller wants to modify parent.config
155 211 (not override), the caller should make a copy and change
156 212 attributes and then pass the copy to this argument.
157 213
158 214 Notes
159 215 -----
160 216 Subclasses of Component must call the :meth:`__init__` method of
161 217 :class:`Component` *before* doing anything else and using
162 218 :func:`super`::
163 219
164 220 class MyComponent(Component):
165 221 def __init__(self, parent, name=None, config=None):
166 222 super(MyComponent, self).__init__(parent, name, config)
167 223 # Then any other code you need to finish initialization.
168 224
169 225 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
170 226 attributes are handled properly.
171 227 """
172 228 super(Component, self).__init__()
173 229 self._children = []
174 230 if name is None:
175 231 self.name = ComponentNameGenerator()
176 232 else:
177 233 self.name = name
178 234 self.root = self # This is the default, it is set when parent is set
179 235 self.parent = parent
180 236 if config is not None:
181 237 self.config = deepcopy(config)
182 238 else:
183 239 if self.parent is not None:
184 240 self.config = deepcopy(self.parent.config)
185 241
186 242 self.created = datetime.datetime.now()
187 243
188 244 #-------------------------------------------------------------------------
189 245 # Static traitlet notifiations
190 246 #-------------------------------------------------------------------------
191 247
192 248 def _parent_changed(self, name, old, new):
193 249 if old is not None:
194 250 old._remove_child(self)
195 251 if new is not None:
196 252 new._add_child(self)
197 253
198 254 if new is None:
199 255 self.root = self
200 256 else:
201 257 self.root = new.root
202 258
203 259 def _root_changed(self, name, old, new):
204 260 if self.parent is None:
205 261 if not (new is self):
206 262 raise ComponentError("Root not self, but parent is None.")
207 263 else:
208 264 if not self.parent.root is new:
209 265 raise ComponentError("Error in setting the root attribute: "
210 266 "root != parent.root")
211 267
212 268 def _config_changed(self, name, old, new):
213 269 """Update all the class traits having a config_key with the config.
214 270
215 271 For any class traitlet with a ``config_key`` metadata attribute, we
216 272 update the traitlet with the value of the corresponding config entry.
217 273
218 274 In the future, we might want to do a pop here so stale config info
219 275 is not passed onto children.
220 276 """
221 277 # Get all traitlets with a config_key metadata entry
222 278 traitlets = self.traitlets('config_key')
223 279 for k, v in traitlets.items():
224 280 try:
225 281 config_value = new[v.get_metadata('config_key')]
226 282 except KeyError:
227 283 pass
228 284 else:
229 285 setattr(self, k, config_value)
230 286
231 287 @property
232 288 def children(self):
233 289 """A list of all my child components."""
234 290 return self._children
235 291
236 292 def _remove_child(self, child):
237 293 """A private method for removing children components."""
238 294 if child in self._children:
239 295 index = self._children.index(child)
240 296 del self._children[index]
241 297
242 298 def _add_child(self, child):
243 299 """A private method for adding children components."""
244 300 if child not in self._children:
245 301 self._children.append(child)
246 302
247 303 def __repr__(self):
248 return "<Component('%s')>" % self.name
304 return "<%s('%s')>" % (self.__class__.__name__, "DummyName")
305 # return "<Component('%s')>" % self.name
@@ -1,317 +1,318 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The main IPython application object
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 import os
27 27 import sys
28 28 import warnings
29 29
30 30 from IPython.core.application import Application
31 31 from IPython.core import release
32 32 from IPython.core.iplib import InteractiveShell
33 33 from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault
34 34
35 35 from IPython.utils.ipstruct import Struct
36 36
37 37
38 38 #-----------------------------------------------------------------------------
39 39 # Utilities and helpers
40 40 #-----------------------------------------------------------------------------
41 41
42 42
43 43 ipython_desc = """
44 44 A Python shell with automatic history (input and output), dynamic object
45 45 introspection, easier configuration, command completion, access to the system
46 46 shell and more.
47 47 """
48 48
49 49 def threaded_shell_warning():
50 50 msg = """
51 51
52 52 The IPython threaded shells and their associated command line
53 53 arguments (pylab/wthread/gthread/qthread/q4thread) have been
54 54 deprecated. See the %gui magic for information on the new interface.
55 55 """
56 56 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
57 57
58 58
59 59 #-----------------------------------------------------------------------------
60 60 # Main classes and functions
61 61 #-----------------------------------------------------------------------------
62 62
63 63 cl_args = (
64 64 (('-autocall',), dict(
65 65 type=int, dest='AUTOCALL', default=NoDefault,
66 66 help='Set the autocall value (0,1,2).')
67 67 ),
68 68 (('-autoindent',), dict(
69 69 action='store_true', dest='AUTOINDENT', default=NoDefault,
70 70 help='Turn on autoindenting.')
71 71 ),
72 72 (('-noautoindent',), dict(
73 73 action='store_false', dest='AUTOINDENT', default=NoDefault,
74 74 help='Turn off autoindenting.')
75 75 ),
76 76 (('-automagic',), dict(
77 77 action='store_true', dest='AUTOMAGIC', default=NoDefault,
78 78 help='Turn on the auto calling of magic commands.')
79 79 ),
80 80 (('-noautomagic',), dict(
81 81 action='store_false', dest='AUTOMAGIC', default=NoDefault,
82 82 help='Turn off the auto calling of magic commands.')
83 83 ),
84 84 (('-autoedit_syntax',), dict(
85 85 action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault,
86 86 help='Turn on auto editing of files with syntax errors.')
87 87 ),
88 88 (('-noautoedit_syntax',), dict(
89 89 action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault,
90 90 help='Turn off auto editing of files with syntax errors.')
91 91 ),
92 92 (('-banner',), dict(
93 93 action='store_true', dest='DISPLAY_BANNER', default=NoDefault,
94 94 help='Display a banner upon starting IPython.')
95 95 ),
96 96 (('-nobanner',), dict(
97 97 action='store_false', dest='DISPLAY_BANNER', default=NoDefault,
98 98 help="Don't display a banner upon starting IPython.")
99 99 ),
100 100 (('-c',), dict(
101 101 type=str, dest='C', default=NoDefault,
102 102 help="Execute the given command string.")
103 103 ),
104 104 (('-cache_size',), dict(
105 105 type=int, dest='CACHE_SIZE', default=NoDefault,
106 106 help="Set the size of the output cache.")
107 107 ),
108 108 (('-classic',), dict(
109 109 action='store_true', dest='CLASSIC', default=NoDefault,
110 110 help="Gives IPython a similar feel to the classic Python prompt.")
111 111 ),
112 112 (('-colors',), dict(
113 113 type=str, dest='COLORS', default=NoDefault,
114 114 help="Set the color scheme (NoColor, Linux, and LightBG).")
115 115 ),
116 116 (('-color_info',), dict(
117 117 action='store_true', dest='COLOR_INFO', default=NoDefault,
118 118 help="Enable using colors for info related things.")
119 119 ),
120 120 (('-nocolor_info',), dict(
121 121 action='store_false', dest='COLOR_INFO', default=NoDefault,
122 122 help="Disable using colors for info related things.")
123 123 ),
124 124 (('-confirm_exit',), dict(
125 125 action='store_true', dest='CONFIRM_EXIT', default=NoDefault,
126 126 help="Prompt the user when existing.")
127 127 ),
128 128 (('-noconfirm_exit',), dict(
129 129 action='store_false', dest='CONFIRM_EXIT', default=NoDefault,
130 130 help="Don't prompt the user when existing.")
131 131 ),
132 132 (('-deep_reload',), dict(
133 133 action='store_true', dest='DEEP_RELOAD', default=NoDefault,
134 134 help="Enable deep (recursive) reloading by default.")
135 135 ),
136 136 (('-nodeep_reload',), dict(
137 137 action='store_false', dest='DEEP_RELOAD', default=NoDefault,
138 138 help="Disable deep (recursive) reloading by default.")
139 139 ),
140 140 (('-editor',), dict(
141 141 type=str, dest='EDITOR', default=NoDefault,
142 142 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).")
143 143 ),
144 144 (('-log','-l'), dict(
145 145 action='store_true', dest='LOGSTART', default=NoDefault,
146 146 help="Start logging to the default file (./ipython_log.py).")
147 147 ),
148 148 (('-logfile','-lf'), dict(
149 149 type=str, dest='LOGFILE', default=NoDefault,
150 150 help="Specify the name of your logfile.")
151 151 ),
152 152 (('-logplay','-lp'), dict(
153 153 type=str, dest='LOGPLAY', default=NoDefault,
154 154 help="Re-play a log file and then append to it.")
155 155 ),
156 156 (('-pdb',), dict(
157 157 action='store_true', dest='PDB', default=NoDefault,
158 158 help="Enable auto calling the pdb debugger after every exception.")
159 159 ),
160 160 (('-nopdb',), dict(
161 161 action='store_false', dest='PDB', default=NoDefault,
162 162 help="Disable auto calling the pdb debugger after every exception.")
163 163 ),
164 164 (('-pprint',), dict(
165 165 action='store_true', dest='PPRINT', default=NoDefault,
166 166 help="Enable auto pretty printing of results.")
167 167 ),
168 168 (('-nopprint',), dict(
169 169 action='store_false', dest='PPRINT', default=NoDefault,
170 170 help="Disable auto auto pretty printing of results.")
171 171 ),
172 172 (('-prompt_in1','-pi1'), dict(
173 173 type=str, dest='PROMPT_IN1', default=NoDefault,
174 174 help="Set the main input prompt ('In [\#]: ')")
175 175 ),
176 176 (('-prompt_in2','-pi2'), dict(
177 177 type=str, dest='PROMPT_IN2', default=NoDefault,
178 178 help="Set the secondary input prompt (' .\D.: ')")
179 179 ),
180 180 (('-prompt_out','-po'), dict(
181 181 type=str, dest='PROMPT_OUT', default=NoDefault,
182 182 help="Set the output prompt ('Out[\#]:')")
183 183 ),
184 184 (('-quick',), dict(
185 185 action='store_true', dest='QUICK', default=NoDefault,
186 186 help="Enable quick startup with no config files.")
187 187 ),
188 188 (('-readline',), dict(
189 189 action='store_true', dest='READLINE_USE', default=NoDefault,
190 190 help="Enable readline for command line usage.")
191 191 ),
192 192 (('-noreadline',), dict(
193 193 action='store_false', dest='READLINE_USE', default=NoDefault,
194 194 help="Disable readline for command line usage.")
195 195 ),
196 196 (('-screen_length','-sl'), dict(
197 197 type=int, dest='SCREEN_LENGTH', default=NoDefault,
198 198 help='Number of lines on screen, used to control printing of long strings.')
199 199 ),
200 200 (('-separate_in','-si'), dict(
201 201 type=str, dest='SEPARATE_IN', default=NoDefault,
202 202 help="Separator before input prompts. Default '\n'.")
203 203 ),
204 204 (('-separate_out','-so'), dict(
205 205 type=str, dest='SEPARATE_OUT', default=NoDefault,
206 206 help="Separator before output prompts. Default 0 (nothing).")
207 207 ),
208 208 (('-separate_out2','-so2'), dict(
209 209 type=str, dest='SEPARATE_OUT2', default=NoDefault,
210 210 help="Separator after output prompts. Default 0 (nonight).")
211 211 ),
212 212 (('-nosep',), dict(
213 213 action='store_true', dest='NOSEP', default=NoDefault,
214 214 help="Eliminate all spacing between prompts.")
215 215 ),
216 216 (('-term_title',), dict(
217 217 action='store_true', dest='TERM_TITLE', default=NoDefault,
218 218 help="Enable auto setting the terminal title.")
219 219 ),
220 220 (('-noterm_title',), dict(
221 221 action='store_false', dest='TERM_TITLE', default=NoDefault,
222 222 help="Disable auto setting the terminal title.")
223 223 ),
224 224 (('-xmode',), dict(
225 225 type=str, dest='XMODE', default=NoDefault,
226 226 help="Exception mode ('Plain','Context','Verbose')")
227 227 ),
228 228 # These are only here to get the proper deprecation warnings
229 229 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
230 230 action='store_true', dest='THREADED_SHELL', default=NoDefault,
231 231 help="These command line flags are deprecated, see the 'gui' magic.")
232 232 ),
233 233 )
234 234
235 235
236 236 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
237 237
238 238 arguments = cl_args
239 239
240 240
241 241 class IPythonApp(Application):
242 242 name = 'ipython'
243 243 config_file_name = 'ipython_config.py'
244 244
245 245 def create_command_line_config(self):
246 246 """Create and return a command line config loader."""
247 247 return IPythonAppCLConfigLoader(
248 248 description=ipython_desc,
249 249 version=release.version)
250 250
251 251 def post_load_command_line_config(self):
252 252 """Do actions after loading cl config."""
253 253 clc = self.command_line_config
254 254
255 255 # This needs to be set here, the rest are set in pre_construct.
256 256 if hasattr(clc, 'CLASSIC'):
257 257 if clc.CLASSIC: clc.QUICK = 1
258 258
259 259 # Display the deprecation warnings about threaded shells
260 260 if hasattr(clc, 'THREADED_SHELL'):
261 261 threaded_shell_warning()
262 262 del clc['THREADED_SHELL']
263 263
264 264 def load_file_config(self):
265 265 if hasattr(self.command_line_config, 'QUICK'):
266 266 if self.command_line_config.QUICK:
267 267 self.file_config = Struct()
268 268 return
269 269 super(IPythonApp, self).load_file_config()
270 270
271 271 def post_load_file_config(self):
272 272 """Logic goes here."""
273 273
274 274 def pre_construct(self):
275 275 config = self.master_config
276 276
277 277 if hasattr(config, 'CLASSIC'):
278 278 if config.CLASSIC:
279 279 config.QUICK = 1
280 280 config.CACHE_SIZE = 0
281 281 config.PPRINT = 0
282 282 config.PROMPT_IN1 = '>>> '
283 283 config.PROMPT_IN2 = '... '
284 284 config.PROMPT_OUT = ''
285 285 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
286 286 config.COLORS = 'NoColor'
287 287 config.XMODE = 'Plain'
288 288
289 289 # All this should be moved to traitlet handlers in InteractiveShell
290 290 # But, currently InteractiveShell doesn't have support for changing
291 291 # these values at runtime. Once we support that, this should
292 292 # be moved there!!!
293 293 if hasattr(config, 'NOSEP'):
294 294 if config.NOSEP:
295 295 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
296 296
297 297 def construct(self):
298 298 # I am a little hesitant to put these into InteractiveShell itself.
299 299 # But that might be the place for them
300 300 sys.path.insert(0, '')
301 301 # add personal ipythondir to sys.path so that users can put things in
302 302 # there for customization
303 303 sys.path.append(os.path.abspath(self.ipythondir))
304 304
305 305 # Create an InteractiveShell instance
306 306 self.shell = InteractiveShell(
307 307 parent=None,
308 308 config=self.master_config
309 309 )
310
310 print self.shell
311
311 312 def start_app(self):
312 313 self.shell.mainloop()
313 314
314 315
315 316 if __name__ == '__main__':
316 317 app = IPythonApp()
317 318 app.start() No newline at end of file
@@ -1,3018 +1,2849 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Main IPython Component
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 9 # Copyright (C) 2008-2009 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18
19 19 from __future__ import with_statement
20 20
21 21 import __main__
22 22 import __builtin__
23 23 import StringIO
24 24 import bdb
25 25 import codeop
26 26 import exceptions
27 27 import glob
28 28 import keyword
29 29 import new
30 30 import os
31 31 import re
32 32 import shutil
33 33 import string
34 34 import sys
35 35 import tempfile
36 36 from contextlib import nested
37 37
38 38 from IPython.core import ultratb
39 39 from IPython.core import debugger, oinspect
40 40 from IPython.core import shadowns
41 41 from IPython.core import history as ipcorehist
42 42 from IPython.core import prefilter
43 from IPython.core.alias import AliasManager
43 44 from IPython.core.autocall import IPyAutocall
44 45 from IPython.core.builtin_trap import BuiltinTrap
45 46 from IPython.core.display_trap import DisplayTrap
46 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 48 from IPython.core.logger import Logger
48 49 from IPython.core.magic import Magic
49 50 from IPython.core.prompts import CachedOutput
50 51 from IPython.core.page import page
51 52 from IPython.core.component import Component
52 53 from IPython.core.oldusersetup import user_setup
53 54 from IPython.core.usage import interactive_usage, default_banner
54 55 from IPython.core.error import TryNext, UsageError
55 56
56 57 from IPython.extensions import pickleshare
57 58 from IPython.external.Itpl import ItplNS
58 59 from IPython.lib.backgroundjobs import BackgroundJobManager
59 60 from IPython.utils.ipstruct import Struct
60 61 from IPython.utils import PyColorize
61 62 from IPython.utils.genutils import *
62 63 from IPython.utils.strdispatch import StrDispatch
63 64 from IPython.utils.platutils import toggle_set_term_title, set_term_title
64 65
66 from IPython.utils import growl
67 growl.start("IPython")
68
65 69 from IPython.utils.traitlets import (
66 70 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 71 )
68 72
69 73 #-----------------------------------------------------------------------------
70 74 # Globals
71 75 #-----------------------------------------------------------------------------
72 76
73 77
74 78 # store the builtin raw_input globally, and use this always, in case user code
75 79 # overwrites it (like wx.py.PyShell does)
76 80 raw_input_original = raw_input
77 81
78 82 # compiled regexps for autoindent management
79 83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80 84
81 85
82 86 #-----------------------------------------------------------------------------
83 87 # Utilities
84 88 #-----------------------------------------------------------------------------
85 89
86 90
87 91 ini_spaces_re = re.compile(r'^(\s+)')
88 92
89 93
90 94 def num_ini_spaces(strng):
91 95 """Return the number of initial spaces in a string"""
92 96
93 97 ini_spaces = ini_spaces_re.match(strng)
94 98 if ini_spaces:
95 99 return ini_spaces.end()
96 100 else:
97 101 return 0
98 102
99 103
100 104 def softspace(file, newvalue):
101 105 """Copied from code.py, to remove the dependency"""
102 106
103 107 oldvalue = 0
104 108 try:
105 109 oldvalue = file.softspace
106 110 except AttributeError:
107 111 pass
108 112 try:
109 113 file.softspace = newvalue
110 114 except (AttributeError, TypeError):
111 115 # "attribute-less object" or "read-only attributes"
112 116 pass
113 117 return oldvalue
114 118
115 119
116 120 class SpaceInInput(exceptions.Exception): pass
117 121
118 122 class Bunch: pass
119 123
120 124 class InputList(list):
121 125 """Class to store user input.
122 126
123 127 It's basically a list, but slices return a string instead of a list, thus
124 128 allowing things like (assuming 'In' is an instance):
125 129
126 130 exec In[4:7]
127 131
128 132 or
129 133
130 134 exec In[5:9] + In[14] + In[21:25]"""
131 135
132 136 def __getslice__(self,i,j):
133 137 return ''.join(list.__getslice__(self,i,j))
134 138
135 139
136 140 class SyntaxTB(ultratb.ListTB):
137 141 """Extension which holds some state: the last exception value"""
138 142
139 143 def __init__(self,color_scheme = 'NoColor'):
140 144 ultratb.ListTB.__init__(self,color_scheme)
141 145 self.last_syntax_error = None
142 146
143 147 def __call__(self, etype, value, elist):
144 148 self.last_syntax_error = value
145 149 ultratb.ListTB.__call__(self,etype,value,elist)
146 150
147 151 def clear_err_state(self):
148 152 """Return the current error state and clear it"""
149 153 e = self.last_syntax_error
150 154 self.last_syntax_error = None
151 155 return e
152 156
153 157
154 158 def get_default_editor():
155 159 try:
156 160 ed = os.environ['EDITOR']
157 161 except KeyError:
158 162 if os.name == 'posix':
159 163 ed = 'vi' # the only one guaranteed to be there!
160 164 else:
161 165 ed = 'notepad' # same in Windows!
162 166 return ed
163 167
164 168
165 169 class SeparateStr(Str):
166 170 """A Str subclass to validate separate_in, separate_out, etc.
167 171
168 172 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
169 173 """
170 174
171 175 def validate(self, obj, value):
172 176 if value == '0': value = ''
173 177 value = value.replace('\\n','\n')
174 178 return super(SeparateStr, self).validate(obj, value)
175 179
176 180
177 181 #-----------------------------------------------------------------------------
178 182 # Main IPython class
179 183 #-----------------------------------------------------------------------------
180 184
181 185
182 186 class InteractiveShell(Component, Magic):
183 187 """An enhanced, interactive shell for Python."""
184 188
185 189 autocall = Enum((0,1,2), config_key='AUTOCALL')
186 190 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
187 191 autoindent = CBool(True, config_key='AUTOINDENT')
188 192 automagic = CBool(True, config_key='AUTOMAGIC')
189 193 display_banner = CBool(True, config_key='DISPLAY_BANNER')
190 194 banner = Str('')
191 195 banner1 = Str(default_banner, config_key='BANNER1')
192 196 banner2 = Str('', config_key='BANNER2')
193 197 c = Str('', config_key='C')
194 198 cache_size = Int(1000, config_key='CACHE_SIZE')
195 199 classic = CBool(False, config_key='CLASSIC')
196 200 color_info = CBool(True, config_key='COLOR_INFO')
197 201 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
198 202 default_value='LightBG', config_key='COLORS')
199 203 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
200 204 debug = CBool(False, config_key='DEBUG')
201 205 deep_reload = CBool(False, config_key='DEEP_RELOAD')
202 206 embedded = CBool(False)
203 207 embedded_active = CBool(False)
204 208 editor = Str(get_default_editor(), config_key='EDITOR')
205 209 filename = Str("<ipython console>")
206 210 interactive = CBool(False, config_key='INTERACTIVE')
207 211 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
208 212 logstart = CBool(False, config_key='LOGSTART')
209 213 logfile = Str('', config_key='LOGFILE')
210 214 logplay = Str('', config_key='LOGPLAY')
211 215 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
212 216 object_info_string_level = Enum((0,1,2), default_value=0,
213 217 config_keys='OBJECT_INFO_STRING_LEVEL')
214 218 pager = Str('less', config_key='PAGER')
215 219 pdb = CBool(False, config_key='PDB')
216 220 pprint = CBool(True, config_key='PPRINT')
217 221 profile = Str('', config_key='PROFILE')
218 222 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
219 223 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
220 224 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
221 225 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
222 226 quiet = CBool(False, config_key='QUIET')
223 227
224 228 readline_use = CBool(True, config_key='READLINE_USE')
225 229 readline_merge_completions = CBool(True,
226 230 config_key='READLINE_MERGE_COMPLETIONS')
227 231 readline_omit__names = Enum((0,1,2), default_value=0,
228 232 config_key='READLINE_OMIT_NAMES')
229 233 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
230 234 readline_parse_and_bind = List([
231 235 'tab: complete',
232 236 '"\C-l": possible-completions',
233 237 'set show-all-if-ambiguous on',
234 238 '"\C-o": tab-insert',
235 239 '"\M-i": " "',
236 240 '"\M-o": "\d\d\d\d"',
237 241 '"\M-I": "\d\d\d\d"',
238 242 '"\C-r": reverse-search-history',
239 243 '"\C-s": forward-search-history',
240 244 '"\C-p": history-search-backward',
241 245 '"\C-n": history-search-forward',
242 246 '"\e[A": history-search-backward',
243 247 '"\e[B": history-search-forward',
244 248 '"\C-k": kill-line',
245 249 '"\C-u": unix-line-discard',
246 250 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
247 251 )
248 252
249 253 screen_length = Int(0, config_key='SCREEN_LENGTH')
250 254
251 255 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
252 256 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
253 257 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
254 258 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
255 259
256 260 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
257 261 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
258 262 term_title = CBool(False, config_key='TERM_TITLE')
259 263 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
260 264 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
261 265 default_value='Context', config_key='XMODE')
262 266
263 267 alias = List(allow_none=False, config_key='ALIAS')
264 268 autoexec = List(allow_none=False)
265 269
266 270 # class attribute to indicate whether the class supports threads or not.
267 271 # Subclasses with thread support should override this as needed.
268 272 isthreaded = False
269 273
270 274 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
271 275 user_ns=None, user_global_ns=None,
272 276 banner1=None, banner2=None,
273 277 custom_exceptions=((),None)):
274 278
275 279 # This is where traitlets with a config_key argument are updated
276 280 # from the values on config.
277 281 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
278 282
279 283 # These are relatively independent and stateless
280 284 self.init_ipythondir(ipythondir)
281 285 self.init_instance_attrs()
282 286 self.init_term_title()
283 287 self.init_usage(usage)
284 288 self.init_banner(banner1, banner2)
285 289
286 290 # Create namespaces (user_ns, user_global_ns, alias_table, etc.)
287 291 self.init_create_namespaces(user_ns, user_global_ns)
288 292 # This has to be done after init_create_namespaces because it uses
289 293 # something in self.user_ns, but before init_sys_modules, which
290 294 # is the first thing to modify sys.
291 295 self.save_sys_module_state()
292 296 self.init_sys_modules()
293 297
294 298 self.init_history()
295 299 self.init_encoding()
296 300 self.init_handlers()
297 301
298 302 Magic.__init__(self, self)
299 303
300 304 self.init_syntax_highlighting()
301 305 self.init_hooks()
302 306 self.init_pushd_popd_magic()
303 307 self.init_traceback_handlers(custom_exceptions)
304 308 self.init_user_ns()
305 309 self.init_logger()
306 self.init_aliases()
310 self.init_alias()
307 311 self.init_builtins()
308 312
309 313 # pre_config_initialization
310 314 self.init_shadow_hist()
311 315
312 316 # The next section should contain averything that was in ipmaker.
313 317 self.init_logstart()
314 318
315 319 # The following was in post_config_initialization
316 320 self.init_inspector()
317 321 self.init_readline()
318 322 self.init_prompts()
319 323 self.init_displayhook()
320 324 self.init_reload_doctest()
321 325 self.init_magics()
322 326 self.init_pdb()
323 327 self.hooks.late_startup_hook()
324 328
325 329 #-------------------------------------------------------------------------
326 330 # Traitlet changed handlers
327 331 #-------------------------------------------------------------------------
328 332
329 333 def _banner1_changed(self):
330 334 self.compute_banner()
331 335
332 336 def _banner2_changed(self):
333 337 self.compute_banner()
334 338
335 339 @property
336 340 def usable_screen_length(self):
337 341 if self.screen_length == 0:
338 342 return 0
339 343 else:
340 344 num_lines_bot = self.separate_in.count('\n')+1
341 345 return self.screen_length - num_lines_bot
342 346
343 347 def _term_title_changed(self, name, new_value):
344 348 self.init_term_title()
345 349
346 350 def set_autoindent(self,value=None):
347 351 """Set the autoindent flag, checking for readline support.
348 352
349 353 If called with no arguments, it acts as a toggle."""
350 354
351 355 if not self.has_readline:
352 356 if os.name == 'posix':
353 357 warn("The auto-indent feature requires the readline library")
354 358 self.autoindent = 0
355 359 return
356 360 if value is None:
357 361 self.autoindent = not self.autoindent
358 362 else:
359 363 self.autoindent = value
360 364
361 365 #-------------------------------------------------------------------------
362 366 # init_* methods called by __init__
363 367 #-------------------------------------------------------------------------
364 368
365 369 def init_ipythondir(self, ipythondir):
366 370 if ipythondir is not None:
367 371 self.ipythondir = ipythondir
368 372 self.config.IPYTHONDIR = self.ipythondir
369 373 return
370 374
371 375 if hasattr(self.config, 'IPYTHONDIR'):
372 376 self.ipythondir = self.config.IPYTHONDIR
373 377 if not hasattr(self.config, 'IPYTHONDIR'):
374 378 # cdw is always defined
375 379 self.ipythondir = os.getcwd()
376 380
377 381 # The caller must make sure that ipythondir exists. We should
378 382 # probably handle this using a Dir traitlet.
379 383 if not os.path.isdir(self.ipythondir):
380 384 raise IOError('IPython dir does not exist: %s' % self.ipythondir)
381 385
382 386 # All children can just read this
383 387 self.config.IPYTHONDIR = self.ipythondir
384 388
385 389 def init_instance_attrs(self):
386 390 self.jobs = BackgroundJobManager()
387 391 self.more = False
388 392
389 393 # command compiler
390 394 self.compile = codeop.CommandCompiler()
391 395
392 396 # User input buffer
393 397 self.buffer = []
394 398
395 399 # Make an empty namespace, which extension writers can rely on both
396 400 # existing and NEVER being used by ipython itself. This gives them a
397 401 # convenient location for storing additional information and state
398 402 # their extensions may require, without fear of collisions with other
399 403 # ipython names that may develop later.
400 404 self.meta = Struct()
401 405
402 406 # Object variable to store code object waiting execution. This is
403 407 # used mainly by the multithreaded shells, but it can come in handy in
404 408 # other situations. No need to use a Queue here, since it's a single
405 409 # item which gets cleared once run.
406 410 self.code_to_run = None
407 411
408 412 # Flag to mark unconditional exit
409 413 self.exit_now = False
410 414
411 415 # Temporary files used for various purposes. Deleted at exit.
412 416 self.tempfiles = []
413 417
414 418 # Keep track of readline usage (later set by init_readline)
415 419 self.has_readline = False
416 420
417 421 # keep track of where we started running (mainly for crash post-mortem)
418 422 # This is not being used anywhere currently.
419 423 self.starting_dir = os.getcwd()
420 424
421 425 # Indentation management
422 426 self.indent_current_nsp = 0
423 427
424 428 def init_term_title(self):
425 429 # Enable or disable the terminal title.
426 430 if self.term_title:
427 431 toggle_set_term_title(True)
428 432 set_term_title('IPython: ' + abbrev_cwd())
429 433 else:
430 434 toggle_set_term_title(False)
431 435
432 436 def init_usage(self, usage=None):
433 437 if usage is None:
434 438 self.usage = interactive_usage
435 439 else:
436 440 self.usage = usage
437 441
438 442 def init_banner(self, banner1, banner2):
439 443 if self.c: # regular python doesn't print the banner with -c
440 444 self.display_banner = False
441 445 if banner1 is not None:
442 446 self.banner1 = banner1
443 447 if banner2 is not None:
444 448 self.banner2 = banner2
445 449 self.compute_banner()
446 450
447 451 def compute_banner(self):
448 452 self.banner = self.banner1 + '\n'
449 453 if self.profile:
450 454 self.banner += '\nIPython profile: %s\n' % self.profile
451 455 if self.banner2:
452 456 self.banner += '\n' + self.banner2 + '\n'
453 457
454 458 def init_encoding(self):
455 459 # Get system encoding at startup time. Certain terminals (like Emacs
456 460 # under Win32 have it set to None, and we need to have a known valid
457 461 # encoding to use in the raw_input() method
458 462 try:
459 463 self.stdin_encoding = sys.stdin.encoding or 'ascii'
460 464 except AttributeError:
461 465 self.stdin_encoding = 'ascii'
462 466
463 467 def init_syntax_highlighting(self):
464 468 # Python source parser/formatter for syntax highlighting
465 469 pyformat = PyColorize.Parser().format
466 470 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
467 471
468 472 def init_pushd_popd_magic(self):
469 473 # for pushd/popd management
470 474 try:
471 475 self.home_dir = get_home_dir()
472 476 except HomeDirError, msg:
473 477 fatal(msg)
474 478
475 479 self.dir_stack = []
476 480
477 481 def init_logger(self):
478 482 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
479 483 # local shortcut, this is used a LOT
480 484 self.log = self.logger.log
481 485 # template for logfile headers. It gets resolved at runtime by the
482 486 # logstart method.
483 487 self.loghead_tpl = \
484 488 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
485 489 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
486 490 #log# opts = %s
487 491 #log# args = %s
488 492 #log# It is safe to make manual edits below here.
489 493 #log#-----------------------------------------------------------------------
490 494 """
491 495
492 496 def init_logstart(self):
493 497 if self.logplay:
494 498 self.magic_logstart(self.logplay + ' append')
495 499 elif self.logfile:
496 500 self.magic_logstart(self.logfile)
497 501 elif self.logstart:
498 502 self.magic_logstart()
499 503
500 504 def init_builtins(self):
501 505 self.builtin_trap = BuiltinTrap(self)
502 506
503 507 def init_inspector(self):
504 508 # Object inspector
505 509 self.inspector = oinspect.Inspector(oinspect.InspectColors,
506 510 PyColorize.ANSICodeColors,
507 511 'NoColor',
508 512 self.object_info_string_level)
509 513
510 514 def init_prompts(self):
511 515 # Initialize cache, set in/out prompts and printing system
512 516 self.outputcache = CachedOutput(self,
513 517 self.cache_size,
514 518 self.pprint,
515 519 input_sep = self.separate_in,
516 520 output_sep = self.separate_out,
517 521 output_sep2 = self.separate_out2,
518 522 ps1 = self.prompt_in1,
519 523 ps2 = self.prompt_in2,
520 524 ps_out = self.prompt_out,
521 525 pad_left = self.prompts_pad_left)
522 526
523 527 # user may have over-ridden the default print hook:
524 528 try:
525 529 self.outputcache.__class__.display = self.hooks.display
526 530 except AttributeError:
527 531 pass
528 532
529 533 def init_displayhook(self):
530 534 self.display_trap = DisplayTrap(self, self.outputcache)
531 535
532 536 def init_reload_doctest(self):
533 537 # Do a proper resetting of doctest, including the necessary displayhook
534 538 # monkeypatching
535 539 try:
536 540 doctest_reload()
537 541 except ImportError:
538 542 warn("doctest module does not exist.")
539 543
540 544 #-------------------------------------------------------------------------
541 545 # Things related to injections into the sys module
542 546 #-------------------------------------------------------------------------
543 547
544 548 def save_sys_module_state(self):
545 549 """Save the state of hooks in the sys module.
546 550
547 551 This has to be called after self.user_ns is created.
548 552 """
549 553 self._orig_sys_module_state = {}
550 554 self._orig_sys_module_state['stdin'] = sys.stdin
551 555 self._orig_sys_module_state['stdout'] = sys.stdout
552 556 self._orig_sys_module_state['stderr'] = sys.stderr
553 557 self._orig_sys_module_state['excepthook'] = sys.excepthook
554 558 try:
555 559 self._orig_sys_modules_main_name = self.user_ns['__name__']
556 560 except KeyError:
557 561 pass
558 562
559 563 def restore_sys_module_state(self):
560 564 """Restore the state of the sys module."""
561 565 try:
562 566 for k, v in self._orig_sys_module_state.items():
563 567 setattr(sys, k, v)
564 568 except AttributeError:
565 569 pass
566 570 try:
567 571 delattr(sys, 'ipcompleter')
568 572 except AttributeError:
569 573 pass
570 574 # Reset what what done in self.init_sys_modules
571 575 try:
572 576 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
573 577 except (AttributeError, KeyError):
574 578 pass
575 579
576 580 #-------------------------------------------------------------------------
577 581 # Things related to hooks
578 582 #-------------------------------------------------------------------------
579 583
580 584 def init_hooks(self):
581 585 # hooks holds pointers used for user-side customizations
582 586 self.hooks = Struct()
583 587
584 588 self.strdispatchers = {}
585 589
586 590 # Set all default hooks, defined in the IPython.hooks module.
587 591 import IPython.core.hooks
588 592 hooks = IPython.core.hooks
589 593 for hook_name in hooks.__all__:
590 594 # default hooks have priority 100, i.e. low; user hooks should have
591 595 # 0-100 priority
592 596 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
593 597
594 598 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
595 599 """set_hook(name,hook) -> sets an internal IPython hook.
596 600
597 601 IPython exposes some of its internal API as user-modifiable hooks. By
598 602 adding your function to one of these hooks, you can modify IPython's
599 603 behavior to call at runtime your own routines."""
600 604
601 605 # At some point in the future, this should validate the hook before it
602 606 # accepts it. Probably at least check that the hook takes the number
603 607 # of args it's supposed to.
604 608
605 609 f = new.instancemethod(hook,self,self.__class__)
606 610
607 611 # check if the hook is for strdispatcher first
608 612 if str_key is not None:
609 613 sdp = self.strdispatchers.get(name, StrDispatch())
610 614 sdp.add_s(str_key, f, priority )
611 615 self.strdispatchers[name] = sdp
612 616 return
613 617 if re_key is not None:
614 618 sdp = self.strdispatchers.get(name, StrDispatch())
615 619 sdp.add_re(re.compile(re_key), f, priority )
616 620 self.strdispatchers[name] = sdp
617 621 return
618 622
619 623 dp = getattr(self.hooks, name, None)
620 624 if name not in IPython.core.hooks.__all__:
621 625 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
622 626 if not dp:
623 627 dp = IPython.core.hooks.CommandChainDispatcher()
624 628
625 629 try:
626 630 dp.add(f,priority)
627 631 except AttributeError:
628 632 # it was not commandchain, plain old func - replace
629 633 dp = f
630 634
631 635 setattr(self.hooks,name, dp)
632 636
633 637 #-------------------------------------------------------------------------
634 638 # Things related to the "main" module
635 639 #-------------------------------------------------------------------------
636 640
637 641 def new_main_mod(self,ns=None):
638 642 """Return a new 'main' module object for user code execution.
639 643 """
640 644 main_mod = self._user_main_module
641 645 init_fakemod_dict(main_mod,ns)
642 646 return main_mod
643 647
644 648 def cache_main_mod(self,ns,fname):
645 649 """Cache a main module's namespace.
646 650
647 651 When scripts are executed via %run, we must keep a reference to the
648 652 namespace of their __main__ module (a FakeModule instance) around so
649 653 that Python doesn't clear it, rendering objects defined therein
650 654 useless.
651 655
652 656 This method keeps said reference in a private dict, keyed by the
653 657 absolute path of the module object (which corresponds to the script
654 658 path). This way, for multiple executions of the same script we only
655 659 keep one copy of the namespace (the last one), thus preventing memory
656 660 leaks from old references while allowing the objects from the last
657 661 execution to be accessible.
658 662
659 663 Note: we can not allow the actual FakeModule instances to be deleted,
660 664 because of how Python tears down modules (it hard-sets all their
661 665 references to None without regard for reference counts). This method
662 666 must therefore make a *copy* of the given namespace, to allow the
663 667 original module's __dict__ to be cleared and reused.
664 668
665 669
666 670 Parameters
667 671 ----------
668 672 ns : a namespace (a dict, typically)
669 673
670 674 fname : str
671 675 Filename associated with the namespace.
672 676
673 677 Examples
674 678 --------
675 679
676 680 In [10]: import IPython
677 681
678 682 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
679 683
680 684 In [12]: IPython.__file__ in _ip._main_ns_cache
681 685 Out[12]: True
682 686 """
683 687 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
684 688
685 689 def clear_main_mod_cache(self):
686 690 """Clear the cache of main modules.
687 691
688 692 Mainly for use by utilities like %reset.
689 693
690 694 Examples
691 695 --------
692 696
693 697 In [15]: import IPython
694 698
695 699 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
696 700
697 701 In [17]: len(_ip._main_ns_cache) > 0
698 702 Out[17]: True
699 703
700 704 In [18]: _ip.clear_main_mod_cache()
701 705
702 706 In [19]: len(_ip._main_ns_cache) == 0
703 707 Out[19]: True
704 708 """
705 709 self._main_ns_cache.clear()
706 710
707 711 #-------------------------------------------------------------------------
708 712 # Things related to debugging
709 713 #-------------------------------------------------------------------------
710 714
711 715 def init_pdb(self):
712 716 # Set calling of pdb on exceptions
713 717 # self.call_pdb is a property
714 718 self.call_pdb = self.pdb
715 719
716 720 def _get_call_pdb(self):
717 721 return self._call_pdb
718 722
719 723 def _set_call_pdb(self,val):
720 724
721 725 if val not in (0,1,False,True):
722 726 raise ValueError,'new call_pdb value must be boolean'
723 727
724 728 # store value in instance
725 729 self._call_pdb = val
726 730
727 731 # notify the actual exception handlers
728 732 self.InteractiveTB.call_pdb = val
729 733 if self.isthreaded:
730 734 try:
731 735 self.sys_excepthook.call_pdb = val
732 736 except:
733 737 warn('Failed to activate pdb for threaded exception handler')
734 738
735 739 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
736 740 'Control auto-activation of pdb at exceptions')
737 741
738 742 def debugger(self,force=False):
739 743 """Call the pydb/pdb debugger.
740 744
741 745 Keywords:
742 746
743 747 - force(False): by default, this routine checks the instance call_pdb
744 748 flag and does not actually invoke the debugger if the flag is false.
745 749 The 'force' option forces the debugger to activate even if the flag
746 750 is false.
747 751 """
748 752
749 753 if not (force or self.call_pdb):
750 754 return
751 755
752 756 if not hasattr(sys,'last_traceback'):
753 757 error('No traceback has been produced, nothing to debug.')
754 758 return
755 759
756 760 # use pydb if available
757 761 if debugger.has_pydb:
758 762 from pydb import pm
759 763 else:
760 764 # fallback to our internal debugger
761 765 pm = lambda : self.InteractiveTB.debugger(force=True)
762 766 self.history_saving_wrapper(pm)()
763 767
764 768 #-------------------------------------------------------------------------
765 769 # Things related to IPython's various namespaces
766 770 #-------------------------------------------------------------------------
767 771
768 772 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
769 773 # Create the namespace where the user will operate. user_ns is
770 774 # normally the only one used, and it is passed to the exec calls as
771 775 # the locals argument. But we do carry a user_global_ns namespace
772 776 # given as the exec 'globals' argument, This is useful in embedding
773 777 # situations where the ipython shell opens in a context where the
774 778 # distinction between locals and globals is meaningful. For
775 779 # non-embedded contexts, it is just the same object as the user_ns dict.
776 780
777 781 # FIXME. For some strange reason, __builtins__ is showing up at user
778 782 # level as a dict instead of a module. This is a manual fix, but I
779 783 # should really track down where the problem is coming from. Alex
780 784 # Schmolck reported this problem first.
781 785
782 786 # A useful post by Alex Martelli on this topic:
783 787 # Re: inconsistent value from __builtins__
784 788 # Von: Alex Martelli <aleaxit@yahoo.com>
785 789 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
786 790 # Gruppen: comp.lang.python
787 791
788 792 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
789 793 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
790 794 # > <type 'dict'>
791 795 # > >>> print type(__builtins__)
792 796 # > <type 'module'>
793 797 # > Is this difference in return value intentional?
794 798
795 799 # Well, it's documented that '__builtins__' can be either a dictionary
796 800 # or a module, and it's been that way for a long time. Whether it's
797 801 # intentional (or sensible), I don't know. In any case, the idea is
798 802 # that if you need to access the built-in namespace directly, you
799 803 # should start with "import __builtin__" (note, no 's') which will
800 804 # definitely give you a module. Yeah, it's somewhat confusing:-(.
801 805
802 806 # These routines return properly built dicts as needed by the rest of
803 807 # the code, and can also be used by extension writers to generate
804 808 # properly initialized namespaces.
805 809 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
806 810 user_global_ns)
807 811
808 812 # Assign namespaces
809 813 # This is the namespace where all normal user variables live
810 814 self.user_ns = user_ns
811 815 self.user_global_ns = user_global_ns
812 816
813 817 # An auxiliary namespace that checks what parts of the user_ns were
814 818 # loaded at startup, so we can list later only variables defined in
815 819 # actual interactive use. Since it is always a subset of user_ns, it
816 820 # doesn't need to be seaparately tracked in the ns_table
817 821 self.user_config_ns = {}
818 822
819 823 # A namespace to keep track of internal data structures to prevent
820 824 # them from cluttering user-visible stuff. Will be updated later
821 825 self.internal_ns = {}
822 826
823 827 # Namespace of system aliases. Each entry in the alias
824 828 # table must be a 2-tuple of the form (N,name), where N is the number
825 829 # of positional arguments of the alias.
826 830 self.alias_table = {}
827 831
828 832 # Now that FakeModule produces a real module, we've run into a nasty
829 833 # problem: after script execution (via %run), the module where the user
830 834 # code ran is deleted. Now that this object is a true module (needed
831 835 # so docetst and other tools work correctly), the Python module
832 836 # teardown mechanism runs over it, and sets to None every variable
833 837 # present in that module. Top-level references to objects from the
834 838 # script survive, because the user_ns is updated with them. However,
835 839 # calling functions defined in the script that use other things from
836 840 # the script will fail, because the function's closure had references
837 841 # to the original objects, which are now all None. So we must protect
838 842 # these modules from deletion by keeping a cache.
839 843 #
840 844 # To avoid keeping stale modules around (we only need the one from the
841 845 # last run), we use a dict keyed with the full path to the script, so
842 846 # only the last version of the module is held in the cache. Note,
843 847 # however, that we must cache the module *namespace contents* (their
844 848 # __dict__). Because if we try to cache the actual modules, old ones
845 849 # (uncached) could be destroyed while still holding references (such as
846 850 # those held by GUI objects that tend to be long-lived)>
847 851 #
848 852 # The %reset command will flush this cache. See the cache_main_mod()
849 853 # and clear_main_mod_cache() methods for details on use.
850 854
851 855 # This is the cache used for 'main' namespaces
852 856 self._main_ns_cache = {}
853 857 # And this is the single instance of FakeModule whose __dict__ we keep
854 858 # copying and clearing for reuse on each %run
855 859 self._user_main_module = FakeModule()
856 860
857 861 # A table holding all the namespaces IPython deals with, so that
858 862 # introspection facilities can search easily.
859 863 self.ns_table = {'user':user_ns,
860 864 'user_global':user_global_ns,
861 865 'alias':self.alias_table,
862 866 'internal':self.internal_ns,
863 867 'builtin':__builtin__.__dict__
864 868 }
865 869
866 870 # Similarly, track all namespaces where references can be held and that
867 871 # we can safely clear (so it can NOT include builtin). This one can be
868 872 # a simple list.
869 873 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
870 874 self.alias_table, self.internal_ns,
871 875 self._main_ns_cache ]
872 876
873 877 def init_sys_modules(self):
874 878 # We need to insert into sys.modules something that looks like a
875 879 # module but which accesses the IPython namespace, for shelve and
876 880 # pickle to work interactively. Normally they rely on getting
877 881 # everything out of __main__, but for embedding purposes each IPython
878 882 # instance has its own private namespace, so we can't go shoving
879 883 # everything into __main__.
880 884
881 885 # note, however, that we should only do this for non-embedded
882 886 # ipythons, which really mimic the __main__.__dict__ with their own
883 887 # namespace. Embedded instances, on the other hand, should not do
884 888 # this because they need to manage the user local/global namespaces
885 889 # only, but they live within a 'normal' __main__ (meaning, they
886 890 # shouldn't overtake the execution environment of the script they're
887 891 # embedded in).
888 892
889 893 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
890 894
891 895 try:
892 896 main_name = self.user_ns['__name__']
893 897 except KeyError:
894 898 raise KeyError('user_ns dictionary MUST have a "__name__" key')
895 899 else:
896 900 sys.modules[main_name] = FakeModule(self.user_ns)
897 901
898 902 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
899 903 """Return a valid local and global user interactive namespaces.
900 904
901 905 This builds a dict with the minimal information needed to operate as a
902 906 valid IPython user namespace, which you can pass to the various
903 907 embedding classes in ipython. The default implementation returns the
904 908 same dict for both the locals and the globals to allow functions to
905 909 refer to variables in the namespace. Customized implementations can
906 910 return different dicts. The locals dictionary can actually be anything
907 911 following the basic mapping protocol of a dict, but the globals dict
908 912 must be a true dict, not even a subclass. It is recommended that any
909 913 custom object for the locals namespace synchronize with the globals
910 914 dict somehow.
911 915
912 916 Raises TypeError if the provided globals namespace is not a true dict.
913 917
914 918 :Parameters:
915 919 user_ns : dict-like, optional
916 920 The current user namespace. The items in this namespace should
917 921 be included in the output. If None, an appropriate blank
918 922 namespace should be created.
919 923 user_global_ns : dict, optional
920 924 The current user global namespace. The items in this namespace
921 925 should be included in the output. If None, an appropriate
922 926 blank namespace should be created.
923 927
924 928 :Returns:
925 929 A tuple pair of dictionary-like object to be used as the local namespace
926 930 of the interpreter and a dict to be used as the global namespace.
927 931 """
928 932
929 933 if user_ns is None:
930 934 # Set __name__ to __main__ to better match the behavior of the
931 935 # normal interpreter.
932 936 user_ns = {'__name__' :'__main__',
933 937 '__builtins__' : __builtin__,
934 938 }
935 939 else:
936 940 user_ns.setdefault('__name__','__main__')
937 941 user_ns.setdefault('__builtins__',__builtin__)
938 942
939 943 if user_global_ns is None:
940 944 user_global_ns = user_ns
941 945 if type(user_global_ns) is not dict:
942 946 raise TypeError("user_global_ns must be a true dict; got %r"
943 947 % type(user_global_ns))
944 948
945 949 return user_ns, user_global_ns
946 950
947 951 def init_user_ns(self):
948 952 """Initialize all user-visible namespaces to their minimum defaults.
949 953
950 954 Certain history lists are also initialized here, as they effectively
951 955 act as user namespaces.
952 956
953 957 Notes
954 958 -----
955 959 All data structures here are only filled in, they are NOT reset by this
956 960 method. If they were not empty before, data will simply be added to
957 961 therm.
958 962 """
959 963 # The user namespace MUST have a pointer to the shell itself.
960 964 self.user_ns[self.name] = self
961 965
962 966 # Store myself as the public api!!!
963 967 self.user_ns['_ip'] = self
964 968
965 969 # make global variables for user access to the histories
966 970 self.user_ns['_ih'] = self.input_hist
967 971 self.user_ns['_oh'] = self.output_hist
968 972 self.user_ns['_dh'] = self.dir_hist
969 973
970 974 # user aliases to input and output histories
971 975 self.user_ns['In'] = self.input_hist
972 976 self.user_ns['Out'] = self.output_hist
973 977
974 978 self.user_ns['_sh'] = shadowns
975 979
976 980 # Put 'help' in the user namespace
977 981 try:
978 982 from site import _Helper
979 983 self.user_ns['help'] = _Helper()
980 984 except ImportError:
981 985 warn('help() not available - check site.py')
982 986
983 987 def reset(self):
984 988 """Clear all internal namespaces.
985 989
986 990 Note that this is much more aggressive than %reset, since it clears
987 991 fully all namespaces, as well as all input/output lists.
988 992 """
989 993 for ns in self.ns_refs_table:
990 994 ns.clear()
991 995
992 996 # Clear input and output histories
993 997 self.input_hist[:] = []
994 998 self.input_hist_raw[:] = []
995 999 self.output_hist.clear()
996 1000 # Restore the user namespaces to minimal usability
997 1001 self.init_user_ns()
998 1002
999 1003 def push(self, variables, interactive=True):
1000 1004 """Inject a group of variables into the IPython user namespace.
1001 1005
1002 1006 Parameters
1003 1007 ----------
1004 1008 variables : dict, str or list/tuple of str
1005 1009 The variables to inject into the user's namespace. If a dict,
1006 1010 a simple update is done. If a str, the string is assumed to
1007 1011 have variable names separated by spaces. A list/tuple of str
1008 1012 can also be used to give the variable names. If just the variable
1009 1013 names are give (list/tuple/str) then the variable values looked
1010 1014 up in the callers frame.
1011 1015 interactive : bool
1012 1016 If True (default), the variables will be listed with the ``who``
1013 1017 magic.
1014 1018 """
1015 1019 vdict = None
1016 1020
1017 1021 # We need a dict of name/value pairs to do namespace updates.
1018 1022 if isinstance(variables, dict):
1019 1023 vdict = variables
1020 1024 elif isinstance(variables, (basestring, list, tuple)):
1021 1025 if isinstance(variables, basestring):
1022 1026 vlist = variables.split()
1023 1027 else:
1024 1028 vlist = variables
1025 1029 vdict = {}
1026 1030 cf = sys._getframe(1)
1027 1031 for name in vlist:
1028 1032 try:
1029 1033 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1030 1034 except:
1031 1035 print ('Could not get variable %s from %s' %
1032 1036 (name,cf.f_code.co_name))
1033 1037 else:
1034 1038 raise ValueError('variables must be a dict/str/list/tuple')
1035 1039
1036 1040 # Propagate variables to user namespace
1037 1041 self.user_ns.update(vdict)
1038 1042
1039 1043 # And configure interactive visibility
1040 1044 config_ns = self.user_config_ns
1041 1045 if interactive:
1042 1046 for name, val in vdict.iteritems():
1043 1047 config_ns.pop(name, None)
1044 1048 else:
1045 1049 for name,val in vdict.iteritems():
1046 1050 config_ns[name] = val
1047 1051
1048 1052 #-------------------------------------------------------------------------
1049 1053 # Things related to history management
1050 1054 #-------------------------------------------------------------------------
1051 1055
1052 1056 def init_history(self):
1053 1057 # List of input with multi-line handling.
1054 1058 self.input_hist = InputList()
1055 1059 # This one will hold the 'raw' input history, without any
1056 1060 # pre-processing. This will allow users to retrieve the input just as
1057 1061 # it was exactly typed in by the user, with %hist -r.
1058 1062 self.input_hist_raw = InputList()
1059 1063
1060 1064 # list of visited directories
1061 1065 try:
1062 1066 self.dir_hist = [os.getcwd()]
1063 1067 except OSError:
1064 1068 self.dir_hist = []
1065 1069
1066 1070 # dict of output history
1067 1071 self.output_hist = {}
1068 1072
1069 1073 # Now the history file
1070 1074 try:
1071 1075 histfname = 'history-%s' % self.profile
1072 1076 except AttributeError:
1073 1077 histfname = 'history'
1074 1078 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
1075 1079
1076 1080 # Fill the history zero entry, user counter starts at 1
1077 1081 self.input_hist.append('\n')
1078 1082 self.input_hist_raw.append('\n')
1079 1083
1080 1084 def init_shadow_hist(self):
1081 1085 try:
1082 1086 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
1083 1087 except exceptions.UnicodeDecodeError:
1084 1088 print "Your ipythondir can't be decoded to unicode!"
1085 1089 print "Please set HOME environment variable to something that"
1086 1090 print r"only has ASCII characters, e.g. c:\home"
1087 1091 print "Now it is", self.config.IPYTHONDIR
1088 1092 sys.exit()
1089 1093 self.shadowhist = ipcorehist.ShadowHist(self.db)
1090 1094
1091 1095 def savehist(self):
1092 1096 """Save input history to a file (via readline library)."""
1093 1097
1094 1098 if not self.has_readline:
1095 1099 return
1096 1100
1097 1101 try:
1098 1102 self.readline.write_history_file(self.histfile)
1099 1103 except:
1100 1104 print 'Unable to save IPython command history to file: ' + \
1101 1105 `self.histfile`
1102 1106
1103 1107 def reloadhist(self):
1104 1108 """Reload the input history from disk file."""
1105 1109
1106 1110 if self.has_readline:
1107 1111 try:
1108 1112 self.readline.clear_history()
1109 1113 self.readline.read_history_file(self.shell.histfile)
1110 1114 except AttributeError:
1111 1115 pass
1112 1116
1113 1117 def history_saving_wrapper(self, func):
1114 1118 """ Wrap func for readline history saving
1115 1119
1116 1120 Convert func into callable that saves & restores
1117 1121 history around the call """
1118 1122
1119 1123 if not self.has_readline:
1120 1124 return func
1121 1125
1122 1126 def wrapper():
1123 1127 self.savehist()
1124 1128 try:
1125 1129 func()
1126 1130 finally:
1127 1131 readline.read_history_file(self.histfile)
1128 1132 return wrapper
1129 1133
1130 1134 #-------------------------------------------------------------------------
1131 1135 # Things related to exception handling and tracebacks (not debugging)
1132 1136 #-------------------------------------------------------------------------
1133 1137
1134 1138 def init_traceback_handlers(self, custom_exceptions):
1135 1139 # Syntax error handler.
1136 1140 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1137 1141
1138 1142 # The interactive one is initialized with an offset, meaning we always
1139 1143 # want to remove the topmost item in the traceback, which is our own
1140 1144 # internal code. Valid modes: ['Plain','Context','Verbose']
1141 1145 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1142 1146 color_scheme='NoColor',
1143 1147 tb_offset = 1)
1144 1148
1145 1149 # IPython itself shouldn't crash. This will produce a detailed
1146 1150 # post-mortem if it does. But we only install the crash handler for
1147 1151 # non-threaded shells, the threaded ones use a normal verbose reporter
1148 1152 # and lose the crash handler. This is because exceptions in the main
1149 1153 # thread (such as in GUI code) propagate directly to sys.excepthook,
1150 1154 # and there's no point in printing crash dumps for every user exception.
1151 1155 if self.isthreaded:
1152 1156 ipCrashHandler = ultratb.FormattedTB()
1153 1157 else:
1154 1158 from IPython.core import crashhandler
1155 1159 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1156 1160 self.set_crash_handler(ipCrashHandler)
1157 1161
1158 1162 # and add any custom exception handlers the user may have specified
1159 1163 self.set_custom_exc(*custom_exceptions)
1160 1164
1161 1165 def set_crash_handler(self, crashHandler):
1162 1166 """Set the IPython crash handler.
1163 1167
1164 1168 This must be a callable with a signature suitable for use as
1165 1169 sys.excepthook."""
1166 1170
1167 1171 # Install the given crash handler as the Python exception hook
1168 1172 sys.excepthook = crashHandler
1169 1173
1170 1174 # The instance will store a pointer to this, so that runtime code
1171 1175 # (such as magics) can access it. This is because during the
1172 1176 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1173 1177 # frameworks).
1174 1178 self.sys_excepthook = sys.excepthook
1175 1179
1176 1180 def set_custom_exc(self,exc_tuple,handler):
1177 1181 """set_custom_exc(exc_tuple,handler)
1178 1182
1179 1183 Set a custom exception handler, which will be called if any of the
1180 1184 exceptions in exc_tuple occur in the mainloop (specifically, in the
1181 1185 runcode() method.
1182 1186
1183 1187 Inputs:
1184 1188
1185 1189 - exc_tuple: a *tuple* of valid exceptions to call the defined
1186 1190 handler for. It is very important that you use a tuple, and NOT A
1187 1191 LIST here, because of the way Python's except statement works. If
1188 1192 you only want to trap a single exception, use a singleton tuple:
1189 1193
1190 1194 exc_tuple == (MyCustomException,)
1191 1195
1192 1196 - handler: this must be defined as a function with the following
1193 1197 basic interface: def my_handler(self,etype,value,tb).
1194 1198
1195 1199 This will be made into an instance method (via new.instancemethod)
1196 1200 of IPython itself, and it will be called if any of the exceptions
1197 1201 listed in the exc_tuple are caught. If the handler is None, an
1198 1202 internal basic one is used, which just prints basic info.
1199 1203
1200 1204 WARNING: by putting in your own exception handler into IPython's main
1201 1205 execution loop, you run a very good chance of nasty crashes. This
1202 1206 facility should only be used if you really know what you are doing."""
1203 1207
1204 1208 assert type(exc_tuple)==type(()) , \
1205 1209 "The custom exceptions must be given AS A TUPLE."
1206 1210
1207 1211 def dummy_handler(self,etype,value,tb):
1208 1212 print '*** Simple custom exception handler ***'
1209 1213 print 'Exception type :',etype
1210 1214 print 'Exception value:',value
1211 1215 print 'Traceback :',tb
1212 1216 print 'Source code :','\n'.join(self.buffer)
1213 1217
1214 1218 if handler is None: handler = dummy_handler
1215 1219
1216 1220 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1217 1221 self.custom_exceptions = exc_tuple
1218 1222
1219 1223 def excepthook(self, etype, value, tb):
1220 1224 """One more defense for GUI apps that call sys.excepthook.
1221 1225
1222 1226 GUI frameworks like wxPython trap exceptions and call
1223 1227 sys.excepthook themselves. I guess this is a feature that
1224 1228 enables them to keep running after exceptions that would
1225 1229 otherwise kill their mainloop. This is a bother for IPython
1226 1230 which excepts to catch all of the program exceptions with a try:
1227 1231 except: statement.
1228 1232
1229 1233 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1230 1234 any app directly invokes sys.excepthook, it will look to the user like
1231 1235 IPython crashed. In order to work around this, we can disable the
1232 1236 CrashHandler and replace it with this excepthook instead, which prints a
1233 1237 regular traceback using our InteractiveTB. In this fashion, apps which
1234 1238 call sys.excepthook will generate a regular-looking exception from
1235 1239 IPython, and the CrashHandler will only be triggered by real IPython
1236 1240 crashes.
1237 1241
1238 1242 This hook should be used sparingly, only in places which are not likely
1239 1243 to be true IPython errors.
1240 1244 """
1241 1245 self.showtraceback((etype,value,tb),tb_offset=0)
1242 1246
1243 1247 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1244 1248 """Display the exception that just occurred.
1245 1249
1246 1250 If nothing is known about the exception, this is the method which
1247 1251 should be used throughout the code for presenting user tracebacks,
1248 1252 rather than directly invoking the InteractiveTB object.
1249 1253
1250 1254 A specific showsyntaxerror() also exists, but this method can take
1251 1255 care of calling it if needed, so unless you are explicitly catching a
1252 1256 SyntaxError exception, don't try to analyze the stack manually and
1253 1257 simply call this method."""
1254 1258
1255 1259
1256 1260 # Though this won't be called by syntax errors in the input line,
1257 1261 # there may be SyntaxError cases whith imported code.
1258 1262
1259 1263 try:
1260 1264 if exc_tuple is None:
1261 1265 etype, value, tb = sys.exc_info()
1262 1266 else:
1263 1267 etype, value, tb = exc_tuple
1264 1268
1265 1269 if etype is SyntaxError:
1266 1270 self.showsyntaxerror(filename)
1267 1271 elif etype is UsageError:
1268 1272 print "UsageError:", value
1269 1273 else:
1270 1274 # WARNING: these variables are somewhat deprecated and not
1271 1275 # necessarily safe to use in a threaded environment, but tools
1272 1276 # like pdb depend on their existence, so let's set them. If we
1273 1277 # find problems in the field, we'll need to revisit their use.
1274 1278 sys.last_type = etype
1275 1279 sys.last_value = value
1276 1280 sys.last_traceback = tb
1277 1281
1278 1282 if etype in self.custom_exceptions:
1279 1283 self.CustomTB(etype,value,tb)
1280 1284 else:
1281 1285 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1282 1286 if self.InteractiveTB.call_pdb and self.has_readline:
1283 1287 # pdb mucks up readline, fix it back
1284 1288 self.set_completer()
1285 1289 except KeyboardInterrupt:
1286 1290 self.write("\nKeyboardInterrupt\n")
1287 1291
1288 1292 def showsyntaxerror(self, filename=None):
1289 1293 """Display the syntax error that just occurred.
1290 1294
1291 1295 This doesn't display a stack trace because there isn't one.
1292 1296
1293 1297 If a filename is given, it is stuffed in the exception instead
1294 1298 of what was there before (because Python's parser always uses
1295 1299 "<string>" when reading from a string).
1296 1300 """
1297 1301 etype, value, last_traceback = sys.exc_info()
1298 1302
1299 1303 # See note about these variables in showtraceback() below
1300 1304 sys.last_type = etype
1301 1305 sys.last_value = value
1302 1306 sys.last_traceback = last_traceback
1303 1307
1304 1308 if filename and etype is SyntaxError:
1305 1309 # Work hard to stuff the correct filename in the exception
1306 1310 try:
1307 1311 msg, (dummy_filename, lineno, offset, line) = value
1308 1312 except:
1309 1313 # Not the format we expect; leave it alone
1310 1314 pass
1311 1315 else:
1312 1316 # Stuff in the right filename
1313 1317 try:
1314 1318 # Assume SyntaxError is a class exception
1315 1319 value = SyntaxError(msg, (filename, lineno, offset, line))
1316 1320 except:
1317 1321 # If that failed, assume SyntaxError is a string
1318 1322 value = msg, (filename, lineno, offset, line)
1319 1323 self.SyntaxTB(etype,value,[])
1320 1324
1321 1325 def edit_syntax_error(self):
1322 1326 """The bottom half of the syntax error handler called in the main loop.
1323 1327
1324 1328 Loop until syntax error is fixed or user cancels.
1325 1329 """
1326 1330
1327 1331 while self.SyntaxTB.last_syntax_error:
1328 1332 # copy and clear last_syntax_error
1329 1333 err = self.SyntaxTB.clear_err_state()
1330 1334 if not self._should_recompile(err):
1331 1335 return
1332 1336 try:
1333 1337 # may set last_syntax_error again if a SyntaxError is raised
1334 1338 self.safe_execfile(err.filename,self.user_ns)
1335 1339 except:
1336 1340 self.showtraceback()
1337 1341 else:
1338 1342 try:
1339 1343 f = file(err.filename)
1340 1344 try:
1341 1345 # This should be inside a display_trap block and I
1342 1346 # think it is.
1343 1347 sys.displayhook(f.read())
1344 1348 finally:
1345 1349 f.close()
1346 1350 except:
1347 1351 self.showtraceback()
1348 1352
1349 1353 def _should_recompile(self,e):
1350 1354 """Utility routine for edit_syntax_error"""
1351 1355
1352 1356 if e.filename in ('<ipython console>','<input>','<string>',
1353 1357 '<console>','<BackgroundJob compilation>',
1354 1358 None):
1355 1359
1356 1360 return False
1357 1361 try:
1358 1362 if (self.autoedit_syntax and
1359 1363 not self.ask_yes_no('Return to editor to correct syntax error? '
1360 1364 '[Y/n] ','y')):
1361 1365 return False
1362 1366 except EOFError:
1363 1367 return False
1364 1368
1365 1369 def int0(x):
1366 1370 try:
1367 1371 return int(x)
1368 1372 except TypeError:
1369 1373 return 0
1370 1374 # always pass integer line and offset values to editor hook
1371 1375 try:
1372 1376 self.hooks.fix_error_editor(e.filename,
1373 1377 int0(e.lineno),int0(e.offset),e.msg)
1374 1378 except TryNext:
1375 1379 warn('Could not open editor')
1376 1380 return False
1377 1381 return True
1378 1382
1379 1383 #-------------------------------------------------------------------------
1380 1384 # Things related to tab completion
1381 1385 #-------------------------------------------------------------------------
1382 1386
1383 1387 def complete(self, text):
1384 1388 """Return a sorted list of all possible completions on text.
1385 1389
1386 1390 Inputs:
1387 1391
1388 1392 - text: a string of text to be completed on.
1389 1393
1390 1394 This is a wrapper around the completion mechanism, similar to what
1391 1395 readline does at the command line when the TAB key is hit. By
1392 1396 exposing it as a method, it can be used by other non-readline
1393 1397 environments (such as GUIs) for text completion.
1394 1398
1395 1399 Simple usage example:
1396 1400
1397 1401 In [7]: x = 'hello'
1398 1402
1399 1403 In [8]: x
1400 1404 Out[8]: 'hello'
1401 1405
1402 1406 In [9]: print x
1403 1407 hello
1404 1408
1405 1409 In [10]: _ip.complete('x.l')
1406 1410 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1407 1411 """
1408 1412
1409 1413 # Inject names into __builtin__ so we can complete on the added names.
1410 1414 with self.builtin_trap:
1411 1415 complete = self.Completer.complete
1412 1416 state = 0
1413 1417 # use a dict so we get unique keys, since ipyhton's multiple
1414 1418 # completers can return duplicates. When we make 2.4 a requirement,
1415 1419 # start using sets instead, which are faster.
1416 1420 comps = {}
1417 1421 while True:
1418 1422 newcomp = complete(text,state,line_buffer=text)
1419 1423 if newcomp is None:
1420 1424 break
1421 1425 comps[newcomp] = 1
1422 1426 state += 1
1423 1427 outcomps = comps.keys()
1424 1428 outcomps.sort()
1425 1429 #print "T:",text,"OC:",outcomps # dbg
1426 1430 #print "vars:",self.user_ns.keys()
1427 1431 return outcomps
1428 1432
1429 1433 def set_custom_completer(self,completer,pos=0):
1430 1434 """set_custom_completer(completer,pos=0)
1431 1435
1432 1436 Adds a new custom completer function.
1433 1437
1434 1438 The position argument (defaults to 0) is the index in the completers
1435 1439 list where you want the completer to be inserted."""
1436 1440
1437 1441 newcomp = new.instancemethod(completer,self.Completer,
1438 1442 self.Completer.__class__)
1439 1443 self.Completer.matchers.insert(pos,newcomp)
1440 1444
1441 1445 def set_completer(self):
1442 1446 """reset readline's completer to be our own."""
1443 1447 self.readline.set_completer(self.Completer.complete)
1444 1448
1445 1449 #-------------------------------------------------------------------------
1446 1450 # Things related to readline
1447 1451 #-------------------------------------------------------------------------
1448 1452
1449 1453 def init_readline(self):
1450 1454 """Command history completion/saving/reloading."""
1451 1455
1452 1456 self.rl_next_input = None
1453 1457 self.rl_do_indent = False
1454 1458
1455 1459 if not self.readline_use:
1456 1460 return
1457 1461
1458 1462 import IPython.utils.rlineimpl as readline
1459 1463
1460 1464 if not readline.have_readline:
1461 1465 self.has_readline = 0
1462 1466 self.readline = None
1463 1467 # no point in bugging windows users with this every time:
1464 1468 warn('Readline services not available on this platform.')
1465 1469 else:
1466 1470 sys.modules['readline'] = readline
1467 1471 import atexit
1468 1472 from IPython.core.completer import IPCompleter
1469 1473 self.Completer = IPCompleter(self,
1470 1474 self.user_ns,
1471 1475 self.user_global_ns,
1472 1476 self.readline_omit__names,
1473 1477 self.alias_table)
1474 1478 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1475 1479 self.strdispatchers['complete_command'] = sdisp
1476 1480 self.Completer.custom_completers = sdisp
1477 1481 # Platform-specific configuration
1478 1482 if os.name == 'nt':
1479 1483 self.readline_startup_hook = readline.set_pre_input_hook
1480 1484 else:
1481 1485 self.readline_startup_hook = readline.set_startup_hook
1482 1486
1483 1487 # Load user's initrc file (readline config)
1484 1488 # Or if libedit is used, load editrc.
1485 1489 inputrc_name = os.environ.get('INPUTRC')
1486 1490 if inputrc_name is None:
1487 1491 home_dir = get_home_dir()
1488 1492 if home_dir is not None:
1489 1493 inputrc_name = '.inputrc'
1490 1494 if readline.uses_libedit:
1491 1495 inputrc_name = '.editrc'
1492 1496 inputrc_name = os.path.join(home_dir, inputrc_name)
1493 1497 if os.path.isfile(inputrc_name):
1494 1498 try:
1495 1499 readline.read_init_file(inputrc_name)
1496 1500 except:
1497 1501 warn('Problems reading readline initialization file <%s>'
1498 1502 % inputrc_name)
1499 1503
1500 1504 self.has_readline = 1
1501 1505 self.readline = readline
1502 1506 # save this in sys so embedded copies can restore it properly
1503 1507 sys.ipcompleter = self.Completer.complete
1504 1508 self.set_completer()
1505 1509
1506 1510 # Configure readline according to user's prefs
1507 1511 # This is only done if GNU readline is being used. If libedit
1508 1512 # is being used (as on Leopard) the readline config is
1509 1513 # not run as the syntax for libedit is different.
1510 1514 if not readline.uses_libedit:
1511 1515 for rlcommand in self.readline_parse_and_bind:
1512 1516 #print "loading rl:",rlcommand # dbg
1513 1517 readline.parse_and_bind(rlcommand)
1514 1518
1515 1519 # Remove some chars from the delimiters list. If we encounter
1516 1520 # unicode chars, discard them.
1517 1521 delims = readline.get_completer_delims().encode("ascii", "ignore")
1518 1522 delims = delims.translate(string._idmap,
1519 1523 self.readline_remove_delims)
1520 1524 readline.set_completer_delims(delims)
1521 1525 # otherwise we end up with a monster history after a while:
1522 1526 readline.set_history_length(1000)
1523 1527 try:
1524 1528 #print '*** Reading readline history' # dbg
1525 1529 readline.read_history_file(self.histfile)
1526 1530 except IOError:
1527 1531 pass # It doesn't exist yet.
1528 1532
1529 1533 atexit.register(self.atexit_operations)
1530 1534 del atexit
1531 1535
1532 1536 # Configure auto-indent for all platforms
1533 1537 self.set_autoindent(self.autoindent)
1534 1538
1535 1539 def set_next_input(self, s):
1536 1540 """ Sets the 'default' input string for the next command line.
1537 1541
1538 1542 Requires readline.
1539 1543
1540 1544 Example:
1541 1545
1542 1546 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1543 1547 [D:\ipython]|2> Hello Word_ # cursor is here
1544 1548 """
1545 1549
1546 1550 self.rl_next_input = s
1547 1551
1548 1552 def pre_readline(self):
1549 1553 """readline hook to be used at the start of each line.
1550 1554
1551 1555 Currently it handles auto-indent only."""
1552 1556
1553 1557 #debugx('self.indent_current_nsp','pre_readline:')
1554 1558
1555 1559 if self.rl_do_indent:
1556 1560 self.readline.insert_text(self._indent_current_str())
1557 1561 if self.rl_next_input is not None:
1558 1562 self.readline.insert_text(self.rl_next_input)
1559 1563 self.rl_next_input = None
1560 1564
1561 1565 def _indent_current_str(self):
1562 1566 """return the current level of indentation as a string"""
1563 1567 return self.indent_current_nsp * ' '
1564 1568
1565 1569 #-------------------------------------------------------------------------
1566 1570 # Things related to magics
1567 1571 #-------------------------------------------------------------------------
1568 1572
1569 1573 def init_magics(self):
1570 1574 # Set user colors (don't do it in the constructor above so that it
1571 1575 # doesn't crash if colors option is invalid)
1572 1576 self.magic_colors(self.colors)
1573 1577
1574 1578 def magic(self,arg_s):
1575 1579 """Call a magic function by name.
1576 1580
1577 1581 Input: a string containing the name of the magic function to call and any
1578 1582 additional arguments to be passed to the magic.
1579 1583
1580 1584 magic('name -opt foo bar') is equivalent to typing at the ipython
1581 1585 prompt:
1582 1586
1583 1587 In[1]: %name -opt foo bar
1584 1588
1585 1589 To call a magic without arguments, simply use magic('name').
1586 1590
1587 1591 This provides a proper Python function to call IPython's magics in any
1588 1592 valid Python code you can type at the interpreter, including loops and
1589 1593 compound statements.
1590 1594 """
1591 1595
1592 1596 args = arg_s.split(' ',1)
1593 1597 magic_name = args[0]
1594 1598 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1595 1599
1596 1600 try:
1597 1601 magic_args = args[1]
1598 1602 except IndexError:
1599 1603 magic_args = ''
1600 1604 fn = getattr(self,'magic_'+magic_name,None)
1601 1605 if fn is None:
1602 1606 error("Magic function `%s` not found." % magic_name)
1603 1607 else:
1604 1608 magic_args = self.var_expand(magic_args,1)
1605 1609 with nested(self.builtin_trap, self.display_trap):
1606 1610 return fn(magic_args)
1607 1611 # return result
1608 1612
1609 1613 def define_magic(self, magicname, func):
1610 1614 """Expose own function as magic function for ipython
1611 1615
1612 1616 def foo_impl(self,parameter_s=''):
1613 1617 'My very own magic!. (Use docstrings, IPython reads them).'
1614 1618 print 'Magic function. Passed parameter is between < >:'
1615 1619 print '<%s>' % parameter_s
1616 1620 print 'The self object is:',self
1617 1621
1618 1622 self.define_magic('foo',foo_impl)
1619 1623 """
1620 1624
1621 1625 import new
1622 1626 im = new.instancemethod(func,self, self.__class__)
1623 1627 old = getattr(self, "magic_" + magicname, None)
1624 1628 setattr(self, "magic_" + magicname, im)
1625 1629 return old
1626 1630
1627 1631 #-------------------------------------------------------------------------
1628 1632 # Things related to macros
1629 1633 #-------------------------------------------------------------------------
1630 1634
1631 1635 def define_macro(self, name, themacro):
1632 1636 """Define a new macro
1633 1637
1634 1638 Parameters
1635 1639 ----------
1636 1640 name : str
1637 1641 The name of the macro.
1638 1642 themacro : str or Macro
1639 1643 The action to do upon invoking the macro. If a string, a new
1640 1644 Macro object is created by passing the string to it.
1641 1645 """
1642 1646
1643 1647 from IPython.core import macro
1644 1648
1645 1649 if isinstance(themacro, basestring):
1646 1650 themacro = macro.Macro(themacro)
1647 1651 if not isinstance(themacro, macro.Macro):
1648 1652 raise ValueError('A macro must be a string or a Macro instance.')
1649 1653 self.user_ns[name] = themacro
1650 1654
1651 1655 #-------------------------------------------------------------------------
1652 1656 # Things related to the running of system commands
1653 1657 #-------------------------------------------------------------------------
1654 1658
1655 1659 def system(self, cmd):
1656 1660 """Make a system call, using IPython."""
1657 1661 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1658 1662
1659 1663 #-------------------------------------------------------------------------
1660 1664 # Things related to aliases
1661 1665 #-------------------------------------------------------------------------
1662 1666
1663 def init_aliases(self):
1664 # dict of things NOT to alias (keywords, builtins and some magics)
1665 no_alias = {}
1666 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
1667 for key in keyword.kwlist + no_alias_magics:
1668 no_alias[key] = 1
1669 no_alias.update(__builtin__.__dict__)
1670 self.no_alias = no_alias
1671
1672 # Make some aliases automatically
1673 # Prepare list of shell aliases to auto-define
1674 if os.name == 'posix':
1675 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
1676 'mv mv -i','rm rm -i','cp cp -i',
1677 'cat cat','less less','clear clear',
1678 # a better ls
1679 'ls ls -F',
1680 # long ls
1681 'll ls -lF')
1682 # Extra ls aliases with color, which need special treatment on BSD
1683 # variants
1684 ls_extra = ( # color ls
1685 'lc ls -F -o --color',
1686 # ls normal files only
1687 'lf ls -F -o --color %l | grep ^-',
1688 # ls symbolic links
1689 'lk ls -F -o --color %l | grep ^l',
1690 # directories or links to directories,
1691 'ldir ls -F -o --color %l | grep /$',
1692 # things which are executable
1693 'lx ls -F -o --color %l | grep ^-..x',
1694 )
1695 # The BSDs don't ship GNU ls, so they don't understand the
1696 # --color switch out of the box
1697 if 'bsd' in sys.platform:
1698 ls_extra = ( # ls normal files only
1699 'lf ls -lF | grep ^-',
1700 # ls symbolic links
1701 'lk ls -lF | grep ^l',
1702 # directories or links to directories,
1703 'ldir ls -lF | grep /$',
1704 # things which are executable
1705 'lx ls -lF | grep ^-..x',
1706 )
1707 auto_alias = auto_alias + ls_extra
1708 elif os.name in ['nt','dos']:
1709 auto_alias = ('ls dir /on',
1710 'ddir dir /ad /on', 'ldir dir /ad /on',
1711 'mkdir mkdir','rmdir rmdir','echo echo',
1712 'ren ren','cls cls','copy copy')
1713 else:
1714 auto_alias = ()
1715 self.auto_alias = [s.split(None,1) for s in auto_alias]
1716
1717 # Load default aliases
1718 for alias, cmd in self.auto_alias:
1719 self.define_alias(alias,cmd)
1720
1721 # Load user aliases
1722 for alias in self.alias:
1723 self.magic_alias(alias)
1724
1725 def call_alias(self,alias,rest=''):
1726 """Call an alias given its name and the rest of the line.
1727
1728 This is only used to provide backwards compatibility for users of
1729 ipalias(), use of which is not recommended for anymore."""
1730
1731 # Now call the macro, evaluating in the user's namespace
1732 cmd = self.transform_alias(alias, rest)
1733 try:
1734 self.system(cmd)
1735 except:
1736 self.showtraceback()
1737
1738 def define_alias(self, name, cmd):
1739 """ Define a new alias."""
1740
1741 if callable(cmd):
1742 self.alias_table[name] = cmd
1743 from IPython.core import shadowns
1744 setattr(shadowns, name, cmd)
1745 return
1746
1747 if isinstance(cmd, basestring):
1748 nargs = cmd.count('%s')
1749 if nargs>0 and cmd.find('%l')>=0:
1750 raise Exception('The %s and %l specifiers are mutually '
1751 'exclusive in alias definitions.')
1752
1753 self.alias_table[name] = (nargs,cmd)
1754 return
1755
1756 self.alias_table[name] = cmd
1757
1758 def ipalias(self,arg_s):
1759 """Call an alias by name.
1760
1761 Input: a string containing the name of the alias to call and any
1762 additional arguments to be passed to the magic.
1763
1764 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1765 prompt:
1766
1767 In[1]: name -opt foo bar
1768
1769 To call an alias without arguments, simply use ipalias('name').
1770
1771 This provides a proper Python function to call IPython's aliases in any
1772 valid Python code you can type at the interpreter, including loops and
1773 compound statements. It is added by IPython to the Python builtin
1774 namespace upon initialization."""
1775
1776 args = arg_s.split(' ',1)
1777 alias_name = args[0]
1778 try:
1779 alias_args = args[1]
1780 except IndexError:
1781 alias_args = ''
1782 if alias_name in self.alias_table:
1783 self.call_alias(alias_name,alias_args)
1784 else:
1785 error("Alias `%s` not found." % alias_name)
1667 def init_alias(self):
1668 self.alias_manager = AliasManager(self, config=self.config)
1786 1669
1787 1670 def expand_alias(self, line):
1788 1671 """ Expand an alias in the command line
1789 1672
1790 1673 Returns the provided command line, possibly with the first word
1791 1674 (command) translated according to alias expansion rules.
1792 1675
1793 1676 [ipython]|16> _ip.expand_aliases("np myfile.txt")
1794 1677 <16> 'q:/opt/np/notepad++.exe myfile.txt'
1795 1678 """
1796 1679
1797 1680 pre,fn,rest = self.split_user_input(line)
1798 1681 res = pre + self.expand_aliases(fn, rest)
1799 1682 return res
1800 1683
1801 1684 def expand_aliases(self, fn, rest):
1802 1685 """Expand multiple levels of aliases:
1803 1686
1804 1687 if:
1805 1688
1806 1689 alias foo bar /tmp
1807 1690 alias baz foo
1808 1691
1809 1692 then:
1810 1693
1811 1694 baz huhhahhei -> bar /tmp huhhahhei
1812 1695
1813 1696 """
1814 1697 line = fn + " " + rest
1815 1698
1816 1699 done = set()
1817 1700 while 1:
1818 1701 pre,fn,rest = prefilter.splitUserInput(line,
1819 1702 prefilter.shell_line_split)
1820 if fn in self.alias_table:
1703 if fn in self.alias_manager.alias_table:
1821 1704 if fn in done:
1822 1705 warn("Cyclic alias definition, repeated '%s'" % fn)
1823 1706 return ""
1824 1707 done.add(fn)
1825 1708
1826 l2 = self.transform_alias(fn,rest)
1827 # dir -> dir
1828 # print "alias",line, "->",l2 #dbg
1709 l2 = self.alias_manager.transform_alias(fn, rest)
1829 1710 if l2 == line:
1830 1711 break
1831 1712 # ls -> ls -F should not recurse forever
1832 1713 if l2.split(None,1)[0] == line.split(None,1)[0]:
1833 1714 line = l2
1834 1715 break
1835
1836 1716 line=l2
1837
1838
1839 # print "al expand to",line #dbg
1840 1717 else:
1841 1718 break
1842 1719
1843 1720 return line
1844 1721
1845 def transform_alias(self, alias,rest=''):
1846 """ Transform alias to system command string.
1847 """
1848 trg = self.alias_table[alias]
1849
1850 nargs,cmd = trg
1851 # print trg #dbg
1852 if ' ' in cmd and os.path.isfile(cmd):
1853 cmd = '"%s"' % cmd
1854
1855 # Expand the %l special to be the user's input line
1856 if cmd.find('%l') >= 0:
1857 cmd = cmd.replace('%l',rest)
1858 rest = ''
1859 if nargs==0:
1860 # Simple, argument-less aliases
1861 cmd = '%s %s' % (cmd,rest)
1862 else:
1863 # Handle aliases with positional arguments
1864 args = rest.split(None,nargs)
1865 if len(args)< nargs:
1866 error('Alias <%s> requires %s arguments, %s given.' %
1867 (alias,nargs,len(args)))
1868 return None
1869 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1870 # Now call the macro, evaluating in the user's namespace
1871 #print 'new command: <%r>' % cmd # dbg
1872 return cmd
1873
1874 def init_auto_alias(self):
1875 """Define some aliases automatically.
1876
1877 These are ALL parameter-less aliases"""
1878
1879 for alias,cmd in self.auto_alias:
1880 self.define_alias(alias,cmd)
1881
1882 def alias_table_validate(self,verbose=0):
1883 """Update information about the alias table.
1884
1885 In particular, make sure no Python keywords/builtins are in it."""
1886
1887 no_alias = self.no_alias
1888 for k in self.alias_table.keys():
1889 if k in no_alias:
1890 del self.alias_table[k]
1891 if verbose:
1892 print ("Deleting alias <%s>, it's a Python "
1893 "keyword or builtin." % k)
1894
1895 1722 #-------------------------------------------------------------------------
1896 1723 # Things related to the running of code
1897 1724 #-------------------------------------------------------------------------
1898 1725
1899 1726 def ex(self, cmd):
1900 1727 """Execute a normal python statement in user namespace."""
1901 1728 with nested(self.builtin_trap, self.display_trap):
1902 1729 exec cmd in self.user_global_ns, self.user_ns
1903 1730
1904 1731 def ev(self, expr):
1905 1732 """Evaluate python expression expr in user namespace.
1906 1733
1907 1734 Returns the result of evaluation
1908 1735 """
1909 1736 with nested(self.builtin_trap, self.display_trap):
1910 1737 return eval(expr, self.user_global_ns, self.user_ns)
1911 1738
1912 1739 def mainloop(self, banner=None):
1913 1740 """Start the mainloop.
1914 1741
1915 1742 If an optional banner argument is given, it will override the
1916 1743 internally created default banner.
1917 1744 """
1918 1745
1919 1746 with nested(self.builtin_trap, self.display_trap):
1920 1747 if self.c: # Emulate Python's -c option
1921 1748 self.exec_init_cmd()
1922 1749
1923 1750 if self.display_banner:
1924 1751 if banner is None:
1925 1752 banner = self.banner
1926 1753
1927 1754 # if you run stuff with -c <cmd>, raw hist is not updated
1928 1755 # ensure that it's in sync
1929 1756 if len(self.input_hist) != len (self.input_hist_raw):
1930 1757 self.input_hist_raw = InputList(self.input_hist)
1931 1758
1932 1759 while 1:
1933 1760 try:
1934 1761 self.interact()
1935 1762 #self.interact_with_readline()
1936 1763 # XXX for testing of a readline-decoupled repl loop, call
1937 1764 # interact_with_readline above
1938 1765 break
1939 1766 except KeyboardInterrupt:
1940 1767 # this should not be necessary, but KeyboardInterrupt
1941 1768 # handling seems rather unpredictable...
1942 1769 self.write("\nKeyboardInterrupt in interact()\n")
1943 1770
1944 1771 def exec_init_cmd(self):
1945 1772 """Execute a command given at the command line.
1946 1773
1947 1774 This emulates Python's -c option."""
1948 1775
1949 1776 #sys.argv = ['-c']
1950 1777 self.push_line(self.prefilter(self.c, False))
1951 1778 if not self.interactive:
1952 1779 self.ask_exit()
1953 1780
1954 1781 def interact_prompt(self):
1955 1782 """ Print the prompt (in read-eval-print loop)
1956 1783
1957 1784 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1958 1785 used in standard IPython flow.
1959 1786 """
1960 1787 if self.more:
1961 1788 try:
1962 1789 prompt = self.hooks.generate_prompt(True)
1963 1790 except:
1964 1791 self.showtraceback()
1965 1792 if self.autoindent:
1966 1793 self.rl_do_indent = True
1967 1794
1968 1795 else:
1969 1796 try:
1970 1797 prompt = self.hooks.generate_prompt(False)
1971 1798 except:
1972 1799 self.showtraceback()
1973 1800 self.write(prompt)
1974 1801
1975 1802 def interact_handle_input(self,line):
1976 1803 """ Handle the input line (in read-eval-print loop)
1977 1804
1978 1805 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1979 1806 used in standard IPython flow.
1980 1807 """
1981 1808 if line.lstrip() == line:
1982 1809 self.shadowhist.add(line.strip())
1983 1810 lineout = self.prefilter(line,self.more)
1984 1811
1985 1812 if line.strip():
1986 1813 if self.more:
1987 1814 self.input_hist_raw[-1] += '%s\n' % line
1988 1815 else:
1989 1816 self.input_hist_raw.append('%s\n' % line)
1990 1817
1991 1818
1992 1819 self.more = self.push_line(lineout)
1993 1820 if (self.SyntaxTB.last_syntax_error and
1994 1821 self.autoedit_syntax):
1995 1822 self.edit_syntax_error()
1996 1823
1997 1824 def interact_with_readline(self):
1998 1825 """ Demo of using interact_handle_input, interact_prompt
1999 1826
2000 1827 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
2001 1828 it should work like this.
2002 1829 """
2003 1830 self.readline_startup_hook(self.pre_readline)
2004 1831 while not self.exit_now:
2005 1832 self.interact_prompt()
2006 1833 if self.more:
2007 1834 self.rl_do_indent = True
2008 1835 else:
2009 1836 self.rl_do_indent = False
2010 1837 line = raw_input_original().decode(self.stdin_encoding)
2011 1838 self.interact_handle_input(line)
2012 1839
2013 1840 def interact(self, banner=None):
2014 1841 """Closely emulate the interactive Python console."""
2015 1842
2016 1843 # batch run -> do not interact
2017 1844 if self.exit_now:
2018 1845 return
2019 1846
2020 1847 if self.display_banner:
2021 1848 if banner is None:
2022 1849 banner = self.banner
2023 1850 self.write(banner)
2024 1851
2025 1852 more = 0
2026 1853
2027 1854 # Mark activity in the builtins
2028 1855 __builtin__.__dict__['__IPYTHON__active'] += 1
2029 1856
2030 1857 if self.has_readline:
2031 1858 self.readline_startup_hook(self.pre_readline)
2032 1859 # exit_now is set by a call to %Exit or %Quit, through the
2033 1860 # ask_exit callback.
2034 1861
2035 1862 while not self.exit_now:
2036 1863 self.hooks.pre_prompt_hook()
2037 1864 if more:
2038 1865 try:
2039 1866 prompt = self.hooks.generate_prompt(True)
2040 1867 except:
2041 1868 self.showtraceback()
2042 1869 if self.autoindent:
2043 1870 self.rl_do_indent = True
2044 1871
2045 1872 else:
2046 1873 try:
2047 1874 prompt = self.hooks.generate_prompt(False)
2048 1875 except:
2049 1876 self.showtraceback()
2050 1877 try:
2051 1878 line = self.raw_input(prompt, more)
2052 1879 if self.exit_now:
2053 1880 # quick exit on sys.std[in|out] close
2054 1881 break
2055 1882 if self.autoindent:
2056 1883 self.rl_do_indent = False
2057 1884
2058 1885 except KeyboardInterrupt:
2059 1886 #double-guard against keyboardinterrupts during kbdint handling
2060 1887 try:
2061 1888 self.write('\nKeyboardInterrupt\n')
2062 1889 self.resetbuffer()
2063 1890 # keep cache in sync with the prompt counter:
2064 1891 self.outputcache.prompt_count -= 1
2065 1892
2066 1893 if self.autoindent:
2067 1894 self.indent_current_nsp = 0
2068 1895 more = 0
2069 1896 except KeyboardInterrupt:
2070 1897 pass
2071 1898 except EOFError:
2072 1899 if self.autoindent:
2073 1900 self.rl_do_indent = False
2074 1901 self.readline_startup_hook(None)
2075 1902 self.write('\n')
2076 1903 self.exit()
2077 1904 except bdb.BdbQuit:
2078 1905 warn('The Python debugger has exited with a BdbQuit exception.\n'
2079 1906 'Because of how pdb handles the stack, it is impossible\n'
2080 1907 'for IPython to properly format this particular exception.\n'
2081 1908 'IPython will resume normal operation.')
2082 1909 except:
2083 1910 # exceptions here are VERY RARE, but they can be triggered
2084 1911 # asynchronously by signal handlers, for example.
2085 1912 self.showtraceback()
2086 1913 else:
2087 1914 more = self.push_line(line)
2088 1915 if (self.SyntaxTB.last_syntax_error and
2089 1916 self.autoedit_syntax):
2090 1917 self.edit_syntax_error()
2091 1918
2092 1919 # We are off again...
2093 1920 __builtin__.__dict__['__IPYTHON__active'] -= 1
2094 1921
2095 1922 def safe_execfile(self,fname,*where,**kw):
2096 1923 """A safe version of the builtin execfile().
2097 1924
2098 1925 This version will never throw an exception, and knows how to handle
2099 1926 ipython logs as well.
2100 1927
2101 1928 :Parameters:
2102 1929 fname : string
2103 1930 Name of the file to be executed.
2104 1931
2105 1932 where : tuple
2106 1933 One or two namespaces, passed to execfile() as (globals,locals).
2107 1934 If only one is given, it is passed as both.
2108 1935
2109 1936 :Keywords:
2110 1937 islog : boolean (False)
2111 1938
2112 1939 quiet : boolean (True)
2113 1940
2114 1941 exit_ignore : boolean (False)
2115 1942 """
2116 1943
2117 1944 def syspath_cleanup():
2118 1945 """Internal cleanup routine for sys.path."""
2119 1946 if add_dname:
2120 1947 try:
2121 1948 sys.path.remove(dname)
2122 1949 except ValueError:
2123 1950 # For some reason the user has already removed it, ignore.
2124 1951 pass
2125 1952
2126 1953 fname = os.path.expanduser(fname)
2127 1954
2128 1955 # Find things also in current directory. This is needed to mimic the
2129 1956 # behavior of running a script from the system command line, where
2130 1957 # Python inserts the script's directory into sys.path
2131 1958 dname = os.path.dirname(os.path.abspath(fname))
2132 1959 add_dname = False
2133 1960 if dname not in sys.path:
2134 1961 sys.path.insert(0,dname)
2135 1962 add_dname = True
2136 1963
2137 1964 try:
2138 1965 xfile = open(fname)
2139 1966 except:
2140 1967 print >> Term.cerr, \
2141 1968 'Could not open file <%s> for safe execution.' % fname
2142 1969 syspath_cleanup()
2143 1970 return None
2144 1971
2145 1972 kw.setdefault('islog',0)
2146 1973 kw.setdefault('quiet',1)
2147 1974 kw.setdefault('exit_ignore',0)
2148 1975
2149 1976 first = xfile.readline()
2150 1977 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2151 1978 xfile.close()
2152 1979 # line by line execution
2153 1980 if first.startswith(loghead) or kw['islog']:
2154 1981 print 'Loading log file <%s> one line at a time...' % fname
2155 1982 if kw['quiet']:
2156 1983 stdout_save = sys.stdout
2157 1984 sys.stdout = StringIO.StringIO()
2158 1985 try:
2159 1986 globs,locs = where[0:2]
2160 1987 except:
2161 1988 try:
2162 1989 globs = locs = where[0]
2163 1990 except:
2164 1991 globs = locs = globals()
2165 1992 badblocks = []
2166 1993
2167 1994 # we also need to identify indented blocks of code when replaying
2168 1995 # logs and put them together before passing them to an exec
2169 1996 # statement. This takes a bit of regexp and look-ahead work in the
2170 1997 # file. It's easiest if we swallow the whole thing in memory
2171 1998 # first, and manually walk through the lines list moving the
2172 1999 # counter ourselves.
2173 2000 indent_re = re.compile('\s+\S')
2174 2001 xfile = open(fname)
2175 2002 filelines = xfile.readlines()
2176 2003 xfile.close()
2177 2004 nlines = len(filelines)
2178 2005 lnum = 0
2179 2006 while lnum < nlines:
2180 2007 line = filelines[lnum]
2181 2008 lnum += 1
2182 2009 # don't re-insert logger status info into cache
2183 2010 if line.startswith('#log#'):
2184 2011 continue
2185 2012 else:
2186 2013 # build a block of code (maybe a single line) for execution
2187 2014 block = line
2188 2015 try:
2189 2016 next = filelines[lnum] # lnum has already incremented
2190 2017 except:
2191 2018 next = None
2192 2019 while next and indent_re.match(next):
2193 2020 block += next
2194 2021 lnum += 1
2195 2022 try:
2196 2023 next = filelines[lnum]
2197 2024 except:
2198 2025 next = None
2199 2026 # now execute the block of one or more lines
2200 2027 try:
2201 2028 exec block in globs,locs
2202 2029 except SystemExit:
2203 2030 pass
2204 2031 except:
2205 2032 badblocks.append(block.rstrip())
2206 2033 if kw['quiet']: # restore stdout
2207 2034 sys.stdout.close()
2208 2035 sys.stdout = stdout_save
2209 2036 print 'Finished replaying log file <%s>' % fname
2210 2037 if badblocks:
2211 2038 print >> sys.stderr, ('\nThe following lines/blocks in file '
2212 2039 '<%s> reported errors:' % fname)
2213 2040
2214 2041 for badline in badblocks:
2215 2042 print >> sys.stderr, badline
2216 2043 else: # regular file execution
2217 2044 try:
2218 2045 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2219 2046 # Work around a bug in Python for Windows. The bug was
2220 2047 # fixed in in Python 2.5 r54159 and 54158, but that's still
2221 2048 # SVN Python as of March/07. For details, see:
2222 2049 # http://projects.scipy.org/ipython/ipython/ticket/123
2223 2050 try:
2224 2051 globs,locs = where[0:2]
2225 2052 except:
2226 2053 try:
2227 2054 globs = locs = where[0]
2228 2055 except:
2229 2056 globs = locs = globals()
2230 2057 exec file(fname) in globs,locs
2231 2058 else:
2232 2059 execfile(fname,*where)
2233 2060 except SyntaxError:
2234 2061 self.showsyntaxerror()
2235 2062 warn('Failure executing file: <%s>' % fname)
2236 2063 except SystemExit,status:
2237 2064 # Code that correctly sets the exit status flag to success (0)
2238 2065 # shouldn't be bothered with a traceback. Note that a plain
2239 2066 # sys.exit() does NOT set the message to 0 (it's empty) so that
2240 2067 # will still get a traceback. Note that the structure of the
2241 2068 # SystemExit exception changed between Python 2.4 and 2.5, so
2242 2069 # the checks must be done in a version-dependent way.
2243 2070 show = False
2244 2071
2245 2072 if sys.version_info[:2] > (2,5):
2246 2073 if status.message!=0 and not kw['exit_ignore']:
2247 2074 show = True
2248 2075 else:
2249 2076 if status.code and not kw['exit_ignore']:
2250 2077 show = True
2251 2078 if show:
2252 2079 self.showtraceback()
2253 2080 warn('Failure executing file: <%s>' % fname)
2254 2081 except:
2255 2082 self.showtraceback()
2256 2083 warn('Failure executing file: <%s>' % fname)
2257 2084
2258 2085 syspath_cleanup()
2259 2086
2260 2087 def cleanup_ipy_script(self, script):
2261 2088 """Make a script safe for self.runlines()
2262 2089
2263 2090 Notes
2264 2091 -----
2265 2092 This was copied over from the old ipapi and probably can be done
2266 2093 away with once we move to block based interpreter.
2267 2094
2268 2095 - Removes empty lines Suffixes all indented blocks that end with
2269 2096 - unindented lines with empty lines
2270 2097 """
2271 2098
2272 2099 res = []
2273 2100 lines = script.splitlines()
2274 2101
2275 2102 level = 0
2276 2103 for l in lines:
2277 2104 lstripped = l.lstrip()
2278 2105 stripped = l.strip()
2279 2106 if not stripped:
2280 2107 continue
2281 2108 newlevel = len(l) - len(lstripped)
2282 2109 def is_secondary_block_start(s):
2283 2110 if not s.endswith(':'):
2284 2111 return False
2285 2112 if (s.startswith('elif') or
2286 2113 s.startswith('else') or
2287 2114 s.startswith('except') or
2288 2115 s.startswith('finally')):
2289 2116 return True
2290 2117
2291 2118 if level > 0 and newlevel == 0 and \
2292 2119 not is_secondary_block_start(stripped):
2293 2120 # add empty line
2294 2121 res.append('')
2295 2122
2296 2123 res.append(l)
2297 2124 level = newlevel
2298 2125 return '\n'.join(res) + '\n'
2299 2126
2300 2127 def runlines(self, lines, clean=False):
2301 2128 """Run a string of one or more lines of source.
2302 2129
2303 2130 This method is capable of running a string containing multiple source
2304 2131 lines, as if they had been entered at the IPython prompt. Since it
2305 2132 exposes IPython's processing machinery, the given strings can contain
2306 2133 magic calls (%magic), special shell access (!cmd), etc.
2307 2134 """
2308 2135
2309 2136 if isinstance(lines, (list, tuple)):
2310 2137 lines = '\n'.join(lines)
2311 2138
2312 2139 if clean:
2313 2140 lines = self.cleanup_ipy_script(lines)
2314 2141
2315 2142 # We must start with a clean buffer, in case this is run from an
2316 2143 # interactive IPython session (via a magic, for example).
2317 2144 self.resetbuffer()
2318 2145 lines = lines.splitlines()
2319 2146 more = 0
2320 2147
2321 2148 with nested(self.builtin_trap, self.display_trap):
2322 2149 for line in lines:
2323 2150 # skip blank lines so we don't mess up the prompt counter, but do
2324 2151 # NOT skip even a blank line if we are in a code block (more is
2325 2152 # true)
2326 2153
2327 2154 if line or more:
2328 2155 # push to raw history, so hist line numbers stay in sync
2329 2156 self.input_hist_raw.append("# " + line + "\n")
2330 2157 more = self.push_line(self.prefilter(line,more))
2331 2158 # IPython's runsource returns None if there was an error
2332 2159 # compiling the code. This allows us to stop processing right
2333 2160 # away, so the user gets the error message at the right place.
2334 2161 if more is None:
2335 2162 break
2336 2163 else:
2337 2164 self.input_hist_raw.append("\n")
2338 2165 # final newline in case the input didn't have it, so that the code
2339 2166 # actually does get executed
2340 2167 if more:
2341 2168 self.push_line('\n')
2342 2169
2343 2170 def runsource(self, source, filename='<input>', symbol='single'):
2344 2171 """Compile and run some source in the interpreter.
2345 2172
2346 2173 Arguments are as for compile_command().
2347 2174
2348 2175 One several things can happen:
2349 2176
2350 2177 1) The input is incorrect; compile_command() raised an
2351 2178 exception (SyntaxError or OverflowError). A syntax traceback
2352 2179 will be printed by calling the showsyntaxerror() method.
2353 2180
2354 2181 2) The input is incomplete, and more input is required;
2355 2182 compile_command() returned None. Nothing happens.
2356 2183
2357 2184 3) The input is complete; compile_command() returned a code
2358 2185 object. The code is executed by calling self.runcode() (which
2359 2186 also handles run-time exceptions, except for SystemExit).
2360 2187
2361 2188 The return value is:
2362 2189
2363 2190 - True in case 2
2364 2191
2365 2192 - False in the other cases, unless an exception is raised, where
2366 2193 None is returned instead. This can be used by external callers to
2367 2194 know whether to continue feeding input or not.
2368 2195
2369 2196 The return value can be used to decide whether to use sys.ps1 or
2370 2197 sys.ps2 to prompt the next line."""
2371 2198
2372 2199 # if the source code has leading blanks, add 'if 1:\n' to it
2373 2200 # this allows execution of indented pasted code. It is tempting
2374 2201 # to add '\n' at the end of source to run commands like ' a=1'
2375 2202 # directly, but this fails for more complicated scenarios
2376 2203 source=source.encode(self.stdin_encoding)
2377 2204 if source[:1] in [' ', '\t']:
2378 2205 source = 'if 1:\n%s' % source
2379 2206
2380 2207 try:
2381 2208 code = self.compile(source,filename,symbol)
2382 2209 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2383 2210 # Case 1
2384 2211 self.showsyntaxerror(filename)
2385 2212 return None
2386 2213
2387 2214 if code is None:
2388 2215 # Case 2
2389 2216 return True
2390 2217
2391 2218 # Case 3
2392 2219 # We store the code object so that threaded shells and
2393 2220 # custom exception handlers can access all this info if needed.
2394 2221 # The source corresponding to this can be obtained from the
2395 2222 # buffer attribute as '\n'.join(self.buffer).
2396 2223 self.code_to_run = code
2397 2224 # now actually execute the code object
2398 2225 if self.runcode(code) == 0:
2399 2226 return False
2400 2227 else:
2401 2228 return None
2402 2229
2403 2230 def runcode(self,code_obj):
2404 2231 """Execute a code object.
2405 2232
2406 2233 When an exception occurs, self.showtraceback() is called to display a
2407 2234 traceback.
2408 2235
2409 2236 Return value: a flag indicating whether the code to be run completed
2410 2237 successfully:
2411 2238
2412 2239 - 0: successful execution.
2413 2240 - 1: an error occurred.
2414 2241 """
2415 2242
2416 2243 # Set our own excepthook in case the user code tries to call it
2417 2244 # directly, so that the IPython crash handler doesn't get triggered
2418 2245 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2419 2246
2420 2247 # we save the original sys.excepthook in the instance, in case config
2421 2248 # code (such as magics) needs access to it.
2422 2249 self.sys_excepthook = old_excepthook
2423 2250 outflag = 1 # happens in more places, so it's easier as default
2424 2251 try:
2425 2252 try:
2426 2253 self.hooks.pre_runcode_hook()
2427 2254 exec code_obj in self.user_global_ns, self.user_ns
2428 2255 finally:
2429 2256 # Reset our crash handler in place
2430 2257 sys.excepthook = old_excepthook
2431 2258 except SystemExit:
2432 2259 self.resetbuffer()
2433 2260 self.showtraceback()
2434 2261 warn("Type %exit or %quit to exit IPython "
2435 2262 "(%Exit or %Quit do so unconditionally).",level=1)
2436 2263 except self.custom_exceptions:
2437 2264 etype,value,tb = sys.exc_info()
2438 2265 self.CustomTB(etype,value,tb)
2439 2266 except:
2440 2267 self.showtraceback()
2441 2268 else:
2442 2269 outflag = 0
2443 2270 if softspace(sys.stdout, 0):
2444 2271 print
2445 2272 # Flush out code object which has been run (and source)
2446 2273 self.code_to_run = None
2447 2274 return outflag
2448 2275
2449 2276 def push_line(self, line):
2450 2277 """Push a line to the interpreter.
2451 2278
2452 2279 The line should not have a trailing newline; it may have
2453 2280 internal newlines. The line is appended to a buffer and the
2454 2281 interpreter's runsource() method is called with the
2455 2282 concatenated contents of the buffer as source. If this
2456 2283 indicates that the command was executed or invalid, the buffer
2457 2284 is reset; otherwise, the command is incomplete, and the buffer
2458 2285 is left as it was after the line was appended. The return
2459 2286 value is 1 if more input is required, 0 if the line was dealt
2460 2287 with in some way (this is the same as runsource()).
2461 2288 """
2462 2289
2463 2290 # autoindent management should be done here, and not in the
2464 2291 # interactive loop, since that one is only seen by keyboard input. We
2465 2292 # need this done correctly even for code run via runlines (which uses
2466 2293 # push).
2467 2294
2468 2295 #print 'push line: <%s>' % line # dbg
2469 2296 for subline in line.splitlines():
2470 2297 self._autoindent_update(subline)
2471 2298 self.buffer.append(line)
2472 2299 more = self.runsource('\n'.join(self.buffer), self.filename)
2473 2300 if not more:
2474 2301 self.resetbuffer()
2475 2302 return more
2476 2303
2477 2304 def _autoindent_update(self,line):
2478 2305 """Keep track of the indent level."""
2479 2306
2480 2307 #debugx('line')
2481 2308 #debugx('self.indent_current_nsp')
2482 2309 if self.autoindent:
2483 2310 if line:
2484 2311 inisp = num_ini_spaces(line)
2485 2312 if inisp < self.indent_current_nsp:
2486 2313 self.indent_current_nsp = inisp
2487 2314
2488 2315 if line[-1] == ':':
2489 2316 self.indent_current_nsp += 4
2490 2317 elif dedent_re.match(line):
2491 2318 self.indent_current_nsp -= 4
2492 2319 else:
2493 2320 self.indent_current_nsp = 0
2494 2321
2495 2322 def split_user_input(self, line):
2496 2323 # This is really a hold-over to support ipapi and some extensions
2497 2324 return prefilter.splitUserInput(line)
2498 2325
2499 2326 def resetbuffer(self):
2500 2327 """Reset the input buffer."""
2501 2328 self.buffer[:] = []
2502 2329
2503 2330 def raw_input(self,prompt='',continue_prompt=False):
2504 2331 """Write a prompt and read a line.
2505 2332
2506 2333 The returned line does not include the trailing newline.
2507 2334 When the user enters the EOF key sequence, EOFError is raised.
2508 2335
2509 2336 Optional inputs:
2510 2337
2511 2338 - prompt(''): a string to be printed to prompt the user.
2512 2339
2513 2340 - continue_prompt(False): whether this line is the first one or a
2514 2341 continuation in a sequence of inputs.
2515 2342 """
2516
2343 growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2517 2344 # Code run by the user may have modified the readline completer state.
2518 2345 # We must ensure that our completer is back in place.
2346
2519 2347 if self.has_readline:
2520 2348 self.set_completer()
2521 2349
2522 2350 try:
2523 2351 line = raw_input_original(prompt).decode(self.stdin_encoding)
2524 2352 except ValueError:
2525 2353 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2526 2354 " or sys.stdout.close()!\nExiting IPython!")
2527 2355 self.ask_exit()
2528 2356 return ""
2529 2357
2530 2358 # Try to be reasonably smart about not re-indenting pasted input more
2531 2359 # than necessary. We do this by trimming out the auto-indent initial
2532 2360 # spaces, if the user's actual input started itself with whitespace.
2533 2361 #debugx('self.buffer[-1]')
2534 2362
2535 2363 if self.autoindent:
2536 2364 if num_ini_spaces(line) > self.indent_current_nsp:
2537 2365 line = line[self.indent_current_nsp:]
2538 2366 self.indent_current_nsp = 0
2539 2367
2540 2368 # store the unfiltered input before the user has any chance to modify
2541 2369 # it.
2542 2370 if line.strip():
2543 2371 if continue_prompt:
2544 2372 self.input_hist_raw[-1] += '%s\n' % line
2545 2373 if self.has_readline: # and some config option is set?
2546 2374 try:
2547 2375 histlen = self.readline.get_current_history_length()
2548 2376 if histlen > 1:
2549 2377 newhist = self.input_hist_raw[-1].rstrip()
2550 2378 self.readline.remove_history_item(histlen-1)
2551 2379 self.readline.replace_history_item(histlen-2,
2552 2380 newhist.encode(self.stdin_encoding))
2553 2381 except AttributeError:
2554 2382 pass # re{move,place}_history_item are new in 2.4.
2555 2383 else:
2556 2384 self.input_hist_raw.append('%s\n' % line)
2557 2385 # only entries starting at first column go to shadow history
2558 2386 if line.lstrip() == line:
2559 2387 self.shadowhist.add(line.strip())
2560 2388 elif not continue_prompt:
2561 2389 self.input_hist_raw.append('\n')
2562 2390 try:
2563 2391 lineout = self.prefilter(line,continue_prompt)
2564 2392 except:
2565 2393 # blanket except, in case a user-defined prefilter crashes, so it
2566 2394 # can't take all of ipython with it.
2567 2395 self.showtraceback()
2568 2396 return ''
2569 2397 else:
2570 2398 return lineout
2571 2399
2572 2400 # def init_exec_commands(self):
2573 2401 # for cmd in self.config.EXECUTE:
2574 2402 # print "execute:", cmd
2575 2403 # self.api.runlines(cmd)
2576 2404 #
2577 2405 # batchrun = False
2578 2406 # if self.config.has_key('EXECFILE'):
2579 2407 # for batchfile in [path(arg) for arg in self.config.EXECFILE
2580 2408 # if arg.lower().endswith('.ipy')]:
2581 2409 # if not batchfile.isfile():
2582 2410 # print "No such batch file:", batchfile
2583 2411 # continue
2584 2412 # self.api.runlines(batchfile.text())
2585 2413 # batchrun = True
2586 2414 # # without -i option, exit after running the batch file
2587 2415 # if batchrun and not self.interactive:
2588 2416 # self.ask_exit()
2589 2417
2590 2418 # def load(self, mod):
2591 2419 # """ Load an extension.
2592 2420 #
2593 2421 # Some modules should (or must) be 'load()':ed, rather than just imported.
2594 2422 #
2595 2423 # Loading will do:
2596 2424 #
2597 2425 # - run init_ipython(ip)
2598 2426 # - run ipython_firstrun(ip)
2599 2427 # """
2600 2428 #
2601 2429 # if mod in self.extensions:
2602 2430 # # just to make sure we don't init it twice
2603 2431 # # note that if you 'load' a module that has already been
2604 2432 # # imported, init_ipython gets run anyway
2605 2433 #
2606 2434 # return self.extensions[mod]
2607 2435 # __import__(mod)
2608 2436 # m = sys.modules[mod]
2609 2437 # if hasattr(m,'init_ipython'):
2610 2438 # m.init_ipython(self)
2611 2439 #
2612 2440 # if hasattr(m,'ipython_firstrun'):
2613 2441 # already_loaded = self.db.get('firstrun_done', set())
2614 2442 # if mod not in already_loaded:
2615 2443 # m.ipython_firstrun(self)
2616 2444 # already_loaded.add(mod)
2617 2445 # self.db['firstrun_done'] = already_loaded
2618 2446 #
2619 2447 # self.extensions[mod] = m
2620 2448 # return m
2621 2449
2622 2450 #-------------------------------------------------------------------------
2623 2451 # Things related to the prefilter
2624 2452 #-------------------------------------------------------------------------
2625 2453
2626 2454 def init_handlers(self):
2627 2455 # escapes for automatic behavior on the command line
2628 2456 self.ESC_SHELL = '!'
2629 2457 self.ESC_SH_CAP = '!!'
2630 2458 self.ESC_HELP = '?'
2631 2459 self.ESC_MAGIC = '%'
2632 2460 self.ESC_QUOTE = ','
2633 2461 self.ESC_QUOTE2 = ';'
2634 2462 self.ESC_PAREN = '/'
2635 2463
2636 2464 # And their associated handlers
2637 2465 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
2638 2466 self.ESC_QUOTE : self.handle_auto,
2639 2467 self.ESC_QUOTE2 : self.handle_auto,
2640 2468 self.ESC_MAGIC : self.handle_magic,
2641 2469 self.ESC_HELP : self.handle_help,
2642 2470 self.ESC_SHELL : self.handle_shell_escape,
2643 2471 self.ESC_SH_CAP : self.handle_shell_escape,
2644 2472 }
2645 2473
2646 2474 def _prefilter(self, line, continue_prompt):
2647 2475 """Calls different preprocessors, depending on the form of line."""
2648 2476
2649 2477 # All handlers *must* return a value, even if it's blank ('').
2650 2478
2651 2479 # Lines are NOT logged here. Handlers should process the line as
2652 2480 # needed, update the cache AND log it (so that the input cache array
2653 2481 # stays synced).
2654 2482
2655 2483 #.....................................................................
2656 2484 # Code begins
2657 2485
2658 2486 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2659 2487
2660 2488 # save the line away in case we crash, so the post-mortem handler can
2661 2489 # record it
2490 growl.notify("_prefilter: ", "line = %s\ncontinue_prompt = %s" % (line, continue_prompt))
2491
2662 2492 self._last_input_line = line
2663 2493
2664 2494 #print '***line: <%s>' % line # dbg
2665 2495
2666 2496 if not line:
2667 2497 # Return immediately on purely empty lines, so that if the user
2668 2498 # previously typed some whitespace that started a continuation
2669 2499 # prompt, he can break out of that loop with just an empty line.
2670 2500 # This is how the default python prompt works.
2671 2501
2672 2502 # Only return if the accumulated input buffer was just whitespace!
2673 2503 if ''.join(self.buffer).isspace():
2674 2504 self.buffer[:] = []
2675 2505 return ''
2676 2506
2677 2507 line_info = prefilter.LineInfo(line, continue_prompt)
2678 2508
2679 2509 # the input history needs to track even empty lines
2680 2510 stripped = line.strip()
2681 2511
2682 2512 if not stripped:
2683 2513 if not continue_prompt:
2684 2514 self.outputcache.prompt_count -= 1
2685 2515 return self.handle_normal(line_info)
2686 2516
2687 2517 # print '***cont',continue_prompt # dbg
2688 2518 # special handlers are only allowed for single line statements
2689 2519 if continue_prompt and not self.multi_line_specials:
2690 2520 return self.handle_normal(line_info)
2691 2521
2692 2522
2693 2523 # See whether any pre-existing handler can take care of it
2694 2524 rewritten = self.hooks.input_prefilter(stripped)
2695 2525 if rewritten != stripped: # ok, some prefilter did something
2696 2526 rewritten = line_info.pre + rewritten # add indentation
2697 2527 return self.handle_normal(prefilter.LineInfo(rewritten,
2698 2528 continue_prompt))
2699 2529
2700 2530 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2701 2531
2702 2532 return prefilter.prefilter(line_info, self)
2703 2533
2704 2534
2705 2535 def _prefilter_dumb(self, line, continue_prompt):
2706 2536 """simple prefilter function, for debugging"""
2707 2537 return self.handle_normal(line,continue_prompt)
2708 2538
2709 2539
2710 2540 def multiline_prefilter(self, line, continue_prompt):
2711 2541 """ Run _prefilter for each line of input
2712 2542
2713 2543 Covers cases where there are multiple lines in the user entry,
2714 2544 which is the case when the user goes back to a multiline history
2715 2545 entry and presses enter.
2716 2546
2717 2547 """
2548 growl.notify("multiline_prefilter: ", "%s\n%s" % (line, continue_prompt))
2718 2549 out = []
2719 2550 for l in line.rstrip('\n').split('\n'):
2720 2551 out.append(self._prefilter(l, continue_prompt))
2552 growl.notify("multiline_prefilter return: ", '\n'.join(out))
2721 2553 return '\n'.join(out)
2722 2554
2723 2555 # Set the default prefilter() function (this can be user-overridden)
2724 2556 prefilter = multiline_prefilter
2725 2557
2726 def handle_normal(self,line_info):
2558 def handle_normal(self, line_info):
2727 2559 """Handle normal input lines. Use as a template for handlers."""
2728 2560
2729 2561 # With autoindent on, we need some way to exit the input loop, and I
2730 2562 # don't want to force the user to have to backspace all the way to
2731 2563 # clear the line. The rule will be in this case, that either two
2732 2564 # lines of pure whitespace in a row, or a line of pure whitespace but
2733 2565 # of a size different to the indent level, will exit the input loop.
2734 2566 line = line_info.line
2735 2567 continue_prompt = line_info.continue_prompt
2736 2568
2737 2569 if (continue_prompt and self.autoindent and line.isspace() and
2738 2570 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2739 2571 (self.buffer[-1]).isspace() )):
2740 2572 line = ''
2741 2573
2742 2574 self.log(line,line,continue_prompt)
2743 2575 return line
2744 2576
2745 def handle_alias(self,line_info):
2577 def handle_alias(self, line_info):
2746 2578 """Handle alias input lines. """
2747 tgt = self.alias_table[line_info.iFun]
2748 # print "=>",tgt #dbg
2579 tgt = self.alias_manager.alias_table[line_info.iFun]
2749 2580 if callable(tgt):
2750 2581 if '$' in line_info.line:
2751 2582 call_meth = '(_ip, _ip.var_expand(%s))'
2752 2583 else:
2753 2584 call_meth = '(_ip,%s)'
2754 2585 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2755 2586 line_info.iFun,
2756 2587 make_quoted_expr(line_info.line))
2757 2588 else:
2758 2589 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2759 2590
2760 2591 # pre is needed, because it carries the leading whitespace. Otherwise
2761 2592 # aliases won't work in indented sections.
2762 2593 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2763 2594 make_quoted_expr( transformed ))
2764 2595
2765 2596 self.log(line_info.line,line_out,line_info.continue_prompt)
2766 2597 #print 'line out:',line_out # dbg
2767 2598 return line_out
2768 2599
2769 2600 def handle_shell_escape(self, line_info):
2770 2601 """Execute the line in a shell, empty return value"""
2771 2602 #print 'line in :', `line` # dbg
2772 2603 line = line_info.line
2773 2604 if line.lstrip().startswith('!!'):
2774 2605 # rewrite LineInfo's line, iFun and theRest to properly hold the
2775 2606 # call to %sx and the actual command to be executed, so
2776 2607 # handle_magic can work correctly. Note that this works even if
2777 2608 # the line is indented, so it handles multi_line_specials
2778 2609 # properly.
2779 2610 new_rest = line.lstrip()[2:]
2780 2611 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2781 2612 line_info.iFun = 'sx'
2782 2613 line_info.theRest = new_rest
2783 2614 return self.handle_magic(line_info)
2784 2615 else:
2785 2616 cmd = line.lstrip().lstrip('!')
2786 2617 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2787 2618 make_quoted_expr(cmd))
2788 2619 # update cache/log and return
2789 2620 self.log(line,line_out,line_info.continue_prompt)
2790 2621 return line_out
2791 2622
2792 2623 def handle_magic(self, line_info):
2793 2624 """Execute magic functions."""
2794 2625 iFun = line_info.iFun
2795 2626 theRest = line_info.theRest
2796 2627 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2797 2628 make_quoted_expr(iFun + " " + theRest))
2798 2629 self.log(line_info.line,cmd,line_info.continue_prompt)
2799 2630 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2800 2631 return cmd
2801 2632
2802 2633 def handle_auto(self, line_info):
2803 2634 """Hande lines which can be auto-executed, quoting if requested."""
2804 2635
2805 2636 line = line_info.line
2806 2637 iFun = line_info.iFun
2807 2638 theRest = line_info.theRest
2808 2639 pre = line_info.pre
2809 2640 continue_prompt = line_info.continue_prompt
2810 2641 obj = line_info.ofind(self)['obj']
2811 2642
2812 2643 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2813 2644
2814 2645 # This should only be active for single-line input!
2815 2646 if continue_prompt:
2816 2647 self.log(line,line,continue_prompt)
2817 2648 return line
2818 2649
2819 2650 force_auto = isinstance(obj, IPyAutocall)
2820 2651 auto_rewrite = True
2821 2652
2822 2653 if pre == self.ESC_QUOTE:
2823 2654 # Auto-quote splitting on whitespace
2824 2655 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2825 2656 elif pre == self.ESC_QUOTE2:
2826 2657 # Auto-quote whole string
2827 2658 newcmd = '%s("%s")' % (iFun,theRest)
2828 2659 elif pre == self.ESC_PAREN:
2829 2660 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2830 2661 else:
2831 2662 # Auto-paren.
2832 2663 # We only apply it to argument-less calls if the autocall
2833 2664 # parameter is set to 2. We only need to check that autocall is <
2834 2665 # 2, since this function isn't called unless it's at least 1.
2835 2666 if not theRest and (self.autocall < 2) and not force_auto:
2836 2667 newcmd = '%s %s' % (iFun,theRest)
2837 2668 auto_rewrite = False
2838 2669 else:
2839 2670 if not force_auto and theRest.startswith('['):
2840 2671 if hasattr(obj,'__getitem__'):
2841 2672 # Don't autocall in this case: item access for an object
2842 2673 # which is BOTH callable and implements __getitem__.
2843 2674 newcmd = '%s %s' % (iFun,theRest)
2844 2675 auto_rewrite = False
2845 2676 else:
2846 2677 # if the object doesn't support [] access, go ahead and
2847 2678 # autocall
2848 2679 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2849 2680 elif theRest.endswith(';'):
2850 2681 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2851 2682 else:
2852 2683 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2853 2684
2854 2685 if auto_rewrite:
2855 2686 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2856 2687
2857 2688 try:
2858 2689 # plain ascii works better w/ pyreadline, on some machines, so
2859 2690 # we use it and only print uncolored rewrite if we have unicode
2860 2691 rw = str(rw)
2861 2692 print >>Term.cout, rw
2862 2693 except UnicodeEncodeError:
2863 2694 print "-------------->" + newcmd
2864 2695
2865 2696 # log what is now valid Python, not the actual user input (without the
2866 2697 # final newline)
2867 2698 self.log(line,newcmd,continue_prompt)
2868 2699 return newcmd
2869 2700
2870 2701 def handle_help(self, line_info):
2871 2702 """Try to get some help for the object.
2872 2703
2873 2704 obj? or ?obj -> basic information.
2874 2705 obj?? or ??obj -> more details.
2875 2706 """
2876 2707
2877 2708 line = line_info.line
2878 2709 # We need to make sure that we don't process lines which would be
2879 2710 # otherwise valid python, such as "x=1 # what?"
2880 2711 try:
2881 2712 codeop.compile_command(line)
2882 2713 except SyntaxError:
2883 2714 # We should only handle as help stuff which is NOT valid syntax
2884 2715 if line[0]==self.ESC_HELP:
2885 2716 line = line[1:]
2886 2717 elif line[-1]==self.ESC_HELP:
2887 2718 line = line[:-1]
2888 2719 self.log(line,'#?'+line,line_info.continue_prompt)
2889 2720 if line:
2890 2721 #print 'line:<%r>' % line # dbg
2891 2722 self.magic_pinfo(line)
2892 2723 else:
2893 2724 page(self.usage,screen_lines=self.usable_screen_length)
2894 2725 return '' # Empty string is needed here!
2895 2726 except:
2896 2727 # Pass any other exceptions through to the normal handler
2897 2728 return self.handle_normal(line_info)
2898 2729 else:
2899 2730 # If the code compiles ok, we should handle it normally
2900 2731 return self.handle_normal(line_info)
2901 2732
2902 2733 def handle_emacs(self, line_info):
2903 2734 """Handle input lines marked by python-mode."""
2904 2735
2905 2736 # Currently, nothing is done. Later more functionality can be added
2906 2737 # here if needed.
2907 2738
2908 2739 # The input cache shouldn't be updated
2909 2740 return line_info.line
2910 2741
2911 2742 #-------------------------------------------------------------------------
2912 2743 # Utilities
2913 2744 #-------------------------------------------------------------------------
2914 2745
2915 2746 def getoutput(self, cmd):
2916 2747 return getoutput(self.var_expand(cmd,depth=2),
2917 2748 header=self.system_header,
2918 2749 verbose=self.system_verbose)
2919 2750
2920 2751 def getoutputerror(self, cmd):
2921 2752 return getoutputerror(self.var_expand(cmd,depth=2),
2922 2753 header=self.system_header,
2923 2754 verbose=self.system_verbose)
2924 2755
2925 2756 def var_expand(self,cmd,depth=0):
2926 2757 """Expand python variables in a string.
2927 2758
2928 2759 The depth argument indicates how many frames above the caller should
2929 2760 be walked to look for the local namespace where to expand variables.
2930 2761
2931 2762 The global namespace for expansion is always the user's interactive
2932 2763 namespace.
2933 2764 """
2934 2765
2935 2766 return str(ItplNS(cmd,
2936 2767 self.user_ns, # globals
2937 2768 # Skip our own frame in searching for locals:
2938 2769 sys._getframe(depth+1).f_locals # locals
2939 2770 ))
2940 2771
2941 2772 def mktempfile(self,data=None):
2942 2773 """Make a new tempfile and return its filename.
2943 2774
2944 2775 This makes a call to tempfile.mktemp, but it registers the created
2945 2776 filename internally so ipython cleans it up at exit time.
2946 2777
2947 2778 Optional inputs:
2948 2779
2949 2780 - data(None): if data is given, it gets written out to the temp file
2950 2781 immediately, and the file is closed again."""
2951 2782
2952 2783 filename = tempfile.mktemp('.py','ipython_edit_')
2953 2784 self.tempfiles.append(filename)
2954 2785
2955 2786 if data:
2956 2787 tmp_file = open(filename,'w')
2957 2788 tmp_file.write(data)
2958 2789 tmp_file.close()
2959 2790 return filename
2960 2791
2961 2792 def write(self,data):
2962 2793 """Write a string to the default output"""
2963 2794 Term.cout.write(data)
2964 2795
2965 2796 def write_err(self,data):
2966 2797 """Write a string to the default error output"""
2967 2798 Term.cerr.write(data)
2968 2799
2969 2800 def ask_yes_no(self,prompt,default=True):
2970 2801 if self.quiet:
2971 2802 return True
2972 2803 return ask_yes_no(prompt,default)
2973 2804
2974 2805 #-------------------------------------------------------------------------
2975 2806 # Things related to IPython exiting
2976 2807 #-------------------------------------------------------------------------
2977 2808
2978 2809 def ask_exit(self):
2979 2810 """ Call for exiting. Can be overiden and used as a callback. """
2980 2811 self.exit_now = True
2981 2812
2982 2813 def exit(self):
2983 2814 """Handle interactive exit.
2984 2815
2985 2816 This method calls the ask_exit callback."""
2986 2817 if self.confirm_exit:
2987 2818 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2988 2819 self.ask_exit()
2989 2820 else:
2990 2821 self.ask_exit()
2991 2822
2992 2823 def atexit_operations(self):
2993 2824 """This will be executed at the time of exit.
2994 2825
2995 2826 Saving of persistent data should be performed here.
2996 2827 """
2997 2828 self.savehist()
2998 2829
2999 2830 # Cleanup all tempfiles left around
3000 2831 for tfile in self.tempfiles:
3001 2832 try:
3002 2833 os.unlink(tfile)
3003 2834 except OSError:
3004 2835 pass
3005 2836
3006 2837 # Clear all user namespaces to release all references cleanly.
3007 2838 self.reset()
3008 2839
3009 2840 # Run user hooks
3010 2841 self.hooks.shutdown_hook()
3011 2842
3012 2843 def cleanup(self):
3013 2844 self.restore_sys_module_state()
3014 2845
3015 2846
3016 2847
3017 2848
3018 2849
@@ -1,321 +1,321 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes and functions for prefiltering (transforming) a line of user input.
4 4 This module is responsible, primarily, for breaking the line up into useful
5 5 pieces and triggering the appropriate handlers in iplib to do the actual
6 6 transforming work.
7 7 """
8 8 __docformat__ = "restructuredtext en"
9 9
10 10 import re
11 11 from IPython.core.autocall import IPyAutocall
12 12
13 13
14 14 class LineInfo(object):
15 15 """A single line of input and associated info.
16 16
17 17 Includes the following as properties:
18 18
19 19 line
20 20 The original, raw line
21 21
22 22 continue_prompt
23 23 Is this line a continuation in a sequence of multiline input?
24 24
25 25 pre
26 26 The initial esc character or whitespace.
27 27
28 28 preChar
29 29 The escape character(s) in pre or the empty string if there isn't one.
30 30 Note that '!!' is a possible value for preChar. Otherwise it will
31 31 always be a single character.
32 32
33 33 preWhitespace
34 34 The leading whitespace from pre if it exists. If there is a preChar,
35 35 this is just ''.
36 36
37 37 iFun
38 38 The 'function part', which is basically the maximal initial sequence
39 39 of valid python identifiers and the '.' character. This is what is
40 40 checked for alias and magic transformations, used for auto-calling,
41 41 etc.
42 42
43 43 theRest
44 44 Everything else on the line.
45 45 """
46 46 def __init__(self, line, continue_prompt):
47 47 self.line = line
48 48 self.continue_prompt = continue_prompt
49 49 self.pre, self.iFun, self.theRest = splitUserInput(line)
50 50
51 51 self.preChar = self.pre.strip()
52 52 if self.preChar:
53 53 self.preWhitespace = '' # No whitespace allowd before esc chars
54 54 else:
55 55 self.preWhitespace = self.pre
56 56
57 57 self._oinfo = None
58 58
59 59 def ofind(self, ip):
60 60 """Do a full, attribute-walking lookup of the iFun in the various
61 61 namespaces for the given IPython InteractiveShell instance.
62 62
63 63 Return a dict with keys: found,obj,ospace,ismagic
64 64
65 65 Note: can cause state changes because of calling getattr, but should
66 66 only be run if autocall is on and if the line hasn't matched any
67 67 other, less dangerous handlers.
68 68
69 69 Does cache the results of the call, so can be called multiple times
70 70 without worrying about *further* damaging state.
71 71 """
72 72 if not self._oinfo:
73 73 self._oinfo = ip._ofind(self.iFun)
74 74 return self._oinfo
75 75 def __str__(self):
76 76 return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest)
77 77
78 78 def splitUserInput(line, pattern=None):
79 79 """Split user input into pre-char/whitespace, function part and rest.
80 80
81 81 Mostly internal to this module, but also used by iplib.expand_aliases,
82 82 which passes in a shell pattern.
83 83 """
84 84 # It seems to me that the shell splitting should be a separate method.
85 85
86 86 if not pattern:
87 87 pattern = line_split
88 88 match = pattern.match(line)
89 89 if not match:
90 90 #print "match failed for line '%s'" % line
91 91 try:
92 92 iFun,theRest = line.split(None,1)
93 93 except ValueError:
94 94 #print "split failed for line '%s'" % line
95 95 iFun,theRest = line,''
96 96 pre = re.match('^(\s*)(.*)',line).groups()[0]
97 97 else:
98 98 pre,iFun,theRest = match.groups()
99 99
100 100 # iFun has to be a valid python identifier, so it better be only pure
101 101 # ascii, no unicode:
102 102 try:
103 103 iFun = iFun.encode('ascii')
104 104 except UnicodeEncodeError:
105 105 theRest = iFun + u' ' + theRest
106 106 iFun = u''
107 107
108 108 #print 'line:<%s>' % line # dbg
109 109 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
110 110 return pre,iFun.strip(),theRest.lstrip()
111 111
112 112
113 113 # RegExp for splitting line contents into pre-char//first word-method//rest.
114 114 # For clarity, each group in on one line.
115 115
116 116 # WARNING: update the regexp if the escapes in iplib are changed, as they
117 117 # are hardwired in.
118 118
119 119 # Although it's not solely driven by the regex, note that:
120 120 # ,;/% only trigger if they are the first character on the line
121 121 # ! and !! trigger if they are first char(s) *or* follow an indent
122 122 # ? triggers as first or last char.
123 123
124 124 # The three parts of the regex are:
125 125 # 1) pre: pre_char *or* initial whitespace
126 126 # 2) iFun: first word/method (mix of \w and '.')
127 127 # 3) theRest: rest of line (separated from iFun by space if non-empty)
128 128 line_split = re.compile(r'^([,;/%?]|!!?|\s*)'
129 129 r'\s*([\w\.]+)'
130 130 r'(\s+.*$|$)')
131 131
132 132 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
133 133
134 134 def prefilter(line_info, ip):
135 135 """Call one of the passed-in InteractiveShell's handler preprocessors,
136 136 depending on the form of the line. Return the results, which must be a
137 137 value, even if it's a blank ('')."""
138 138 # Note: the order of these checks does matter.
139 139 for check in [ checkEmacs,
140 140 checkShellEscape,
141 141 checkIPyAutocall,
142 142 checkMultiLineMagic,
143 143 checkEscChars,
144 144 checkAssignment,
145 145 checkAutomagic,
146 146 checkAlias,
147 147 checkPythonOps,
148 148 checkAutocall,
149 149 ]:
150 150 handler = check(line_info, ip)
151 151 if handler:
152 152 return handler(line_info)
153 153
154 154 return ip.handle_normal(line_info)
155 155
156 156 # Handler checks
157 157 #
158 158 # All have the same interface: they take a LineInfo object and a ref to the
159 159 # iplib.InteractiveShell object. They check the line to see if a particular
160 160 # handler should be called, and return either a handler or None. The
161 161 # handlers which they return are *bound* methods of the InteractiveShell
162 162 # object.
163 163 #
164 164 # In general, these checks should only take responsibility for their 'own'
165 165 # handler. If it doesn't get triggered, they should just return None and
166 166 # let the rest of the check sequence run.
167 167
168 168 def checkShellEscape(l_info,ip):
169 169 if l_info.line.lstrip().startswith(ip.ESC_SHELL):
170 170 return ip.handle_shell_escape
171 171
172 172 def checkEmacs(l_info,ip):
173 173 "Emacs ipython-mode tags certain input lines."
174 174 if l_info.line.endswith('# PYTHON-MODE'):
175 175 return ip.handle_emacs
176 176 else:
177 177 return None
178 178
179 179 def checkIPyAutocall(l_info,ip):
180 180 "Instances of IPyAutocall in user_ns get autocalled immediately"
181 181 obj = ip.user_ns.get(l_info.iFun, None)
182 182 if isinstance(obj, IPyAutocall):
183 183 obj.set_ip(ip)
184 184 return ip.handle_auto
185 185 else:
186 186 return None
187 187
188 188
189 189 def checkMultiLineMagic(l_info,ip):
190 190 "Allow ! and !! in multi-line statements if multi_line_specials is on"
191 191 # Note that this one of the only places we check the first character of
192 192 # iFun and *not* the preChar. Also note that the below test matches
193 193 # both ! and !!.
194 194 if l_info.continue_prompt \
195 195 and ip.multi_line_specials:
196 196 if l_info.iFun.startswith(ip.ESC_MAGIC):
197 197 return ip.handle_magic
198 198 else:
199 199 return None
200 200
201 201 def checkEscChars(l_info,ip):
202 202 """Check for escape character and return either a handler to handle it,
203 203 or None if there is no escape char."""
204 204 if l_info.line[-1] == ip.ESC_HELP \
205 205 and l_info.preChar != ip.ESC_SHELL \
206 206 and l_info.preChar != ip.ESC_SH_CAP:
207 207 # the ? can be at the end, but *not* for either kind of shell escape,
208 208 # because a ? can be a vaild final char in a shell cmd
209 209 return ip.handle_help
210 210 elif l_info.preChar in ip.esc_handlers:
211 211 return ip.esc_handlers[l_info.preChar]
212 212 else:
213 213 return None
214 214
215 215
216 216 def checkAssignment(l_info,ip):
217 217 """Check to see if user is assigning to a var for the first time, in
218 218 which case we want to avoid any sort of automagic / autocall games.
219 219
220 220 This allows users to assign to either alias or magic names true python
221 221 variables (the magic/alias systems always take second seat to true
222 222 python code). E.g. ls='hi', or ls,that=1,2"""
223 223 if l_info.theRest and l_info.theRest[0] in '=,':
224 224 return ip.handle_normal
225 225 else:
226 226 return None
227 227
228 228
229 229 def checkAutomagic(l_info,ip):
230 230 """If the iFun is magic, and automagic is on, run it. Note: normal,
231 231 non-auto magic would already have been triggered via '%' in
232 232 check_esc_chars. This just checks for automagic. Also, before
233 233 triggering the magic handler, make sure that there is nothing in the
234 234 user namespace which could shadow it."""
235 235 if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun):
236 236 return None
237 237
238 238 # We have a likely magic method. Make sure we should actually call it.
239 239 if l_info.continue_prompt and not ip.multi_line_specials:
240 240 return None
241 241
242 242 head = l_info.iFun.split('.',1)[0]
243 243 if isShadowed(head,ip):
244 244 return None
245 245
246 246 return ip.handle_magic
247 247
248 248
249 249 def checkAlias(l_info,ip):
250 250 "Check if the initital identifier on the line is an alias."
251 251 # Note: aliases can not contain '.'
252 252 head = l_info.iFun.split('.',1)[0]
253 253
254 if l_info.iFun not in ip.alias_table \
255 or head not in ip.alias_table \
254 if l_info.iFun not in ip.alias_manager \
255 or head not in ip.alias_manager \
256 256 or isShadowed(head,ip):
257 257 return None
258 258
259 259 return ip.handle_alias
260 260
261 261
262 262 def checkPythonOps(l_info,ip):
263 263 """If the 'rest' of the line begins with a function call or pretty much
264 264 any python operator, we should simply execute the line (regardless of
265 265 whether or not there's a possible autocall expansion). This avoids
266 266 spurious (and very confusing) geattr() accesses."""
267 267 if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|':
268 268 return ip.handle_normal
269 269 else:
270 270 return None
271 271
272 272
273 273 def checkAutocall(l_info,ip):
274 274 "Check if the initial word/function is callable and autocall is on."
275 275 if not ip.autocall:
276 276 return None
277 277
278 278 oinfo = l_info.ofind(ip) # This can mutate state via getattr
279 279 if not oinfo['found']:
280 280 return None
281 281
282 282 if callable(oinfo['obj']) \
283 283 and (not re_exclude_auto.match(l_info.theRest)) \
284 284 and re_fun_name.match(l_info.iFun):
285 285 #print 'going auto' # dbg
286 286 return ip.handle_auto
287 287 else:
288 288 #print 'was callable?', callable(l_info.oinfo['obj']) # dbg
289 289 return None
290 290
291 291 # RegExp to identify potential function names
292 292 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
293 293
294 294 # RegExp to exclude strings with this start from autocalling. In
295 295 # particular, all binary operators should be excluded, so that if foo is
296 296 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
297 297 # characters '!=()' don't need to be checked for, as the checkPythonChars
298 298 # routine explicitely does so, to catch direct calls and rebindings of
299 299 # existing names.
300 300
301 301 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
302 302 # it affects the rest of the group in square brackets.
303 303 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
304 304 r'|^is |^not |^in |^and |^or ')
305 305
306 306 # try to catch also methods for stuff in lists/tuples/dicts: off
307 307 # (experimental). For this to work, the line_split regexp would need
308 308 # to be modified so it wouldn't break things at '['. That line is
309 309 # nasty enough that I shouldn't change it until I can test it _well_.
310 310 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
311 311
312 312 # Handler Check Utilities
313 313 def isShadowed(identifier,ip):
314 314 """Is the given identifier defined in one of the namespaces which shadow
315 315 the alias and magic namespaces? Note that an identifier is different
316 316 than iFun, because it can not contain a '.' character."""
317 317 # This is much safer than calling ofind, which can change state
318 318 return (identifier in ip.user_ns \
319 319 or identifier in ip.internal_ns \
320 320 or identifier in ip.ns_table['builtin'])
321 321
@@ -1,49 +1,49 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 4
5 5 class IPythonGrowlError(Exception):
6 6 pass
7 7
8 8 class Notifier(object):
9 9
10 10 def __init__(self, app_name):
11 11 try:
12 12 import Growl
13 13 except ImportError:
14 14 self.g_notifier = None
15 15 else:
16 16 self.g_notifier = Growl.GrowlNotifier(app_name, ['kernel', 'core'])
17 17 self.g_notifier.register()
18 18
19 19 def _notify(self, title, msg):
20 20 if self.g_notifier is not None:
21 self.g_notifier.notify('kernel', title, msg)
21 self.g_notifier.notify('core', title, msg)
22 22
23 23 def notify(self, title, msg):
24 24 self._notify(title, msg)
25 25
26 26 def notify_deferred(self, r, msg):
27 27 title = "Deferred Result"
28 28 msg = msg + '\n' + repr(r)
29 29 self._notify(title, msg)
30 30 return r
31 31
32 32 _notifier = None
33 33
34 34 def notify(title, msg):
35 35 pass
36 36
37 37 def notify_deferred(r, msg):
38 38 return r
39 39
40 40 def start(app_name):
41 41 global _notifier, notify, notify_deferred
42 42 if _notifier is not None:
43 43 raise IPythonGrowlError("this process is already registered with Growl")
44 44 else:
45 45 _notifier = Notifier(app_name)
46 46 notify = _notifier.notify
47 47 notify_deferred = _notifier.notify_deferred
48 48
49 49
General Comments 0
You need to be logged in to leave comments. Login now