##// END OF EJS Templates
Merge branch 'newapp'...
MinRK -
r4042:fbd5ae94 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,5 b''
1 This is the IPython directory.
2
3 For more information on configuring IPython, do:
4
5 ipython config -h
@@ -0,0 +1,219 b''
1 # encoding: utf-8
2 """
3 An application for managing IPython profiles.
4
5 To be invoked as the `ipython profile` subcommand.
6
7 Authors:
8
9 * Min RK
10
11 """
12
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
19
20 #-----------------------------------------------------------------------------
21 # Imports
22 #-----------------------------------------------------------------------------
23
24 import logging
25 import os
26
27 from IPython.config.application import Application, boolean_flag
28 from IPython.core.application import (
29 BaseIPythonApplication, base_flags, base_aliases
30 )
31 from IPython.core.profiledir import ProfileDir
32 from IPython.utils.path import get_ipython_dir
33 from IPython.utils.traitlets import Unicode, Bool, Dict
34
35 #-----------------------------------------------------------------------------
36 # Constants
37 #-----------------------------------------------------------------------------
38
39 create_help = """Create an IPython profile by name
40
41 Create an ipython profile directory by its name or
42 profile directory path. Profile directories contain
43 configuration, log and security related files and are named
44 using the convention 'profile_<name>'. By default they are
45 located in your ipython directory. Once created, you will
46 can edit the configuration files in the profile
47 directory to configure IPython. Most users will create a
48 profile directory by name,
49 `ipython profile create myprofile`, which will put the directory
50 in `<ipython_dir>/profile_myprofile`.
51 """
52 list_help = """List available IPython profiles
53
54 List all available profiles, by profile location, that can
55 be found in the current working directly or in the ipython
56 directory. Profile directories are named using the convention
57 'profile_<profile>'.
58 """
59 profile_help = """Manage IPython profiles
60
61 Profile directories contain
62 configuration, log and security related files and are named
63 using the convention 'profile_<name>'. By default they are
64 located in your ipython directory. You can create profiles
65 with `ipython profile create <name>`, or see the profiles you
66 already have with `ipython profile list`
67
68 To get started configuring IPython, simply do:
69
70 $> ipython profile create
71
72 and IPython will create the default profile in <ipython_dir>/profile_default,
73 where you can edit ipython_config.py to start configuring IPython.
74
75 """
76
77 #-----------------------------------------------------------------------------
78 # Profile Application Class (for `ipython profile` subcommand)
79 #-----------------------------------------------------------------------------
80
81
82
83 class ProfileList(Application):
84 name = u'ipython-profile'
85 description = list_help
86
87 aliases = Dict(dict(
88 ipython_dir = 'ProfileList.ipython_dir',
89 log_level = 'Application.log_level',
90 ))
91 flags = Dict(dict(
92 debug = ({'Application' : {'log_level' : 0}},
93 "Set log_level to 0, maximizing log output."
94 )
95 ))
96 ipython_dir = Unicode(get_ipython_dir(), config=True,
97 help="""
98 The name of the IPython directory. This directory is used for logging
99 configuration (through profiles), history storage, etc. The default
100 is usually $HOME/.ipython. This options can also be specified through
101 the environment variable IPYTHON_DIR.
102 """
103 )
104
105 def list_profile_dirs(self):
106 # Find the search paths
107 paths = [os.getcwdu(), self.ipython_dir]
108
109 self.log.warn('Searching for IPython profiles in paths: %r' % paths)
110 for path in paths:
111 files = os.listdir(path)
112 for f in files:
113 full_path = os.path.join(path, f)
114 if os.path.isdir(full_path) and f.startswith('profile_'):
115 profile = f.split('_',1)[-1]
116 start_cmd = 'ipython profile=%s' % profile
117 print start_cmd + " ==> " + full_path
118
119 def start(self):
120 self.list_profile_dirs()
121
122
123 create_flags = {}
124 create_flags.update(base_flags)
125 create_flags.update(boolean_flag('reset', 'ProfileCreate.overwrite',
126 "reset config files to defaults", "leave existing config files"))
127 create_flags.update(boolean_flag('parallel', 'ProfileCreate.parallel',
128 "Include parallel computing config files",
129 "Don't include parallel computing config files"))
130
131 class ProfileCreate(BaseIPythonApplication):
132 name = u'ipython-profile'
133 description = create_help
134 auto_create = Bool(True, config=False)
135
136 def _copy_config_files_default(self):
137 return True
138
139 parallel = Bool(False, config=True,
140 help="whether to include parallel computing config files")
141 def _parallel_changed(self, name, old, new):
142 parallel_files = [ 'ipcontroller_config.py',
143 'ipengine_config.py',
144 'ipcluster_config.py'
145 ]
146 if new:
147 for cf in parallel_files:
148 self.config_files.append(cf)
149 else:
150 for cf in parallel_files:
151 if cf in self.config_files:
152 self.config_files.remove(cf)
153
154 def parse_command_line(self, argv):
155 super(ProfileCreate, self).parse_command_line(argv)
156 # accept positional arg as profile name
157 if self.extra_args:
158 self.profile = self.extra_args[0]
159
160 flags = Dict(create_flags)
161
162 aliases = Dict(dict(profile='BaseIPythonApplication.profile'))
163
164 classes = [ProfileDir]
165
166 def init_config_files(self):
167 super(ProfileCreate, self).init_config_files()
168 # use local imports, since these classes may import from here
169 from IPython.frontend.terminal.ipapp import TerminalIPythonApp
170 apps = [TerminalIPythonApp]
171 try:
172 from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp
173 except ImportError:
174 pass
175 else:
176 apps.append(IPythonQtConsoleApp)
177 if self.parallel:
178 from IPython.parallel.apps.ipcontrollerapp import IPControllerApp
179 from IPython.parallel.apps.ipengineapp import IPEngineApp
180 from IPython.parallel.apps.ipclusterapp import IPClusterStart
181 from IPython.parallel.apps.iploggerapp import IPLoggerApp
182 apps.extend([
183 IPControllerApp,
184 IPEngineApp,
185 IPClusterStart,
186 IPLoggerApp,
187 ])
188 for App in apps:
189 app = App()
190 app.config.update(self.config)
191 app.log = self.log
192 app.overwrite = self.overwrite
193 app.copy_config_files=True
194 app.profile = self.profile
195 app.init_profile_dir()
196 app.init_config_files()
197
198 def stage_default_config_file(self):
199 pass
200
201 class ProfileApp(Application):
202 name = u'ipython-profile'
203 description = profile_help
204
205 subcommands = Dict(dict(
206 create = (ProfileCreate, "Create a new profile dir with default config files"),
207 list = (ProfileList, "List existing profiles")
208 ))
209
210 def start(self):
211 if self.subapp is None:
212 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
213 print
214 self.print_description()
215 self.print_subcommands()
216 self.exit(1)
217 else:
218 return self.subapp.start()
219
@@ -0,0 +1,206 b''
1 # encoding: utf-8
2 """
3 An object for managing IPython profile directories.
4
5 Authors:
6
7 * Brian Granger
8 * Fernando Perez
9 * Min RK
10
11 """
12
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
19
20 #-----------------------------------------------------------------------------
21 # Imports
22 #-----------------------------------------------------------------------------
23
24 import os
25 import shutil
26 import sys
27
28 from IPython.config.configurable import Configurable
29 from IPython.config.loader import Config
30 from IPython.utils.path import get_ipython_package_dir, expand_path
31 from IPython.utils.traitlets import List, Unicode, Bool
32
33 #-----------------------------------------------------------------------------
34 # Classes and functions
35 #-----------------------------------------------------------------------------
36
37
38 #-----------------------------------------------------------------------------
39 # Module errors
40 #-----------------------------------------------------------------------------
41
42 class ProfileDirError(Exception):
43 pass
44
45
46 #-----------------------------------------------------------------------------
47 # Class for managing profile directories
48 #-----------------------------------------------------------------------------
49
50 class ProfileDir(Configurable):
51 """An object to manage the profile directory and its resources.
52
53 The profile directory is used by all IPython applications, to manage
54 configuration, logging and security.
55
56 This object knows how to find, create and manage these directories. This
57 should be used by any code that wants to handle profiles.
58 """
59
60 security_dir_name = Unicode('security')
61 log_dir_name = Unicode('log')
62 pid_dir_name = Unicode('pid')
63 security_dir = Unicode(u'')
64 log_dir = Unicode(u'')
65 pid_dir = Unicode(u'')
66
67 location = Unicode(u'', config=True,
68 help="""Set the profile location directly. This overrides the logic used by the
69 `profile` option.""",
70 )
71
72 _location_isset = Bool(False) # flag for detecting multiply set location
73
74 def _location_changed(self, name, old, new):
75 if self._location_isset:
76 raise RuntimeError("Cannot set profile location more than once.")
77 self._location_isset = True
78 if not os.path.isdir(new):
79 os.makedirs(new)
80
81 # ensure config files exist:
82 self.security_dir = os.path.join(new, self.security_dir_name)
83 self.log_dir = os.path.join(new, self.log_dir_name)
84 self.pid_dir = os.path.join(new, self.pid_dir_name)
85 self.check_dirs()
86
87 def _log_dir_changed(self, name, old, new):
88 self.check_log_dir()
89
90 def check_log_dir(self):
91 if not os.path.isdir(self.log_dir):
92 os.mkdir(self.log_dir)
93
94 def _security_dir_changed(self, name, old, new):
95 self.check_security_dir()
96
97 def check_security_dir(self):
98 if not os.path.isdir(self.security_dir):
99 os.mkdir(self.security_dir, 0700)
100 else:
101 os.chmod(self.security_dir, 0700)
102
103 def _pid_dir_changed(self, name, old, new):
104 self.check_pid_dir()
105
106 def check_pid_dir(self):
107 if not os.path.isdir(self.pid_dir):
108 os.mkdir(self.pid_dir, 0700)
109 else:
110 os.chmod(self.pid_dir, 0700)
111
112 def check_dirs(self):
113 self.check_security_dir()
114 self.check_log_dir()
115 self.check_pid_dir()
116
117 def copy_config_file(self, config_file, path=None, overwrite=False):
118 """Copy a default config file into the active profile directory.
119
120 Default configuration files are kept in :mod:`IPython.config.default`.
121 This function moves these from that location to the working profile
122 directory.
123 """
124 dst = os.path.join(self.location, config_file)
125 if os.path.isfile(dst) and not overwrite:
126 return
127 if path is None:
128 path = os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
129 src = os.path.join(path, config_file)
130 shutil.copy(src, dst)
131
132 @classmethod
133 def create_profile_dir(cls, profile_dir, config=None):
134 """Create a new profile directory given a full path.
135
136 Parameters
137 ----------
138 profile_dir : str
139 The full path to the profile directory. If it does exist, it will
140 be used. If not, it will be created.
141 """
142 return cls(location=profile_dir, config=config)
143
144 @classmethod
145 def create_profile_dir_by_name(cls, path, name=u'default', config=None):
146 """Create a profile dir by profile name and path.
147
148 Parameters
149 ----------
150 path : unicode
151 The path (directory) to put the profile directory in.
152 name : unicode
153 The name of the profile. The name of the profile directory will
154 be "profile_<profile>".
155 """
156 if not os.path.isdir(path):
157 raise ProfileDirError('Directory not found: %s' % path)
158 profile_dir = os.path.join(path, u'profile_' + name)
159 return cls(location=profile_dir, config=config)
160
161 @classmethod
162 def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
163 """Find an existing profile dir by profile name, return its ProfileDir.
164
165 This searches through a sequence of paths for a profile dir. If it
166 is not found, a :class:`ProfileDirError` exception will be raised.
167
168 The search path algorithm is:
169 1. ``os.getcwd()``
170 2. ``ipython_dir``
171
172 Parameters
173 ----------
174 ipython_dir : unicode or str
175 The IPython directory to use.
176 name : unicode or str
177 The name of the profile. The name of the profile directory
178 will be "profile_<profile>".
179 """
180 dirname = u'profile_' + name
181 paths = [os.getcwdu(), ipython_dir]
182 for p in paths:
183 profile_dir = os.path.join(p, dirname)
184 if os.path.isdir(profile_dir):
185 return cls(location=profile_dir, config=config)
186 else:
187 raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
188
189 @classmethod
190 def find_profile_dir(cls, profile_dir, config=None):
191 """Find/create a profile dir and return its ProfileDir.
192
193 This will create the profile directory if it doesn't exist.
194
195 Parameters
196 ----------
197 profile_dir : unicode or str
198 The path of the profile directory. This is expanded using
199 :func:`IPython.utils.genutils.expand_path`.
200 """
201 profile_dir = expand_path(profile_dir)
202 if not os.path.isdir(profile_dir):
203 raise ProfileDirError('Profile directory not found: %s' % profile_dir)
204 return cls(location=profile_dir, config=config)
205
206
@@ -0,0 +1,244 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A mixin for :class:`~IPython.core.application.Application` classes that
5 launch InteractiveShell instances, load extensions, etc.
6
7 Authors
8 -------
9
10 * Min Ragan-Kelley
11 """
12
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
19
20 #-----------------------------------------------------------------------------
21 # Imports
22 #-----------------------------------------------------------------------------
23
24 from __future__ import absolute_import
25
26 import os
27 import sys
28
29 from IPython.config.application import boolean_flag
30 from IPython.config.configurable import Configurable
31 from IPython.config.loader import Config
32 from IPython.utils.path import filefind
33 from IPython.utils.traitlets import Unicode, Instance, List
34
35 #-----------------------------------------------------------------------------
36 # Aliases and Flags
37 #-----------------------------------------------------------------------------
38
39 shell_flags = {}
40
41 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
42 addflag('autoindent', 'InteractiveShell.autoindent',
43 'Turn on autoindenting.', 'Turn off autoindenting.'
44 )
45 addflag('automagic', 'InteractiveShell.automagic',
46 """Turn on the auto calling of magic commands. Type %%magic at the
47 IPython prompt for more information.""",
48 'Turn off the auto calling of magic commands.'
49 )
50 addflag('pdb', 'InteractiveShell.pdb',
51 "Enable auto calling the pdb debugger after every exception.",
52 "Disable auto calling the pdb debugger after every exception."
53 )
54 addflag('pprint', 'PlainTextFormatter.pprint',
55 "Enable auto pretty printing of results.",
56 "Disable auto auto pretty printing of results."
57 )
58 addflag('color-info', 'InteractiveShell.color_info',
59 """IPython can display information about objects via a set of func-
60 tions, and optionally can use colors for this, syntax highlighting
61 source code and various other elements. However, because this
62 information is passed through a pager (like 'less') and many pagers get
63 confused with color codes, this option is off by default. You can test
64 it and turn it on permanently in your ipython_config.py file if it
65 works for you. Test it and turn it on permanently if it works with
66 your system. The magic function %%color_info allows you to toggle this
67 interactively for testing.""",
68 "Disable using colors for info related things."
69 )
70 addflag('deep-reload', 'InteractiveShell.deep_reload',
71 """Enable deep (recursive) reloading by default. IPython can use the
72 deep_reload module which reloads changes in modules recursively (it
73 replaces the reload() function, so you don't need to change anything to
74 use it). deep_reload() forces a full reload of modules whose code may
75 have changed, which the default reload() function does not. When
76 deep_reload is off, IPython will use the normal reload(), but
77 deep_reload will still be available as dreload(). This feature is off
78 by default [which means that you have both normal reload() and
79 dreload()].""",
80 "Disable deep (recursive) reloading by default."
81 )
82 nosep_config = Config()
83 nosep_config.InteractiveShell.separate_in = ''
84 nosep_config.InteractiveShell.separate_out = ''
85 nosep_config.InteractiveShell.separate_out2 = ''
86
87 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
88
89
90 # it's possible we don't want short aliases for *all* of these:
91 shell_aliases = dict(
92 autocall='InteractiveShell.autocall',
93 cache_size='InteractiveShell.cache_size',
94 colors='InteractiveShell.colors',
95 logfile='InteractiveShell.logfile',
96 log_append='InteractiveShell.logappend',
97 c='InteractiveShellApp.code_to_run',
98 ext='InteractiveShellApp.extra_extension',
99 )
100
101 #-----------------------------------------------------------------------------
102 # Main classes and functions
103 #-----------------------------------------------------------------------------
104
105 class InteractiveShellApp(Configurable):
106 """A Mixin for applications that start InteractiveShell instances.
107
108 Provides configurables for loading extensions and executing files
109 as part of configuring a Shell environment.
110
111 Provides init_extensions() and init_code() methods, to be called
112 after init_shell(), which must be implemented by subclasses.
113 """
114 extensions = List(Unicode, config=True,
115 help="A list of dotted module names of IPython extensions to load."
116 )
117 extra_extension = Unicode('', config=True,
118 help="dotted module name of an IPython extension to load."
119 )
120 def _extra_extension_changed(self, name, old, new):
121 if new:
122 # add to self.extensions
123 self.extensions.append(new)
124
125 exec_files = List(Unicode, config=True,
126 help="""List of files to run at IPython startup."""
127 )
128 file_to_run = Unicode('', config=True,
129 help="""A file to be run""")
130
131 exec_lines = List(Unicode, config=True,
132 help="""lines of code to run at IPython startup."""
133 )
134 code_to_run = Unicode('', config=True,
135 help="Execute the given command string."
136 )
137 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
138
139 def init_shell(self):
140 raise NotImplementedError("Override in subclasses")
141
142 def init_extensions(self):
143 """Load all IPython extensions in IPythonApp.extensions.
144
145 This uses the :meth:`ExtensionManager.load_extensions` to load all
146 the extensions listed in ``self.extensions``.
147 """
148 if not self.extensions:
149 return
150 try:
151 self.log.debug("Loading IPython extensions...")
152 extensions = self.extensions
153 for ext in extensions:
154 try:
155 self.log.info("Loading IPython extension: %s" % ext)
156 self.shell.extension_manager.load_extension(ext)
157 except:
158 self.log.warn("Error in loading extension: %s" % ext)
159 self.shell.showtraceback()
160 except:
161 self.log.warn("Unknown error in loading extensions:")
162 self.shell.showtraceback()
163
164 def init_code(self):
165 """run the pre-flight code, specified via exec_lines"""
166 self._run_exec_lines()
167 self._run_exec_files()
168 self._run_cmd_line_code()
169
170 def _run_exec_lines(self):
171 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
172 if not self.exec_lines:
173 return
174 try:
175 self.log.debug("Running code from IPythonApp.exec_lines...")
176 for line in self.exec_lines:
177 try:
178 self.log.info("Running code in user namespace: %s" %
179 line)
180 self.shell.run_cell(line, store_history=False)
181 except:
182 self.log.warn("Error in executing line in user "
183 "namespace: %s" % line)
184 self.shell.showtraceback()
185 except:
186 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
187 self.shell.showtraceback()
188
189 def _exec_file(self, fname):
190 full_filename = filefind(fname, [u'.', self.ipython_dir])
191 if os.path.isfile(full_filename):
192 if full_filename.endswith(u'.py'):
193 self.log.info("Running file in user namespace: %s" %
194 full_filename)
195 # Ensure that __file__ is always defined to match Python behavior
196 self.shell.user_ns['__file__'] = fname
197 try:
198 self.shell.safe_execfile(full_filename, self.shell.user_ns)
199 finally:
200 del self.shell.user_ns['__file__']
201 elif full_filename.endswith('.ipy'):
202 self.log.info("Running file in user namespace: %s" %
203 full_filename)
204 self.shell.safe_execfile_ipy(full_filename)
205 else:
206 self.log.warn("File does not have a .py or .ipy extension: <%s>"
207 % full_filename)
208
209 def _run_exec_files(self):
210 """Run files from IPythonApp.exec_files"""
211 if not self.exec_files:
212 return
213
214 self.log.debug("Running files in IPythonApp.exec_files...")
215 try:
216 for fname in self.exec_files:
217 self._exec_file(fname)
218 except:
219 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
220 self.shell.showtraceback()
221
222 def _run_cmd_line_code(self):
223 """Run code or file specified at the command-line"""
224 if self.code_to_run:
225 line = self.code_to_run
226 try:
227 self.log.info("Running code given at command line (c=): %s" %
228 line)
229 self.shell.run_cell(line, store_history=False)
230 except:
231 self.log.warn("Error in executing line in user namespace: %s" %
232 line)
233 self.shell.showtraceback()
234
235 # Like Python itself, ignore the second if the first of these is present
236 elif self.file_to_run:
237 fname = self.file_to_run
238 try:
239 self._exec_file(fname)
240 except:
241 self.log.warn("Error in executing file in user namespace: %s" %
242 fname)
243 self.shell.showtraceback()
244
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,230 +1,393 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A base class for a configurable application.
3 A base class for a configurable application.
4
4
5 Authors:
5 Authors:
6
6
7 * Brian Granger
7 * Brian Granger
8 * Min RK
8 """
9 """
9
10
10 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
12 #
13 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
16
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Imports
19 # Imports
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20
21
21 from copy import deepcopy
22 import logging
22 import logging
23 import os
24 import re
23 import sys
25 import sys
26 from copy import deepcopy
24
27
25 from IPython.config.configurable import SingletonConfigurable
28 from IPython.config.configurable import SingletonConfigurable
26 from IPython.config.loader import (
29 from IPython.config.loader import (
27 KeyValueConfigLoader, PyFileConfigLoader, Config
30 KeyValueConfigLoader, PyFileConfigLoader, Config, ArgumentError
28 )
31 )
29
32
30 from IPython.utils.traitlets import (
33 from IPython.utils.traitlets import (
31 Unicode, List, Int, Enum, Dict
34 Unicode, List, Int, Enum, Dict, Instance
32 )
35 )
33 from IPython.utils.text import indent
36 from IPython.utils.importstring import import_item
37 from IPython.utils.text import indent, wrap_paragraphs, dedent
38
39 #-----------------------------------------------------------------------------
40 # function for re-wrapping a helpstring
41 #-----------------------------------------------------------------------------
34
42
35 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
36 # Descriptions for
44 # Descriptions for the various sections
37 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
38
46
39 flag_description = """
47 flag_description = """
40 Flags are command-line arguments passed as '--<flag>'.
48 Flags are command-line arguments passed as '--<flag>'.
41 These take no parameters, unlike regular key-value arguments.
49 These take no parameters, unlike regular key-value arguments.
42 They are typically used for setting boolean flags, or enabling
50 They are typically used for setting boolean flags, or enabling
43 modes that involve setting multiple options together.
51 modes that involve setting multiple options together.
52
53 Flags *always* begin with '--', never just one '-'.
44 """.strip() # trim newlines of front and back
54 """.strip() # trim newlines of front and back
45
55
46 alias_description = """
56 alias_description = """
47 These are commonly set parameters, given abbreviated aliases for convenience.
57 These are commonly set parameters, given abbreviated aliases for convenience.
48 They are set in the same `name=value` way as class parameters, where
58 They are set in the same `name=value` way as class parameters, where
49 <name> is replaced by the real parameter for which it is an alias.
59 <name> is replaced by the real parameter for which it is an alias.
50 """.strip() # trim newlines of front and back
60 """.strip() # trim newlines of front and back
51
61
52 keyvalue_description = """
62 keyvalue_description = """
53 Parameters are set from command-line arguments of the form:
63 Parameters are set from command-line arguments of the form:
54 `Class.trait=value`. Parameters will *never* be prefixed with '-'.
64 `Class.trait=value`. Parameters will *never* be prefixed with '-'.
55 This line is evaluated in Python, so simple expressions are allowed, e.g.
65 This line is evaluated in Python, so simple expressions are allowed, e.g.
56 `C.a='range(3)'` For setting C.a=[0,1,2]
66 `C.a='range(3)'` For setting C.a=[0,1,2]
57 """.strip() # trim newlines of front and back
67 """.strip() # trim newlines of front and back
58
68
59 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
60 # Application class
70 # Application class
61 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
62
72
63
73
74 class ApplicationError(Exception):
75 pass
76
77
64 class Application(SingletonConfigurable):
78 class Application(SingletonConfigurable):
65 """A singleton application with full configuration support."""
79 """A singleton application with full configuration support."""
66
80
67 # The name of the application, will usually match the name of the command
81 # The name of the application, will usually match the name of the command
68 # line application
82 # line application
69 app_name = Unicode(u'application')
83 name = Unicode(u'application')
70
84
71 # The description of the application that is printed at the beginning
85 # The description of the application that is printed at the beginning
72 # of the help.
86 # of the help.
73 description = Unicode(u'This is an application.')
87 description = Unicode(u'This is an application.')
74 # default section descriptions
88 # default section descriptions
75 flag_description = Unicode(flag_description)
89 flag_description = Unicode(flag_description)
76 alias_description = Unicode(alias_description)
90 alias_description = Unicode(alias_description)
77 keyvalue_description = Unicode(keyvalue_description)
91 keyvalue_description = Unicode(keyvalue_description)
78
92
79
93
80 # A sequence of Configurable subclasses whose config=True attributes will
94 # A sequence of Configurable subclasses whose config=True attributes will
81 # be exposed at the command line.
95 # be exposed at the command line.
82 classes = List([])
96 classes = List([])
83
97
84 # The version string of this application.
98 # The version string of this application.
85 version = Unicode(u'0.0')
99 version = Unicode(u'0.0')
86
100
87 # The log level for the application
101 # The log level for the application
88 log_level = Enum((0,10,20,30,40,50), default_value=logging.WARN,
102 log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
89 config=True,
103 default_value=logging.WARN,
90 help="Set the log level (0,10,20,30,40,50).")
104 config=True,
105 help="Set the log level by value or name.")
106 def _log_level_changed(self, name, old, new):
107 """Adjust the log level when log_level is set."""
108 if isinstance(new, basestring):
109 new = getattr(logging, new)
110 self.log_level = new
111 self.log.setLevel(new)
91
112
92 # the alias map for configurables
113 # the alias map for configurables
93 aliases = Dict(dict(log_level='Application.log_level'))
114 aliases = Dict(dict(log_level='Application.log_level'))
94
115
95 # flags for loading Configurables or store_const style flags
116 # flags for loading Configurables or store_const style flags
96 # flags are loaded from this dict by '--key' flags
117 # flags are loaded from this dict by '--key' flags
97 # this must be a dict of two-tuples, the first element being the Config/dict
118 # this must be a dict of two-tuples, the first element being the Config/dict
98 # and the second being the help string for the flag
119 # and the second being the help string for the flag
99 flags = Dict()
120 flags = Dict()
121 def _flags_changed(self, name, old, new):
122 """ensure flags dict is valid"""
123 for key,value in new.iteritems():
124 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
125 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
126 assert isinstance(value[1], basestring), "Bad flag: %r:%s"%(key,value)
127
128
129 # subcommands for launching other applications
130 # if this is not empty, this will be a parent Application
131 # this must be a dict of two-tuples,
132 # the first element being the application class/import string
133 # and the second being the help string for the subcommand
134 subcommands = Dict()
135 # parse_command_line will initialize a subapp, if requested
136 subapp = Instance('IPython.config.application.Application', allow_none=True)
137
138 # extra command-line arguments that don't set config values
139 extra_args = List(Unicode)
100
140
101
141
102 def __init__(self, **kwargs):
142 def __init__(self, **kwargs):
103 SingletonConfigurable.__init__(self, **kwargs)
143 SingletonConfigurable.__init__(self, **kwargs)
104 # Add my class to self.classes so my attributes appear in command line
144 # Add my class to self.classes so my attributes appear in command line
105 # options.
145 # options.
106 self.classes.insert(0, self.__class__)
146 self.classes.insert(0, self.__class__)
107
147
108 # ensure self.flags dict is valid
109 for key,value in self.flags.iteritems():
110 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
111 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
112 assert isinstance(value[1], basestring), "Bad flag: %r:%s"%(key,value)
113 self.init_logging()
148 self.init_logging()
114
149
150 def _config_changed(self, name, old, new):
151 SingletonConfigurable._config_changed(self, name, old, new)
152 self.log.debug('Config changed:')
153 self.log.debug(repr(new))
154
115 def init_logging(self):
155 def init_logging(self):
116 """Start logging for this application.
156 """Start logging for this application.
117
157
118 The default is to log to stdout using a StreaHandler. The log level
158 The default is to log to stdout using a StreaHandler. The log level
119 starts at loggin.WARN, but this can be adjusted by setting the
159 starts at loggin.WARN, but this can be adjusted by setting the
120 ``log_level`` attribute.
160 ``log_level`` attribute.
121 """
161 """
122 self.log = logging.getLogger(self.__class__.__name__)
162 self.log = logging.getLogger(self.__class__.__name__)
123 self.log.setLevel(self.log_level)
163 self.log.setLevel(self.log_level)
124 self._log_handler = logging.StreamHandler()
164 self._log_handler = logging.StreamHandler()
125 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
165 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
126 self._log_handler.setFormatter(self._log_formatter)
166 self._log_handler.setFormatter(self._log_formatter)
127 self.log.addHandler(self._log_handler)
167 self.log.addHandler(self._log_handler)
128
168
129 def _log_level_changed(self, name, old, new):
169 def initialize(self, argv=None):
130 """Adjust the log level when log_level is set."""
170 """Do the basic steps to configure me.
131 self.log.setLevel(new)
171
172 Override in subclasses.
173 """
174 self.parse_command_line(argv)
175
176
177 def start(self):
178 """Start the app mainloop.
179
180 Override in subclasses.
181 """
182 if self.subapp is not None:
183 return self.subapp.start()
132
184
133 def print_alias_help(self):
185 def print_alias_help(self):
134 """print the alias part of the help"""
186 """Print the alias part of the help."""
135 if not self.aliases:
187 if not self.aliases:
136 return
188 return
137
189
138 print "Aliases"
190 lines = ['Aliases']
139 print "-------"
191 lines.append('-'*len(lines[0]))
140 print self.alias_description
192 lines.append('')
141 print
193 for p in wrap_paragraphs(self.alias_description):
194 lines.append(p)
195 lines.append('')
142
196
143 classdict = {}
197 classdict = {}
144 for c in self.classes:
198 for cls in self.classes:
145 classdict[c.__name__] = c
199 # include all parents (up to, but excluding Configurable) in available names
200 for c in cls.mro()[:-3]:
201 classdict[c.__name__] = c
146
202
147 for alias, longname in self.aliases.iteritems():
203 for alias, longname in self.aliases.iteritems():
148 classname, traitname = longname.split('.',1)
204 classname, traitname = longname.split('.',1)
149 cls = classdict[classname]
205 cls = classdict[classname]
150
206
151 trait = cls.class_traits(config=True)[traitname]
207 trait = cls.class_traits(config=True)[traitname]
152 help = trait.get_metadata('help')
208 help = cls.class_get_trait_help(trait)
153 print alias, "(%s)"%longname, ':', trait.__class__.__name__
209 help = help.replace(longname, "%s (%s)"%(alias, longname), 1)
154 if help:
210 lines.append(help)
155 print indent(help)
211 lines.append('')
156 print
212 print '\n'.join(lines)
157
213
158 def print_flag_help(self):
214 def print_flag_help(self):
159 """print the flag part of the help"""
215 """Print the flag part of the help."""
160 if not self.flags:
216 if not self.flags:
161 return
217 return
162
218
163 print "Flags"
219 lines = ['Flags']
164 print "-----"
220 lines.append('-'*len(lines[0]))
165 print self.flag_description
221 lines.append('')
166 print
222 for p in wrap_paragraphs(self.flag_description):
223 lines.append(p)
224 lines.append('')
167
225
168 for m, (cfg,help) in self.flags.iteritems():
226 for m, (cfg,help) in self.flags.iteritems():
169 print '--'+m
227 lines.append('--'+m)
170 print indent(help)
228 lines.append(indent(dedent(help.strip())))
171 print
229 lines.append('')
230 print '\n'.join(lines)
172
231
173 def print_help(self):
232 def print_subcommands(self):
174 """Print the help for each Configurable class in self.classes."""
233 """Print the subcommand part of the help."""
234 if not self.subcommands:
235 return
236
237 lines = ["Subcommands"]
238 lines.append('-'*len(lines[0]))
239 for subc, (cls,help) in self.subcommands.iteritems():
240 lines.append("%s : %s"%(subc, cls))
241 if help:
242 lines.append(indent(dedent(help.strip())))
243 lines.append('')
244 print '\n'.join(lines)
245
246 def print_help(self, classes=False):
247 """Print the help for each Configurable class in self.classes.
248
249 If classes=False (the default), only flags and aliases are printed.
250 """
251 self.print_subcommands()
175 self.print_flag_help()
252 self.print_flag_help()
176 self.print_alias_help()
253 self.print_alias_help()
177 if self.classes:
178 print "Class parameters"
179 print "----------------"
180 print self.keyvalue_description
181 print
182
254
183 for cls in self.classes:
255 if classes:
184 cls.class_print_help()
256 if self.classes:
257 print "Class parameters"
258 print "----------------"
259 print
260 for p in wrap_paragraphs(self.keyvalue_description):
261 print p
262 print
263
264 for cls in self.classes:
265 cls.class_print_help()
266 print
267 else:
268 print "To see all available configurables, use `--help-all`"
185 print
269 print
186
270
187 def print_description(self):
271 def print_description(self):
188 """Print the application description."""
272 """Print the application description."""
189 print self.description
273 for p in wrap_paragraphs(self.description):
190 print
274 print p
275 print
191
276
192 def print_version(self):
277 def print_version(self):
193 """Print the version string."""
278 """Print the version string."""
194 print self.version
279 print self.version
195
280
196 def update_config(self, config):
281 def update_config(self, config):
197 """Fire the traits events when the config is updated."""
282 """Fire the traits events when the config is updated."""
198 # Save a copy of the current config.
283 # Save a copy of the current config.
199 newconfig = deepcopy(self.config)
284 newconfig = deepcopy(self.config)
200 # Merge the new config into the current one.
285 # Merge the new config into the current one.
201 newconfig._merge(config)
286 newconfig._merge(config)
202 # Save the combined config as self.config, which triggers the traits
287 # Save the combined config as self.config, which triggers the traits
203 # events.
288 # events.
204 self.config = config
289 self.config = newconfig
205
290
291 def initialize_subcommand(self, subc, argv=None):
292 """Initialize a subcommand with argv."""
293 subapp,help = self.subcommands.get(subc)
294
295 if isinstance(subapp, basestring):
296 subapp = import_item(subapp)
297
298 # clear existing instances
299 self.__class__.clear_instance()
300 # instantiate
301 self.subapp = subapp.instance()
302 # and initialize subapp
303 self.subapp.initialize(argv)
304
206 def parse_command_line(self, argv=None):
305 def parse_command_line(self, argv=None):
207 """Parse the command line arguments."""
306 """Parse the command line arguments."""
208 argv = sys.argv[1:] if argv is None else argv
307 argv = sys.argv[1:] if argv is None else argv
209
308
210 if '-h' in argv or '--help' in argv:
309 if self.subcommands and len(argv) > 0:
310 # we have subcommands, and one may have been specified
311 subc, subargv = argv[0], argv[1:]
312 if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
313 # it's a subcommand, and *not* a flag or class parameter
314 return self.initialize_subcommand(subc, subargv)
315
316 if '-h' in argv or '--help' in argv or '--help-all' in argv:
211 self.print_description()
317 self.print_description()
212 self.print_help()
318 self.print_help('--help-all' in argv)
213 sys.exit(1)
319 self.exit(0)
214
320
215 if '--version' in argv:
321 if '--version' in argv:
216 self.print_version()
322 self.print_version()
217 sys.exit(1)
323 self.exit(0)
218
324
219 loader = KeyValueConfigLoader(argv=argv, aliases=self.aliases,
325 loader = KeyValueConfigLoader(argv=argv, aliases=self.aliases,
220 flags=self.flags)
326 flags=self.flags)
221 config = loader.load_config()
327 try:
328 config = loader.load_config()
329 except ArgumentError as e:
330 self.log.fatal(str(e))
331 self.print_description()
332 self.print_help()
333 self.exit(1)
222 self.update_config(config)
334 self.update_config(config)
335 # store unparsed args in extra_args
336 self.extra_args = loader.extra_args
223
337
224 def load_config_file(self, filename, path=None):
338 def load_config_file(self, filename, path=None):
225 """Load a .py based config file by filename and path."""
339 """Load a .py based config file by filename and path."""
226 # TODO: this raises IOError if filename does not exist.
227 loader = PyFileConfigLoader(filename, path=path)
340 loader = PyFileConfigLoader(filename, path=path)
228 config = loader.load_config()
341 config = loader.load_config()
229 self.update_config(config)
342 self.update_config(config)
343
344 def generate_config_file(self):
345 """generate default config file from Configurables"""
346 lines = ["# Configuration file for %s."%self.name]
347 lines.append('')
348 lines.append('c = get_config()')
349 lines.append('')
350 for cls in self.classes:
351 lines.append(cls.class_config_section())
352 return '\n'.join(lines)
353
354 def exit(self, exit_status=0):
355 self.log.debug("Exiting application: %s" % self.name)
356 sys.exit(exit_status)
357
358 #-----------------------------------------------------------------------------
359 # utility functions, for convenience
360 #-----------------------------------------------------------------------------
361
362 def boolean_flag(name, configurable, set_help='', unset_help=''):
363 """Helper for building basic --trait, --no-trait flags.
364
365 Parameters
366 ----------
367
368 name : str
369 The name of the flag.
370 configurable : str
371 The 'Class.trait' string of the trait to be set/unset with the flag
372 set_help : unicode
373 help string for --name flag
374 unset_help : unicode
375 help string for --no-name flag
376
377 Returns
378 -------
379
380 cfg : dict
381 A dict with two keys: 'name', and 'no-name', for setting and unsetting
382 the trait, respectively.
383 """
384 # default helpstrings
385 set_help = set_help or "set %s=True"%configurable
386 unset_help = unset_help or "set %s=False"%configurable
387
388 cls,trait = configurable.split('.')
389
390 setter = {cls : {trait : True}}
391 unsetter = {cls : {trait : False}}
392 return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)}
230
393
@@ -1,225 +1,315 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A base class for objects that are configurable.
4 A base class for objects that are configurable.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 * Min RK
10 """
11 """
11
12
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2010 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
14 #
15 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18
19
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20 # Imports
21 # Imports
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22
23
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from copy import deepcopy
25
26
26 from loader import Config
27 from loader import Config
27 from IPython.utils.traitlets import HasTraits, Instance
28 from IPython.utils.traitlets import HasTraits, Instance
28 from IPython.utils.text import indent
29 from IPython.utils.text import indent, wrap_paragraphs
29
30
30
31
31 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
32 # Helper classes for Configurables
33 # Helper classes for Configurables
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34
35
35
36
36 class ConfigurableError(Exception):
37 class ConfigurableError(Exception):
37 pass
38 pass
38
39
39
40
40 class MultipleInstanceError(ConfigurableError):
41 class MultipleInstanceError(ConfigurableError):
41 pass
42 pass
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44 # Configurable implementation
45 # Configurable implementation
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46
47
47
48 class Configurable(HasTraits):
48 class Configurable(HasTraits):
49
49
50 config = Instance(Config,(),{})
50 config = Instance(Config,(),{})
51 created = None
51 created = None
52
52
53 def __init__(self, **kwargs):
53 def __init__(self, **kwargs):
54 """Create a conigurable given a config config.
54 """Create a configurable given a config config.
55
55
56 Parameters
56 Parameters
57 ----------
57 ----------
58 config : Config
58 config : Config
59 If this is empty, default values are used. If config is a
59 If this is empty, default values are used. If config is a
60 :class:`Config` instance, it will be used to configure the
60 :class:`Config` instance, it will be used to configure the
61 instance.
61 instance.
62
62
63 Notes
63 Notes
64 -----
64 -----
65 Subclasses of Configurable must call the :meth:`__init__` method of
65 Subclasses of Configurable must call the :meth:`__init__` method of
66 :class:`Configurable` *before* doing anything else and using
66 :class:`Configurable` *before* doing anything else and using
67 :func:`super`::
67 :func:`super`::
68
68
69 class MyConfigurable(Configurable):
69 class MyConfigurable(Configurable):
70 def __init__(self, config=None):
70 def __init__(self, config=None):
71 super(MyConfigurable, self).__init__(config)
71 super(MyConfigurable, self).__init__(config)
72 # Then any other code you need to finish initialization.
72 # Then any other code you need to finish initialization.
73
73
74 This ensures that instances will be configured properly.
74 This ensures that instances will be configured properly.
75 """
75 """
76 config = kwargs.pop('config', None)
76 config = kwargs.pop('config', None)
77 if config is not None:
77 if config is not None:
78 # We used to deepcopy, but for now we are trying to just save
78 # We used to deepcopy, but for now we are trying to just save
79 # by reference. This *could* have side effects as all components
79 # by reference. This *could* have side effects as all components
80 # will share config. In fact, I did find such a side effect in
80 # will share config. In fact, I did find such a side effect in
81 # _config_changed below. If a config attribute value was a mutable type
81 # _config_changed below. If a config attribute value was a mutable type
82 # all instances of a component were getting the same copy, effectively
82 # all instances of a component were getting the same copy, effectively
83 # making that a class attribute.
83 # making that a class attribute.
84 # self.config = deepcopy(config)
84 # self.config = deepcopy(config)
85 self.config = config
85 self.config = config
86 # This should go second so individual keyword arguments override
86 # This should go second so individual keyword arguments override
87 # the values in config.
87 # the values in config.
88 super(Configurable, self).__init__(**kwargs)
88 super(Configurable, self).__init__(**kwargs)
89 self.created = datetime.datetime.now()
89 self.created = datetime.datetime.now()
90
90
91 #-------------------------------------------------------------------------
91 #-------------------------------------------------------------------------
92 # Static trait notifiations
92 # Static trait notifiations
93 #-------------------------------------------------------------------------
93 #-------------------------------------------------------------------------
94
94
95 def _config_changed(self, name, old, new):
95 def _config_changed(self, name, old, new):
96 """Update all the class traits having ``config=True`` as metadata.
96 """Update all the class traits having ``config=True`` as metadata.
97
97
98 For any class trait with a ``config`` metadata attribute that is
98 For any class trait with a ``config`` metadata attribute that is
99 ``True``, we update the trait with the value of the corresponding
99 ``True``, we update the trait with the value of the corresponding
100 config entry.
100 config entry.
101 """
101 """
102 # Get all traits with a config metadata entry that is True
102 # Get all traits with a config metadata entry that is True
103 traits = self.traits(config=True)
103 traits = self.traits(config=True)
104
104
105 # We auto-load config section for this class as well as any parent
105 # We auto-load config section for this class as well as any parent
106 # classes that are Configurable subclasses. This starts with Configurable
106 # classes that are Configurable subclasses. This starts with Configurable
107 # and works down the mro loading the config for each section.
107 # and works down the mro loading the config for each section.
108 section_names = [cls.__name__ for cls in \
108 section_names = [cls.__name__ for cls in \
109 reversed(self.__class__.__mro__) if
109 reversed(self.__class__.__mro__) if
110 issubclass(cls, Configurable) and issubclass(self.__class__, cls)]
110 issubclass(cls, Configurable) and issubclass(self.__class__, cls)]
111
111
112 for sname in section_names:
112 for sname in section_names:
113 # Don't do a blind getattr as that would cause the config to
113 # Don't do a blind getattr as that would cause the config to
114 # dynamically create the section with name self.__class__.__name__.
114 # dynamically create the section with name self.__class__.__name__.
115 if new._has_section(sname):
115 if new._has_section(sname):
116 my_config = new[sname]
116 my_config = new[sname]
117 for k, v in traits.iteritems():
117 for k, v in traits.iteritems():
118 # Don't allow traitlets with config=True to start with
118 # Don't allow traitlets with config=True to start with
119 # uppercase. Otherwise, they are confused with Config
119 # uppercase. Otherwise, they are confused with Config
120 # subsections. But, developers shouldn't have uppercase
120 # subsections. But, developers shouldn't have uppercase
121 # attributes anyways! (PEP 6)
121 # attributes anyways! (PEP 6)
122 if k[0].upper()==k[0] and not k.startswith('_'):
122 if k[0].upper()==k[0] and not k.startswith('_'):
123 raise ConfigurableError('Configurable traitlets with '
123 raise ConfigurableError('Configurable traitlets with '
124 'config=True must start with a lowercase so they are '
124 'config=True must start with a lowercase so they are '
125 'not confused with Config subsections: %s.%s' % \
125 'not confused with Config subsections: %s.%s' % \
126 (self.__class__.__name__, k))
126 (self.__class__.__name__, k))
127 try:
127 try:
128 # Here we grab the value from the config
128 # Here we grab the value from the config
129 # If k has the naming convention of a config
129 # If k has the naming convention of a config
130 # section, it will be auto created.
130 # section, it will be auto created.
131 config_value = my_config[k]
131 config_value = my_config[k]
132 except KeyError:
132 except KeyError:
133 pass
133 pass
134 else:
134 else:
135 # print "Setting %s.%s from %s.%s=%r" % \
135 # print "Setting %s.%s from %s.%s=%r" % \
136 # (self.__class__.__name__,k,sname,k,config_value)
136 # (self.__class__.__name__,k,sname,k,config_value)
137 # We have to do a deepcopy here if we don't deepcopy the entire
137 # We have to do a deepcopy here if we don't deepcopy the entire
138 # config object. If we don't, a mutable config_value will be
138 # config object. If we don't, a mutable config_value will be
139 # shared by all instances, effectively making it a class attribute.
139 # shared by all instances, effectively making it a class attribute.
140 setattr(self, k, deepcopy(config_value))
140 setattr(self, k, deepcopy(config_value))
141
141
142 @classmethod
142 @classmethod
143 def class_get_help(cls):
143 def class_get_help(cls):
144 """Get the help string for this class in ReST format."""
144 """Get the help string for this class in ReST format."""
145 cls_traits = cls.class_traits(config=True)
145 cls_traits = cls.class_traits(config=True)
146 final_help = []
146 final_help = []
147 final_help.append(u'%s options' % cls.__name__)
147 final_help.append(u'%s options' % cls.__name__)
148 final_help.append(len(final_help[0])*u'-')
148 final_help.append(len(final_help[0])*u'-')
149 for k, v in cls_traits.items():
149 for k,v in cls.class_traits(config=True).iteritems():
150 help = v.get_metadata('help')
150 help = cls.class_get_trait_help(v)
151 header = "%s.%s : %s" % (cls.__name__, k, v.__class__.__name__)
151 final_help.append(help)
152 final_help.append(header)
153 if help is not None:
154 final_help.append(indent(help))
155 return '\n'.join(final_help)
152 return '\n'.join(final_help)
153
154 @classmethod
155 def class_get_trait_help(cls, trait):
156 """Get the help string for a single trait."""
157 lines = []
158 header = "%s.%s : %s" % (cls.__name__, trait.name, trait.__class__.__name__)
159 lines.append(header)
160 try:
161 dvr = repr(trait.get_default_value())
162 except Exception:
163 dvr = None # ignore defaults we can't construct
164 if dvr is not None:
165 if len(dvr) > 64:
166 dvr = dvr[:61]+'...'
167 lines.append(indent('Default: %s'%dvr, 4))
168 if 'Enum' in trait.__class__.__name__:
169 # include Enum choices
170 lines.append(indent('Choices: %r'%(trait.values,)))
171
172 help = trait.get_metadata('help')
173 if help is not None:
174 help = '\n'.join(wrap_paragraphs(help, 76))
175 lines.append(indent(help, 4))
176 return '\n'.join(lines)
156
177
157 @classmethod
178 @classmethod
158 def class_print_help(cls):
179 def class_print_help(cls):
180 """Get the help string for a single trait and print it."""
159 print cls.class_get_help()
181 print cls.class_get_help()
160
182
183 @classmethod
184 def class_config_section(cls):
185 """Get the config class config section"""
186 def c(s):
187 """return a commented, wrapped block."""
188 s = '\n\n'.join(wrap_paragraphs(s, 78))
189
190 return '# ' + s.replace('\n', '\n# ')
191
192 # section header
193 breaker = '#' + '-'*78
194 s = "# %s configuration"%cls.__name__
195 lines = [breaker, s, breaker, '']
196 # get the description trait
197 desc = cls.class_traits().get('description')
198 if desc:
199 desc = desc.default_value
200 else:
201 # no description trait, use __doc__
202 desc = getattr(cls, '__doc__', '')
203 if desc:
204 lines.append(c(desc))
205 lines.append('')
206
207 for name,trait in cls.class_traits(config=True).iteritems():
208 help = trait.get_metadata('help') or ''
209 lines.append(c(help))
210 lines.append('# c.%s.%s = %r'%(cls.__name__, name, trait.get_default_value()))
211 lines.append('')
212 return '\n'.join(lines)
213
214
161
215
162 class SingletonConfigurable(Configurable):
216 class SingletonConfigurable(Configurable):
163 """A configurable that only allows one instance.
217 """A configurable that only allows one instance.
164
218
165 This class is for classes that should only have one instance of itself
219 This class is for classes that should only have one instance of itself
166 or *any* subclass. To create and retrieve such a class use the
220 or *any* subclass. To create and retrieve such a class use the
167 :meth:`SingletonConfigurable.instance` method.
221 :meth:`SingletonConfigurable.instance` method.
168 """
222 """
169
223
170 _instance = None
224 _instance = None
171
225
226 @classmethod
227 def _walk_mro(cls):
228 """Walk the cls.mro() for parent classes that are also singletons
229
230 For use in instance()
231 """
232
233 for subclass in cls.mro():
234 if issubclass(cls, subclass) and \
235 issubclass(subclass, SingletonConfigurable) and \
236 subclass != SingletonConfigurable:
237 yield subclass
238
239 @classmethod
240 def clear_instance(cls):
241 """unset _instance for this class and singleton parents.
242 """
243 if not cls.initialized():
244 return
245 for subclass in cls._walk_mro():
246 if isinstance(subclass._instance, cls):
247 # only clear instances that are instances
248 # of the calling class
249 subclass._instance = None
250
172 @classmethod
251 @classmethod
173 def instance(cls, *args, **kwargs):
252 def instance(cls, *args, **kwargs):
174 """Returns a global instance of this class.
253 """Returns a global instance of this class.
175
254
176 This method create a new instance if none have previously been created
255 This method create a new instance if none have previously been created
177 and returns a previously created instance is one already exists.
256 and returns a previously created instance is one already exists.
178
257
179 The arguments and keyword arguments passed to this method are passed
258 The arguments and keyword arguments passed to this method are passed
180 on to the :meth:`__init__` method of the class upon instantiation.
259 on to the :meth:`__init__` method of the class upon instantiation.
181
260
182 Examples
261 Examples
183 --------
262 --------
184
263
185 Create a singleton class using instance, and retrieve it::
264 Create a singleton class using instance, and retrieve it::
186
265
187 >>> from IPython.config.configurable import SingletonConfigurable
266 >>> from IPython.config.configurable import SingletonConfigurable
188 >>> class Foo(SingletonConfigurable): pass
267 >>> class Foo(SingletonConfigurable): pass
189 >>> foo = Foo.instance()
268 >>> foo = Foo.instance()
190 >>> foo == Foo.instance()
269 >>> foo == Foo.instance()
191 True
270 True
192
271
193 Create a subclass that is retrived using the base class instance::
272 Create a subclass that is retrived using the base class instance::
194
273
195 >>> class Bar(SingletonConfigurable): pass
274 >>> class Bar(SingletonConfigurable): pass
196 >>> class Bam(Bar): pass
275 >>> class Bam(Bar): pass
197 >>> bam = Bam.instance()
276 >>> bam = Bam.instance()
198 >>> bam == Bar.instance()
277 >>> bam == Bar.instance()
199 True
278 True
200 """
279 """
201 # Create and save the instance
280 # Create and save the instance
202 if cls._instance is None:
281 if cls._instance is None:
203 inst = cls(*args, **kwargs)
282 inst = cls(*args, **kwargs)
204 # Now make sure that the instance will also be returned by
283 # Now make sure that the instance will also be returned by
205 # the subclasses instance attribute.
284 # parent classes' _instance attribute.
206 for subclass in cls.mro():
285 for subclass in cls._walk_mro():
207 if issubclass(cls, subclass) and \
286 subclass._instance = inst
208 issubclass(subclass, SingletonConfigurable) and \
287
209 subclass != SingletonConfigurable:
210 subclass._instance = inst
211 else:
212 break
213 if isinstance(cls._instance, cls):
288 if isinstance(cls._instance, cls):
214 return cls._instance
289 return cls._instance
215 else:
290 else:
216 raise MultipleInstanceError(
291 raise MultipleInstanceError(
217 'Multiple incompatible subclass instances of '
292 'Multiple incompatible subclass instances of '
218 '%s are being created.' % cls.__name__
293 '%s are being created.' % cls.__name__
219 )
294 )
220
295
221 @classmethod
296 @classmethod
222 def initialized(cls):
297 def initialized(cls):
223 """Has an instance been created?"""
298 """Has an instance been created?"""
224 return hasattr(cls, "_instance") and cls._instance is not None
299 return hasattr(cls, "_instance") and cls._instance is not None
225
300
301
302 class LoggingConfigurable(Configurable):
303 """A parent class for Configurables that log.
304
305 Subclasses have a log trait, and the default behavior
306 is to get the logger from the currently running Application
307 via Application.instance().log.
308 """
309
310 log = Instance('logging.Logger')
311 def _log_default(self):
312 from IPython.config.application import Application
313 return Application.instance().log
314
315
@@ -1,501 +1,541 b''
1 """A simple configuration system.
1 """A simple configuration system.
2
2
3 Authors
3 Authors
4 -------
4 -------
5 * Brian Granger
5 * Brian Granger
6 * Fernando Perez
6 * Fernando Perez
7 * Min RK
7 """
8 """
8
9
9 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2011 The IPython Development Team
11 #
12 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
17 # Imports
18 # Imports
18 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
19
20
20 import __builtin__
21 import __builtin__
21 import re
22 import re
22 import sys
23 import sys
23
24
24 from IPython.external import argparse
25 from IPython.external import argparse
25 from IPython.utils.path import filefind
26 from IPython.utils.path import filefind, get_ipython_dir
26
27
27 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
28 # Exceptions
29 # Exceptions
29 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
30
31
31
32
32 class ConfigError(Exception):
33 class ConfigError(Exception):
33 pass
34 pass
34
35
35
36
36 class ConfigLoaderError(ConfigError):
37 class ConfigLoaderError(ConfigError):
37 pass
38 pass
38
39
40 class ArgumentError(ConfigLoaderError):
41 pass
42
39 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
40 # Argparse fix
44 # Argparse fix
41 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
42
46
43 # Unfortunately argparse by default prints help messages to stderr instead of
47 # Unfortunately argparse by default prints help messages to stderr instead of
44 # stdout. This makes it annoying to capture long help screens at the command
48 # stdout. This makes it annoying to capture long help screens at the command
45 # line, since one must know how to pipe stderr, which many users don't know how
49 # line, since one must know how to pipe stderr, which many users don't know how
46 # to do. So we override the print_help method with one that defaults to
50 # to do. So we override the print_help method with one that defaults to
47 # stdout and use our class instead.
51 # stdout and use our class instead.
48
52
49 class ArgumentParser(argparse.ArgumentParser):
53 class ArgumentParser(argparse.ArgumentParser):
50 """Simple argparse subclass that prints help to stdout by default."""
54 """Simple argparse subclass that prints help to stdout by default."""
51
55
52 def print_help(self, file=None):
56 def print_help(self, file=None):
53 if file is None:
57 if file is None:
54 file = sys.stdout
58 file = sys.stdout
55 return super(ArgumentParser, self).print_help(file)
59 return super(ArgumentParser, self).print_help(file)
56
60
57 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
61 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
58
62
59 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
60 # Config class for holding config information
64 # Config class for holding config information
61 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
62
66
63
67
64 class Config(dict):
68 class Config(dict):
65 """An attribute based dict that can do smart merges."""
69 """An attribute based dict that can do smart merges."""
66
70
67 def __init__(self, *args, **kwds):
71 def __init__(self, *args, **kwds):
68 dict.__init__(self, *args, **kwds)
72 dict.__init__(self, *args, **kwds)
69 # This sets self.__dict__ = self, but it has to be done this way
73 # This sets self.__dict__ = self, but it has to be done this way
70 # because we are also overriding __setattr__.
74 # because we are also overriding __setattr__.
71 dict.__setattr__(self, '__dict__', self)
75 dict.__setattr__(self, '__dict__', self)
72
76
73 def _merge(self, other):
77 def _merge(self, other):
74 to_update = {}
78 to_update = {}
75 for k, v in other.iteritems():
79 for k, v in other.iteritems():
76 if not self.has_key(k):
80 if not self.has_key(k):
77 to_update[k] = v
81 to_update[k] = v
78 else: # I have this key
82 else: # I have this key
79 if isinstance(v, Config):
83 if isinstance(v, Config):
80 # Recursively merge common sub Configs
84 # Recursively merge common sub Configs
81 self[k]._merge(v)
85 self[k]._merge(v)
82 else:
86 else:
83 # Plain updates for non-Configs
87 # Plain updates for non-Configs
84 to_update[k] = v
88 to_update[k] = v
85
89
86 self.update(to_update)
90 self.update(to_update)
87
91
88 def _is_section_key(self, key):
92 def _is_section_key(self, key):
89 if key[0].upper()==key[0] and not key.startswith('_'):
93 if key[0].upper()==key[0] and not key.startswith('_'):
90 return True
94 return True
91 else:
95 else:
92 return False
96 return False
93
97
94 def __contains__(self, key):
98 def __contains__(self, key):
95 if self._is_section_key(key):
99 if self._is_section_key(key):
96 return True
100 return True
97 else:
101 else:
98 return super(Config, self).__contains__(key)
102 return super(Config, self).__contains__(key)
99 # .has_key is deprecated for dictionaries.
103 # .has_key is deprecated for dictionaries.
100 has_key = __contains__
104 has_key = __contains__
101
105
102 def _has_section(self, key):
106 def _has_section(self, key):
103 if self._is_section_key(key):
107 if self._is_section_key(key):
104 if super(Config, self).__contains__(key):
108 if super(Config, self).__contains__(key):
105 return True
109 return True
106 return False
110 return False
107
111
108 def copy(self):
112 def copy(self):
109 return type(self)(dict.copy(self))
113 return type(self)(dict.copy(self))
110
114
111 def __copy__(self):
115 def __copy__(self):
112 return self.copy()
116 return self.copy()
113
117
114 def __deepcopy__(self, memo):
118 def __deepcopy__(self, memo):
115 import copy
119 import copy
116 return type(self)(copy.deepcopy(self.items()))
120 return type(self)(copy.deepcopy(self.items()))
117
121
118 def __getitem__(self, key):
122 def __getitem__(self, key):
119 # We cannot use directly self._is_section_key, because it triggers
123 # We cannot use directly self._is_section_key, because it triggers
120 # infinite recursion on top of PyPy. Instead, we manually fish the
124 # infinite recursion on top of PyPy. Instead, we manually fish the
121 # bound method.
125 # bound method.
122 is_section_key = self.__class__._is_section_key.__get__(self)
126 is_section_key = self.__class__._is_section_key.__get__(self)
123
127
124 # Because we use this for an exec namespace, we need to delegate
128 # Because we use this for an exec namespace, we need to delegate
125 # the lookup of names in __builtin__ to itself. This means
129 # the lookup of names in __builtin__ to itself. This means
126 # that you can't have section or attribute names that are
130 # that you can't have section or attribute names that are
127 # builtins.
131 # builtins.
128 try:
132 try:
129 return getattr(__builtin__, key)
133 return getattr(__builtin__, key)
130 except AttributeError:
134 except AttributeError:
131 pass
135 pass
132 if is_section_key(key):
136 if is_section_key(key):
133 try:
137 try:
134 return dict.__getitem__(self, key)
138 return dict.__getitem__(self, key)
135 except KeyError:
139 except KeyError:
136 c = Config()
140 c = Config()
137 dict.__setitem__(self, key, c)
141 dict.__setitem__(self, key, c)
138 return c
142 return c
139 else:
143 else:
140 return dict.__getitem__(self, key)
144 return dict.__getitem__(self, key)
141
145
142 def __setitem__(self, key, value):
146 def __setitem__(self, key, value):
143 # Don't allow names in __builtin__ to be modified.
147 # Don't allow names in __builtin__ to be modified.
144 if hasattr(__builtin__, key):
148 if hasattr(__builtin__, key):
145 raise ConfigError('Config variable names cannot have the same name '
149 raise ConfigError('Config variable names cannot have the same name '
146 'as a Python builtin: %s' % key)
150 'as a Python builtin: %s' % key)
147 if self._is_section_key(key):
151 if self._is_section_key(key):
148 if not isinstance(value, Config):
152 if not isinstance(value, Config):
149 raise ValueError('values whose keys begin with an uppercase '
153 raise ValueError('values whose keys begin with an uppercase '
150 'char must be Config instances: %r, %r' % (key, value))
154 'char must be Config instances: %r, %r' % (key, value))
151 else:
155 else:
152 dict.__setitem__(self, key, value)
156 dict.__setitem__(self, key, value)
153
157
154 def __getattr__(self, key):
158 def __getattr__(self, key):
155 try:
159 try:
156 return self.__getitem__(key)
160 return self.__getitem__(key)
157 except KeyError, e:
161 except KeyError, e:
158 raise AttributeError(e)
162 raise AttributeError(e)
159
163
160 def __setattr__(self, key, value):
164 def __setattr__(self, key, value):
161 try:
165 try:
162 self.__setitem__(key, value)
166 self.__setitem__(key, value)
163 except KeyError, e:
167 except KeyError, e:
164 raise AttributeError(e)
168 raise AttributeError(e)
165
169
166 def __delattr__(self, key):
170 def __delattr__(self, key):
167 try:
171 try:
168 dict.__delitem__(self, key)
172 dict.__delitem__(self, key)
169 except KeyError, e:
173 except KeyError, e:
170 raise AttributeError(e)
174 raise AttributeError(e)
171
175
172
176
173 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
174 # Config loading classes
178 # Config loading classes
175 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
176
180
177
181
178 class ConfigLoader(object):
182 class ConfigLoader(object):
179 """A object for loading configurations from just about anywhere.
183 """A object for loading configurations from just about anywhere.
180
184
181 The resulting configuration is packaged as a :class:`Struct`.
185 The resulting configuration is packaged as a :class:`Struct`.
182
186
183 Notes
187 Notes
184 -----
188 -----
185 A :class:`ConfigLoader` does one thing: load a config from a source
189 A :class:`ConfigLoader` does one thing: load a config from a source
186 (file, command line arguments) and returns the data as a :class:`Struct`.
190 (file, command line arguments) and returns the data as a :class:`Struct`.
187 There are lots of things that :class:`ConfigLoader` does not do. It does
191 There are lots of things that :class:`ConfigLoader` does not do. It does
188 not implement complex logic for finding config files. It does not handle
192 not implement complex logic for finding config files. It does not handle
189 default values or merge multiple configs. These things need to be
193 default values or merge multiple configs. These things need to be
190 handled elsewhere.
194 handled elsewhere.
191 """
195 """
192
196
193 def __init__(self):
197 def __init__(self):
194 """A base class for config loaders.
198 """A base class for config loaders.
195
199
196 Examples
200 Examples
197 --------
201 --------
198
202
199 >>> cl = ConfigLoader()
203 >>> cl = ConfigLoader()
200 >>> config = cl.load_config()
204 >>> config = cl.load_config()
201 >>> config
205 >>> config
202 {}
206 {}
203 """
207 """
204 self.clear()
208 self.clear()
205
209
206 def clear(self):
210 def clear(self):
207 self.config = Config()
211 self.config = Config()
208
212
209 def load_config(self):
213 def load_config(self):
210 """Load a config from somewhere, return a :class:`Config` instance.
214 """Load a config from somewhere, return a :class:`Config` instance.
211
215
212 Usually, this will cause self.config to be set and then returned.
216 Usually, this will cause self.config to be set and then returned.
213 However, in most cases, :meth:`ConfigLoader.clear` should be called
217 However, in most cases, :meth:`ConfigLoader.clear` should be called
214 to erase any previous state.
218 to erase any previous state.
215 """
219 """
216 self.clear()
220 self.clear()
217 return self.config
221 return self.config
218
222
219
223
220 class FileConfigLoader(ConfigLoader):
224 class FileConfigLoader(ConfigLoader):
221 """A base class for file based configurations.
225 """A base class for file based configurations.
222
226
223 As we add more file based config loaders, the common logic should go
227 As we add more file based config loaders, the common logic should go
224 here.
228 here.
225 """
229 """
226 pass
230 pass
227
231
228
232
229 class PyFileConfigLoader(FileConfigLoader):
233 class PyFileConfigLoader(FileConfigLoader):
230 """A config loader for pure python files.
234 """A config loader for pure python files.
231
235
232 This calls execfile on a plain python file and looks for attributes
236 This calls execfile on a plain python file and looks for attributes
233 that are all caps. These attribute are added to the config Struct.
237 that are all caps. These attribute are added to the config Struct.
234 """
238 """
235
239
236 def __init__(self, filename, path=None):
240 def __init__(self, filename, path=None):
237 """Build a config loader for a filename and path.
241 """Build a config loader for a filename and path.
238
242
239 Parameters
243 Parameters
240 ----------
244 ----------
241 filename : str
245 filename : str
242 The file name of the config file.
246 The file name of the config file.
243 path : str, list, tuple
247 path : str, list, tuple
244 The path to search for the config file on, or a sequence of
248 The path to search for the config file on, or a sequence of
245 paths to try in order.
249 paths to try in order.
246 """
250 """
247 super(PyFileConfigLoader, self).__init__()
251 super(PyFileConfigLoader, self).__init__()
248 self.filename = filename
252 self.filename = filename
249 self.path = path
253 self.path = path
250 self.full_filename = ''
254 self.full_filename = ''
251 self.data = None
255 self.data = None
252
256
253 def load_config(self):
257 def load_config(self):
254 """Load the config from a file and return it as a Struct."""
258 """Load the config from a file and return it as a Struct."""
255 self.clear()
259 self.clear()
256 self._find_file()
260 self._find_file()
257 self._read_file_as_dict()
261 self._read_file_as_dict()
258 self._convert_to_config()
262 self._convert_to_config()
259 return self.config
263 return self.config
260
264
261 def _find_file(self):
265 def _find_file(self):
262 """Try to find the file by searching the paths."""
266 """Try to find the file by searching the paths."""
263 self.full_filename = filefind(self.filename, self.path)
267 self.full_filename = filefind(self.filename, self.path)
264
268
265 def _read_file_as_dict(self):
269 def _read_file_as_dict(self):
266 """Load the config file into self.config, with recursive loading."""
270 """Load the config file into self.config, with recursive loading."""
267 # This closure is made available in the namespace that is used
271 # This closure is made available in the namespace that is used
268 # to exec the config file. This allows users to call
272 # to exec the config file. It allows users to call
269 # load_subconfig('myconfig.py') to load config files recursively.
273 # load_subconfig('myconfig.py') to load config files recursively.
270 # It needs to be a closure because it has references to self.path
274 # It needs to be a closure because it has references to self.path
271 # and self.config. The sub-config is loaded with the same path
275 # and self.config. The sub-config is loaded with the same path
272 # as the parent, but it uses an empty config which is then merged
276 # as the parent, but it uses an empty config which is then merged
273 # with the parents.
277 # with the parents.
274 def load_subconfig(fname):
278
275 loader = PyFileConfigLoader(fname, self.path)
279 # If a profile is specified, the config file will be loaded
280 # from that profile
281
282 def load_subconfig(fname, profile=None):
283 # import here to prevent circular imports
284 from IPython.core.profiledir import ProfileDir, ProfileDirError
285 if profile is not None:
286 try:
287 profile_dir = ProfileDir.find_profile_dir_by_name(
288 get_ipython_dir(),
289 profile,
290 )
291 except ProfileDirError:
292 return
293 path = profile_dir.location
294 else:
295 path = self.path
296 loader = PyFileConfigLoader(fname, path)
276 try:
297 try:
277 sub_config = loader.load_config()
298 sub_config = loader.load_config()
278 except IOError:
299 except IOError:
279 # Pass silently if the sub config is not there. This happens
300 # Pass silently if the sub config is not there. This happens
280 # when a user us using a profile, but not the default config.
301 # when a user s using a profile, but not the default config.
281 pass
302 pass
282 else:
303 else:
283 self.config._merge(sub_config)
304 self.config._merge(sub_config)
284
305
285 # Again, this needs to be a closure and should be used in config
306 # Again, this needs to be a closure and should be used in config
286 # files to get the config being loaded.
307 # files to get the config being loaded.
287 def get_config():
308 def get_config():
288 return self.config
309 return self.config
289
310
290 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
311 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
291 fs_encoding = sys.getfilesystemencoding() or 'ascii'
312 fs_encoding = sys.getfilesystemencoding() or 'ascii'
292 conf_filename = self.full_filename.encode(fs_encoding)
313 conf_filename = self.full_filename.encode(fs_encoding)
293 execfile(conf_filename, namespace)
314 execfile(conf_filename, namespace)
294
315
295 def _convert_to_config(self):
316 def _convert_to_config(self):
296 if self.data is None:
317 if self.data is None:
297 ConfigLoaderError('self.data does not exist')
318 ConfigLoaderError('self.data does not exist')
298
319
299
320
300 class CommandLineConfigLoader(ConfigLoader):
321 class CommandLineConfigLoader(ConfigLoader):
301 """A config loader for command line arguments.
322 """A config loader for command line arguments.
302
323
303 As we add more command line based loaders, the common logic should go
324 As we add more command line based loaders, the common logic should go
304 here.
325 here.
305 """
326 """
306
327
307 kv_pattern = re.compile(r'[A-Za-z]\w*(\.\w+)*\=.+')
328 kv_pattern = re.compile(r'[A-Za-z]\w*(\.\w+)*\=.*')
308 flag_pattern = re.compile(r'\-\-\w+(\-\w)*')
329 flag_pattern = re.compile(r'\-\-\w+(\-\w)*')
309
330
310 class KeyValueConfigLoader(CommandLineConfigLoader):
331 class KeyValueConfigLoader(CommandLineConfigLoader):
311 """A config loader that loads key value pairs from the command line.
332 """A config loader that loads key value pairs from the command line.
312
333
313 This allows command line options to be gives in the following form::
334 This allows command line options to be gives in the following form::
314
335
315 ipython Global.profile="foo" InteractiveShell.autocall=False
336 ipython Global.profile="foo" InteractiveShell.autocall=False
316 """
337 """
317
338
318 def __init__(self, argv=None, aliases=None, flags=None):
339 def __init__(self, argv=None, aliases=None, flags=None):
319 """Create a key value pair config loader.
340 """Create a key value pair config loader.
320
341
321 Parameters
342 Parameters
322 ----------
343 ----------
323 argv : list
344 argv : list
324 A list that has the form of sys.argv[1:] which has unicode
345 A list that has the form of sys.argv[1:] which has unicode
325 elements of the form u"key=value". If this is None (default),
346 elements of the form u"key=value". If this is None (default),
326 then sys.argv[1:] will be used.
347 then sys.argv[1:] will be used.
327 aliases : dict
348 aliases : dict
328 A dict of aliases for configurable traits.
349 A dict of aliases for configurable traits.
329 Keys are the short aliases, Values are the resolved trait.
350 Keys are the short aliases, Values are the resolved trait.
330 Of the form: `{'alias' : 'Configurable.trait'}`
351 Of the form: `{'alias' : 'Configurable.trait'}`
331 flags : dict
352 flags : dict
332 A dict of flags, keyed by str name. Vaues can be Config objects,
353 A dict of flags, keyed by str name. Vaues can be Config objects,
333 dicts, or "key=value" strings. If Config or dict, when the flag
354 dicts, or "key=value" strings. If Config or dict, when the flag
334 is triggered, The flag is loaded as `self.config.update(m)`.
355 is triggered, The flag is loaded as `self.config.update(m)`.
335
356
336 Returns
357 Returns
337 -------
358 -------
338 config : Config
359 config : Config
339 The resulting Config object.
360 The resulting Config object.
340
361
341 Examples
362 Examples
342 --------
363 --------
343
364
344 >>> from IPython.config.loader import KeyValueConfigLoader
365 >>> from IPython.config.loader import KeyValueConfigLoader
345 >>> cl = KeyValueConfigLoader()
366 >>> cl = KeyValueConfigLoader()
346 >>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
367 >>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
347 {'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
368 {'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
348 """
369 """
370 self.clear()
349 if argv is None:
371 if argv is None:
350 argv = sys.argv[1:]
372 argv = sys.argv[1:]
351 self.argv = argv
373 self.argv = argv
352 self.aliases = aliases or {}
374 self.aliases = aliases or {}
353 self.flags = flags or {}
375 self.flags = flags or {}
376
377
378 def clear(self):
379 super(KeyValueConfigLoader, self).clear()
380 self.extra_args = []
381
354
382
355 def load_config(self, argv=None, aliases=None, flags=None):
383 def load_config(self, argv=None, aliases=None, flags=None):
356 """Parse the configuration and generate the Config object.
384 """Parse the configuration and generate the Config object.
357
385
386 After loading, any arguments that are not key-value or
387 flags will be stored in self.extra_args - a list of
388 unparsed command-line arguments. This is used for
389 arguments such as input files or subcommands.
390
358 Parameters
391 Parameters
359 ----------
392 ----------
360 argv : list, optional
393 argv : list, optional
361 A list that has the form of sys.argv[1:] which has unicode
394 A list that has the form of sys.argv[1:] which has unicode
362 elements of the form u"key=value". If this is None (default),
395 elements of the form u"key=value". If this is None (default),
363 then self.argv will be used.
396 then self.argv will be used.
364 aliases : dict
397 aliases : dict
365 A dict of aliases for configurable traits.
398 A dict of aliases for configurable traits.
366 Keys are the short aliases, Values are the resolved trait.
399 Keys are the short aliases, Values are the resolved trait.
367 Of the form: `{'alias' : 'Configurable.trait'}`
400 Of the form: `{'alias' : 'Configurable.trait'}`
368 flags : dict
401 flags : dict
369 A dict of flags, keyed by str name. Values can be Config objects
402 A dict of flags, keyed by str name. Values can be Config objects
370 or dicts. When the flag is triggered, The config is loaded as
403 or dicts. When the flag is triggered, The config is loaded as
371 `self.config.update(cfg)`.
404 `self.config.update(cfg)`.
372 """
405 """
373 from IPython.config.configurable import Configurable
406 from IPython.config.configurable import Configurable
374
407
375 self.clear()
408 self.clear()
376 if argv is None:
409 if argv is None:
377 argv = self.argv
410 argv = self.argv
378 if aliases is None:
411 if aliases is None:
379 aliases = self.aliases
412 aliases = self.aliases
380 if flags is None:
413 if flags is None:
381 flags = self.flags
414 flags = self.flags
382
415
383 for item in argv:
416 for item in argv:
384 if kv_pattern.match(item):
417 if kv_pattern.match(item):
385 lhs,rhs = item.split('=',1)
418 lhs,rhs = item.split('=',1)
386 # Substitute longnames for aliases.
419 # Substitute longnames for aliases.
387 if lhs in aliases:
420 if lhs in aliases:
388 lhs = aliases[lhs]
421 lhs = aliases[lhs]
389 exec_str = 'self.config.' + lhs + '=' + rhs
422 exec_str = 'self.config.' + lhs + '=' + rhs
390 try:
423 try:
391 # Try to see if regular Python syntax will work. This
424 # Try to see if regular Python syntax will work. This
392 # won't handle strings as the quote marks are removed
425 # won't handle strings as the quote marks are removed
393 # by the system shell.
426 # by the system shell.
394 exec exec_str in locals(), globals()
427 exec exec_str in locals(), globals()
395 except (NameError, SyntaxError):
428 except (NameError, SyntaxError):
396 # This case happens if the rhs is a string but without
429 # This case happens if the rhs is a string but without
397 # the quote marks. We add the quote marks and see if
430 # the quote marks. We add the quote marks and see if
398 # it succeeds. If it still fails, we let it raise.
431 # it succeeds. If it still fails, we let it raise.
399 exec_str = 'self.config.' + lhs + '="' + rhs + '"'
432 exec_str = 'self.config.' + lhs + '="' + rhs + '"'
400 exec exec_str in locals(), globals()
433 exec exec_str in locals(), globals()
401 elif flag_pattern.match(item):
434 elif flag_pattern.match(item):
402 # trim leading '--'
435 # trim leading '--'
403 m = item[2:]
436 m = item[2:]
404 cfg,_ = flags.get(m, (None,None))
437 cfg,_ = flags.get(m, (None,None))
405 if cfg is None:
438 if cfg is None:
406 raise ValueError("Unrecognized flag: %r"%item)
439 raise ArgumentError("Unrecognized flag: %r"%item)
407 elif isinstance(cfg, (dict, Config)):
440 elif isinstance(cfg, (dict, Config)):
408 # update self.config with Config:
441 # don't clobber whole config sections, update
409 self.config.update(cfg)
442 # each section from config:
443 for sec,c in cfg.iteritems():
444 self.config[sec].update(c)
410 else:
445 else:
411 raise ValueError("Invalid flag: %r"%flag)
446 raise ValueError("Invalid flag: %r"%flag)
447 elif item.startswith('-'):
448 # this shouldn't ever be valid
449 raise ArgumentError("Invalid argument: %r"%item)
412 else:
450 else:
413 raise ValueError("Invalid argument: %r"%item)
451 # keep all args that aren't valid in a list,
452 # in case our parent knows what to do with them.
453 self.extra_args.append(item)
414 return self.config
454 return self.config
415
455
416 class ArgParseConfigLoader(CommandLineConfigLoader):
456 class ArgParseConfigLoader(CommandLineConfigLoader):
417 """A loader that uses the argparse module to load from the command line."""
457 """A loader that uses the argparse module to load from the command line."""
418
458
419 def __init__(self, argv=None, *parser_args, **parser_kw):
459 def __init__(self, argv=None, *parser_args, **parser_kw):
420 """Create a config loader for use with argparse.
460 """Create a config loader for use with argparse.
421
461
422 Parameters
462 Parameters
423 ----------
463 ----------
424
464
425 argv : optional, list
465 argv : optional, list
426 If given, used to read command-line arguments from, otherwise
466 If given, used to read command-line arguments from, otherwise
427 sys.argv[1:] is used.
467 sys.argv[1:] is used.
428
468
429 parser_args : tuple
469 parser_args : tuple
430 A tuple of positional arguments that will be passed to the
470 A tuple of positional arguments that will be passed to the
431 constructor of :class:`argparse.ArgumentParser`.
471 constructor of :class:`argparse.ArgumentParser`.
432
472
433 parser_kw : dict
473 parser_kw : dict
434 A tuple of keyword arguments that will be passed to the
474 A tuple of keyword arguments that will be passed to the
435 constructor of :class:`argparse.ArgumentParser`.
475 constructor of :class:`argparse.ArgumentParser`.
436
476
437 Returns
477 Returns
438 -------
478 -------
439 config : Config
479 config : Config
440 The resulting Config object.
480 The resulting Config object.
441 """
481 """
442 super(CommandLineConfigLoader, self).__init__()
482 super(CommandLineConfigLoader, self).__init__()
443 if argv == None:
483 if argv == None:
444 argv = sys.argv[1:]
484 argv = sys.argv[1:]
445 self.argv = argv
485 self.argv = argv
446 self.parser_args = parser_args
486 self.parser_args = parser_args
447 self.version = parser_kw.pop("version", None)
487 self.version = parser_kw.pop("version", None)
448 kwargs = dict(argument_default=argparse.SUPPRESS)
488 kwargs = dict(argument_default=argparse.SUPPRESS)
449 kwargs.update(parser_kw)
489 kwargs.update(parser_kw)
450 self.parser_kw = kwargs
490 self.parser_kw = kwargs
451
491
452 def load_config(self, argv=None):
492 def load_config(self, argv=None):
453 """Parse command line arguments and return as a Config object.
493 """Parse command line arguments and return as a Config object.
454
494
455 Parameters
495 Parameters
456 ----------
496 ----------
457
497
458 args : optional, list
498 args : optional, list
459 If given, a list with the structure of sys.argv[1:] to parse
499 If given, a list with the structure of sys.argv[1:] to parse
460 arguments from. If not given, the instance's self.argv attribute
500 arguments from. If not given, the instance's self.argv attribute
461 (given at construction time) is used."""
501 (given at construction time) is used."""
462 self.clear()
502 self.clear()
463 if argv is None:
503 if argv is None:
464 argv = self.argv
504 argv = self.argv
465 self._create_parser()
505 self._create_parser()
466 self._parse_args(argv)
506 self._parse_args(argv)
467 self._convert_to_config()
507 self._convert_to_config()
468 return self.config
508 return self.config
469
509
470 def get_extra_args(self):
510 def get_extra_args(self):
471 if hasattr(self, 'extra_args'):
511 if hasattr(self, 'extra_args'):
472 return self.extra_args
512 return self.extra_args
473 else:
513 else:
474 return []
514 return []
475
515
476 def _create_parser(self):
516 def _create_parser(self):
477 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
517 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
478 self._add_arguments()
518 self._add_arguments()
479
519
480 def _add_arguments(self):
520 def _add_arguments(self):
481 raise NotImplementedError("subclasses must implement _add_arguments")
521 raise NotImplementedError("subclasses must implement _add_arguments")
482
522
483 def _parse_args(self, args):
523 def _parse_args(self, args):
484 """self.parser->self.parsed_data"""
524 """self.parser->self.parsed_data"""
485 # decode sys.argv to support unicode command-line options
525 # decode sys.argv to support unicode command-line options
486 uargs = []
526 uargs = []
487 for a in args:
527 for a in args:
488 if isinstance(a, str):
528 if isinstance(a, str):
489 # don't decode if we already got unicode
529 # don't decode if we already got unicode
490 a = a.decode(sys.stdin.encoding or
530 a = a.decode(sys.stdin.encoding or
491 sys.getdefaultencoding())
531 sys.getdefaultencoding())
492 uargs.append(a)
532 uargs.append(a)
493 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
533 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
494
534
495 def _convert_to_config(self):
535 def _convert_to_config(self):
496 """self.parsed_data->self.config"""
536 """self.parsed_data->self.config"""
497 for k, v in vars(self.parsed_data).iteritems():
537 for k, v in vars(self.parsed_data).iteritems():
498 exec_str = 'self.config.' + k + '= v'
538 exec_str = 'self.config.' + k + '= v'
499 exec exec_str in locals(), globals()
539 exec exec_str in locals(), globals()
500
540
501
541
@@ -1,24 +1,25 b''
1 c = get_config()
1 c = get_config()
2 app = c.InteractiveShellApp
2
3
3 # This can be used at any point in a config file to load a sub config
4 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6 load_subconfig('ipython_config.py', profile='default')
6
7
7 lines = """
8 lines = """
8 from IPython.kernel.client import *
9 from IPython.parallel import *
9 """
10 """
10
11
11 # You have to make sure that attributes that are containers already
12 # You have to make sure that attributes that are containers already
12 # exist before using them. Simple assigning a new list will override
13 # exist before using them. Simple assigning a new list will override
13 # all previous values.
14 # all previous values.
14 if hasattr(c.Global, 'exec_lines'):
15 if hasattr(app, 'exec_lines'):
15 c.Global.exec_lines.append(lines)
16 app.exec_lines.append(lines)
16 else:
17 else:
17 c.Global.exec_lines = [lines]
18 app.exec_lines = [lines]
18
19
19 # Load the parallelmagic extension to enable %result, %px, %autopx magics.
20 # Load the parallelmagic extension to enable %result, %px, %autopx magics.
20 if hasattr(c.Global, 'extensions'):
21 if hasattr(app, 'extensions'):
21 c.Global.extensions.append('parallelmagic')
22 app.extensions.append('parallelmagic')
22 else:
23 else:
23 c.Global.extensions = ['parallelmagic']
24 app.extensions = ['parallelmagic']
24
25
@@ -1,19 +1,21 b''
1 c = get_config()
1 c = get_config()
2 app = c.InteractiveShellApp
2
3
3 # This can be used at any point in a config file to load a sub config
4 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6 load_subconfig('ipython_config.py', profile='default')
6
7
7 lines = """
8 lines = """
8 import cmath
9 import cmath
9 from math import *
10 from math import *
10 """
11 """
11
12
12 # You have to make sure that attributes that are containers already
13 # You have to make sure that attributes that are containers already
13 # exist before using them. Simple assigning a new list will override
14 # exist before using them. Simple assigning a new list will override
14 # all previous values.
15 # all previous values.
15 if hasattr(c.Global, 'exec_lines'):
16
16 c.Global.exec_lines.append(lines)
17 if hasattr(app, 'exec_lines'):
18 app.exec_lines.append(lines)
17 else:
19 else:
18 c.Global.exec_lines = [lines]
20 app.exec_lines = [lines]
19
21
@@ -1,22 +1,23 b''
1 c = get_config()
1 c = get_config()
2 app = c.InteractiveShellApp
2
3
3 # This can be used at any point in a config file to load a sub config
4 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6 load_subconfig('ipython_config.py', profile='default')
6
7
7 lines = """
8 lines = """
8 import matplotlib
9 import matplotlib
9 %gui -a wx
10 %gui qt
10 matplotlib.use('wxagg')
11 matplotlib.use('qtagg')
11 matplotlib.interactive(True)
12 matplotlib.interactive(True)
12 from matplotlib import pyplot as plt
13 from matplotlib import pyplot as plt
13 from matplotlib.pyplot import *
14 from matplotlib.pyplot import *
14 """
15 """
15
16
16 # You have to make sure that attributes that are containers already
17 # You have to make sure that attributes that are containers already
17 # exist before using them. Simple assigning a new list will override
18 # exist before using them. Simple assigning a new list will override
18 # all previous values.
19 # all previous values.
19 if hasattr(c.Global, 'exec_lines'):
20 if hasattr(app, 'exec_lines'):
20 c.Global.exec_lines.append(lines)
21 app.exec_lines.append(lines)
21 else:
22 else:
22 c.Global.exec_lines = [lines] No newline at end of file
23 app.exec_lines = [lines] No newline at end of file
@@ -1,29 +1,30 b''
1 c = get_config()
1 c = get_config()
2 app = c.InteractiveShellApp
2
3
3 # This can be used at any point in a config file to load a sub config
4 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6 load_subconfig('ipython_config.py', profile='default')
6
7
7 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
8 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
8 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
9 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
9 c.InteractiveShell.prompt_out = '<\#> '
10 c.InteractiveShell.prompt_out = '<\#> '
10
11
11 c.InteractiveShell.prompts_pad_left = True
12 c.InteractiveShell.prompts_pad_left = True
12
13
13 c.InteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out2 = ''
16 c.InteractiveShell.separate_out2 = ''
16
17
17 c.PrefilterManager.multi_line_specials = True
18 c.PrefilterManager.multi_line_specials = True
18
19
19 lines = """
20 lines = """
20 %rehashx
21 %rehashx
21 """
22 """
22
23
23 # You have to make sure that attributes that are containers already
24 # You have to make sure that attributes that are containers already
24 # exist before using them. Simple assigning a new list will override
25 # exist before using them. Simple assigning a new list will override
25 # all previous values.
26 # all previous values.
26 if hasattr(c.Global, 'exec_lines'):
27 if hasattr(app, 'exec_lines'):
27 c.Global.exec_lines.append(lines)
28 app.exec_lines.append(lines)
28 else:
29 else:
29 c.Global.exec_lines = [lines] No newline at end of file
30 app.exec_lines = [lines] No newline at end of file
@@ -1,29 +1,30 b''
1 c = get_config()
1 c = get_config()
2 app = c.InteractiveShellApp
2
3
3 # This can be used at any point in a config file to load a sub config
4 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6 load_subconfig('ipython_config.py', profile='default')
6
7
7 lines = """
8 lines = """
8 from __future__ import division
9 from __future__ import division
9 from sympy import *
10 from sympy import *
10 x, y, z = symbols('xyz')
11 x, y, z = symbols('xyz')
11 k, m, n = symbols('kmn', integer=True)
12 k, m, n = symbols('kmn', integer=True)
12 f, g, h = map(Function, 'fgh')
13 f, g, h = map(Function, 'fgh')
13 """
14 """
14
15
15 # You have to make sure that attributes that are containers already
16 # You have to make sure that attributes that are containers already
16 # exist before using them. Simple assigning a new list will override
17 # exist before using them. Simple assigning a new list will override
17 # all previous values.
18 # all previous values.
18
19
19 if hasattr(c.Global, 'exec_lines'):
20 if hasattr(app, 'exec_lines'):
20 c.Global.exec_lines.append(lines)
21 app.exec_lines.append(lines)
21 else:
22 else:
22 c.Global.exec_lines = [lines]
23 app.exec_lines = [lines]
23
24
24 # Load the sympy_printing extension to enable nice printing of sympy expr's.
25 # Load the sympy_printing extension to enable nice printing of sympy expr's.
25 if hasattr(c.Global, 'extensions'):
26 if hasattr(app, 'extensions'):
26 c.Global.extensions.append('sympy_printing')
27 app.extensions.append('sympyprinting')
27 else:
28 else:
28 c.Global.extensions = ['sympy_printing']
29 app.extensions = ['sympyprinting']
29
30
@@ -1,105 +1,135 b''
1 """
1 """
2 Tests for IPython.config.application.Application
2 Tests for IPython.config.application.Application
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from unittest import TestCase
20 from unittest import TestCase
21
21
22 from IPython.config.configurable import Configurable
22 from IPython.config.configurable import Configurable
23
23
24 from IPython.config.application import (
24 from IPython.config.application import (
25 Application
25 Application
26 )
26 )
27
27
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 Bool, Unicode, Int, Float, List, Dict
29 Bool, Unicode, Int, Float, List, Dict
30 )
30 )
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Code
33 # Code
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 class Foo(Configurable):
36 class Foo(Configurable):
37
37
38 i = Int(0, config=True, help="The integer i.")
38 i = Int(0, config=True, help="The integer i.")
39 j = Int(1, config=True, help="The integer j.")
39 j = Int(1, config=True, help="The integer j.")
40 name = Unicode(u'Brian', config=True, help="First name.")
40 name = Unicode(u'Brian', config=True, help="First name.")
41
41
42
42
43 class Bar(Configurable):
43 class Bar(Configurable):
44
44
45 b = Int(0, config=True, help="The integer b.")
45 enabled = Bool(True, config=True, help="Enable bar.")
46 enabled = Bool(True, config=True, help="Enable bar.")
46
47
47
48
48 class MyApp(Application):
49 class MyApp(Application):
49
50
50 app_name = Unicode(u'myapp')
51 name = Unicode(u'myapp')
51 running = Bool(False, config=True,
52 running = Bool(False, config=True,
52 help="Is the app running?")
53 help="Is the app running?")
53 classes = List([Bar, Foo])
54 classes = List([Bar, Foo])
54 config_file = Unicode(u'', config=True,
55 config_file = Unicode(u'', config=True,
55 help="Load this config file")
56 help="Load this config file")
56
57
57 aliases = Dict(dict(i='Foo.i',j='Foo.j',name='Foo.name',
58 aliases = Dict(dict(i='Foo.i',j='Foo.j',name='Foo.name',
58 enabled='Bar.enabled', log_level='MyApp.log_level'))
59 enabled='Bar.enabled', log_level='MyApp.log_level'))
59
60
60 flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"),
61 flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"),
61 disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False")))
62 disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False")))
62
63
63 def init_foo(self):
64 def init_foo(self):
64 self.foo = Foo(config=self.config)
65 self.foo = Foo(config=self.config)
65
66
66 def init_bar(self):
67 def init_bar(self):
67 self.bar = Bar(config=self.config)
68 self.bar = Bar(config=self.config)
68
69
69
70
70 class TestApplication(TestCase):
71 class TestApplication(TestCase):
71
72
72 def test_basic(self):
73 def test_basic(self):
73 app = MyApp()
74 app = MyApp()
74 self.assertEquals(app.app_name, u'myapp')
75 self.assertEquals(app.name, u'myapp')
75 self.assertEquals(app.running, False)
76 self.assertEquals(app.running, False)
76 self.assertEquals(app.classes, [MyApp,Bar,Foo])
77 self.assertEquals(app.classes, [MyApp,Bar,Foo])
77 self.assertEquals(app.config_file, u'')
78 self.assertEquals(app.config_file, u'')
78
79
79 def test_config(self):
80 def test_config(self):
80 app = MyApp()
81 app = MyApp()
81 app.parse_command_line(["i=10","Foo.j=10","enabled=False","log_level=0"])
82 app.parse_command_line(["i=10","Foo.j=10","enabled=False","log_level=50"])
82 config = app.config
83 config = app.config
83 self.assertEquals(config.Foo.i, 10)
84 self.assertEquals(config.Foo.i, 10)
84 self.assertEquals(config.Foo.j, 10)
85 self.assertEquals(config.Foo.j, 10)
85 self.assertEquals(config.Bar.enabled, False)
86 self.assertEquals(config.Bar.enabled, False)
86 self.assertEquals(config.MyApp.log_level,0)
87 self.assertEquals(config.MyApp.log_level,50)
87
88
88 def test_config_propagation(self):
89 def test_config_propagation(self):
89 app = MyApp()
90 app = MyApp()
90 app.parse_command_line(["i=10","Foo.j=10","enabled=False","log_level=0"])
91 app.parse_command_line(["i=10","Foo.j=10","enabled=False","log_level=50"])
91 app.init_foo()
92 app.init_foo()
92 app.init_bar()
93 app.init_bar()
93 self.assertEquals(app.foo.i, 10)
94 self.assertEquals(app.foo.i, 10)
94 self.assertEquals(app.foo.j, 10)
95 self.assertEquals(app.foo.j, 10)
95 self.assertEquals(app.bar.enabled, False)
96 self.assertEquals(app.bar.enabled, False)
96
97
97 def test_alias(self):
98 def test_flags(self):
98 app = MyApp()
99 app = MyApp()
99 app.parse_command_line(["--disable"])
100 app.parse_command_line(["--disable"])
100 app.init_bar()
101 app.init_bar()
101 self.assertEquals(app.bar.enabled, False)
102 self.assertEquals(app.bar.enabled, False)
102 app.parse_command_line(["--enable"])
103 app.parse_command_line(["--enable"])
103 app.init_bar()
104 app.init_bar()
104 self.assertEquals(app.bar.enabled, True)
105 self.assertEquals(app.bar.enabled, True)
105
106
107 def test_aliases(self):
108 app = MyApp()
109 app.parse_command_line(["i=5", "j=10"])
110 app.init_foo()
111 self.assertEquals(app.foo.i, 5)
112 app.init_foo()
113 self.assertEquals(app.foo.j, 10)
114
115 def test_flag_clobber(self):
116 """test that setting flags doesn't clobber existing settings"""
117 app = MyApp()
118 app.parse_command_line(["Bar.b=5", "--disable"])
119 app.init_bar()
120 self.assertEquals(app.bar.enabled, False)
121 self.assertEquals(app.bar.b, 5)
122 app.parse_command_line(["--enable", "Bar.b=10"])
123 app.init_bar()
124 self.assertEquals(app.bar.enabled, True)
125 self.assertEquals(app.bar.b, 10)
126
127 def test_extra_args(self):
128 app = MyApp()
129 app.parse_command_line(['extra', "Bar.b=5", "--disable", 'args'])
130 app.init_bar()
131 self.assertEquals(app.bar.enabled, False)
132 self.assertEquals(app.bar.b, 5)
133 self.assertEquals(app.extra_args, ['extra', 'args'])
134
135
@@ -1,164 +1,166 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.config.configurable
4 Tests for IPython.config.configurable
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez (design help)
9 * Fernando Perez (design help)
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2010 The IPython Development Team
13 # Copyright (C) 2008-2010 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from unittest import TestCase
23 from unittest import TestCase
24
24
25 from IPython.config.configurable import (
25 from IPython.config.configurable import (
26 Configurable,
26 Configurable,
27 SingletonConfigurable
27 SingletonConfigurable
28 )
28 )
29
29
30 from IPython.utils.traitlets import (
30 from IPython.utils.traitlets import (
31 Int, Float, Str
31 Int, Float, Str
32 )
32 )
33
33
34 from IPython.config.loader import Config
34 from IPython.config.loader import Config
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Test cases
38 # Test cases
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 class MyConfigurable(Configurable):
42 class MyConfigurable(Configurable):
43 a = Int(1, config=True, help="The integer a.")
43 a = Int(1, config=True, help="The integer a.")
44 b = Float(1.0, config=True, help="The integer b.")
44 b = Float(1.0, config=True, help="The integer b.")
45 c = Str('no config')
45 c = Str('no config')
46
46
47
47
48 mc_help=u"""MyConfigurable options
48 mc_help=u"""MyConfigurable options
49 ----------------------
49 ----------------------
50 MyConfigurable.a : Int
50 MyConfigurable.a : Int
51 Default: 1
51 The integer a.
52 The integer a.
52 MyConfigurable.b : Float
53 MyConfigurable.b : Float
54 Default: 1.0
53 The integer b."""
55 The integer b."""
54
56
55 class Foo(Configurable):
57 class Foo(Configurable):
56 a = Int(0, config=True, help="The integer a.")
58 a = Int(0, config=True, help="The integer a.")
57 b = Str('nope', config=True)
59 b = Str('nope', config=True)
58
60
59
61
60 class Bar(Foo):
62 class Bar(Foo):
61 b = Str('gotit', config=False, help="The string b.")
63 b = Str('gotit', config=False, help="The string b.")
62 c = Float(config=True, help="The string c.")
64 c = Float(config=True, help="The string c.")
63
65
64
66
65 class TestConfigurable(TestCase):
67 class TestConfigurable(TestCase):
66
68
67 def test_default(self):
69 def test_default(self):
68 c1 = Configurable()
70 c1 = Configurable()
69 c2 = Configurable(config=c1.config)
71 c2 = Configurable(config=c1.config)
70 c3 = Configurable(config=c2.config)
72 c3 = Configurable(config=c2.config)
71 self.assertEquals(c1.config, c2.config)
73 self.assertEquals(c1.config, c2.config)
72 self.assertEquals(c2.config, c3.config)
74 self.assertEquals(c2.config, c3.config)
73
75
74 def test_custom(self):
76 def test_custom(self):
75 config = Config()
77 config = Config()
76 config.foo = 'foo'
78 config.foo = 'foo'
77 config.bar = 'bar'
79 config.bar = 'bar'
78 c1 = Configurable(config=config)
80 c1 = Configurable(config=config)
79 c2 = Configurable(config=c1.config)
81 c2 = Configurable(config=c1.config)
80 c3 = Configurable(config=c2.config)
82 c3 = Configurable(config=c2.config)
81 self.assertEquals(c1.config, config)
83 self.assertEquals(c1.config, config)
82 self.assertEquals(c2.config, config)
84 self.assertEquals(c2.config, config)
83 self.assertEquals(c3.config, config)
85 self.assertEquals(c3.config, config)
84 # Test that copies are not made
86 # Test that copies are not made
85 self.assert_(c1.config is config)
87 self.assert_(c1.config is config)
86 self.assert_(c2.config is config)
88 self.assert_(c2.config is config)
87 self.assert_(c3.config is config)
89 self.assert_(c3.config is config)
88 self.assert_(c1.config is c2.config)
90 self.assert_(c1.config is c2.config)
89 self.assert_(c2.config is c3.config)
91 self.assert_(c2.config is c3.config)
90
92
91 def test_inheritance(self):
93 def test_inheritance(self):
92 config = Config()
94 config = Config()
93 config.MyConfigurable.a = 2
95 config.MyConfigurable.a = 2
94 config.MyConfigurable.b = 2.0
96 config.MyConfigurable.b = 2.0
95 c1 = MyConfigurable(config=config)
97 c1 = MyConfigurable(config=config)
96 c2 = MyConfigurable(config=c1.config)
98 c2 = MyConfigurable(config=c1.config)
97 self.assertEquals(c1.a, config.MyConfigurable.a)
99 self.assertEquals(c1.a, config.MyConfigurable.a)
98 self.assertEquals(c1.b, config.MyConfigurable.b)
100 self.assertEquals(c1.b, config.MyConfigurable.b)
99 self.assertEquals(c2.a, config.MyConfigurable.a)
101 self.assertEquals(c2.a, config.MyConfigurable.a)
100 self.assertEquals(c2.b, config.MyConfigurable.b)
102 self.assertEquals(c2.b, config.MyConfigurable.b)
101
103
102 def test_parent(self):
104 def test_parent(self):
103 config = Config()
105 config = Config()
104 config.Foo.a = 10
106 config.Foo.a = 10
105 config.Foo.b = "wow"
107 config.Foo.b = "wow"
106 config.Bar.b = 'later'
108 config.Bar.b = 'later'
107 config.Bar.c = 100.0
109 config.Bar.c = 100.0
108 f = Foo(config=config)
110 f = Foo(config=config)
109 b = Bar(config=f.config)
111 b = Bar(config=f.config)
110 self.assertEquals(f.a, 10)
112 self.assertEquals(f.a, 10)
111 self.assertEquals(f.b, 'wow')
113 self.assertEquals(f.b, 'wow')
112 self.assertEquals(b.b, 'gotit')
114 self.assertEquals(b.b, 'gotit')
113 self.assertEquals(b.c, 100.0)
115 self.assertEquals(b.c, 100.0)
114
116
115 def test_override1(self):
117 def test_override1(self):
116 config = Config()
118 config = Config()
117 config.MyConfigurable.a = 2
119 config.MyConfigurable.a = 2
118 config.MyConfigurable.b = 2.0
120 config.MyConfigurable.b = 2.0
119 c = MyConfigurable(a=3, config=config)
121 c = MyConfigurable(a=3, config=config)
120 self.assertEquals(c.a, 3)
122 self.assertEquals(c.a, 3)
121 self.assertEquals(c.b, config.MyConfigurable.b)
123 self.assertEquals(c.b, config.MyConfigurable.b)
122 self.assertEquals(c.c, 'no config')
124 self.assertEquals(c.c, 'no config')
123
125
124 def test_override2(self):
126 def test_override2(self):
125 config = Config()
127 config = Config()
126 config.Foo.a = 1
128 config.Foo.a = 1
127 config.Bar.b = 'or' # Up above b is config=False, so this won't do it.
129 config.Bar.b = 'or' # Up above b is config=False, so this won't do it.
128 config.Bar.c = 10.0
130 config.Bar.c = 10.0
129 c = Bar(config=config)
131 c = Bar(config=config)
130 self.assertEquals(c.a, config.Foo.a)
132 self.assertEquals(c.a, config.Foo.a)
131 self.assertEquals(c.b, 'gotit')
133 self.assertEquals(c.b, 'gotit')
132 self.assertEquals(c.c, config.Bar.c)
134 self.assertEquals(c.c, config.Bar.c)
133 c = Bar(a=2, b='and', c=20.0, config=config)
135 c = Bar(a=2, b='and', c=20.0, config=config)
134 self.assertEquals(c.a, 2)
136 self.assertEquals(c.a, 2)
135 self.assertEquals(c.b, 'and')
137 self.assertEquals(c.b, 'and')
136 self.assertEquals(c.c, 20.0)
138 self.assertEquals(c.c, 20.0)
137
139
138 def test_help(self):
140 def test_help(self):
139 self.assertEquals(MyConfigurable.class_get_help(), mc_help)
141 self.assertEquals(MyConfigurable.class_get_help(), mc_help)
140
142
141
143
142 class TestSingletonConfigurable(TestCase):
144 class TestSingletonConfigurable(TestCase):
143
145
144 def test_instance(self):
146 def test_instance(self):
145 from IPython.config.configurable import SingletonConfigurable
147 from IPython.config.configurable import SingletonConfigurable
146 class Foo(SingletonConfigurable): pass
148 class Foo(SingletonConfigurable): pass
147 self.assertEquals(Foo.initialized(), False)
149 self.assertEquals(Foo.initialized(), False)
148 foo = Foo.instance()
150 foo = Foo.instance()
149 self.assertEquals(Foo.initialized(), True)
151 self.assertEquals(Foo.initialized(), True)
150 self.assertEquals(foo, Foo.instance())
152 self.assertEquals(foo, Foo.instance())
151 self.assertEquals(SingletonConfigurable._instance, None)
153 self.assertEquals(SingletonConfigurable._instance, None)
152
154
153 def test_inheritance(self):
155 def test_inheritance(self):
154 class Bar(SingletonConfigurable): pass
156 class Bar(SingletonConfigurable): pass
155 class Bam(Bar): pass
157 class Bam(Bar): pass
156 self.assertEquals(Bar.initialized(), False)
158 self.assertEquals(Bar.initialized(), False)
157 self.assertEquals(Bam.initialized(), False)
159 self.assertEquals(Bam.initialized(), False)
158 bam = Bam.instance()
160 bam = Bam.instance()
159 bam == Bar.instance()
161 bam == Bar.instance()
160 self.assertEquals(Bar.initialized(), True)
162 self.assertEquals(Bar.initialized(), True)
161 self.assertEquals(Bam.initialized(), True)
163 self.assertEquals(Bam.initialized(), True)
162 self.assertEquals(bam, Bam._instance)
164 self.assertEquals(bam, Bam._instance)
163 self.assertEquals(bam, Bar._instance)
165 self.assertEquals(bam, Bar._instance)
164 self.assertEquals(SingletonConfigurable._instance, None)
166 self.assertEquals(SingletonConfigurable._instance, None)
@@ -1,190 +1,197 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.config.loader
4 Tests for IPython.config.loader
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez (design help)
9 * Fernando Perez (design help)
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import os
23 import os
24 from tempfile import mkstemp
24 from tempfile import mkstemp
25 from unittest import TestCase
25 from unittest import TestCase
26
26
27 from IPython.utils.traitlets import Int, Unicode
27 from IPython.utils.traitlets import Int, Unicode
28 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
29 from IPython.config.loader import (
29 from IPython.config.loader import (
30 Config,
30 Config,
31 PyFileConfigLoader,
31 PyFileConfigLoader,
32 KeyValueConfigLoader,
32 KeyValueConfigLoader,
33 ArgParseConfigLoader,
33 ArgParseConfigLoader,
34 ConfigError
34 ConfigError
35 )
35 )
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Actual tests
38 # Actual tests
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 pyfile = """
42 pyfile = """
43 c = get_config()
43 c = get_config()
44 c.a=10
44 c.a=10
45 c.b=20
45 c.b=20
46 c.Foo.Bar.value=10
46 c.Foo.Bar.value=10
47 c.Foo.Bam.value=range(10)
47 c.Foo.Bam.value=range(10)
48 c.D.C.value='hi there'
48 c.D.C.value='hi there'
49 """
49 """
50
50
51 class TestPyFileCL(TestCase):
51 class TestPyFileCL(TestCase):
52
52
53 def test_basic(self):
53 def test_basic(self):
54 fd, fname = mkstemp('.py')
54 fd, fname = mkstemp('.py')
55 f = os.fdopen(fd, 'w')
55 f = os.fdopen(fd, 'w')
56 f.write(pyfile)
56 f.write(pyfile)
57 f.close()
57 f.close()
58 # Unlink the file
58 # Unlink the file
59 cl = PyFileConfigLoader(fname)
59 cl = PyFileConfigLoader(fname)
60 config = cl.load_config()
60 config = cl.load_config()
61 self.assertEquals(config.a, 10)
61 self.assertEquals(config.a, 10)
62 self.assertEquals(config.b, 20)
62 self.assertEquals(config.b, 20)
63 self.assertEquals(config.Foo.Bar.value, 10)
63 self.assertEquals(config.Foo.Bar.value, 10)
64 self.assertEquals(config.Foo.Bam.value, range(10))
64 self.assertEquals(config.Foo.Bam.value, range(10))
65 self.assertEquals(config.D.C.value, 'hi there')
65 self.assertEquals(config.D.C.value, 'hi there')
66
66
67 class MyLoader1(ArgParseConfigLoader):
67 class MyLoader1(ArgParseConfigLoader):
68 def _add_arguments(self):
68 def _add_arguments(self):
69 p = self.parser
69 p = self.parser
70 p.add_argument('-f', '--foo', dest='Global.foo', type=str)
70 p.add_argument('-f', '--foo', dest='Global.foo', type=str)
71 p.add_argument('-b', dest='MyClass.bar', type=int)
71 p.add_argument('-b', dest='MyClass.bar', type=int)
72 p.add_argument('-n', dest='n', action='store_true')
72 p.add_argument('-n', dest='n', action='store_true')
73 p.add_argument('Global.bam', type=str)
73 p.add_argument('Global.bam', type=str)
74
74
75 class MyLoader2(ArgParseConfigLoader):
75 class MyLoader2(ArgParseConfigLoader):
76 def _add_arguments(self):
76 def _add_arguments(self):
77 subparsers = self.parser.add_subparsers(dest='subparser_name')
77 subparsers = self.parser.add_subparsers(dest='subparser_name')
78 subparser1 = subparsers.add_parser('1')
78 subparser1 = subparsers.add_parser('1')
79 subparser1.add_argument('-x',dest='Global.x')
79 subparser1.add_argument('-x',dest='Global.x')
80 subparser2 = subparsers.add_parser('2')
80 subparser2 = subparsers.add_parser('2')
81 subparser2.add_argument('y')
81 subparser2.add_argument('y')
82
82
83 class TestArgParseCL(TestCase):
83 class TestArgParseCL(TestCase):
84
84
85 def test_basic(self):
85 def test_basic(self):
86 cl = MyLoader1()
86 cl = MyLoader1()
87 config = cl.load_config('-f hi -b 10 -n wow'.split())
87 config = cl.load_config('-f hi -b 10 -n wow'.split())
88 self.assertEquals(config.Global.foo, 'hi')
88 self.assertEquals(config.Global.foo, 'hi')
89 self.assertEquals(config.MyClass.bar, 10)
89 self.assertEquals(config.MyClass.bar, 10)
90 self.assertEquals(config.n, True)
90 self.assertEquals(config.n, True)
91 self.assertEquals(config.Global.bam, 'wow')
91 self.assertEquals(config.Global.bam, 'wow')
92 config = cl.load_config(['wow'])
92 config = cl.load_config(['wow'])
93 self.assertEquals(config.keys(), ['Global'])
93 self.assertEquals(config.keys(), ['Global'])
94 self.assertEquals(config.Global.keys(), ['bam'])
94 self.assertEquals(config.Global.keys(), ['bam'])
95 self.assertEquals(config.Global.bam, 'wow')
95 self.assertEquals(config.Global.bam, 'wow')
96
96
97 def test_add_arguments(self):
97 def test_add_arguments(self):
98 cl = MyLoader2()
98 cl = MyLoader2()
99 config = cl.load_config('2 frobble'.split())
99 config = cl.load_config('2 frobble'.split())
100 self.assertEquals(config.subparser_name, '2')
100 self.assertEquals(config.subparser_name, '2')
101 self.assertEquals(config.y, 'frobble')
101 self.assertEquals(config.y, 'frobble')
102 config = cl.load_config('1 -x frobble'.split())
102 config = cl.load_config('1 -x frobble'.split())
103 self.assertEquals(config.subparser_name, '1')
103 self.assertEquals(config.subparser_name, '1')
104 self.assertEquals(config.Global.x, 'frobble')
104 self.assertEquals(config.Global.x, 'frobble')
105
105
106 def test_argv(self):
106 def test_argv(self):
107 cl = MyLoader1(argv='-f hi -b 10 -n wow'.split())
107 cl = MyLoader1(argv='-f hi -b 10 -n wow'.split())
108 config = cl.load_config()
108 config = cl.load_config()
109 self.assertEquals(config.Global.foo, 'hi')
109 self.assertEquals(config.Global.foo, 'hi')
110 self.assertEquals(config.MyClass.bar, 10)
110 self.assertEquals(config.MyClass.bar, 10)
111 self.assertEquals(config.n, True)
111 self.assertEquals(config.n, True)
112 self.assertEquals(config.Global.bam, 'wow')
112 self.assertEquals(config.Global.bam, 'wow')
113
113
114
114
115 class TestKeyValueCL(TestCase):
115 class TestKeyValueCL(TestCase):
116
116
117 def test_basic(self):
117 def test_basic(self):
118 cl = KeyValueConfigLoader()
118 cl = KeyValueConfigLoader()
119 argv = [s.strip('c.') for s in pyfile.split('\n')[2:-1]]
119 argv = [s.strip('c.') for s in pyfile.split('\n')[2:-1]]
120 config = cl.load_config(argv)
120 config = cl.load_config(argv)
121 self.assertEquals(config.a, 10)
121 self.assertEquals(config.a, 10)
122 self.assertEquals(config.b, 20)
122 self.assertEquals(config.b, 20)
123 self.assertEquals(config.Foo.Bar.value, 10)
123 self.assertEquals(config.Foo.Bar.value, 10)
124 self.assertEquals(config.Foo.Bam.value, range(10))
124 self.assertEquals(config.Foo.Bam.value, range(10))
125 self.assertEquals(config.D.C.value, 'hi there')
125 self.assertEquals(config.D.C.value, 'hi there')
126
127 def test_extra_args(self):
128 cl = KeyValueConfigLoader()
129 config = cl.load_config(['a=5', 'b', 'c=10', 'd'])
130 self.assertEquals(cl.extra_args, ['b', 'd'])
131 self.assertEquals(config.a, 5)
132 self.assertEquals(config.c, 10)
126
133
127
134
128 class TestConfig(TestCase):
135 class TestConfig(TestCase):
129
136
130 def test_setget(self):
137 def test_setget(self):
131 c = Config()
138 c = Config()
132 c.a = 10
139 c.a = 10
133 self.assertEquals(c.a, 10)
140 self.assertEquals(c.a, 10)
134 self.assertEquals(c.has_key('b'), False)
141 self.assertEquals(c.has_key('b'), False)
135
142
136 def test_auto_section(self):
143 def test_auto_section(self):
137 c = Config()
144 c = Config()
138 self.assertEquals(c.has_key('A'), True)
145 self.assertEquals(c.has_key('A'), True)
139 self.assertEquals(c._has_section('A'), False)
146 self.assertEquals(c._has_section('A'), False)
140 A = c.A
147 A = c.A
141 A.foo = 'hi there'
148 A.foo = 'hi there'
142 self.assertEquals(c._has_section('A'), True)
149 self.assertEquals(c._has_section('A'), True)
143 self.assertEquals(c.A.foo, 'hi there')
150 self.assertEquals(c.A.foo, 'hi there')
144 del c.A
151 del c.A
145 self.assertEquals(len(c.A.keys()),0)
152 self.assertEquals(len(c.A.keys()),0)
146
153
147 def test_merge_doesnt_exist(self):
154 def test_merge_doesnt_exist(self):
148 c1 = Config()
155 c1 = Config()
149 c2 = Config()
156 c2 = Config()
150 c2.bar = 10
157 c2.bar = 10
151 c2.Foo.bar = 10
158 c2.Foo.bar = 10
152 c1._merge(c2)
159 c1._merge(c2)
153 self.assertEquals(c1.Foo.bar, 10)
160 self.assertEquals(c1.Foo.bar, 10)
154 self.assertEquals(c1.bar, 10)
161 self.assertEquals(c1.bar, 10)
155 c2.Bar.bar = 10
162 c2.Bar.bar = 10
156 c1._merge(c2)
163 c1._merge(c2)
157 self.assertEquals(c1.Bar.bar, 10)
164 self.assertEquals(c1.Bar.bar, 10)
158
165
159 def test_merge_exists(self):
166 def test_merge_exists(self):
160 c1 = Config()
167 c1 = Config()
161 c2 = Config()
168 c2 = Config()
162 c1.Foo.bar = 10
169 c1.Foo.bar = 10
163 c1.Foo.bam = 30
170 c1.Foo.bam = 30
164 c2.Foo.bar = 20
171 c2.Foo.bar = 20
165 c2.Foo.wow = 40
172 c2.Foo.wow = 40
166 c1._merge(c2)
173 c1._merge(c2)
167 self.assertEquals(c1.Foo.bam, 30)
174 self.assertEquals(c1.Foo.bam, 30)
168 self.assertEquals(c1.Foo.bar, 20)
175 self.assertEquals(c1.Foo.bar, 20)
169 self.assertEquals(c1.Foo.wow, 40)
176 self.assertEquals(c1.Foo.wow, 40)
170 c2.Foo.Bam.bam = 10
177 c2.Foo.Bam.bam = 10
171 c1._merge(c2)
178 c1._merge(c2)
172 self.assertEquals(c1.Foo.Bam.bam, 10)
179 self.assertEquals(c1.Foo.Bam.bam, 10)
173
180
174 def test_deepcopy(self):
181 def test_deepcopy(self):
175 c1 = Config()
182 c1 = Config()
176 c1.Foo.bar = 10
183 c1.Foo.bar = 10
177 c1.Foo.bam = 30
184 c1.Foo.bam = 30
178 c1.a = 'asdf'
185 c1.a = 'asdf'
179 c1.b = range(10)
186 c1.b = range(10)
180 import copy
187 import copy
181 c2 = copy.deepcopy(c1)
188 c2 = copy.deepcopy(c1)
182 self.assertEquals(c1, c2)
189 self.assertEquals(c1, c2)
183 self.assert_(c1 is not c2)
190 self.assert_(c1 is not c2)
184 self.assert_(c1.Foo is not c2.Foo)
191 self.assert_(c1.Foo is not c2.Foo)
185
192
186 def test_builtin(self):
193 def test_builtin(self):
187 c1 = Config()
194 c1 = Config()
188 exec 'foo = True' in c1
195 exec 'foo = True' in c1
189 self.assertEquals(c1.foo, True)
196 self.assertEquals(c1.foo, True)
190 self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10)
197 self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10)
This diff has been collapsed as it changes many lines, (616 lines changed) Show them Hide them
@@ -1,468 +1,290 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for IPython.
3 An application for IPython.
4
4
5 All top-level applications should use the classes in this module for
5 All top-level applications should use the classes in this module for
6 handling configuration and creating componenets.
6 handling configuration and creating componenets.
7
7
8 The job of an :class:`Application` is to create the master configuration
8 The job of an :class:`Application` is to create the master configuration
9 object and then create the configurable objects, passing the config to them.
9 object and then create the configurable objects, passing the config to them.
10
10
11 Authors:
11 Authors:
12
12
13 * Brian Granger
13 * Brian Granger
14 * Fernando Perez
14 * Fernando Perez
15 * Min RK
15
16
16 Notes
17 -----
18 """
17 """
19
18
20 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
21 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2011 The IPython Development Team
22 #
21 #
23 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
24 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
25 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
26
25
27 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
28 # Imports
27 # Imports
29 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
30
29
31 import logging
30 import logging
32 import os
31 import os
32 import shutil
33 import sys
33 import sys
34
34
35 from IPython.config.application import Application
36 from IPython.config.configurable import Configurable
37 from IPython.config.loader import Config
35 from IPython.core import release, crashhandler
38 from IPython.core import release, crashhandler
39 from IPython.core.profiledir import ProfileDir, ProfileDirError
36 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
40 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
37 from IPython.config.loader import (
41 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict
38 PyFileConfigLoader,
39 ArgParseConfigLoader,
40 Config,
41 )
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Classes and functions
44 # Classes and functions
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 class ApplicationError(Exception):
48 pass
49
50
51 class BaseAppConfigLoader(ArgParseConfigLoader):
52 """Default command line options for IPython based applications."""
53
54 def _add_ipython_dir(self, parser):
55 """Add the --ipython-dir option to the parser."""
56 paa = parser.add_argument
57 paa('--ipython-dir',
58 dest='Global.ipython_dir',type=unicode,
59 help=
60 """Set to override default location of the IPython directory
61 IPYTHON_DIR, stored as Global.ipython_dir. This can also be
62 specified through the environment variable IPYTHON_DIR.""",
63 metavar='Global.ipython_dir')
64
65 def _add_log_level(self, parser):
66 """Add the --log-level option to the parser."""
67 paa = parser.add_argument
68 paa('--log-level',
69 dest="Global.log_level",type=int,
70 help='Set the log level (0,10,20,30,40,50). Default is 30.',
71 metavar='Global.log_level')
72
73 def _add_version(self, parser):
74 """Add the --version option to the parser."""
75 parser.add_argument('--version', action="version",
76 version=self.version)
77
78 def _add_arguments(self):
79 self._add_ipython_dir(self.parser)
80 self._add_log_level(self.parser)
81 try: # Old versions of argparse don't have a version action
82 self._add_version(self.parser)
83 except Exception:
84 pass
85
86
87 class Application(object):
88 """Load a config, construct configurables and set them running.
89
90 The configuration of an application can be done via three different Config
91 objects, which are loaded and ultimately merged into a single one used
92 from that point on by the app. These are:
93
94 1. default_config: internal defaults, implemented in code.
95 2. file_config: read from the filesystem.
96 3. command_line_config: read from the system's command line flags.
97
98 During initialization, 3 is actually read before 2, since at the
99 command-line one may override the location of the file to be read. But the
100 above is the order in which the merge is made.
101 """
102
103 name = u'ipython'
104 description = 'IPython: an enhanced interactive Python shell.'
105 #: Usage message printed by argparse. If None, auto-generate
106 usage = None
107 #: The command line config loader. Subclass of ArgParseConfigLoader.
108 command_line_loader = BaseAppConfigLoader
109 #: The name of the config file to load, determined at runtime
110 config_file_name = None
111 #: The name of the default config file. Track separately from the actual
112 #: name because some logic happens only if we aren't using the default.
113 default_config_file_name = u'ipython_config.py'
114 default_log_level = logging.WARN
115 #: Set by --profile option
116 profile_name = None
117 #: User's ipython directory, typically ~/.ipython or ~/.config/ipython/
118 ipython_dir = None
119 #: Internal defaults, implemented in code.
120 default_config = None
121 #: Read from the filesystem.
122 file_config = None
123 #: Read from the system's command line flags.
124 command_line_config = None
125 #: The final config that will be passed to the main object.
126 master_config = None
127 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
128 argv = None
129 #: extra arguments computed by the command-line loader
130 extra_args = None
131 #: The class to use as the crash handler.
132 crash_handler_class = crashhandler.CrashHandler
133
134 # Private attributes
135 _exiting = False
136 _initialized = False
137
138 def __init__(self, argv=None):
139 self.argv = sys.argv[1:] if argv is None else argv
140 self.init_logger()
141
142 def init_logger(self):
143 self.log = logging.getLogger(self.__class__.__name__)
144 # This is used as the default until the command line arguments are read.
145 self.log.setLevel(self.default_log_level)
146 self._log_handler = logging.StreamHandler()
147 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
148 self._log_handler.setFormatter(self._log_formatter)
149 self.log.addHandler(self._log_handler)
150
151 def _set_log_level(self, level):
152 self.log.setLevel(level)
153
154 def _get_log_level(self):
155 return self.log.level
156
157 log_level = property(_get_log_level, _set_log_level)
158
159 def initialize(self):
160 """Initialize the application.
161
162 Loads all configuration information and sets all application state, but
163 does not start any relevant processing (typically some kind of event
164 loop).
165
166 Once this method has been called, the application is flagged as
167 initialized and the method becomes a no-op."""
168
169 if self._initialized:
170 return
171
172 # The first part is protected with an 'attempt' wrapper, that will log
173 # failures with the basic system traceback machinery. Once our crash
174 # handler is in place, we can let any subsequent exception propagate,
175 # as our handler will log it with much better detail than the default.
176 self.attempt(self.create_crash_handler)
177
178 # Configuration phase
179 # Default config (internally hardwired in application code)
180 self.create_default_config()
181 self.log_default_config()
182 self.set_default_config_log_level()
183
184 # Command-line config
185 self.pre_load_command_line_config()
186 self.load_command_line_config()
187 self.set_command_line_config_log_level()
188 self.post_load_command_line_config()
189 self.log_command_line_config()
190
47
191 # Find resources needed for filesystem access, using information from
48 #-----------------------------------------------------------------------------
192 # the above two
49 # Base Application Class
193 self.find_ipython_dir()
50 #-----------------------------------------------------------------------------
194 self.find_resources()
195 self.find_config_file_name()
196 self.find_config_file_paths()
197
198 # File-based config
199 self.pre_load_file_config()
200 self.load_file_config()
201 self.set_file_config_log_level()
202 self.post_load_file_config()
203 self.log_file_config()
204
51
205 # Merge all config objects into a single one the app can then use
52 # aliases and flags
206 self.merge_configs()
207 self.log_master_config()
208
53
209 # Construction phase
54 base_aliases = dict(
210 self.pre_construct()
55 profile='BaseIPythonApplication.profile',
211 self.construct()
56 ipython_dir='BaseIPythonApplication.ipython_dir',
212 self.post_construct()
57 )
213
58
214 # Done, flag as such and
59 base_flags = dict(
215 self._initialized = True
60 debug = ({'Application' : {'log_level' : logging.DEBUG}},
61 "set log level to logging.DEBUG (maximize logging output)"),
62 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
63 "set log level to logging.CRITICAL (minimize logging output)"),
64 init = ({'BaseIPythonApplication' : {
65 'copy_config_files' : True,
66 'auto_create' : True}
67 }, "Initialize profile with default config files")
68 )
216
69
217 def start(self):
218 """Start the application."""
219 self.initialize()
220 self.start_app()
221
70
71 class BaseIPythonApplication(Application):
72
73 name = Unicode(u'ipython')
74 description = Unicode(u'IPython: an enhanced interactive Python shell.')
75 version = Unicode(release.version)
76
77 aliases = Dict(base_aliases)
78 flags = Dict(base_flags)
79
80 # Track whether the config_file has changed,
81 # because some logic happens only if we aren't using the default.
82 config_file_specified = Bool(False)
83
84 config_file_name = Unicode(u'ipython_config.py')
85 def _config_file_name_default(self):
86 return self.name.replace('-','_') + u'_config.py'
87 def _config_file_name_changed(self, name, old, new):
88 if new != old:
89 self.config_file_specified = True
90
91 # The directory that contains IPython's builtin profiles.
92 builtin_profile_dir = Unicode(
93 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
94 )
95
96 config_file_paths = List(Unicode)
97 def _config_file_paths_default(self):
98 return [os.getcwdu()]
99
100 profile = Unicode(u'default', config=True,
101 help="""The IPython profile to use."""
102 )
103 def _profile_changed(self, name, old, new):
104 self.builtin_profile_dir = os.path.join(
105 get_ipython_package_dir(), u'config', u'profile', new
106 )
107
108 ipython_dir = Unicode(get_ipython_dir(), config=True,
109 help="""
110 The name of the IPython directory. This directory is used for logging
111 configuration (through profiles), history storage, etc. The default
112 is usually $HOME/.ipython. This options can also be specified through
113 the environment variable IPYTHON_DIR.
114 """
115 )
116
117 overwrite = Bool(False, config=True,
118 help="""Whether to overwrite existing config files when copying""")
119 auto_create = Bool(False, config=True,
120 help="""Whether to create profile dir if it doesn't exist""")
121
122 config_files = List(Unicode)
123 def _config_files_default(self):
124 return [u'ipython_config.py']
125
126 copy_config_files = Bool(False, config=True,
127 help="""Whether to install the default config files into the profile dir.
128 If a new profile is being created, and IPython contains config files for that
129 profile, then they will be staged into the new directory. Otherwise,
130 default config files will be automatically generated.
131 """)
132
133 # The class to use as the crash handler.
134 crash_handler_class = Type(crashhandler.CrashHandler)
135
136 def __init__(self, **kwargs):
137 super(BaseIPythonApplication, self).__init__(**kwargs)
138 # ensure even default IPYTHON_DIR exists
139 if not os.path.exists(self.ipython_dir):
140 self._ipython_dir_changed('ipython_dir', self.ipython_dir, self.ipython_dir)
141
222 #-------------------------------------------------------------------------
142 #-------------------------------------------------------------------------
223 # Various stages of Application creation
143 # Various stages of Application creation
224 #-------------------------------------------------------------------------
144 #-------------------------------------------------------------------------
225
145
226 def create_crash_handler(self):
146 def init_crash_handler(self):
227 """Create a crash handler, typically setting sys.excepthook to it."""
147 """Create a crash handler, typically setting sys.excepthook to it."""
228 self.crash_handler = self.crash_handler_class(self)
148 self.crash_handler = self.crash_handler_class(self)
229 sys.excepthook = self.crash_handler
149 sys.excepthook = self.crash_handler
230
150
231 def create_default_config(self):
151 def _ipython_dir_changed(self, name, old, new):
232 """Create defaults that can't be set elsewhere.
152 if old in sys.path:
233
153 sys.path.remove(old)
234 For the most part, we try to set default in the class attributes
154 sys.path.append(os.path.abspath(new))
235 of Configurables. But, defaults the top-level Application (which is
155 if not os.path.isdir(new):
236 not a HasTraits or Configurables) are not set in this way. Instead
156 os.makedirs(new, mode=0777)
237 we set them here. The Global section is for variables like this that
157 readme = os.path.join(new, 'README')
238 don't belong to a particular configurable.
158 if not os.path.exists(readme):
239 """
159 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
240 c = Config()
160 shutil.copy(os.path.join(path, 'README'), readme)
241 c.Global.ipython_dir = get_ipython_dir()
161 self.log.debug("IPYTHON_DIR set to: %s" % new)
242 c.Global.log_level = self.log_level
162
243 self.default_config = c
163 def load_config_file(self, suppress_errors=True):
244
245 def log_default_config(self):
246 self.log.debug('Default config loaded:')
247 self.log.debug(repr(self.default_config))
248
249 def set_default_config_log_level(self):
250 try:
251 self.log_level = self.default_config.Global.log_level
252 except AttributeError:
253 # Fallback to the default_log_level class attribute
254 pass
255
256 def create_command_line_config(self):
257 """Create and return a command line config loader."""
258 return self.command_line_loader(
259 self.argv,
260 description=self.description,
261 version=release.version,
262 usage=self.usage
263 )
264
265 def pre_load_command_line_config(self):
266 """Do actions just before loading the command line config."""
267 pass
268
269 def load_command_line_config(self):
270 """Load the command line config."""
271 loader = self.create_command_line_config()
272 self.command_line_config = loader.load_config()
273 self.extra_args = loader.get_extra_args()
274
275 def set_command_line_config_log_level(self):
276 try:
277 self.log_level = self.command_line_config.Global.log_level
278 except AttributeError:
279 pass
280
281 def post_load_command_line_config(self):
282 """Do actions just after loading the command line config."""
283 pass
284
285 def log_command_line_config(self):
286 self.log.debug("Command line config loaded:")
287 self.log.debug(repr(self.command_line_config))
288
289 def find_ipython_dir(self):
290 """Set the IPython directory.
291
292 This sets ``self.ipython_dir``, but the actual value that is passed to
293 the application is kept in either ``self.default_config`` or
294 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
295 ``sys.path`` so config files there can be referenced by other config
296 files.
297 """
298
299 try:
300 self.ipython_dir = self.command_line_config.Global.ipython_dir
301 except AttributeError:
302 self.ipython_dir = self.default_config.Global.ipython_dir
303 sys.path.append(os.path.abspath(self.ipython_dir))
304 if not os.path.isdir(self.ipython_dir):
305 os.makedirs(self.ipython_dir, mode=0777)
306 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
307
308 def find_resources(self):
309 """Find other resources that need to be in place.
310
311 Things like cluster directories need to be in place to find the
312 config file. These happen right after the IPython directory has
313 been set.
314 """
315 pass
316
317 def find_config_file_name(self):
318 """Find the config file name for this application.
319
320 This must set ``self.config_file_name`` to the filename of the
321 config file to use (just the filename). The search paths for the
322 config file are set in :meth:`find_config_file_paths` and then passed
323 to the config file loader where they are resolved to an absolute path.
324
325 If a profile has been set at the command line, this will resolve it.
326 """
327 try:
328 self.config_file_name = self.command_line_config.Global.config_file
329 except AttributeError:
330 pass
331 else:
332 return
333
334 try:
335 self.profile_name = self.command_line_config.Global.profile
336 except AttributeError:
337 # Just use the default as there is no profile
338 self.config_file_name = self.default_config_file_name
339 else:
340 # Use the default config file name and profile name if set
341 # to determine the used config file name.
342 name_parts = self.default_config_file_name.split('.')
343 name_parts.insert(1, u'_' + self.profile_name + u'.')
344 self.config_file_name = ''.join(name_parts)
345
346 def find_config_file_paths(self):
347 """Set the search paths for resolving the config file.
348
349 This must set ``self.config_file_paths`` to a sequence of search
350 paths to pass to the config file loader.
351 """
352 # Include our own profiles directory last, so that users can still find
353 # our shipped copies of builtin profiles even if they don't have them
354 # in their local ipython directory.
355 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
356 self.config_file_paths = (os.getcwdu(), self.ipython_dir, prof_dir)
357
358 def pre_load_file_config(self):
359 """Do actions before the config file is loaded."""
360 pass
361
362 def load_file_config(self, suppress_errors=True):
363 """Load the config file.
164 """Load the config file.
364
165
365 This tries to load the config file from disk. If successful, the
366 ``CONFIG_FILE`` config variable is set to the resolved config file
367 location. If not successful, an empty config is used.
368
369 By default, errors in loading config are handled, and a warning
166 By default, errors in loading config are handled, and a warning
370 printed on screen. For testing, the suppress_errors option is set
167 printed on screen. For testing, the suppress_errors option is set
371 to False, so errors will make tests fail.
168 to False, so errors will make tests fail.
372 """
169 """
170 base_config = 'ipython_config.py'
171 self.log.debug("Attempting to load config file: %s" %
172 base_config)
173 try:
174 Application.load_config_file(
175 self,
176 base_config,
177 path=self.config_file_paths
178 )
179 except IOError:
180 # ignore errors loading parent
181 pass
182 if self.config_file_name == base_config:
183 # don't load secondary config
184 return
373 self.log.debug("Attempting to load config file: %s" %
185 self.log.debug("Attempting to load config file: %s" %
374 self.config_file_name)
186 self.config_file_name)
375 loader = PyFileConfigLoader(self.config_file_name,
376 path=self.config_file_paths)
377 try:
187 try:
378 self.file_config = loader.load_config()
188 Application.load_config_file(
379 self.file_config.Global.config_file = loader.full_filename
189 self,
190 self.config_file_name,
191 path=self.config_file_paths
192 )
380 except IOError:
193 except IOError:
381 # Only warn if the default config file was NOT being used.
194 # Only warn if the default config file was NOT being used.
382 if not self.config_file_name==self.default_config_file_name:
195 if self.config_file_specified:
383 self.log.warn("Config file not found, skipping: %s" %
196 self.log.warn("Config file not found, skipping: %s" %
384 self.config_file_name, exc_info=True)
197 self.config_file_name)
385 self.file_config = Config()
386 except:
198 except:
387 if not suppress_errors: # For testing purposes
199 # For testing purposes.
200 if not suppress_errors:
388 raise
201 raise
389 self.log.warn("Error loading config file: %s" %
202 self.log.warn("Error loading config file: %s" %
390 self.config_file_name, exc_info=True)
203 self.config_file_name, exc_info=True)
391 self.file_config = Config()
392
204
393 def set_file_config_log_level(self):
205 def init_profile_dir(self):
394 # We need to keeep self.log_level updated. But we only use the value
206 """initialize the profile dir"""
395 # of the file_config if a value was not specified at the command
207 try:
396 # line, because the command line overrides everything.
208 # location explicitly specified:
397 if not hasattr(self.command_line_config.Global, 'log_level'):
209 location = self.config.ProfileDir.location
210 except AttributeError:
211 # location not specified, find by profile name
398 try:
212 try:
399 self.log_level = self.file_config.Global.log_level
213 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
400 except AttributeError:
214 except ProfileDirError:
401 pass # Use existing value
215 # not found, maybe create it (always create default profile)
402
216 if self.auto_create or self.profile=='default':
403 def post_load_file_config(self):
217 try:
404 """Do actions after the config file is loaded."""
218 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
405 pass
219 except ProfileDirError:
406
220 self.log.fatal("Could not create profile: %r"%self.profile)
407 def log_file_config(self):
221 self.exit(1)
408 if hasattr(self.file_config.Global, 'config_file'):
222 else:
409 self.log.debug("Config file loaded: %s" %
223 self.log.info("Created profile dir: %r"%p.location)
410 self.file_config.Global.config_file)
224 else:
411 self.log.debug(repr(self.file_config))
225 self.log.fatal("Profile %r not found."%self.profile)
412
226 self.exit(1)
413 def merge_configs(self):
227 else:
414 """Merge the default, command line and file config objects."""
228 self.log.info("Using existing profile dir: %r"%p.location)
415 config = Config()
416 config._merge(self.default_config)
417 config._merge(self.file_config)
418 config._merge(self.command_line_config)
419
420 # XXX fperez - propose to Brian we rename master_config to simply
421 # config, I think this is going to be heavily used in examples and
422 # application code and the name is shorter/easier to find/remember.
423 # For now, just alias it...
424 self.master_config = config
425 self.config = config
426
427 def log_master_config(self):
428 self.log.debug("Master config created:")
429 self.log.debug(repr(self.master_config))
430
431 def pre_construct(self):
432 """Do actions after the config has been built, but before construct."""
433 pass
434
435 def construct(self):
436 """Construct the main objects that make up this app."""
437 self.log.debug("Constructing main objects for application")
438
439 def post_construct(self):
440 """Do actions after construct, but before starting the app."""
441 pass
442
443 def start_app(self):
444 """Actually start the app."""
445 self.log.debug("Starting application")
446
447 #-------------------------------------------------------------------------
448 # Utility methods
449 #-------------------------------------------------------------------------
450
451 def exit(self, exit_status=0):
452 if self._exiting:
453 pass
454 else:
229 else:
455 self.log.debug("Exiting application: %s" % self.name)
230 # location is fully specified
456 self._exiting = True
231 try:
457 sys.exit(exit_status)
232 p = ProfileDir.find_profile_dir(location, self.config)
458
233 except ProfileDirError:
459 def attempt(self, func):
234 # not found, maybe create it
460 try:
235 if self.auto_create:
461 func()
236 try:
462 except SystemExit:
237 p = ProfileDir.create_profile_dir(location, self.config)
463 raise
238 except ProfileDirError:
464 except:
239 self.log.fatal("Could not create profile directory: %r"%location)
465 self.log.critical("Aborting application: %s" % self.name,
240 self.exit(1)
466 exc_info=True)
241 else:
467 self.exit(0)
242 self.log.info("Creating new profile dir: %r"%location)
243 else:
244 self.log.fatal("Profile directory %r not found."%location)
245 self.exit(1)
246 else:
247 self.log.info("Using existing profile dir: %r"%location)
248
249 self.profile_dir = p
250 self.config_file_paths.append(p.location)
251
252 def init_config_files(self):
253 """[optionally] copy default config files into profile dir."""
254 # copy config files
255 if self.copy_config_files:
256 path = self.builtin_profile_dir
257 src = self.profile
258
259 cfg = self.config_file_name
260 if path and os.path.exists(os.path.join(path, cfg)):
261 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
262 cfg, src, self.profile_dir.location, self.overwrite)
263 )
264 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
265 else:
266 self.stage_default_config_file()
267
268 def stage_default_config_file(self):
269 """auto generate default config file, and stage it into the profile."""
270 s = self.generate_config_file()
271 fname = os.path.join(self.profile_dir.location, self.config_file_name)
272 if self.overwrite or not os.path.exists(fname):
273 self.log.warn("Generating default config file: %r"%(fname))
274 with open(fname, 'w') as f:
275 f.write(s)
276
277
278 def initialize(self, argv=None):
279 self.init_crash_handler()
280 self.parse_command_line(argv)
281 if self.subapp is not None:
282 # stop here if subapp is taking over
283 return
284 cl_config = self.config
285 self.init_profile_dir()
286 self.init_config_files()
287 self.load_config_file()
288 # enforce cl-opts override configfile opts:
289 self.update_config(cl_config)
468
290
@@ -1,802 +1,799 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
3 # Copyright (C) 2010 The IPython Development Team.
4 #
4 #
5 # Distributed under the terms of the BSD License.
5 # Distributed under the terms of the BSD License.
6 #
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # Stdlib imports
15 # Stdlib imports
16 import atexit
16 import atexit
17 import datetime
17 import datetime
18 import os
18 import os
19 import re
19 import re
20 import sqlite3
20 import sqlite3
21 import threading
21 import threading
22
22
23 # Our own packages
23 # Our own packages
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25
25
26 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.utils import io
27 from IPython.utils import io
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
29 from IPython.utils.warn import warn
29 from IPython.utils.warn import warn
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Classes and functions
32 # Classes and functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 class HistoryManager(Configurable):
35 class HistoryManager(Configurable):
36 """A class to organize all history-related functionality in one place.
36 """A class to organize all history-related functionality in one place.
37 """
37 """
38 # Public interface
38 # Public interface
39
39
40 # An instance of the IPython shell we are attached to
40 # An instance of the IPython shell we are attached to
41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
42 # Lists to hold processed and raw history. These start with a blank entry
42 # Lists to hold processed and raw history. These start with a blank entry
43 # so that we can index them starting from 1
43 # so that we can index them starting from 1
44 input_hist_parsed = List([""])
44 input_hist_parsed = List([""])
45 input_hist_raw = List([""])
45 input_hist_raw = List([""])
46 # A list of directories visited during session
46 # A list of directories visited during session
47 dir_hist = List()
47 dir_hist = List()
48 def _dir_hist_default(self):
48 def _dir_hist_default(self):
49 try:
49 try:
50 return [os.getcwd()]
50 return [os.getcwd()]
51 except OSError:
51 except OSError:
52 return []
52 return []
53
53
54 # A dict of output history, keyed with ints from the shell's
54 # A dict of output history, keyed with ints from the shell's
55 # execution count.
55 # execution count.
56 output_hist = Dict()
56 output_hist = Dict()
57 # The text/plain repr of outputs.
57 # The text/plain repr of outputs.
58 output_hist_reprs = Dict()
58 output_hist_reprs = Dict()
59
59
60 # String holding the path to the history file
60 # String holding the path to the history file
61 hist_file = Unicode(config=True)
61 hist_file = Unicode(config=True)
62
62
63 # The SQLite database
63 # The SQLite database
64 db = Instance(sqlite3.Connection)
64 db = Instance(sqlite3.Connection)
65 # The number of the current session in the history database
65 # The number of the current session in the history database
66 session_number = Int()
66 session_number = Int()
67 # Should we log output to the database? (default no)
67 # Should we log output to the database? (default no)
68 db_log_output = Bool(False, config=True)
68 db_log_output = Bool(False, config=True)
69 # Write to database every x commands (higher values save disk access & power)
69 # Write to database every x commands (higher values save disk access & power)
70 # Values of 1 or less effectively disable caching.
70 # Values of 1 or less effectively disable caching.
71 db_cache_size = Int(0, config=True)
71 db_cache_size = Int(0, config=True)
72 # The input and output caches
72 # The input and output caches
73 db_input_cache = List()
73 db_input_cache = List()
74 db_output_cache = List()
74 db_output_cache = List()
75
75
76 # History saving in separate thread
76 # History saving in separate thread
77 save_thread = Instance('IPython.core.history.HistorySavingThread')
77 save_thread = Instance('IPython.core.history.HistorySavingThread')
78 # N.B. Event is a function returning an instance of _Event.
78 # N.B. Event is a function returning an instance of _Event.
79 save_flag = Instance(threading._Event)
79 save_flag = Instance(threading._Event)
80
80
81 # Private interface
81 # Private interface
82 # Variables used to store the three last inputs from the user. On each new
82 # Variables used to store the three last inputs from the user. On each new
83 # history update, we populate the user's namespace with these, shifted as
83 # history update, we populate the user's namespace with these, shifted as
84 # necessary.
84 # necessary.
85 _i00 = Unicode(u'')
85 _i00 = Unicode(u'')
86 _i = Unicode(u'')
86 _i = Unicode(u'')
87 _ii = Unicode(u'')
87 _ii = Unicode(u'')
88 _iii = Unicode(u'')
88 _iii = Unicode(u'')
89
89
90 # A regex matching all forms of the exit command, so that we don't store
90 # A regex matching all forms of the exit command, so that we don't store
91 # them in the history (it's annoying to rewind the first entry and land on
91 # them in the history (it's annoying to rewind the first entry and land on
92 # an exit call).
92 # an exit call).
93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
94
94
95 def __init__(self, shell, config=None, **traits):
95 def __init__(self, shell, config=None, **traits):
96 """Create a new history manager associated with a shell instance.
96 """Create a new history manager associated with a shell instance.
97 """
97 """
98 # We need a pointer back to the shell for various tasks.
98 # We need a pointer back to the shell for various tasks.
99 super(HistoryManager, self).__init__(shell=shell, config=config,
99 super(HistoryManager, self).__init__(shell=shell, config=config,
100 **traits)
100 **traits)
101
101
102 if self.hist_file == u'':
102 if self.hist_file == u'':
103 # No one has set the hist_file, yet.
103 # No one has set the hist_file, yet.
104 if shell.profile:
104 histfname = 'history'
105 histfname = 'history-%s' % shell.profile
105 self.hist_file = os.path.join(shell.profile_dir.location, histfname + '.sqlite')
106 else:
107 histfname = 'history'
108 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
109
106
110 try:
107 try:
111 self.init_db()
108 self.init_db()
112 except sqlite3.DatabaseError:
109 except sqlite3.DatabaseError:
113 if os.path.isfile(self.hist_file):
110 if os.path.isfile(self.hist_file):
114 # Try to move the file out of the way.
111 # Try to move the file out of the way.
115 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
112 newpath = os.path.join(self.shell.profile_dir.location, "hist-corrupt.sqlite")
116 os.rename(self.hist_file, newpath)
113 os.rename(self.hist_file, newpath)
117 print("ERROR! History file wasn't a valid SQLite database.",
114 print("ERROR! History file wasn't a valid SQLite database.",
118 "It was moved to %s" % newpath, "and a new file created.")
115 "It was moved to %s" % newpath, "and a new file created.")
119 self.init_db()
116 self.init_db()
120 else:
117 else:
121 # The hist_file is probably :memory: or something else.
118 # The hist_file is probably :memory: or something else.
122 raise
119 raise
123
120
124 self.save_flag = threading.Event()
121 self.save_flag = threading.Event()
125 self.db_input_cache_lock = threading.Lock()
122 self.db_input_cache_lock = threading.Lock()
126 self.db_output_cache_lock = threading.Lock()
123 self.db_output_cache_lock = threading.Lock()
127 self.save_thread = HistorySavingThread(self)
124 self.save_thread = HistorySavingThread(self)
128 self.save_thread.start()
125 self.save_thread.start()
129
126
130 self.new_session()
127 self.new_session()
131
128
132
129
133 def init_db(self):
130 def init_db(self):
134 """Connect to the database, and create tables if necessary."""
131 """Connect to the database, and create tables if necessary."""
135 self.db = sqlite3.connect(self.hist_file)
132 self.db = sqlite3.connect(self.hist_file)
136 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
133 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
137 primary key autoincrement, start timestamp,
134 primary key autoincrement, start timestamp,
138 end timestamp, num_cmds integer, remark text)""")
135 end timestamp, num_cmds integer, remark text)""")
139 self.db.execute("""CREATE TABLE IF NOT EXISTS history
136 self.db.execute("""CREATE TABLE IF NOT EXISTS history
140 (session integer, line integer, source text, source_raw text,
137 (session integer, line integer, source text, source_raw text,
141 PRIMARY KEY (session, line))""")
138 PRIMARY KEY (session, line))""")
142 # Output history is optional, but ensure the table's there so it can be
139 # Output history is optional, but ensure the table's there so it can be
143 # enabled later.
140 # enabled later.
144 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
141 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
145 (session integer, line integer, output text,
142 (session integer, line integer, output text,
146 PRIMARY KEY (session, line))""")
143 PRIMARY KEY (session, line))""")
147 self.db.commit()
144 self.db.commit()
148
145
149 def new_session(self, conn=None):
146 def new_session(self, conn=None):
150 """Get a new session number."""
147 """Get a new session number."""
151 if conn is None:
148 if conn is None:
152 conn = self.db
149 conn = self.db
153
150
154 with conn:
151 with conn:
155 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
152 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
156 NULL, "") """, (datetime.datetime.now(),))
153 NULL, "") """, (datetime.datetime.now(),))
157 self.session_number = cur.lastrowid
154 self.session_number = cur.lastrowid
158
155
159 def end_session(self):
156 def end_session(self):
160 """Close the database session, filling in the end time and line count."""
157 """Close the database session, filling in the end time and line count."""
161 self.writeout_cache()
158 self.writeout_cache()
162 with self.db:
159 with self.db:
163 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
160 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
164 session==?""", (datetime.datetime.now(),
161 session==?""", (datetime.datetime.now(),
165 len(self.input_hist_parsed)-1, self.session_number))
162 len(self.input_hist_parsed)-1, self.session_number))
166 self.session_number = 0
163 self.session_number = 0
167
164
168 def name_session(self, name):
165 def name_session(self, name):
169 """Give the current session a name in the history database."""
166 """Give the current session a name in the history database."""
170 with self.db:
167 with self.db:
171 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
168 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
172 (name, self.session_number))
169 (name, self.session_number))
173
170
174 def reset(self, new_session=True):
171 def reset(self, new_session=True):
175 """Clear the session history, releasing all object references, and
172 """Clear the session history, releasing all object references, and
176 optionally open a new session."""
173 optionally open a new session."""
177 self.output_hist.clear()
174 self.output_hist.clear()
178 # The directory history can't be completely empty
175 # The directory history can't be completely empty
179 self.dir_hist[:] = [os.getcwd()]
176 self.dir_hist[:] = [os.getcwd()]
180
177
181 if new_session:
178 if new_session:
182 if self.session_number:
179 if self.session_number:
183 self.end_session()
180 self.end_session()
184 self.input_hist_parsed[:] = [""]
181 self.input_hist_parsed[:] = [""]
185 self.input_hist_raw[:] = [""]
182 self.input_hist_raw[:] = [""]
186 self.new_session()
183 self.new_session()
187
184
188 ## -------------------------------
185 ## -------------------------------
189 ## Methods for retrieving history:
186 ## Methods for retrieving history:
190 ## -------------------------------
187 ## -------------------------------
191 def _run_sql(self, sql, params, raw=True, output=False):
188 def _run_sql(self, sql, params, raw=True, output=False):
192 """Prepares and runs an SQL query for the history database.
189 """Prepares and runs an SQL query for the history database.
193
190
194 Parameters
191 Parameters
195 ----------
192 ----------
196 sql : str
193 sql : str
197 Any filtering expressions to go after SELECT ... FROM ...
194 Any filtering expressions to go after SELECT ... FROM ...
198 params : tuple
195 params : tuple
199 Parameters passed to the SQL query (to replace "?")
196 Parameters passed to the SQL query (to replace "?")
200 raw, output : bool
197 raw, output : bool
201 See :meth:`get_range`
198 See :meth:`get_range`
202
199
203 Returns
200 Returns
204 -------
201 -------
205 Tuples as :meth:`get_range`
202 Tuples as :meth:`get_range`
206 """
203 """
207 toget = 'source_raw' if raw else 'source'
204 toget = 'source_raw' if raw else 'source'
208 sqlfrom = "history"
205 sqlfrom = "history"
209 if output:
206 if output:
210 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
207 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
211 toget = "history.%s, output_history.output" % toget
208 toget = "history.%s, output_history.output" % toget
212 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
209 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
213 (toget, sqlfrom) + sql, params)
210 (toget, sqlfrom) + sql, params)
214 if output: # Regroup into 3-tuples, and parse JSON
211 if output: # Regroup into 3-tuples, and parse JSON
215 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
212 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
216 return cur
213 return cur
217
214
218
215
219 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
216 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
220 """Get the last n lines from the history database.
217 """Get the last n lines from the history database.
221
218
222 Parameters
219 Parameters
223 ----------
220 ----------
224 n : int
221 n : int
225 The number of lines to get
222 The number of lines to get
226 raw, output : bool
223 raw, output : bool
227 See :meth:`get_range`
224 See :meth:`get_range`
228 include_latest : bool
225 include_latest : bool
229 If False (default), n+1 lines are fetched, and the latest one
226 If False (default), n+1 lines are fetched, and the latest one
230 is discarded. This is intended to be used where the function
227 is discarded. This is intended to be used where the function
231 is called by a user command, which it should not return.
228 is called by a user command, which it should not return.
232
229
233 Returns
230 Returns
234 -------
231 -------
235 Tuples as :meth:`get_range`
232 Tuples as :meth:`get_range`
236 """
233 """
237 self.writeout_cache()
234 self.writeout_cache()
238 if not include_latest:
235 if not include_latest:
239 n += 1
236 n += 1
240 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
237 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
241 (n,), raw=raw, output=output)
238 (n,), raw=raw, output=output)
242 if not include_latest:
239 if not include_latest:
243 return reversed(list(cur)[1:])
240 return reversed(list(cur)[1:])
244 return reversed(list(cur))
241 return reversed(list(cur))
245
242
246 def search(self, pattern="*", raw=True, search_raw=True,
243 def search(self, pattern="*", raw=True, search_raw=True,
247 output=False):
244 output=False):
248 """Search the database using unix glob-style matching (wildcards
245 """Search the database using unix glob-style matching (wildcards
249 * and ?).
246 * and ?).
250
247
251 Parameters
248 Parameters
252 ----------
249 ----------
253 pattern : str
250 pattern : str
254 The wildcarded pattern to match when searching
251 The wildcarded pattern to match when searching
255 search_raw : bool
252 search_raw : bool
256 If True, search the raw input, otherwise, the parsed input
253 If True, search the raw input, otherwise, the parsed input
257 raw, output : bool
254 raw, output : bool
258 See :meth:`get_range`
255 See :meth:`get_range`
259
256
260 Returns
257 Returns
261 -------
258 -------
262 Tuples as :meth:`get_range`
259 Tuples as :meth:`get_range`
263 """
260 """
264 tosearch = "source_raw" if search_raw else "source"
261 tosearch = "source_raw" if search_raw else "source"
265 if output:
262 if output:
266 tosearch = "history." + tosearch
263 tosearch = "history." + tosearch
267 self.writeout_cache()
264 self.writeout_cache()
268 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
265 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
269 raw=raw, output=output)
266 raw=raw, output=output)
270
267
271 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
268 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
272 """Get input and output history from the current session. Called by
269 """Get input and output history from the current session. Called by
273 get_range, and takes similar parameters."""
270 get_range, and takes similar parameters."""
274 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
271 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
275
272
276 n = len(input_hist)
273 n = len(input_hist)
277 if start < 0:
274 if start < 0:
278 start += n
275 start += n
279 if not stop:
276 if not stop:
280 stop = n
277 stop = n
281 elif stop < 0:
278 elif stop < 0:
282 stop += n
279 stop += n
283
280
284 for i in range(start, stop):
281 for i in range(start, stop):
285 if output:
282 if output:
286 line = (input_hist[i], self.output_hist_reprs.get(i))
283 line = (input_hist[i], self.output_hist_reprs.get(i))
287 else:
284 else:
288 line = input_hist[i]
285 line = input_hist[i]
289 yield (0, i, line)
286 yield (0, i, line)
290
287
291 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
288 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
292 """Retrieve input by session.
289 """Retrieve input by session.
293
290
294 Parameters
291 Parameters
295 ----------
292 ----------
296 session : int
293 session : int
297 Session number to retrieve. The current session is 0, and negative
294 Session number to retrieve. The current session is 0, and negative
298 numbers count back from current session, so -1 is previous session.
295 numbers count back from current session, so -1 is previous session.
299 start : int
296 start : int
300 First line to retrieve.
297 First line to retrieve.
301 stop : int
298 stop : int
302 End of line range (excluded from output itself). If None, retrieve
299 End of line range (excluded from output itself). If None, retrieve
303 to the end of the session.
300 to the end of the session.
304 raw : bool
301 raw : bool
305 If True, return untranslated input
302 If True, return untranslated input
306 output : bool
303 output : bool
307 If True, attempt to include output. This will be 'real' Python
304 If True, attempt to include output. This will be 'real' Python
308 objects for the current session, or text reprs from previous
305 objects for the current session, or text reprs from previous
309 sessions if db_log_output was enabled at the time. Where no output
306 sessions if db_log_output was enabled at the time. Where no output
310 is found, None is used.
307 is found, None is used.
311
308
312 Returns
309 Returns
313 -------
310 -------
314 An iterator over the desired lines. Each line is a 3-tuple, either
311 An iterator over the desired lines. Each line is a 3-tuple, either
315 (session, line, input) if output is False, or
312 (session, line, input) if output is False, or
316 (session, line, (input, output)) if output is True.
313 (session, line, (input, output)) if output is True.
317 """
314 """
318 if session == 0 or session==self.session_number: # Current session
315 if session == 0 or session==self.session_number: # Current session
319 return self._get_range_session(start, stop, raw, output)
316 return self._get_range_session(start, stop, raw, output)
320 if session < 0:
317 if session < 0:
321 session += self.session_number
318 session += self.session_number
322
319
323 if stop:
320 if stop:
324 lineclause = "line >= ? AND line < ?"
321 lineclause = "line >= ? AND line < ?"
325 params = (session, start, stop)
322 params = (session, start, stop)
326 else:
323 else:
327 lineclause = "line>=?"
324 lineclause = "line>=?"
328 params = (session, start)
325 params = (session, start)
329
326
330 return self._run_sql("WHERE session==? AND %s""" % lineclause,
327 return self._run_sql("WHERE session==? AND %s""" % lineclause,
331 params, raw=raw, output=output)
328 params, raw=raw, output=output)
332
329
333 def get_range_by_str(self, rangestr, raw=True, output=False):
330 def get_range_by_str(self, rangestr, raw=True, output=False):
334 """Get lines of history from a string of ranges, as used by magic
331 """Get lines of history from a string of ranges, as used by magic
335 commands %hist, %save, %macro, etc.
332 commands %hist, %save, %macro, etc.
336
333
337 Parameters
334 Parameters
338 ----------
335 ----------
339 rangestr : str
336 rangestr : str
340 A string specifying ranges, e.g. "5 ~2/1-4". See
337 A string specifying ranges, e.g. "5 ~2/1-4". See
341 :func:`magic_history` for full details.
338 :func:`magic_history` for full details.
342 raw, output : bool
339 raw, output : bool
343 As :meth:`get_range`
340 As :meth:`get_range`
344
341
345 Returns
342 Returns
346 -------
343 -------
347 Tuples as :meth:`get_range`
344 Tuples as :meth:`get_range`
348 """
345 """
349 for sess, s, e in extract_hist_ranges(rangestr):
346 for sess, s, e in extract_hist_ranges(rangestr):
350 for line in self.get_range(sess, s, e, raw=raw, output=output):
347 for line in self.get_range(sess, s, e, raw=raw, output=output):
351 yield line
348 yield line
352
349
353 ## ----------------------------
350 ## ----------------------------
354 ## Methods for storing history:
351 ## Methods for storing history:
355 ## ----------------------------
352 ## ----------------------------
356 def store_inputs(self, line_num, source, source_raw=None):
353 def store_inputs(self, line_num, source, source_raw=None):
357 """Store source and raw input in history and create input cache
354 """Store source and raw input in history and create input cache
358 variables _i*.
355 variables _i*.
359
356
360 Parameters
357 Parameters
361 ----------
358 ----------
362 line_num : int
359 line_num : int
363 The prompt number of this input.
360 The prompt number of this input.
364
361
365 source : str
362 source : str
366 Python input.
363 Python input.
367
364
368 source_raw : str, optional
365 source_raw : str, optional
369 If given, this is the raw input without any IPython transformations
366 If given, this is the raw input without any IPython transformations
370 applied to it. If not given, ``source`` is used.
367 applied to it. If not given, ``source`` is used.
371 """
368 """
372 if source_raw is None:
369 if source_raw is None:
373 source_raw = source
370 source_raw = source
374 source = source.rstrip('\n')
371 source = source.rstrip('\n')
375 source_raw = source_raw.rstrip('\n')
372 source_raw = source_raw.rstrip('\n')
376
373
377 # do not store exit/quit commands
374 # do not store exit/quit commands
378 if self._exit_re.match(source_raw.strip()):
375 if self._exit_re.match(source_raw.strip()):
379 return
376 return
380
377
381 self.input_hist_parsed.append(source)
378 self.input_hist_parsed.append(source)
382 self.input_hist_raw.append(source_raw)
379 self.input_hist_raw.append(source_raw)
383
380
384 with self.db_input_cache_lock:
381 with self.db_input_cache_lock:
385 self.db_input_cache.append((line_num, source, source_raw))
382 self.db_input_cache.append((line_num, source, source_raw))
386 # Trigger to flush cache and write to DB.
383 # Trigger to flush cache and write to DB.
387 if len(self.db_input_cache) >= self.db_cache_size:
384 if len(self.db_input_cache) >= self.db_cache_size:
388 self.save_flag.set()
385 self.save_flag.set()
389
386
390 # update the auto _i variables
387 # update the auto _i variables
391 self._iii = self._ii
388 self._iii = self._ii
392 self._ii = self._i
389 self._ii = self._i
393 self._i = self._i00
390 self._i = self._i00
394 self._i00 = source_raw
391 self._i00 = source_raw
395
392
396 # hackish access to user namespace to create _i1,_i2... dynamically
393 # hackish access to user namespace to create _i1,_i2... dynamically
397 new_i = '_i%s' % line_num
394 new_i = '_i%s' % line_num
398 to_main = {'_i': self._i,
395 to_main = {'_i': self._i,
399 '_ii': self._ii,
396 '_ii': self._ii,
400 '_iii': self._iii,
397 '_iii': self._iii,
401 new_i : self._i00 }
398 new_i : self._i00 }
402 self.shell.user_ns.update(to_main)
399 self.shell.user_ns.update(to_main)
403
400
404 def store_output(self, line_num):
401 def store_output(self, line_num):
405 """If database output logging is enabled, this saves all the
402 """If database output logging is enabled, this saves all the
406 outputs from the indicated prompt number to the database. It's
403 outputs from the indicated prompt number to the database. It's
407 called by run_cell after code has been executed.
404 called by run_cell after code has been executed.
408
405
409 Parameters
406 Parameters
410 ----------
407 ----------
411 line_num : int
408 line_num : int
412 The line number from which to save outputs
409 The line number from which to save outputs
413 """
410 """
414 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
411 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
415 return
412 return
416 output = self.output_hist_reprs[line_num]
413 output = self.output_hist_reprs[line_num]
417
414
418 with self.db_output_cache_lock:
415 with self.db_output_cache_lock:
419 self.db_output_cache.append((line_num, output))
416 self.db_output_cache.append((line_num, output))
420 if self.db_cache_size <= 1:
417 if self.db_cache_size <= 1:
421 self.save_flag.set()
418 self.save_flag.set()
422
419
423 def _writeout_input_cache(self, conn):
420 def _writeout_input_cache(self, conn):
424 with conn:
421 with conn:
425 for line in self.db_input_cache:
422 for line in self.db_input_cache:
426 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
423 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
427 (self.session_number,)+line)
424 (self.session_number,)+line)
428
425
429 def _writeout_output_cache(self, conn):
426 def _writeout_output_cache(self, conn):
430 with conn:
427 with conn:
431 for line in self.db_output_cache:
428 for line in self.db_output_cache:
432 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
429 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
433 (self.session_number,)+line)
430 (self.session_number,)+line)
434
431
435 def writeout_cache(self, conn=None):
432 def writeout_cache(self, conn=None):
436 """Write any entries in the cache to the database."""
433 """Write any entries in the cache to the database."""
437 if conn is None:
434 if conn is None:
438 conn = self.db
435 conn = self.db
439
436
440 with self.db_input_cache_lock:
437 with self.db_input_cache_lock:
441 try:
438 try:
442 self._writeout_input_cache(conn)
439 self._writeout_input_cache(conn)
443 except sqlite3.IntegrityError:
440 except sqlite3.IntegrityError:
444 self.new_session(conn)
441 self.new_session(conn)
445 print("ERROR! Session/line number was not unique in",
442 print("ERROR! Session/line number was not unique in",
446 "database. History logging moved to new session",
443 "database. History logging moved to new session",
447 self.session_number)
444 self.session_number)
448 try: # Try writing to the new session. If this fails, don't recurse
445 try: # Try writing to the new session. If this fails, don't recurse
449 self._writeout_input_cache(conn)
446 self._writeout_input_cache(conn)
450 except sqlite3.IntegrityError:
447 except sqlite3.IntegrityError:
451 pass
448 pass
452 finally:
449 finally:
453 self.db_input_cache = []
450 self.db_input_cache = []
454
451
455 with self.db_output_cache_lock:
452 with self.db_output_cache_lock:
456 try:
453 try:
457 self._writeout_output_cache(conn)
454 self._writeout_output_cache(conn)
458 except sqlite3.IntegrityError:
455 except sqlite3.IntegrityError:
459 print("!! Session/line number for output was not unique",
456 print("!! Session/line number for output was not unique",
460 "in database. Output will not be stored.")
457 "in database. Output will not be stored.")
461 finally:
458 finally:
462 self.db_output_cache = []
459 self.db_output_cache = []
463
460
464
461
465 class HistorySavingThread(threading.Thread):
462 class HistorySavingThread(threading.Thread):
466 """This thread takes care of writing history to the database, so that
463 """This thread takes care of writing history to the database, so that
467 the UI isn't held up while that happens.
464 the UI isn't held up while that happens.
468
465
469 It waits for the HistoryManager's save_flag to be set, then writes out
466 It waits for the HistoryManager's save_flag to be set, then writes out
470 the history cache. The main thread is responsible for setting the flag when
467 the history cache. The main thread is responsible for setting the flag when
471 the cache size reaches a defined threshold."""
468 the cache size reaches a defined threshold."""
472 daemon = True
469 daemon = True
473 stop_now = False
470 stop_now = False
474 def __init__(self, history_manager):
471 def __init__(self, history_manager):
475 super(HistorySavingThread, self).__init__()
472 super(HistorySavingThread, self).__init__()
476 self.history_manager = history_manager
473 self.history_manager = history_manager
477 atexit.register(self.stop)
474 atexit.register(self.stop)
478
475
479 def run(self):
476 def run(self):
480 # We need a separate db connection per thread:
477 # We need a separate db connection per thread:
481 try:
478 try:
482 self.db = sqlite3.connect(self.history_manager.hist_file)
479 self.db = sqlite3.connect(self.history_manager.hist_file)
483 while True:
480 while True:
484 self.history_manager.save_flag.wait()
481 self.history_manager.save_flag.wait()
485 if self.stop_now:
482 if self.stop_now:
486 return
483 return
487 self.history_manager.save_flag.clear()
484 self.history_manager.save_flag.clear()
488 self.history_manager.writeout_cache(self.db)
485 self.history_manager.writeout_cache(self.db)
489 except Exception as e:
486 except Exception as e:
490 print(("The history saving thread hit an unexpected error (%s)."
487 print(("The history saving thread hit an unexpected error (%s)."
491 "History will not be written to the database.") % repr(e))
488 "History will not be written to the database.") % repr(e))
492
489
493 def stop(self):
490 def stop(self):
494 """This can be called from the main thread to safely stop this thread.
491 """This can be called from the main thread to safely stop this thread.
495
492
496 Note that it does not attempt to write out remaining history before
493 Note that it does not attempt to write out remaining history before
497 exiting. That should be done by calling the HistoryManager's
494 exiting. That should be done by calling the HistoryManager's
498 end_session method."""
495 end_session method."""
499 self.stop_now = True
496 self.stop_now = True
500 self.history_manager.save_flag.set()
497 self.history_manager.save_flag.set()
501 self.join()
498 self.join()
502
499
503
500
504 # To match, e.g. ~5/8-~2/3
501 # To match, e.g. ~5/8-~2/3
505 range_re = re.compile(r"""
502 range_re = re.compile(r"""
506 ((?P<startsess>~?\d+)/)?
503 ((?P<startsess>~?\d+)/)?
507 (?P<start>\d+) # Only the start line num is compulsory
504 (?P<start>\d+) # Only the start line num is compulsory
508 ((?P<sep>[\-:])
505 ((?P<sep>[\-:])
509 ((?P<endsess>~?\d+)/)?
506 ((?P<endsess>~?\d+)/)?
510 (?P<end>\d+))?
507 (?P<end>\d+))?
511 $""", re.VERBOSE)
508 $""", re.VERBOSE)
512
509
513 def extract_hist_ranges(ranges_str):
510 def extract_hist_ranges(ranges_str):
514 """Turn a string of history ranges into 3-tuples of (session, start, stop).
511 """Turn a string of history ranges into 3-tuples of (session, start, stop).
515
512
516 Examples
513 Examples
517 --------
514 --------
518 list(extract_input_ranges("~8/5-~7/4 2"))
515 list(extract_input_ranges("~8/5-~7/4 2"))
519 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
516 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
520 """
517 """
521 for range_str in ranges_str.split():
518 for range_str in ranges_str.split():
522 rmatch = range_re.match(range_str)
519 rmatch = range_re.match(range_str)
523 if not rmatch:
520 if not rmatch:
524 continue
521 continue
525 start = int(rmatch.group("start"))
522 start = int(rmatch.group("start"))
526 end = rmatch.group("end")
523 end = rmatch.group("end")
527 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
524 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
528 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
525 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
529 end += 1
526 end += 1
530 startsess = rmatch.group("startsess") or "0"
527 startsess = rmatch.group("startsess") or "0"
531 endsess = rmatch.group("endsess") or startsess
528 endsess = rmatch.group("endsess") or startsess
532 startsess = int(startsess.replace("~","-"))
529 startsess = int(startsess.replace("~","-"))
533 endsess = int(endsess.replace("~","-"))
530 endsess = int(endsess.replace("~","-"))
534 assert endsess >= startsess
531 assert endsess >= startsess
535
532
536 if endsess == startsess:
533 if endsess == startsess:
537 yield (startsess, start, end)
534 yield (startsess, start, end)
538 continue
535 continue
539 # Multiple sessions in one range:
536 # Multiple sessions in one range:
540 yield (startsess, start, None)
537 yield (startsess, start, None)
541 for sess in range(startsess+1, endsess):
538 for sess in range(startsess+1, endsess):
542 yield (sess, 1, None)
539 yield (sess, 1, None)
543 yield (endsess, 1, end)
540 yield (endsess, 1, end)
544
541
545 def _format_lineno(session, line):
542 def _format_lineno(session, line):
546 """Helper function to format line numbers properly."""
543 """Helper function to format line numbers properly."""
547 if session == 0:
544 if session == 0:
548 return str(line)
545 return str(line)
549 return "%s#%s" % (session, line)
546 return "%s#%s" % (session, line)
550
547
551 @skip_doctest
548 @skip_doctest
552 def magic_history(self, parameter_s = ''):
549 def magic_history(self, parameter_s = ''):
553 """Print input history (_i<n> variables), with most recent last.
550 """Print input history (_i<n> variables), with most recent last.
554
551
555 %history -> print at most 40 inputs (some may be multi-line)\\
552 %history -> print at most 40 inputs (some may be multi-line)\\
556 %history n -> print at most n inputs\\
553 %history n -> print at most n inputs\\
557 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
554 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
558
555
559 By default, input history is printed without line numbers so it can be
556 By default, input history is printed without line numbers so it can be
560 directly pasted into an editor. Use -n to show them.
557 directly pasted into an editor. Use -n to show them.
561
558
562 Ranges of history can be indicated using the syntax:
559 Ranges of history can be indicated using the syntax:
563 4 : Line 4, current session
560 4 : Line 4, current session
564 4-6 : Lines 4-6, current session
561 4-6 : Lines 4-6, current session
565 243/1-5: Lines 1-5, session 243
562 243/1-5: Lines 1-5, session 243
566 ~2/7 : Line 7, session 2 before current
563 ~2/7 : Line 7, session 2 before current
567 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
564 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
568 of 6 sessions ago.
565 of 6 sessions ago.
569 Multiple ranges can be entered, separated by spaces
566 Multiple ranges can be entered, separated by spaces
570
567
571 The same syntax is used by %macro, %save, %edit, %rerun
568 The same syntax is used by %macro, %save, %edit, %rerun
572
569
573 Options:
570 Options:
574
571
575 -n: print line numbers for each input.
572 -n: print line numbers for each input.
576 This feature is only available if numbered prompts are in use.
573 This feature is only available if numbered prompts are in use.
577
574
578 -o: also print outputs for each input.
575 -o: also print outputs for each input.
579
576
580 -p: print classic '>>>' python prompts before each input. This is useful
577 -p: print classic '>>>' python prompts before each input. This is useful
581 for making documentation, and in conjunction with -o, for producing
578 for making documentation, and in conjunction with -o, for producing
582 doctest-ready output.
579 doctest-ready output.
583
580
584 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
581 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
585
582
586 -t: print the 'translated' history, as IPython understands it. IPython
583 -t: print the 'translated' history, as IPython understands it. IPython
587 filters your input and converts it all into valid Python source before
584 filters your input and converts it all into valid Python source before
588 executing it (things like magics or aliases are turned into function
585 executing it (things like magics or aliases are turned into function
589 calls, for example). With this option, you'll see the native history
586 calls, for example). With this option, you'll see the native history
590 instead of the user-entered version: '%cd /' will be seen as
587 instead of the user-entered version: '%cd /' will be seen as
591 'get_ipython().magic("%cd /")' instead of '%cd /'.
588 'get_ipython().magic("%cd /")' instead of '%cd /'.
592
589
593 -g: treat the arg as a pattern to grep for in (full) history.
590 -g: treat the arg as a pattern to grep for in (full) history.
594 This includes the saved history (almost all commands ever written).
591 This includes the saved history (almost all commands ever written).
595 Use '%hist -g' to show full saved history (may be very long).
592 Use '%hist -g' to show full saved history (may be very long).
596
593
597 -l: get the last n lines from all sessions. Specify n as a single arg, or
594 -l: get the last n lines from all sessions. Specify n as a single arg, or
598 the default is the last 10 lines.
595 the default is the last 10 lines.
599
596
600 -f FILENAME: instead of printing the output to the screen, redirect it to
597 -f FILENAME: instead of printing the output to the screen, redirect it to
601 the given file. The file is always overwritten, though IPython asks for
598 the given file. The file is always overwritten, though IPython asks for
602 confirmation first if it already exists.
599 confirmation first if it already exists.
603
600
604 Examples
601 Examples
605 --------
602 --------
606 ::
603 ::
607
604
608 In [6]: %hist -n 4 6
605 In [6]: %hist -n 4 6
609 4:a = 12
606 4:a = 12
610 5:print a**2
607 5:print a**2
611
608
612 """
609 """
613
610
614 if not self.shell.displayhook.do_full_cache:
611 if not self.shell.displayhook.do_full_cache:
615 print('This feature is only available if numbered prompts are in use.')
612 print('This feature is only available if numbered prompts are in use.')
616 return
613 return
617 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
614 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
618
615
619 # For brevity
616 # For brevity
620 history_manager = self.shell.history_manager
617 history_manager = self.shell.history_manager
621
618
622 def _format_lineno(session, line):
619 def _format_lineno(session, line):
623 """Helper function to format line numbers properly."""
620 """Helper function to format line numbers properly."""
624 if session in (0, history_manager.session_number):
621 if session in (0, history_manager.session_number):
625 return str(line)
622 return str(line)
626 return "%s/%s" % (session, line)
623 return "%s/%s" % (session, line)
627
624
628 # Check if output to specific file was requested.
625 # Check if output to specific file was requested.
629 try:
626 try:
630 outfname = opts['f']
627 outfname = opts['f']
631 except KeyError:
628 except KeyError:
632 outfile = io.stdout # default
629 outfile = io.stdout # default
633 # We don't want to close stdout at the end!
630 # We don't want to close stdout at the end!
634 close_at_end = False
631 close_at_end = False
635 else:
632 else:
636 if os.path.exists(outfname):
633 if os.path.exists(outfname):
637 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
634 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
638 print('Aborting.')
635 print('Aborting.')
639 return
636 return
640
637
641 outfile = open(outfname,'w')
638 outfile = open(outfname,'w')
642 close_at_end = True
639 close_at_end = True
643
640
644 print_nums = 'n' in opts
641 print_nums = 'n' in opts
645 get_output = 'o' in opts
642 get_output = 'o' in opts
646 pyprompts = 'p' in opts
643 pyprompts = 'p' in opts
647 # Raw history is the default
644 # Raw history is the default
648 raw = not('t' in opts)
645 raw = not('t' in opts)
649
646
650 default_length = 40
647 default_length = 40
651 pattern = None
648 pattern = None
652
649
653 if 'g' in opts: # Glob search
650 if 'g' in opts: # Glob search
654 pattern = "*" + args + "*" if args else "*"
651 pattern = "*" + args + "*" if args else "*"
655 hist = history_manager.search(pattern, raw=raw, output=get_output)
652 hist = history_manager.search(pattern, raw=raw, output=get_output)
656 elif 'l' in opts: # Get 'tail'
653 elif 'l' in opts: # Get 'tail'
657 try:
654 try:
658 n = int(args)
655 n = int(args)
659 except ValueError, IndexError:
656 except ValueError, IndexError:
660 n = 10
657 n = 10
661 hist = history_manager.get_tail(n, raw=raw, output=get_output)
658 hist = history_manager.get_tail(n, raw=raw, output=get_output)
662 else:
659 else:
663 if args: # Get history by ranges
660 if args: # Get history by ranges
664 hist = history_manager.get_range_by_str(args, raw, get_output)
661 hist = history_manager.get_range_by_str(args, raw, get_output)
665 else: # Just get history for the current session
662 else: # Just get history for the current session
666 hist = history_manager.get_range(raw=raw, output=get_output)
663 hist = history_manager.get_range(raw=raw, output=get_output)
667
664
668 # We could be displaying the entire history, so let's not try to pull it
665 # We could be displaying the entire history, so let's not try to pull it
669 # into a list in memory. Anything that needs more space will just misalign.
666 # into a list in memory. Anything that needs more space will just misalign.
670 width = 4
667 width = 4
671
668
672 for session, lineno, inline in hist:
669 for session, lineno, inline in hist:
673 # Print user history with tabs expanded to 4 spaces. The GUI clients
670 # Print user history with tabs expanded to 4 spaces. The GUI clients
674 # use hard tabs for easier usability in auto-indented code, but we want
671 # use hard tabs for easier usability in auto-indented code, but we want
675 # to produce PEP-8 compliant history for safe pasting into an editor.
672 # to produce PEP-8 compliant history for safe pasting into an editor.
676 if get_output:
673 if get_output:
677 inline, output = inline
674 inline, output = inline
678 inline = inline.expandtabs(4).rstrip()
675 inline = inline.expandtabs(4).rstrip()
679
676
680 multiline = "\n" in inline
677 multiline = "\n" in inline
681 line_sep = '\n' if multiline else ' '
678 line_sep = '\n' if multiline else ' '
682 if print_nums:
679 if print_nums:
683 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
680 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
684 line_sep), file=outfile, end='')
681 line_sep), file=outfile, end='')
685 if pyprompts:
682 if pyprompts:
686 print(">>> ", end="", file=outfile)
683 print(">>> ", end="", file=outfile)
687 if multiline:
684 if multiline:
688 inline = "\n... ".join(inline.splitlines()) + "\n..."
685 inline = "\n... ".join(inline.splitlines()) + "\n..."
689 print(inline, file=outfile)
686 print(inline, file=outfile)
690 if get_output and output:
687 if get_output and output:
691 print(output, file=outfile)
688 print(output, file=outfile)
692
689
693 if close_at_end:
690 if close_at_end:
694 outfile.close()
691 outfile.close()
695
692
696
693
697 def magic_rep(self, arg):
694 def magic_rep(self, arg):
698 r""" Repeat a command, or get command to input line for editing
695 r""" Repeat a command, or get command to input line for editing
699
696
700 - %rep (no arguments):
697 - %rep (no arguments):
701
698
702 Place a string version of last computation result (stored in the special '_'
699 Place a string version of last computation result (stored in the special '_'
703 variable) to the next input prompt. Allows you to create elaborate command
700 variable) to the next input prompt. Allows you to create elaborate command
704 lines without using copy-paste::
701 lines without using copy-paste::
705
702
706 In[1]: l = ["hei", "vaan"]
703 In[1]: l = ["hei", "vaan"]
707 In[2]: "".join(l)
704 In[2]: "".join(l)
708 Out[2]: heivaan
705 Out[2]: heivaan
709 In[3]: %rep
706 In[3]: %rep
710 In[4]: heivaan_ <== cursor blinking
707 In[4]: heivaan_ <== cursor blinking
711
708
712 %rep 45
709 %rep 45
713
710
714 Place history line 45 on the next input prompt. Use %hist to find
711 Place history line 45 on the next input prompt. Use %hist to find
715 out the number.
712 out the number.
716
713
717 %rep 1-4
714 %rep 1-4
718
715
719 Combine the specified lines into one cell, and place it on the next
716 Combine the specified lines into one cell, and place it on the next
720 input prompt. See %history for the slice syntax.
717 input prompt. See %history for the slice syntax.
721
718
722 %rep foo+bar
719 %rep foo+bar
723
720
724 If foo+bar can be evaluated in the user namespace, the result is
721 If foo+bar can be evaluated in the user namespace, the result is
725 placed at the next input prompt. Otherwise, the history is searched
722 placed at the next input prompt. Otherwise, the history is searched
726 for lines which contain that substring, and the most recent one is
723 for lines which contain that substring, and the most recent one is
727 placed at the next input prompt.
724 placed at the next input prompt.
728 """
725 """
729 if not arg: # Last output
726 if not arg: # Last output
730 self.set_next_input(str(self.shell.user_ns["_"]))
727 self.set_next_input(str(self.shell.user_ns["_"]))
731 return
728 return
732 # Get history range
729 # Get history range
733 histlines = self.history_manager.get_range_by_str(arg)
730 histlines = self.history_manager.get_range_by_str(arg)
734 cmd = "\n".join(x[2] for x in histlines)
731 cmd = "\n".join(x[2] for x in histlines)
735 if cmd:
732 if cmd:
736 self.set_next_input(cmd.rstrip())
733 self.set_next_input(cmd.rstrip())
737 return
734 return
738
735
739 try: # Variable in user namespace
736 try: # Variable in user namespace
740 cmd = str(eval(arg, self.shell.user_ns))
737 cmd = str(eval(arg, self.shell.user_ns))
741 except Exception: # Search for term in history
738 except Exception: # Search for term in history
742 histlines = self.history_manager.search("*"+arg+"*")
739 histlines = self.history_manager.search("*"+arg+"*")
743 for h in reversed([x[2] for x in histlines]):
740 for h in reversed([x[2] for x in histlines]):
744 if 'rep' in h:
741 if 'rep' in h:
745 continue
742 continue
746 self.set_next_input(h.rstrip())
743 self.set_next_input(h.rstrip())
747 return
744 return
748 else:
745 else:
749 self.set_next_input(cmd.rstrip())
746 self.set_next_input(cmd.rstrip())
750 print("Couldn't evaluate or find in history:", arg)
747 print("Couldn't evaluate or find in history:", arg)
751
748
752 def magic_rerun(self, parameter_s=''):
749 def magic_rerun(self, parameter_s=''):
753 """Re-run previous input
750 """Re-run previous input
754
751
755 By default, you can specify ranges of input history to be repeated
752 By default, you can specify ranges of input history to be repeated
756 (as with %history). With no arguments, it will repeat the last line.
753 (as with %history). With no arguments, it will repeat the last line.
757
754
758 Options:
755 Options:
759
756
760 -l <n> : Repeat the last n lines of input, not including the
757 -l <n> : Repeat the last n lines of input, not including the
761 current command.
758 current command.
762
759
763 -g foo : Repeat the most recent line which contains foo
760 -g foo : Repeat the most recent line which contains foo
764 """
761 """
765 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
762 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
766 if "l" in opts: # Last n lines
763 if "l" in opts: # Last n lines
767 n = int(opts['l'])
764 n = int(opts['l'])
768 hist = self.history_manager.get_tail(n)
765 hist = self.history_manager.get_tail(n)
769 elif "g" in opts: # Search
766 elif "g" in opts: # Search
770 p = "*"+opts['g']+"*"
767 p = "*"+opts['g']+"*"
771 hist = list(self.history_manager.search(p))
768 hist = list(self.history_manager.search(p))
772 for l in reversed(hist):
769 for l in reversed(hist):
773 if "rerun" not in l[2]:
770 if "rerun" not in l[2]:
774 hist = [l] # The last match which isn't a %rerun
771 hist = [l] # The last match which isn't a %rerun
775 break
772 break
776 else:
773 else:
777 hist = [] # No matches except %rerun
774 hist = [] # No matches except %rerun
778 elif args: # Specify history ranges
775 elif args: # Specify history ranges
779 hist = self.history_manager.get_range_by_str(args)
776 hist = self.history_manager.get_range_by_str(args)
780 else: # Last line
777 else: # Last line
781 hist = self.history_manager.get_tail(1)
778 hist = self.history_manager.get_tail(1)
782 hist = [x[2] for x in hist]
779 hist = [x[2] for x in hist]
783 if not hist:
780 if not hist:
784 print("No lines in history match specification")
781 print("No lines in history match specification")
785 return
782 return
786 histlines = "\n".join(hist)
783 histlines = "\n".join(hist)
787 print("=== Executing: ===")
784 print("=== Executing: ===")
788 print(histlines)
785 print(histlines)
789 print("=== Output: ===")
786 print("=== Output: ===")
790 self.run_cell("\n".join(hist), store_history=False)
787 self.run_cell("\n".join(hist), store_history=False)
791
788
792
789
793 def init_ipython(ip):
790 def init_ipython(ip):
794 ip.define_magic("rep", magic_rep)
791 ip.define_magic("rep", magic_rep)
795 ip.define_magic("recall", magic_rep)
792 ip.define_magic("recall", magic_rep)
796 ip.define_magic("rerun", magic_rerun)
793 ip.define_magic("rerun", magic_rerun)
797 ip.define_magic("hist",magic_history) # Alternative name
794 ip.define_magic("hist",magic_history) # Alternative name
798 ip.define_magic("history",magic_history)
795 ip.define_magic("history",magic_history)
799
796
800 # XXX - ipy_completers are in quarantine, need to be updated to new apis
797 # XXX - ipy_completers are in quarantine, need to be updated to new apis
801 #import ipy_completers
798 #import ipy_completers
802 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
799 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2542 +1,2553 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager, AliasError
41 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import TryNext, UsageError
48 from IPython.core.error import TryNext, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import IPythonInputSplitter
53 from IPython.core.inputsplitter import IPythonInputSplitter
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.magic import Magic
56 from IPython.core.magic import Magic
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.plugin import PluginManager
58 from IPython.core.plugin import PluginManager
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.core.profiledir import ProfileDir
60 from IPython.external.Itpl import ItplNS
61 from IPython.external.Itpl import ItplNS
61 from IPython.utils import PyColorize
62 from IPython.utils import PyColorize
62 from IPython.utils import io
63 from IPython.utils import io
63 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 List, Unicode, Instance, Type)
74 List, Unicode, Instance, Type)
74 from IPython.utils.warn import warn, error, fatal
75 from IPython.utils.warn import warn, error, fatal
75 import IPython.core.hooks
76 import IPython.core.hooks
76
77
77 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
78 # Globals
79 # Globals
79 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
80
81
81 # compiled regexps for autoindent management
82 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
84
84 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
85 # Utilities
86 # Utilities
86 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
87
88
88 # store the builtin raw_input globally, and use this always, in case user code
89 # store the builtin raw_input globally, and use this always, in case user code
89 # overwrites it (like wx.py.PyShell does)
90 # overwrites it (like wx.py.PyShell does)
90 raw_input_original = raw_input
91 raw_input_original = raw_input
91
92
92 def softspace(file, newvalue):
93 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
94 """Copied from code.py, to remove the dependency"""
94
95
95 oldvalue = 0
96 oldvalue = 0
96 try:
97 try:
97 oldvalue = file.softspace
98 oldvalue = file.softspace
98 except AttributeError:
99 except AttributeError:
99 pass
100 pass
100 try:
101 try:
101 file.softspace = newvalue
102 file.softspace = newvalue
102 except (AttributeError, TypeError):
103 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
104 # "attribute-less object" or "read-only attributes"
104 pass
105 pass
105 return oldvalue
106 return oldvalue
106
107
107
108
108 def no_op(*a, **kw): pass
109 def no_op(*a, **kw): pass
109
110
110 class SpaceInInput(Exception): pass
111 class SpaceInInput(Exception): pass
111
112
112 class Bunch: pass
113 class Bunch: pass
113
114
114
115
115 def get_default_colors():
116 def get_default_colors():
116 if sys.platform=='darwin':
117 if sys.platform=='darwin':
117 return "LightBG"
118 return "LightBG"
118 elif os.name=='nt':
119 elif os.name=='nt':
119 return 'Linux'
120 return 'Linux'
120 else:
121 else:
121 return 'Linux'
122 return 'Linux'
122
123
123
124
124 class SeparateStr(Str):
125 class SeparateStr(Str):
125 """A Str subclass to validate separate_in, separate_out, etc.
126 """A Str subclass to validate separate_in, separate_out, etc.
126
127
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 """
129 """
129
130
130 def validate(self, obj, value):
131 def validate(self, obj, value):
131 if value == '0': value = ''
132 if value == '0': value = ''
132 value = value.replace('\\n','\n')
133 value = value.replace('\\n','\n')
133 return super(SeparateStr, self).validate(obj, value)
134 return super(SeparateStr, self).validate(obj, value)
134
135
135
136
136 class ReadlineNoRecord(object):
137 class ReadlineNoRecord(object):
137 """Context manager to execute some code, then reload readline history
138 """Context manager to execute some code, then reload readline history
138 so that interactive input to the code doesn't appear when pressing up."""
139 so that interactive input to the code doesn't appear when pressing up."""
139 def __init__(self, shell):
140 def __init__(self, shell):
140 self.shell = shell
141 self.shell = shell
141 self._nested_level = 0
142 self._nested_level = 0
142
143
143 def __enter__(self):
144 def __enter__(self):
144 if self._nested_level == 0:
145 if self._nested_level == 0:
145 try:
146 try:
146 self.orig_length = self.current_length()
147 self.orig_length = self.current_length()
147 self.readline_tail = self.get_readline_tail()
148 self.readline_tail = self.get_readline_tail()
148 except (AttributeError, IndexError): # Can fail with pyreadline
149 except (AttributeError, IndexError): # Can fail with pyreadline
149 self.orig_length, self.readline_tail = 999999, []
150 self.orig_length, self.readline_tail = 999999, []
150 self._nested_level += 1
151 self._nested_level += 1
151
152
152 def __exit__(self, type, value, traceback):
153 def __exit__(self, type, value, traceback):
153 self._nested_level -= 1
154 self._nested_level -= 1
154 if self._nested_level == 0:
155 if self._nested_level == 0:
155 # Try clipping the end if it's got longer
156 # Try clipping the end if it's got longer
156 try:
157 try:
157 e = self.current_length() - self.orig_length
158 e = self.current_length() - self.orig_length
158 if e > 0:
159 if e > 0:
159 for _ in range(e):
160 for _ in range(e):
160 self.shell.readline.remove_history_item(self.orig_length)
161 self.shell.readline.remove_history_item(self.orig_length)
161
162
162 # If it still doesn't match, just reload readline history.
163 # If it still doesn't match, just reload readline history.
163 if self.current_length() != self.orig_length \
164 if self.current_length() != self.orig_length \
164 or self.get_readline_tail() != self.readline_tail:
165 or self.get_readline_tail() != self.readline_tail:
165 self.shell.refill_readline_hist()
166 self.shell.refill_readline_hist()
166 except (AttributeError, IndexError):
167 except (AttributeError, IndexError):
167 pass
168 pass
168 # Returning False will cause exceptions to propagate
169 # Returning False will cause exceptions to propagate
169 return False
170 return False
170
171
171 def current_length(self):
172 def current_length(self):
172 return self.shell.readline.get_current_history_length()
173 return self.shell.readline.get_current_history_length()
173
174
174 def get_readline_tail(self, n=10):
175 def get_readline_tail(self, n=10):
175 """Get the last n items in readline history."""
176 """Get the last n items in readline history."""
176 end = self.shell.readline.get_current_history_length() + 1
177 end = self.shell.readline.get_current_history_length() + 1
177 start = max(end-n, 1)
178 start = max(end-n, 1)
178 ghi = self.shell.readline.get_history_item
179 ghi = self.shell.readline.get_history_item
179 return [ghi(x) for x in range(start, end)]
180 return [ghi(x) for x in range(start, end)]
180
181
181
182
182 _autocall_help = """
183 _autocall_help = """
183 Make IPython automatically call any callable object even if
184 Make IPython automatically call any callable object even if
184 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 autocall, where it is not applied if there are no more arguments on the line,
187 autocall, where it is not applied if there are no more arguments on the line,
187 and '2' for 'full' autocall, where all callable objects are automatically
188 and '2' for 'full' autocall, where all callable objects are automatically
188 called (even if no arguments are present). The default is '1'.
189 called (even if no arguments are present). The default is '1'.
189 """
190 """
190
191
191 #-----------------------------------------------------------------------------
192 #-----------------------------------------------------------------------------
192 # Main IPython class
193 # Main IPython class
193 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
194
195
195 class InteractiveShell(SingletonConfigurable, Magic):
196 class InteractiveShell(SingletonConfigurable, Magic):
196 """An enhanced, interactive shell for Python."""
197 """An enhanced, interactive shell for Python."""
197
198
198 _instance = None
199 _instance = None
199
200
200 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 """
202 """
202 Make IPython automatically call any callable object even if you didn't
203 Make IPython automatically call any callable object even if you didn't
203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 automatically. The value can be '0' to disable the feature, '1' for
205 automatically. The value can be '0' to disable the feature, '1' for
205 'smart' autocall, where it is not applied if there are no more
206 'smart' autocall, where it is not applied if there are no more
206 arguments on the line, and '2' for 'full' autocall, where all callable
207 arguments on the line, and '2' for 'full' autocall, where all callable
207 objects are automatically called (even if no arguments are present).
208 objects are automatically called (even if no arguments are present).
208 The default is '1'.
209 The default is '1'.
209 """
210 """
210 )
211 )
211 # TODO: remove all autoindent logic and put into frontends.
212 # TODO: remove all autoindent logic and put into frontends.
212 # We can't do this yet because even runlines uses the autoindent.
213 # We can't do this yet because even runlines uses the autoindent.
213 autoindent = CBool(True, config=True, help=
214 autoindent = CBool(True, config=True, help=
214 """
215 """
215 Autoindent IPython code entered interactively.
216 Autoindent IPython code entered interactively.
216 """
217 """
217 )
218 )
218 automagic = CBool(True, config=True, help=
219 automagic = CBool(True, config=True, help=
219 """
220 """
220 Enable magic commands to be called without the leading %.
221 Enable magic commands to be called without the leading %.
221 """
222 """
222 )
223 )
223 cache_size = Int(1000, config=True, help=
224 cache_size = Int(1000, config=True, help=
224 """
225 """
225 Set the size of the output cache. The default is 1000, you can
226 Set the size of the output cache. The default is 1000, you can
226 change it permanently in your config file. Setting it to 0 completely
227 change it permanently in your config file. Setting it to 0 completely
227 disables the caching system, and the minimum value accepted is 20 (if
228 disables the caching system, and the minimum value accepted is 20 (if
228 you provide a value less than 20, it is reset to 0 and a warning is
229 you provide a value less than 20, it is reset to 0 and a warning is
229 issued). This limit is defined because otherwise you'll spend more
230 issued). This limit is defined because otherwise you'll spend more
230 time re-flushing a too small cache than working
231 time re-flushing a too small cache than working
231 """
232 """
232 )
233 )
233 color_info = CBool(True, config=True, help=
234 color_info = CBool(True, config=True, help=
234 """
235 """
235 Use colors for displaying information about objects. Because this
236 Use colors for displaying information about objects. Because this
236 information is passed through a pager (like 'less'), and some pagers
237 information is passed through a pager (like 'less'), and some pagers
237 get confused with color codes, this capability can be turned off.
238 get confused with color codes, this capability can be turned off.
238 """
239 """
239 )
240 )
240 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 default_value=get_default_colors(), config=True)
242 default_value=get_default_colors(), config=True,
243 help="Set the color scheme (NoColor, Linux, or LightBG)."
244 )
242 debug = CBool(False, config=True)
245 debug = CBool(False, config=True)
243 deep_reload = CBool(False, config=True, help=
246 deep_reload = CBool(False, config=True, help=
244 """
247 """
245 Enable deep (recursive) reloading by default. IPython can use the
248 Enable deep (recursive) reloading by default. IPython can use the
246 deep_reload module which reloads changes in modules recursively (it
249 deep_reload module which reloads changes in modules recursively (it
247 replaces the reload() function, so you don't need to change anything to
250 replaces the reload() function, so you don't need to change anything to
248 use it). deep_reload() forces a full reload of modules whose code may
251 use it). deep_reload() forces a full reload of modules whose code may
249 have changed, which the default reload() function does not. When
252 have changed, which the default reload() function does not. When
250 deep_reload is off, IPython will use the normal reload(), but
253 deep_reload is off, IPython will use the normal reload(), but
251 deep_reload will still be available as dreload().
254 deep_reload will still be available as dreload().
252 """
255 """
253 )
256 )
254 display_formatter = Instance(DisplayFormatter)
257 display_formatter = Instance(DisplayFormatter)
255 displayhook_class = Type(DisplayHook)
258 displayhook_class = Type(DisplayHook)
256 display_pub_class = Type(DisplayPublisher)
259 display_pub_class = Type(DisplayPublisher)
257
260
258 exit_now = CBool(False)
261 exit_now = CBool(False)
259 exiter = Instance(ExitAutocall)
262 exiter = Instance(ExitAutocall)
260 def _exiter_default(self):
263 def _exiter_default(self):
261 return ExitAutocall(self)
264 return ExitAutocall(self)
262 # Monotonically increasing execution counter
265 # Monotonically increasing execution counter
263 execution_count = Int(1)
266 execution_count = Int(1)
264 filename = Unicode("<ipython console>")
267 filename = Unicode("<ipython console>")
265 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
268 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
266
269
267 # Input splitter, to split entire cells of input into either individual
270 # Input splitter, to split entire cells of input into either individual
268 # interactive statements or whole blocks.
271 # interactive statements or whole blocks.
269 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
272 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
270 (), {})
273 (), {})
271 logstart = CBool(False, config=True, help=
274 logstart = CBool(False, config=True, help=
272 """
275 """
273 Start logging to the default log file.
276 Start logging to the default log file.
274 """
277 """
275 )
278 )
276 logfile = Unicode('', config=True, help=
279 logfile = Unicode('', config=True, help=
277 """
280 """
278 The name of the logfile to use.
281 The name of the logfile to use.
279 """
282 """
280 )
283 )
281 logappend = Unicode('', config=True, help=
284 logappend = Unicode('', config=True, help=
282 """
285 """
283 Start logging to the given file in append mode.
286 Start logging to the given file in append mode.
284 """
287 """
285 )
288 )
286 object_info_string_level = Enum((0,1,2), default_value=0,
289 object_info_string_level = Enum((0,1,2), default_value=0,
287 config=True)
290 config=True)
288 pdb = CBool(False, config=True, help=
291 pdb = CBool(False, config=True, help=
289 """
292 """
290 Automatically call the pdb debugger after every exception.
293 Automatically call the pdb debugger after every exception.
291 """
294 """
292 )
295 )
293
296
294 profile = Unicode('', config=True)
295 prompt_in1 = Str('In [\\#]: ', config=True)
297 prompt_in1 = Str('In [\\#]: ', config=True)
296 prompt_in2 = Str(' .\\D.: ', config=True)
298 prompt_in2 = Str(' .\\D.: ', config=True)
297 prompt_out = Str('Out[\\#]: ', config=True)
299 prompt_out = Str('Out[\\#]: ', config=True)
298 prompts_pad_left = CBool(True, config=True)
300 prompts_pad_left = CBool(True, config=True)
299 quiet = CBool(False, config=True)
301 quiet = CBool(False, config=True)
300
302
301 history_length = Int(10000, config=True)
303 history_length = Int(10000, config=True)
302
304
303 # The readline stuff will eventually be moved to the terminal subclass
305 # The readline stuff will eventually be moved to the terminal subclass
304 # but for now, we can't do that as readline is welded in everywhere.
306 # but for now, we can't do that as readline is welded in everywhere.
305 readline_use = CBool(True, config=True)
307 readline_use = CBool(True, config=True)
306 readline_merge_completions = CBool(True, config=True)
308 readline_merge_completions = CBool(True, config=True)
307 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
309 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
308 readline_remove_delims = Str('-/~', config=True)
310 readline_remove_delims = Str('-/~', config=True)
309 # don't use \M- bindings by default, because they
311 # don't use \M- bindings by default, because they
310 # conflict with 8-bit encodings. See gh-58,gh-88
312 # conflict with 8-bit encodings. See gh-58,gh-88
311 readline_parse_and_bind = List([
313 readline_parse_and_bind = List([
312 'tab: complete',
314 'tab: complete',
313 '"\C-l": clear-screen',
315 '"\C-l": clear-screen',
314 'set show-all-if-ambiguous on',
316 'set show-all-if-ambiguous on',
315 '"\C-o": tab-insert',
317 '"\C-o": tab-insert',
316 '"\C-r": reverse-search-history',
318 '"\C-r": reverse-search-history',
317 '"\C-s": forward-search-history',
319 '"\C-s": forward-search-history',
318 '"\C-p": history-search-backward',
320 '"\C-p": history-search-backward',
319 '"\C-n": history-search-forward',
321 '"\C-n": history-search-forward',
320 '"\e[A": history-search-backward',
322 '"\e[A": history-search-backward',
321 '"\e[B": history-search-forward',
323 '"\e[B": history-search-forward',
322 '"\C-k": kill-line',
324 '"\C-k": kill-line',
323 '"\C-u": unix-line-discard',
325 '"\C-u": unix-line-discard',
324 ], allow_none=False, config=True)
326 ], allow_none=False, config=True)
325
327
326 # TODO: this part of prompt management should be moved to the frontends.
328 # TODO: this part of prompt management should be moved to the frontends.
327 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
329 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
328 separate_in = SeparateStr('\n', config=True)
330 separate_in = SeparateStr('\n', config=True)
329 separate_out = SeparateStr('', config=True)
331 separate_out = SeparateStr('', config=True)
330 separate_out2 = SeparateStr('', config=True)
332 separate_out2 = SeparateStr('', config=True)
331 wildcards_case_sensitive = CBool(True, config=True)
333 wildcards_case_sensitive = CBool(True, config=True)
332 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
334 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
333 default_value='Context', config=True)
335 default_value='Context', config=True)
334
336
335 # Subcomponents of InteractiveShell
337 # Subcomponents of InteractiveShell
336 alias_manager = Instance('IPython.core.alias.AliasManager')
338 alias_manager = Instance('IPython.core.alias.AliasManager')
337 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
339 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
338 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
340 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
339 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
341 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
340 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
342 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
341 plugin_manager = Instance('IPython.core.plugin.PluginManager')
343 plugin_manager = Instance('IPython.core.plugin.PluginManager')
342 payload_manager = Instance('IPython.core.payload.PayloadManager')
344 payload_manager = Instance('IPython.core.payload.PayloadManager')
343 history_manager = Instance('IPython.core.history.HistoryManager')
345 history_manager = Instance('IPython.core.history.HistoryManager')
344
346
347 profile_dir = Instance('IPython.core.application.ProfileDir')
348 @property
349 def profile(self):
350 if self.profile_dir is not None:
351 name = os.path.basename(self.profile_dir.location)
352 return name.replace('profile_','')
353
354
345 # Private interface
355 # Private interface
346 _post_execute = Instance(dict)
356 _post_execute = Instance(dict)
347
357
348 def __init__(self, config=None, ipython_dir=None,
358 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
349 user_ns=None, user_global_ns=None,
359 user_ns=None, user_global_ns=None,
350 custom_exceptions=((), None)):
360 custom_exceptions=((), None)):
351
361
352 # This is where traits with a config_key argument are updated
362 # This is where traits with a config_key argument are updated
353 # from the values on config.
363 # from the values on config.
354 super(InteractiveShell, self).__init__(config=config)
364 super(InteractiveShell, self).__init__(config=config)
355
365
356 # These are relatively independent and stateless
366 # These are relatively independent and stateless
357 self.init_ipython_dir(ipython_dir)
367 self.init_ipython_dir(ipython_dir)
368 self.init_profile_dir(profile_dir)
358 self.init_instance_attrs()
369 self.init_instance_attrs()
359 self.init_environment()
370 self.init_environment()
360
371
361 # Create namespaces (user_ns, user_global_ns, etc.)
372 # Create namespaces (user_ns, user_global_ns, etc.)
362 self.init_create_namespaces(user_ns, user_global_ns)
373 self.init_create_namespaces(user_ns, user_global_ns)
363 # This has to be done after init_create_namespaces because it uses
374 # This has to be done after init_create_namespaces because it uses
364 # something in self.user_ns, but before init_sys_modules, which
375 # something in self.user_ns, but before init_sys_modules, which
365 # is the first thing to modify sys.
376 # is the first thing to modify sys.
366 # TODO: When we override sys.stdout and sys.stderr before this class
377 # TODO: When we override sys.stdout and sys.stderr before this class
367 # is created, we are saving the overridden ones here. Not sure if this
378 # is created, we are saving the overridden ones here. Not sure if this
368 # is what we want to do.
379 # is what we want to do.
369 self.save_sys_module_state()
380 self.save_sys_module_state()
370 self.init_sys_modules()
381 self.init_sys_modules()
371
382
372 # While we're trying to have each part of the code directly access what
383 # While we're trying to have each part of the code directly access what
373 # it needs without keeping redundant references to objects, we have too
384 # it needs without keeping redundant references to objects, we have too
374 # much legacy code that expects ip.db to exist.
385 # much legacy code that expects ip.db to exist.
375 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
386 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
376
387
377 self.init_history()
388 self.init_history()
378 self.init_encoding()
389 self.init_encoding()
379 self.init_prefilter()
390 self.init_prefilter()
380
391
381 Magic.__init__(self, self)
392 Magic.__init__(self, self)
382
393
383 self.init_syntax_highlighting()
394 self.init_syntax_highlighting()
384 self.init_hooks()
395 self.init_hooks()
385 self.init_pushd_popd_magic()
396 self.init_pushd_popd_magic()
386 # self.init_traceback_handlers use to be here, but we moved it below
397 # self.init_traceback_handlers use to be here, but we moved it below
387 # because it and init_io have to come after init_readline.
398 # because it and init_io have to come after init_readline.
388 self.init_user_ns()
399 self.init_user_ns()
389 self.init_logger()
400 self.init_logger()
390 self.init_alias()
401 self.init_alias()
391 self.init_builtins()
402 self.init_builtins()
392
403
393 # pre_config_initialization
404 # pre_config_initialization
394
405
395 # The next section should contain everything that was in ipmaker.
406 # The next section should contain everything that was in ipmaker.
396 self.init_logstart()
407 self.init_logstart()
397
408
398 # The following was in post_config_initialization
409 # The following was in post_config_initialization
399 self.init_inspector()
410 self.init_inspector()
400 # init_readline() must come before init_io(), because init_io uses
411 # init_readline() must come before init_io(), because init_io uses
401 # readline related things.
412 # readline related things.
402 self.init_readline()
413 self.init_readline()
403 # init_completer must come after init_readline, because it needs to
414 # init_completer must come after init_readline, because it needs to
404 # know whether readline is present or not system-wide to configure the
415 # know whether readline is present or not system-wide to configure the
405 # completers, since the completion machinery can now operate
416 # completers, since the completion machinery can now operate
406 # independently of readline (e.g. over the network)
417 # independently of readline (e.g. over the network)
407 self.init_completer()
418 self.init_completer()
408 # TODO: init_io() needs to happen before init_traceback handlers
419 # TODO: init_io() needs to happen before init_traceback handlers
409 # because the traceback handlers hardcode the stdout/stderr streams.
420 # because the traceback handlers hardcode the stdout/stderr streams.
410 # This logic in in debugger.Pdb and should eventually be changed.
421 # This logic in in debugger.Pdb and should eventually be changed.
411 self.init_io()
422 self.init_io()
412 self.init_traceback_handlers(custom_exceptions)
423 self.init_traceback_handlers(custom_exceptions)
413 self.init_prompts()
424 self.init_prompts()
414 self.init_display_formatter()
425 self.init_display_formatter()
415 self.init_display_pub()
426 self.init_display_pub()
416 self.init_displayhook()
427 self.init_displayhook()
417 self.init_reload_doctest()
428 self.init_reload_doctest()
418 self.init_magics()
429 self.init_magics()
419 self.init_pdb()
430 self.init_pdb()
420 self.init_extension_manager()
431 self.init_extension_manager()
421 self.init_plugin_manager()
432 self.init_plugin_manager()
422 self.init_payload()
433 self.init_payload()
423 self.hooks.late_startup_hook()
434 self.hooks.late_startup_hook()
424 atexit.register(self.atexit_operations)
435 atexit.register(self.atexit_operations)
425
436
426 def get_ipython(self):
437 def get_ipython(self):
427 """Return the currently running IPython instance."""
438 """Return the currently running IPython instance."""
428 return self
439 return self
429
440
430 #-------------------------------------------------------------------------
441 #-------------------------------------------------------------------------
431 # Trait changed handlers
442 # Trait changed handlers
432 #-------------------------------------------------------------------------
443 #-------------------------------------------------------------------------
433
444
434 def _ipython_dir_changed(self, name, new):
445 def _ipython_dir_changed(self, name, new):
435 if not os.path.isdir(new):
446 if not os.path.isdir(new):
436 os.makedirs(new, mode = 0777)
447 os.makedirs(new, mode = 0777)
437
448
438 def set_autoindent(self,value=None):
449 def set_autoindent(self,value=None):
439 """Set the autoindent flag, checking for readline support.
450 """Set the autoindent flag, checking for readline support.
440
451
441 If called with no arguments, it acts as a toggle."""
452 If called with no arguments, it acts as a toggle."""
442
453
443 if not self.has_readline:
454 if not self.has_readline:
444 if os.name == 'posix':
455 if os.name == 'posix':
445 warn("The auto-indent feature requires the readline library")
456 warn("The auto-indent feature requires the readline library")
446 self.autoindent = 0
457 self.autoindent = 0
447 return
458 return
448 if value is None:
459 if value is None:
449 self.autoindent = not self.autoindent
460 self.autoindent = not self.autoindent
450 else:
461 else:
451 self.autoindent = value
462 self.autoindent = value
452
463
453 #-------------------------------------------------------------------------
464 #-------------------------------------------------------------------------
454 # init_* methods called by __init__
465 # init_* methods called by __init__
455 #-------------------------------------------------------------------------
466 #-------------------------------------------------------------------------
456
467
457 def init_ipython_dir(self, ipython_dir):
468 def init_ipython_dir(self, ipython_dir):
458 if ipython_dir is not None:
469 if ipython_dir is not None:
459 self.ipython_dir = ipython_dir
470 self.ipython_dir = ipython_dir
460 self.config.Global.ipython_dir = self.ipython_dir
461 return
471 return
462
472
463 if hasattr(self.config.Global, 'ipython_dir'):
473 self.ipython_dir = get_ipython_dir()
464 self.ipython_dir = self.config.Global.ipython_dir
465 else:
466 self.ipython_dir = get_ipython_dir()
467
474
468 # All children can just read this
475 def init_profile_dir(self, profile_dir):
469 self.config.Global.ipython_dir = self.ipython_dir
476 if profile_dir is not None:
477 self.profile_dir = profile_dir
478 return
479 self.profile_dir =\
480 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
470
481
471 def init_instance_attrs(self):
482 def init_instance_attrs(self):
472 self.more = False
483 self.more = False
473
484
474 # command compiler
485 # command compiler
475 self.compile = CachingCompiler()
486 self.compile = CachingCompiler()
476
487
477 # Make an empty namespace, which extension writers can rely on both
488 # Make an empty namespace, which extension writers can rely on both
478 # existing and NEVER being used by ipython itself. This gives them a
489 # existing and NEVER being used by ipython itself. This gives them a
479 # convenient location for storing additional information and state
490 # convenient location for storing additional information and state
480 # their extensions may require, without fear of collisions with other
491 # their extensions may require, without fear of collisions with other
481 # ipython names that may develop later.
492 # ipython names that may develop later.
482 self.meta = Struct()
493 self.meta = Struct()
483
494
484 # Temporary files used for various purposes. Deleted at exit.
495 # Temporary files used for various purposes. Deleted at exit.
485 self.tempfiles = []
496 self.tempfiles = []
486
497
487 # Keep track of readline usage (later set by init_readline)
498 # Keep track of readline usage (later set by init_readline)
488 self.has_readline = False
499 self.has_readline = False
489
500
490 # keep track of where we started running (mainly for crash post-mortem)
501 # keep track of where we started running (mainly for crash post-mortem)
491 # This is not being used anywhere currently.
502 # This is not being used anywhere currently.
492 self.starting_dir = os.getcwd()
503 self.starting_dir = os.getcwd()
493
504
494 # Indentation management
505 # Indentation management
495 self.indent_current_nsp = 0
506 self.indent_current_nsp = 0
496
507
497 # Dict to track post-execution functions that have been registered
508 # Dict to track post-execution functions that have been registered
498 self._post_execute = {}
509 self._post_execute = {}
499
510
500 def init_environment(self):
511 def init_environment(self):
501 """Any changes we need to make to the user's environment."""
512 """Any changes we need to make to the user's environment."""
502 pass
513 pass
503
514
504 def init_encoding(self):
515 def init_encoding(self):
505 # Get system encoding at startup time. Certain terminals (like Emacs
516 # Get system encoding at startup time. Certain terminals (like Emacs
506 # under Win32 have it set to None, and we need to have a known valid
517 # under Win32 have it set to None, and we need to have a known valid
507 # encoding to use in the raw_input() method
518 # encoding to use in the raw_input() method
508 try:
519 try:
509 self.stdin_encoding = sys.stdin.encoding or 'ascii'
520 self.stdin_encoding = sys.stdin.encoding or 'ascii'
510 except AttributeError:
521 except AttributeError:
511 self.stdin_encoding = 'ascii'
522 self.stdin_encoding = 'ascii'
512
523
513 def init_syntax_highlighting(self):
524 def init_syntax_highlighting(self):
514 # Python source parser/formatter for syntax highlighting
525 # Python source parser/formatter for syntax highlighting
515 pyformat = PyColorize.Parser().format
526 pyformat = PyColorize.Parser().format
516 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
527 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
517
528
518 def init_pushd_popd_magic(self):
529 def init_pushd_popd_magic(self):
519 # for pushd/popd management
530 # for pushd/popd management
520 try:
531 try:
521 self.home_dir = get_home_dir()
532 self.home_dir = get_home_dir()
522 except HomeDirError, msg:
533 except HomeDirError, msg:
523 fatal(msg)
534 fatal(msg)
524
535
525 self.dir_stack = []
536 self.dir_stack = []
526
537
527 def init_logger(self):
538 def init_logger(self):
528 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
539 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
529 logmode='rotate')
540 logmode='rotate')
530
541
531 def init_logstart(self):
542 def init_logstart(self):
532 """Initialize logging in case it was requested at the command line.
543 """Initialize logging in case it was requested at the command line.
533 """
544 """
534 if self.logappend:
545 if self.logappend:
535 self.magic_logstart(self.logappend + ' append')
546 self.magic_logstart(self.logappend + ' append')
536 elif self.logfile:
547 elif self.logfile:
537 self.magic_logstart(self.logfile)
548 self.magic_logstart(self.logfile)
538 elif self.logstart:
549 elif self.logstart:
539 self.magic_logstart()
550 self.magic_logstart()
540
551
541 def init_builtins(self):
552 def init_builtins(self):
542 self.builtin_trap = BuiltinTrap(shell=self)
553 self.builtin_trap = BuiltinTrap(shell=self)
543
554
544 def init_inspector(self):
555 def init_inspector(self):
545 # Object inspector
556 # Object inspector
546 self.inspector = oinspect.Inspector(oinspect.InspectColors,
557 self.inspector = oinspect.Inspector(oinspect.InspectColors,
547 PyColorize.ANSICodeColors,
558 PyColorize.ANSICodeColors,
548 'NoColor',
559 'NoColor',
549 self.object_info_string_level)
560 self.object_info_string_level)
550
561
551 def init_io(self):
562 def init_io(self):
552 # This will just use sys.stdout and sys.stderr. If you want to
563 # This will just use sys.stdout and sys.stderr. If you want to
553 # override sys.stdout and sys.stderr themselves, you need to do that
564 # override sys.stdout and sys.stderr themselves, you need to do that
554 # *before* instantiating this class, because io holds onto
565 # *before* instantiating this class, because io holds onto
555 # references to the underlying streams.
566 # references to the underlying streams.
556 if sys.platform == 'win32' and self.has_readline:
567 if sys.platform == 'win32' and self.has_readline:
557 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
568 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
558 else:
569 else:
559 io.stdout = io.IOStream(sys.stdout)
570 io.stdout = io.IOStream(sys.stdout)
560 io.stderr = io.IOStream(sys.stderr)
571 io.stderr = io.IOStream(sys.stderr)
561
572
562 def init_prompts(self):
573 def init_prompts(self):
563 # TODO: This is a pass for now because the prompts are managed inside
574 # TODO: This is a pass for now because the prompts are managed inside
564 # the DisplayHook. Once there is a separate prompt manager, this
575 # the DisplayHook. Once there is a separate prompt manager, this
565 # will initialize that object and all prompt related information.
576 # will initialize that object and all prompt related information.
566 pass
577 pass
567
578
568 def init_display_formatter(self):
579 def init_display_formatter(self):
569 self.display_formatter = DisplayFormatter(config=self.config)
580 self.display_formatter = DisplayFormatter(config=self.config)
570
581
571 def init_display_pub(self):
582 def init_display_pub(self):
572 self.display_pub = self.display_pub_class(config=self.config)
583 self.display_pub = self.display_pub_class(config=self.config)
573
584
574 def init_displayhook(self):
585 def init_displayhook(self):
575 # Initialize displayhook, set in/out prompts and printing system
586 # Initialize displayhook, set in/out prompts and printing system
576 self.displayhook = self.displayhook_class(
587 self.displayhook = self.displayhook_class(
577 config=self.config,
588 config=self.config,
578 shell=self,
589 shell=self,
579 cache_size=self.cache_size,
590 cache_size=self.cache_size,
580 input_sep = self.separate_in,
591 input_sep = self.separate_in,
581 output_sep = self.separate_out,
592 output_sep = self.separate_out,
582 output_sep2 = self.separate_out2,
593 output_sep2 = self.separate_out2,
583 ps1 = self.prompt_in1,
594 ps1 = self.prompt_in1,
584 ps2 = self.prompt_in2,
595 ps2 = self.prompt_in2,
585 ps_out = self.prompt_out,
596 ps_out = self.prompt_out,
586 pad_left = self.prompts_pad_left
597 pad_left = self.prompts_pad_left
587 )
598 )
588 # This is a context manager that installs/revmoes the displayhook at
599 # This is a context manager that installs/revmoes the displayhook at
589 # the appropriate time.
600 # the appropriate time.
590 self.display_trap = DisplayTrap(hook=self.displayhook)
601 self.display_trap = DisplayTrap(hook=self.displayhook)
591
602
592 def init_reload_doctest(self):
603 def init_reload_doctest(self):
593 # Do a proper resetting of doctest, including the necessary displayhook
604 # Do a proper resetting of doctest, including the necessary displayhook
594 # monkeypatching
605 # monkeypatching
595 try:
606 try:
596 doctest_reload()
607 doctest_reload()
597 except ImportError:
608 except ImportError:
598 warn("doctest module does not exist.")
609 warn("doctest module does not exist.")
599
610
600 #-------------------------------------------------------------------------
611 #-------------------------------------------------------------------------
601 # Things related to injections into the sys module
612 # Things related to injections into the sys module
602 #-------------------------------------------------------------------------
613 #-------------------------------------------------------------------------
603
614
604 def save_sys_module_state(self):
615 def save_sys_module_state(self):
605 """Save the state of hooks in the sys module.
616 """Save the state of hooks in the sys module.
606
617
607 This has to be called after self.user_ns is created.
618 This has to be called after self.user_ns is created.
608 """
619 """
609 self._orig_sys_module_state = {}
620 self._orig_sys_module_state = {}
610 self._orig_sys_module_state['stdin'] = sys.stdin
621 self._orig_sys_module_state['stdin'] = sys.stdin
611 self._orig_sys_module_state['stdout'] = sys.stdout
622 self._orig_sys_module_state['stdout'] = sys.stdout
612 self._orig_sys_module_state['stderr'] = sys.stderr
623 self._orig_sys_module_state['stderr'] = sys.stderr
613 self._orig_sys_module_state['excepthook'] = sys.excepthook
624 self._orig_sys_module_state['excepthook'] = sys.excepthook
614 try:
625 try:
615 self._orig_sys_modules_main_name = self.user_ns['__name__']
626 self._orig_sys_modules_main_name = self.user_ns['__name__']
616 except KeyError:
627 except KeyError:
617 pass
628 pass
618
629
619 def restore_sys_module_state(self):
630 def restore_sys_module_state(self):
620 """Restore the state of the sys module."""
631 """Restore the state of the sys module."""
621 try:
632 try:
622 for k, v in self._orig_sys_module_state.iteritems():
633 for k, v in self._orig_sys_module_state.iteritems():
623 setattr(sys, k, v)
634 setattr(sys, k, v)
624 except AttributeError:
635 except AttributeError:
625 pass
636 pass
626 # Reset what what done in self.init_sys_modules
637 # Reset what what done in self.init_sys_modules
627 try:
638 try:
628 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
639 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
629 except (AttributeError, KeyError):
640 except (AttributeError, KeyError):
630 pass
641 pass
631
642
632 #-------------------------------------------------------------------------
643 #-------------------------------------------------------------------------
633 # Things related to hooks
644 # Things related to hooks
634 #-------------------------------------------------------------------------
645 #-------------------------------------------------------------------------
635
646
636 def init_hooks(self):
647 def init_hooks(self):
637 # hooks holds pointers used for user-side customizations
648 # hooks holds pointers used for user-side customizations
638 self.hooks = Struct()
649 self.hooks = Struct()
639
650
640 self.strdispatchers = {}
651 self.strdispatchers = {}
641
652
642 # Set all default hooks, defined in the IPython.hooks module.
653 # Set all default hooks, defined in the IPython.hooks module.
643 hooks = IPython.core.hooks
654 hooks = IPython.core.hooks
644 for hook_name in hooks.__all__:
655 for hook_name in hooks.__all__:
645 # default hooks have priority 100, i.e. low; user hooks should have
656 # default hooks have priority 100, i.e. low; user hooks should have
646 # 0-100 priority
657 # 0-100 priority
647 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
658 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
648
659
649 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
660 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
650 """set_hook(name,hook) -> sets an internal IPython hook.
661 """set_hook(name,hook) -> sets an internal IPython hook.
651
662
652 IPython exposes some of its internal API as user-modifiable hooks. By
663 IPython exposes some of its internal API as user-modifiable hooks. By
653 adding your function to one of these hooks, you can modify IPython's
664 adding your function to one of these hooks, you can modify IPython's
654 behavior to call at runtime your own routines."""
665 behavior to call at runtime your own routines."""
655
666
656 # At some point in the future, this should validate the hook before it
667 # At some point in the future, this should validate the hook before it
657 # accepts it. Probably at least check that the hook takes the number
668 # accepts it. Probably at least check that the hook takes the number
658 # of args it's supposed to.
669 # of args it's supposed to.
659
670
660 f = types.MethodType(hook,self)
671 f = types.MethodType(hook,self)
661
672
662 # check if the hook is for strdispatcher first
673 # check if the hook is for strdispatcher first
663 if str_key is not None:
674 if str_key is not None:
664 sdp = self.strdispatchers.get(name, StrDispatch())
675 sdp = self.strdispatchers.get(name, StrDispatch())
665 sdp.add_s(str_key, f, priority )
676 sdp.add_s(str_key, f, priority )
666 self.strdispatchers[name] = sdp
677 self.strdispatchers[name] = sdp
667 return
678 return
668 if re_key is not None:
679 if re_key is not None:
669 sdp = self.strdispatchers.get(name, StrDispatch())
680 sdp = self.strdispatchers.get(name, StrDispatch())
670 sdp.add_re(re.compile(re_key), f, priority )
681 sdp.add_re(re.compile(re_key), f, priority )
671 self.strdispatchers[name] = sdp
682 self.strdispatchers[name] = sdp
672 return
683 return
673
684
674 dp = getattr(self.hooks, name, None)
685 dp = getattr(self.hooks, name, None)
675 if name not in IPython.core.hooks.__all__:
686 if name not in IPython.core.hooks.__all__:
676 print "Warning! Hook '%s' is not one of %s" % \
687 print "Warning! Hook '%s' is not one of %s" % \
677 (name, IPython.core.hooks.__all__ )
688 (name, IPython.core.hooks.__all__ )
678 if not dp:
689 if not dp:
679 dp = IPython.core.hooks.CommandChainDispatcher()
690 dp = IPython.core.hooks.CommandChainDispatcher()
680
691
681 try:
692 try:
682 dp.add(f,priority)
693 dp.add(f,priority)
683 except AttributeError:
694 except AttributeError:
684 # it was not commandchain, plain old func - replace
695 # it was not commandchain, plain old func - replace
685 dp = f
696 dp = f
686
697
687 setattr(self.hooks,name, dp)
698 setattr(self.hooks,name, dp)
688
699
689 def register_post_execute(self, func):
700 def register_post_execute(self, func):
690 """Register a function for calling after code execution.
701 """Register a function for calling after code execution.
691 """
702 """
692 if not callable(func):
703 if not callable(func):
693 raise ValueError('argument %s must be callable' % func)
704 raise ValueError('argument %s must be callable' % func)
694 self._post_execute[func] = True
705 self._post_execute[func] = True
695
706
696 #-------------------------------------------------------------------------
707 #-------------------------------------------------------------------------
697 # Things related to the "main" module
708 # Things related to the "main" module
698 #-------------------------------------------------------------------------
709 #-------------------------------------------------------------------------
699
710
700 def new_main_mod(self,ns=None):
711 def new_main_mod(self,ns=None):
701 """Return a new 'main' module object for user code execution.
712 """Return a new 'main' module object for user code execution.
702 """
713 """
703 main_mod = self._user_main_module
714 main_mod = self._user_main_module
704 init_fakemod_dict(main_mod,ns)
715 init_fakemod_dict(main_mod,ns)
705 return main_mod
716 return main_mod
706
717
707 def cache_main_mod(self,ns,fname):
718 def cache_main_mod(self,ns,fname):
708 """Cache a main module's namespace.
719 """Cache a main module's namespace.
709
720
710 When scripts are executed via %run, we must keep a reference to the
721 When scripts are executed via %run, we must keep a reference to the
711 namespace of their __main__ module (a FakeModule instance) around so
722 namespace of their __main__ module (a FakeModule instance) around so
712 that Python doesn't clear it, rendering objects defined therein
723 that Python doesn't clear it, rendering objects defined therein
713 useless.
724 useless.
714
725
715 This method keeps said reference in a private dict, keyed by the
726 This method keeps said reference in a private dict, keyed by the
716 absolute path of the module object (which corresponds to the script
727 absolute path of the module object (which corresponds to the script
717 path). This way, for multiple executions of the same script we only
728 path). This way, for multiple executions of the same script we only
718 keep one copy of the namespace (the last one), thus preventing memory
729 keep one copy of the namespace (the last one), thus preventing memory
719 leaks from old references while allowing the objects from the last
730 leaks from old references while allowing the objects from the last
720 execution to be accessible.
731 execution to be accessible.
721
732
722 Note: we can not allow the actual FakeModule instances to be deleted,
733 Note: we can not allow the actual FakeModule instances to be deleted,
723 because of how Python tears down modules (it hard-sets all their
734 because of how Python tears down modules (it hard-sets all their
724 references to None without regard for reference counts). This method
735 references to None without regard for reference counts). This method
725 must therefore make a *copy* of the given namespace, to allow the
736 must therefore make a *copy* of the given namespace, to allow the
726 original module's __dict__ to be cleared and reused.
737 original module's __dict__ to be cleared and reused.
727
738
728
739
729 Parameters
740 Parameters
730 ----------
741 ----------
731 ns : a namespace (a dict, typically)
742 ns : a namespace (a dict, typically)
732
743
733 fname : str
744 fname : str
734 Filename associated with the namespace.
745 Filename associated with the namespace.
735
746
736 Examples
747 Examples
737 --------
748 --------
738
749
739 In [10]: import IPython
750 In [10]: import IPython
740
751
741 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
752 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
742
753
743 In [12]: IPython.__file__ in _ip._main_ns_cache
754 In [12]: IPython.__file__ in _ip._main_ns_cache
744 Out[12]: True
755 Out[12]: True
745 """
756 """
746 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
757 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
747
758
748 def clear_main_mod_cache(self):
759 def clear_main_mod_cache(self):
749 """Clear the cache of main modules.
760 """Clear the cache of main modules.
750
761
751 Mainly for use by utilities like %reset.
762 Mainly for use by utilities like %reset.
752
763
753 Examples
764 Examples
754 --------
765 --------
755
766
756 In [15]: import IPython
767 In [15]: import IPython
757
768
758 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
769 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
759
770
760 In [17]: len(_ip._main_ns_cache) > 0
771 In [17]: len(_ip._main_ns_cache) > 0
761 Out[17]: True
772 Out[17]: True
762
773
763 In [18]: _ip.clear_main_mod_cache()
774 In [18]: _ip.clear_main_mod_cache()
764
775
765 In [19]: len(_ip._main_ns_cache) == 0
776 In [19]: len(_ip._main_ns_cache) == 0
766 Out[19]: True
777 Out[19]: True
767 """
778 """
768 self._main_ns_cache.clear()
779 self._main_ns_cache.clear()
769
780
770 #-------------------------------------------------------------------------
781 #-------------------------------------------------------------------------
771 # Things related to debugging
782 # Things related to debugging
772 #-------------------------------------------------------------------------
783 #-------------------------------------------------------------------------
773
784
774 def init_pdb(self):
785 def init_pdb(self):
775 # Set calling of pdb on exceptions
786 # Set calling of pdb on exceptions
776 # self.call_pdb is a property
787 # self.call_pdb is a property
777 self.call_pdb = self.pdb
788 self.call_pdb = self.pdb
778
789
779 def _get_call_pdb(self):
790 def _get_call_pdb(self):
780 return self._call_pdb
791 return self._call_pdb
781
792
782 def _set_call_pdb(self,val):
793 def _set_call_pdb(self,val):
783
794
784 if val not in (0,1,False,True):
795 if val not in (0,1,False,True):
785 raise ValueError,'new call_pdb value must be boolean'
796 raise ValueError,'new call_pdb value must be boolean'
786
797
787 # store value in instance
798 # store value in instance
788 self._call_pdb = val
799 self._call_pdb = val
789
800
790 # notify the actual exception handlers
801 # notify the actual exception handlers
791 self.InteractiveTB.call_pdb = val
802 self.InteractiveTB.call_pdb = val
792
803
793 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
804 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
794 'Control auto-activation of pdb at exceptions')
805 'Control auto-activation of pdb at exceptions')
795
806
796 def debugger(self,force=False):
807 def debugger(self,force=False):
797 """Call the pydb/pdb debugger.
808 """Call the pydb/pdb debugger.
798
809
799 Keywords:
810 Keywords:
800
811
801 - force(False): by default, this routine checks the instance call_pdb
812 - force(False): by default, this routine checks the instance call_pdb
802 flag and does not actually invoke the debugger if the flag is false.
813 flag and does not actually invoke the debugger if the flag is false.
803 The 'force' option forces the debugger to activate even if the flag
814 The 'force' option forces the debugger to activate even if the flag
804 is false.
815 is false.
805 """
816 """
806
817
807 if not (force or self.call_pdb):
818 if not (force or self.call_pdb):
808 return
819 return
809
820
810 if not hasattr(sys,'last_traceback'):
821 if not hasattr(sys,'last_traceback'):
811 error('No traceback has been produced, nothing to debug.')
822 error('No traceback has been produced, nothing to debug.')
812 return
823 return
813
824
814 # use pydb if available
825 # use pydb if available
815 if debugger.has_pydb:
826 if debugger.has_pydb:
816 from pydb import pm
827 from pydb import pm
817 else:
828 else:
818 # fallback to our internal debugger
829 # fallback to our internal debugger
819 pm = lambda : self.InteractiveTB.debugger(force=True)
830 pm = lambda : self.InteractiveTB.debugger(force=True)
820
831
821 with self.readline_no_record:
832 with self.readline_no_record:
822 pm()
833 pm()
823
834
824 #-------------------------------------------------------------------------
835 #-------------------------------------------------------------------------
825 # Things related to IPython's various namespaces
836 # Things related to IPython's various namespaces
826 #-------------------------------------------------------------------------
837 #-------------------------------------------------------------------------
827
838
828 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
839 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
829 # Create the namespace where the user will operate. user_ns is
840 # Create the namespace where the user will operate. user_ns is
830 # normally the only one used, and it is passed to the exec calls as
841 # normally the only one used, and it is passed to the exec calls as
831 # the locals argument. But we do carry a user_global_ns namespace
842 # the locals argument. But we do carry a user_global_ns namespace
832 # given as the exec 'globals' argument, This is useful in embedding
843 # given as the exec 'globals' argument, This is useful in embedding
833 # situations where the ipython shell opens in a context where the
844 # situations where the ipython shell opens in a context where the
834 # distinction between locals and globals is meaningful. For
845 # distinction between locals and globals is meaningful. For
835 # non-embedded contexts, it is just the same object as the user_ns dict.
846 # non-embedded contexts, it is just the same object as the user_ns dict.
836
847
837 # FIXME. For some strange reason, __builtins__ is showing up at user
848 # FIXME. For some strange reason, __builtins__ is showing up at user
838 # level as a dict instead of a module. This is a manual fix, but I
849 # level as a dict instead of a module. This is a manual fix, but I
839 # should really track down where the problem is coming from. Alex
850 # should really track down where the problem is coming from. Alex
840 # Schmolck reported this problem first.
851 # Schmolck reported this problem first.
841
852
842 # A useful post by Alex Martelli on this topic:
853 # A useful post by Alex Martelli on this topic:
843 # Re: inconsistent value from __builtins__
854 # Re: inconsistent value from __builtins__
844 # Von: Alex Martelli <aleaxit@yahoo.com>
855 # Von: Alex Martelli <aleaxit@yahoo.com>
845 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
856 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
846 # Gruppen: comp.lang.python
857 # Gruppen: comp.lang.python
847
858
848 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
859 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
849 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
860 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
850 # > <type 'dict'>
861 # > <type 'dict'>
851 # > >>> print type(__builtins__)
862 # > >>> print type(__builtins__)
852 # > <type 'module'>
863 # > <type 'module'>
853 # > Is this difference in return value intentional?
864 # > Is this difference in return value intentional?
854
865
855 # Well, it's documented that '__builtins__' can be either a dictionary
866 # Well, it's documented that '__builtins__' can be either a dictionary
856 # or a module, and it's been that way for a long time. Whether it's
867 # or a module, and it's been that way for a long time. Whether it's
857 # intentional (or sensible), I don't know. In any case, the idea is
868 # intentional (or sensible), I don't know. In any case, the idea is
858 # that if you need to access the built-in namespace directly, you
869 # that if you need to access the built-in namespace directly, you
859 # should start with "import __builtin__" (note, no 's') which will
870 # should start with "import __builtin__" (note, no 's') which will
860 # definitely give you a module. Yeah, it's somewhat confusing:-(.
871 # definitely give you a module. Yeah, it's somewhat confusing:-(.
861
872
862 # These routines return properly built dicts as needed by the rest of
873 # These routines return properly built dicts as needed by the rest of
863 # the code, and can also be used by extension writers to generate
874 # the code, and can also be used by extension writers to generate
864 # properly initialized namespaces.
875 # properly initialized namespaces.
865 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
876 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
866 user_global_ns)
877 user_global_ns)
867
878
868 # Assign namespaces
879 # Assign namespaces
869 # This is the namespace where all normal user variables live
880 # This is the namespace where all normal user variables live
870 self.user_ns = user_ns
881 self.user_ns = user_ns
871 self.user_global_ns = user_global_ns
882 self.user_global_ns = user_global_ns
872
883
873 # An auxiliary namespace that checks what parts of the user_ns were
884 # An auxiliary namespace that checks what parts of the user_ns were
874 # loaded at startup, so we can list later only variables defined in
885 # loaded at startup, so we can list later only variables defined in
875 # actual interactive use. Since it is always a subset of user_ns, it
886 # actual interactive use. Since it is always a subset of user_ns, it
876 # doesn't need to be separately tracked in the ns_table.
887 # doesn't need to be separately tracked in the ns_table.
877 self.user_ns_hidden = {}
888 self.user_ns_hidden = {}
878
889
879 # A namespace to keep track of internal data structures to prevent
890 # A namespace to keep track of internal data structures to prevent
880 # them from cluttering user-visible stuff. Will be updated later
891 # them from cluttering user-visible stuff. Will be updated later
881 self.internal_ns = {}
892 self.internal_ns = {}
882
893
883 # Now that FakeModule produces a real module, we've run into a nasty
894 # Now that FakeModule produces a real module, we've run into a nasty
884 # problem: after script execution (via %run), the module where the user
895 # problem: after script execution (via %run), the module where the user
885 # code ran is deleted. Now that this object is a true module (needed
896 # code ran is deleted. Now that this object is a true module (needed
886 # so docetst and other tools work correctly), the Python module
897 # so docetst and other tools work correctly), the Python module
887 # teardown mechanism runs over it, and sets to None every variable
898 # teardown mechanism runs over it, and sets to None every variable
888 # present in that module. Top-level references to objects from the
899 # present in that module. Top-level references to objects from the
889 # script survive, because the user_ns is updated with them. However,
900 # script survive, because the user_ns is updated with them. However,
890 # calling functions defined in the script that use other things from
901 # calling functions defined in the script that use other things from
891 # the script will fail, because the function's closure had references
902 # the script will fail, because the function's closure had references
892 # to the original objects, which are now all None. So we must protect
903 # to the original objects, which are now all None. So we must protect
893 # these modules from deletion by keeping a cache.
904 # these modules from deletion by keeping a cache.
894 #
905 #
895 # To avoid keeping stale modules around (we only need the one from the
906 # To avoid keeping stale modules around (we only need the one from the
896 # last run), we use a dict keyed with the full path to the script, so
907 # last run), we use a dict keyed with the full path to the script, so
897 # only the last version of the module is held in the cache. Note,
908 # only the last version of the module is held in the cache. Note,
898 # however, that we must cache the module *namespace contents* (their
909 # however, that we must cache the module *namespace contents* (their
899 # __dict__). Because if we try to cache the actual modules, old ones
910 # __dict__). Because if we try to cache the actual modules, old ones
900 # (uncached) could be destroyed while still holding references (such as
911 # (uncached) could be destroyed while still holding references (such as
901 # those held by GUI objects that tend to be long-lived)>
912 # those held by GUI objects that tend to be long-lived)>
902 #
913 #
903 # The %reset command will flush this cache. See the cache_main_mod()
914 # The %reset command will flush this cache. See the cache_main_mod()
904 # and clear_main_mod_cache() methods for details on use.
915 # and clear_main_mod_cache() methods for details on use.
905
916
906 # This is the cache used for 'main' namespaces
917 # This is the cache used for 'main' namespaces
907 self._main_ns_cache = {}
918 self._main_ns_cache = {}
908 # And this is the single instance of FakeModule whose __dict__ we keep
919 # And this is the single instance of FakeModule whose __dict__ we keep
909 # copying and clearing for reuse on each %run
920 # copying and clearing for reuse on each %run
910 self._user_main_module = FakeModule()
921 self._user_main_module = FakeModule()
911
922
912 # A table holding all the namespaces IPython deals with, so that
923 # A table holding all the namespaces IPython deals with, so that
913 # introspection facilities can search easily.
924 # introspection facilities can search easily.
914 self.ns_table = {'user':user_ns,
925 self.ns_table = {'user':user_ns,
915 'user_global':user_global_ns,
926 'user_global':user_global_ns,
916 'internal':self.internal_ns,
927 'internal':self.internal_ns,
917 'builtin':__builtin__.__dict__
928 'builtin':__builtin__.__dict__
918 }
929 }
919
930
920 # Similarly, track all namespaces where references can be held and that
931 # Similarly, track all namespaces where references can be held and that
921 # we can safely clear (so it can NOT include builtin). This one can be
932 # we can safely clear (so it can NOT include builtin). This one can be
922 # a simple list. Note that the main execution namespaces, user_ns and
933 # a simple list. Note that the main execution namespaces, user_ns and
923 # user_global_ns, can NOT be listed here, as clearing them blindly
934 # user_global_ns, can NOT be listed here, as clearing them blindly
924 # causes errors in object __del__ methods. Instead, the reset() method
935 # causes errors in object __del__ methods. Instead, the reset() method
925 # clears them manually and carefully.
936 # clears them manually and carefully.
926 self.ns_refs_table = [ self.user_ns_hidden,
937 self.ns_refs_table = [ self.user_ns_hidden,
927 self.internal_ns, self._main_ns_cache ]
938 self.internal_ns, self._main_ns_cache ]
928
939
929 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
940 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
930 """Return a valid local and global user interactive namespaces.
941 """Return a valid local and global user interactive namespaces.
931
942
932 This builds a dict with the minimal information needed to operate as a
943 This builds a dict with the minimal information needed to operate as a
933 valid IPython user namespace, which you can pass to the various
944 valid IPython user namespace, which you can pass to the various
934 embedding classes in ipython. The default implementation returns the
945 embedding classes in ipython. The default implementation returns the
935 same dict for both the locals and the globals to allow functions to
946 same dict for both the locals and the globals to allow functions to
936 refer to variables in the namespace. Customized implementations can
947 refer to variables in the namespace. Customized implementations can
937 return different dicts. The locals dictionary can actually be anything
948 return different dicts. The locals dictionary can actually be anything
938 following the basic mapping protocol of a dict, but the globals dict
949 following the basic mapping protocol of a dict, but the globals dict
939 must be a true dict, not even a subclass. It is recommended that any
950 must be a true dict, not even a subclass. It is recommended that any
940 custom object for the locals namespace synchronize with the globals
951 custom object for the locals namespace synchronize with the globals
941 dict somehow.
952 dict somehow.
942
953
943 Raises TypeError if the provided globals namespace is not a true dict.
954 Raises TypeError if the provided globals namespace is not a true dict.
944
955
945 Parameters
956 Parameters
946 ----------
957 ----------
947 user_ns : dict-like, optional
958 user_ns : dict-like, optional
948 The current user namespace. The items in this namespace should
959 The current user namespace. The items in this namespace should
949 be included in the output. If None, an appropriate blank
960 be included in the output. If None, an appropriate blank
950 namespace should be created.
961 namespace should be created.
951 user_global_ns : dict, optional
962 user_global_ns : dict, optional
952 The current user global namespace. The items in this namespace
963 The current user global namespace. The items in this namespace
953 should be included in the output. If None, an appropriate
964 should be included in the output. If None, an appropriate
954 blank namespace should be created.
965 blank namespace should be created.
955
966
956 Returns
967 Returns
957 -------
968 -------
958 A pair of dictionary-like object to be used as the local namespace
969 A pair of dictionary-like object to be used as the local namespace
959 of the interpreter and a dict to be used as the global namespace.
970 of the interpreter and a dict to be used as the global namespace.
960 """
971 """
961
972
962
973
963 # We must ensure that __builtin__ (without the final 's') is always
974 # We must ensure that __builtin__ (without the final 's') is always
964 # available and pointing to the __builtin__ *module*. For more details:
975 # available and pointing to the __builtin__ *module*. For more details:
965 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
976 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
966
977
967 if user_ns is None:
978 if user_ns is None:
968 # Set __name__ to __main__ to better match the behavior of the
979 # Set __name__ to __main__ to better match the behavior of the
969 # normal interpreter.
980 # normal interpreter.
970 user_ns = {'__name__' :'__main__',
981 user_ns = {'__name__' :'__main__',
971 '__builtin__' : __builtin__,
982 '__builtin__' : __builtin__,
972 '__builtins__' : __builtin__,
983 '__builtins__' : __builtin__,
973 }
984 }
974 else:
985 else:
975 user_ns.setdefault('__name__','__main__')
986 user_ns.setdefault('__name__','__main__')
976 user_ns.setdefault('__builtin__',__builtin__)
987 user_ns.setdefault('__builtin__',__builtin__)
977 user_ns.setdefault('__builtins__',__builtin__)
988 user_ns.setdefault('__builtins__',__builtin__)
978
989
979 if user_global_ns is None:
990 if user_global_ns is None:
980 user_global_ns = user_ns
991 user_global_ns = user_ns
981 if type(user_global_ns) is not dict:
992 if type(user_global_ns) is not dict:
982 raise TypeError("user_global_ns must be a true dict; got %r"
993 raise TypeError("user_global_ns must be a true dict; got %r"
983 % type(user_global_ns))
994 % type(user_global_ns))
984
995
985 return user_ns, user_global_ns
996 return user_ns, user_global_ns
986
997
987 def init_sys_modules(self):
998 def init_sys_modules(self):
988 # We need to insert into sys.modules something that looks like a
999 # We need to insert into sys.modules something that looks like a
989 # module but which accesses the IPython namespace, for shelve and
1000 # module but which accesses the IPython namespace, for shelve and
990 # pickle to work interactively. Normally they rely on getting
1001 # pickle to work interactively. Normally they rely on getting
991 # everything out of __main__, but for embedding purposes each IPython
1002 # everything out of __main__, but for embedding purposes each IPython
992 # instance has its own private namespace, so we can't go shoving
1003 # instance has its own private namespace, so we can't go shoving
993 # everything into __main__.
1004 # everything into __main__.
994
1005
995 # note, however, that we should only do this for non-embedded
1006 # note, however, that we should only do this for non-embedded
996 # ipythons, which really mimic the __main__.__dict__ with their own
1007 # ipythons, which really mimic the __main__.__dict__ with their own
997 # namespace. Embedded instances, on the other hand, should not do
1008 # namespace. Embedded instances, on the other hand, should not do
998 # this because they need to manage the user local/global namespaces
1009 # this because they need to manage the user local/global namespaces
999 # only, but they live within a 'normal' __main__ (meaning, they
1010 # only, but they live within a 'normal' __main__ (meaning, they
1000 # shouldn't overtake the execution environment of the script they're
1011 # shouldn't overtake the execution environment of the script they're
1001 # embedded in).
1012 # embedded in).
1002
1013
1003 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1014 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1004
1015
1005 try:
1016 try:
1006 main_name = self.user_ns['__name__']
1017 main_name = self.user_ns['__name__']
1007 except KeyError:
1018 except KeyError:
1008 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1019 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1009 else:
1020 else:
1010 sys.modules[main_name] = FakeModule(self.user_ns)
1021 sys.modules[main_name] = FakeModule(self.user_ns)
1011
1022
1012 def init_user_ns(self):
1023 def init_user_ns(self):
1013 """Initialize all user-visible namespaces to their minimum defaults.
1024 """Initialize all user-visible namespaces to their minimum defaults.
1014
1025
1015 Certain history lists are also initialized here, as they effectively
1026 Certain history lists are also initialized here, as they effectively
1016 act as user namespaces.
1027 act as user namespaces.
1017
1028
1018 Notes
1029 Notes
1019 -----
1030 -----
1020 All data structures here are only filled in, they are NOT reset by this
1031 All data structures here are only filled in, they are NOT reset by this
1021 method. If they were not empty before, data will simply be added to
1032 method. If they were not empty before, data will simply be added to
1022 therm.
1033 therm.
1023 """
1034 """
1024 # This function works in two parts: first we put a few things in
1035 # This function works in two parts: first we put a few things in
1025 # user_ns, and we sync that contents into user_ns_hidden so that these
1036 # user_ns, and we sync that contents into user_ns_hidden so that these
1026 # initial variables aren't shown by %who. After the sync, we add the
1037 # initial variables aren't shown by %who. After the sync, we add the
1027 # rest of what we *do* want the user to see with %who even on a new
1038 # rest of what we *do* want the user to see with %who even on a new
1028 # session (probably nothing, so theye really only see their own stuff)
1039 # session (probably nothing, so theye really only see their own stuff)
1029
1040
1030 # The user dict must *always* have a __builtin__ reference to the
1041 # The user dict must *always* have a __builtin__ reference to the
1031 # Python standard __builtin__ namespace, which must be imported.
1042 # Python standard __builtin__ namespace, which must be imported.
1032 # This is so that certain operations in prompt evaluation can be
1043 # This is so that certain operations in prompt evaluation can be
1033 # reliably executed with builtins. Note that we can NOT use
1044 # reliably executed with builtins. Note that we can NOT use
1034 # __builtins__ (note the 's'), because that can either be a dict or a
1045 # __builtins__ (note the 's'), because that can either be a dict or a
1035 # module, and can even mutate at runtime, depending on the context
1046 # module, and can even mutate at runtime, depending on the context
1036 # (Python makes no guarantees on it). In contrast, __builtin__ is
1047 # (Python makes no guarantees on it). In contrast, __builtin__ is
1037 # always a module object, though it must be explicitly imported.
1048 # always a module object, though it must be explicitly imported.
1038
1049
1039 # For more details:
1050 # For more details:
1040 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1051 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1041 ns = dict(__builtin__ = __builtin__)
1052 ns = dict(__builtin__ = __builtin__)
1042
1053
1043 # Put 'help' in the user namespace
1054 # Put 'help' in the user namespace
1044 try:
1055 try:
1045 from site import _Helper
1056 from site import _Helper
1046 ns['help'] = _Helper()
1057 ns['help'] = _Helper()
1047 except ImportError:
1058 except ImportError:
1048 warn('help() not available - check site.py')
1059 warn('help() not available - check site.py')
1049
1060
1050 # make global variables for user access to the histories
1061 # make global variables for user access to the histories
1051 ns['_ih'] = self.history_manager.input_hist_parsed
1062 ns['_ih'] = self.history_manager.input_hist_parsed
1052 ns['_oh'] = self.history_manager.output_hist
1063 ns['_oh'] = self.history_manager.output_hist
1053 ns['_dh'] = self.history_manager.dir_hist
1064 ns['_dh'] = self.history_manager.dir_hist
1054
1065
1055 ns['_sh'] = shadowns
1066 ns['_sh'] = shadowns
1056
1067
1057 # user aliases to input and output histories. These shouldn't show up
1068 # user aliases to input and output histories. These shouldn't show up
1058 # in %who, as they can have very large reprs.
1069 # in %who, as they can have very large reprs.
1059 ns['In'] = self.history_manager.input_hist_parsed
1070 ns['In'] = self.history_manager.input_hist_parsed
1060 ns['Out'] = self.history_manager.output_hist
1071 ns['Out'] = self.history_manager.output_hist
1061
1072
1062 # Store myself as the public api!!!
1073 # Store myself as the public api!!!
1063 ns['get_ipython'] = self.get_ipython
1074 ns['get_ipython'] = self.get_ipython
1064
1075
1065 ns['exit'] = self.exiter
1076 ns['exit'] = self.exiter
1066 ns['quit'] = self.exiter
1077 ns['quit'] = self.exiter
1067
1078
1068 # Sync what we've added so far to user_ns_hidden so these aren't seen
1079 # Sync what we've added so far to user_ns_hidden so these aren't seen
1069 # by %who
1080 # by %who
1070 self.user_ns_hidden.update(ns)
1081 self.user_ns_hidden.update(ns)
1071
1082
1072 # Anything put into ns now would show up in %who. Think twice before
1083 # Anything put into ns now would show up in %who. Think twice before
1073 # putting anything here, as we really want %who to show the user their
1084 # putting anything here, as we really want %who to show the user their
1074 # stuff, not our variables.
1085 # stuff, not our variables.
1075
1086
1076 # Finally, update the real user's namespace
1087 # Finally, update the real user's namespace
1077 self.user_ns.update(ns)
1088 self.user_ns.update(ns)
1078
1089
1079 def reset(self, new_session=True):
1090 def reset(self, new_session=True):
1080 """Clear all internal namespaces, and attempt to release references to
1091 """Clear all internal namespaces, and attempt to release references to
1081 user objects.
1092 user objects.
1082
1093
1083 If new_session is True, a new history session will be opened.
1094 If new_session is True, a new history session will be opened.
1084 """
1095 """
1085 # Clear histories
1096 # Clear histories
1086 self.history_manager.reset(new_session)
1097 self.history_manager.reset(new_session)
1087 # Reset counter used to index all histories
1098 # Reset counter used to index all histories
1088 if new_session:
1099 if new_session:
1089 self.execution_count = 1
1100 self.execution_count = 1
1090
1101
1091 # Flush cached output items
1102 # Flush cached output items
1092 if self.displayhook.do_full_cache:
1103 if self.displayhook.do_full_cache:
1093 self.displayhook.flush()
1104 self.displayhook.flush()
1094
1105
1095 # Restore the user namespaces to minimal usability
1106 # Restore the user namespaces to minimal usability
1096 for ns in self.ns_refs_table:
1107 for ns in self.ns_refs_table:
1097 ns.clear()
1108 ns.clear()
1098
1109
1099 # The main execution namespaces must be cleared very carefully,
1110 # The main execution namespaces must be cleared very carefully,
1100 # skipping the deletion of the builtin-related keys, because doing so
1111 # skipping the deletion of the builtin-related keys, because doing so
1101 # would cause errors in many object's __del__ methods.
1112 # would cause errors in many object's __del__ methods.
1102 for ns in [self.user_ns, self.user_global_ns]:
1113 for ns in [self.user_ns, self.user_global_ns]:
1103 drop_keys = set(ns.keys())
1114 drop_keys = set(ns.keys())
1104 drop_keys.discard('__builtin__')
1115 drop_keys.discard('__builtin__')
1105 drop_keys.discard('__builtins__')
1116 drop_keys.discard('__builtins__')
1106 for k in drop_keys:
1117 for k in drop_keys:
1107 del ns[k]
1118 del ns[k]
1108
1119
1109 # Restore the user namespaces to minimal usability
1120 # Restore the user namespaces to minimal usability
1110 self.init_user_ns()
1121 self.init_user_ns()
1111
1122
1112 # Restore the default and user aliases
1123 # Restore the default and user aliases
1113 self.alias_manager.clear_aliases()
1124 self.alias_manager.clear_aliases()
1114 self.alias_manager.init_aliases()
1125 self.alias_manager.init_aliases()
1115
1126
1116 # Flush the private list of module references kept for script
1127 # Flush the private list of module references kept for script
1117 # execution protection
1128 # execution protection
1118 self.clear_main_mod_cache()
1129 self.clear_main_mod_cache()
1119
1130
1120 # Clear out the namespace from the last %run
1131 # Clear out the namespace from the last %run
1121 self.new_main_mod()
1132 self.new_main_mod()
1122
1133
1123 def del_var(self, varname, by_name=False):
1134 def del_var(self, varname, by_name=False):
1124 """Delete a variable from the various namespaces, so that, as
1135 """Delete a variable from the various namespaces, so that, as
1125 far as possible, we're not keeping any hidden references to it.
1136 far as possible, we're not keeping any hidden references to it.
1126
1137
1127 Parameters
1138 Parameters
1128 ----------
1139 ----------
1129 varname : str
1140 varname : str
1130 The name of the variable to delete.
1141 The name of the variable to delete.
1131 by_name : bool
1142 by_name : bool
1132 If True, delete variables with the given name in each
1143 If True, delete variables with the given name in each
1133 namespace. If False (default), find the variable in the user
1144 namespace. If False (default), find the variable in the user
1134 namespace, and delete references to it.
1145 namespace, and delete references to it.
1135 """
1146 """
1136 if varname in ('__builtin__', '__builtins__'):
1147 if varname in ('__builtin__', '__builtins__'):
1137 raise ValueError("Refusing to delete %s" % varname)
1148 raise ValueError("Refusing to delete %s" % varname)
1138 ns_refs = self.ns_refs_table + [self.user_ns,
1149 ns_refs = self.ns_refs_table + [self.user_ns,
1139 self.user_global_ns, self._user_main_module.__dict__] +\
1150 self.user_global_ns, self._user_main_module.__dict__] +\
1140 self._main_ns_cache.values()
1151 self._main_ns_cache.values()
1141
1152
1142 if by_name: # Delete by name
1153 if by_name: # Delete by name
1143 for ns in ns_refs:
1154 for ns in ns_refs:
1144 try:
1155 try:
1145 del ns[varname]
1156 del ns[varname]
1146 except KeyError:
1157 except KeyError:
1147 pass
1158 pass
1148 else: # Delete by object
1159 else: # Delete by object
1149 try:
1160 try:
1150 obj = self.user_ns[varname]
1161 obj = self.user_ns[varname]
1151 except KeyError:
1162 except KeyError:
1152 raise NameError("name '%s' is not defined" % varname)
1163 raise NameError("name '%s' is not defined" % varname)
1153 # Also check in output history
1164 # Also check in output history
1154 ns_refs.append(self.history_manager.output_hist)
1165 ns_refs.append(self.history_manager.output_hist)
1155 for ns in ns_refs:
1166 for ns in ns_refs:
1156 to_delete = [n for n, o in ns.iteritems() if o is obj]
1167 to_delete = [n for n, o in ns.iteritems() if o is obj]
1157 for name in to_delete:
1168 for name in to_delete:
1158 del ns[name]
1169 del ns[name]
1159
1170
1160 # displayhook keeps extra references, but not in a dictionary
1171 # displayhook keeps extra references, but not in a dictionary
1161 for name in ('_', '__', '___'):
1172 for name in ('_', '__', '___'):
1162 if getattr(self.displayhook, name) is obj:
1173 if getattr(self.displayhook, name) is obj:
1163 setattr(self.displayhook, name, None)
1174 setattr(self.displayhook, name, None)
1164
1175
1165 def reset_selective(self, regex=None):
1176 def reset_selective(self, regex=None):
1166 """Clear selective variables from internal namespaces based on a
1177 """Clear selective variables from internal namespaces based on a
1167 specified regular expression.
1178 specified regular expression.
1168
1179
1169 Parameters
1180 Parameters
1170 ----------
1181 ----------
1171 regex : string or compiled pattern, optional
1182 regex : string or compiled pattern, optional
1172 A regular expression pattern that will be used in searching
1183 A regular expression pattern that will be used in searching
1173 variable names in the users namespaces.
1184 variable names in the users namespaces.
1174 """
1185 """
1175 if regex is not None:
1186 if regex is not None:
1176 try:
1187 try:
1177 m = re.compile(regex)
1188 m = re.compile(regex)
1178 except TypeError:
1189 except TypeError:
1179 raise TypeError('regex must be a string or compiled pattern')
1190 raise TypeError('regex must be a string or compiled pattern')
1180 # Search for keys in each namespace that match the given regex
1191 # Search for keys in each namespace that match the given regex
1181 # If a match is found, delete the key/value pair.
1192 # If a match is found, delete the key/value pair.
1182 for ns in self.ns_refs_table:
1193 for ns in self.ns_refs_table:
1183 for var in ns:
1194 for var in ns:
1184 if m.search(var):
1195 if m.search(var):
1185 del ns[var]
1196 del ns[var]
1186
1197
1187 def push(self, variables, interactive=True):
1198 def push(self, variables, interactive=True):
1188 """Inject a group of variables into the IPython user namespace.
1199 """Inject a group of variables into the IPython user namespace.
1189
1200
1190 Parameters
1201 Parameters
1191 ----------
1202 ----------
1192 variables : dict, str or list/tuple of str
1203 variables : dict, str or list/tuple of str
1193 The variables to inject into the user's namespace. If a dict, a
1204 The variables to inject into the user's namespace. If a dict, a
1194 simple update is done. If a str, the string is assumed to have
1205 simple update is done. If a str, the string is assumed to have
1195 variable names separated by spaces. A list/tuple of str can also
1206 variable names separated by spaces. A list/tuple of str can also
1196 be used to give the variable names. If just the variable names are
1207 be used to give the variable names. If just the variable names are
1197 give (list/tuple/str) then the variable values looked up in the
1208 give (list/tuple/str) then the variable values looked up in the
1198 callers frame.
1209 callers frame.
1199 interactive : bool
1210 interactive : bool
1200 If True (default), the variables will be listed with the ``who``
1211 If True (default), the variables will be listed with the ``who``
1201 magic.
1212 magic.
1202 """
1213 """
1203 vdict = None
1214 vdict = None
1204
1215
1205 # We need a dict of name/value pairs to do namespace updates.
1216 # We need a dict of name/value pairs to do namespace updates.
1206 if isinstance(variables, dict):
1217 if isinstance(variables, dict):
1207 vdict = variables
1218 vdict = variables
1208 elif isinstance(variables, (basestring, list, tuple)):
1219 elif isinstance(variables, (basestring, list, tuple)):
1209 if isinstance(variables, basestring):
1220 if isinstance(variables, basestring):
1210 vlist = variables.split()
1221 vlist = variables.split()
1211 else:
1222 else:
1212 vlist = variables
1223 vlist = variables
1213 vdict = {}
1224 vdict = {}
1214 cf = sys._getframe(1)
1225 cf = sys._getframe(1)
1215 for name in vlist:
1226 for name in vlist:
1216 try:
1227 try:
1217 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1228 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1218 except:
1229 except:
1219 print ('Could not get variable %s from %s' %
1230 print ('Could not get variable %s from %s' %
1220 (name,cf.f_code.co_name))
1231 (name,cf.f_code.co_name))
1221 else:
1232 else:
1222 raise ValueError('variables must be a dict/str/list/tuple')
1233 raise ValueError('variables must be a dict/str/list/tuple')
1223
1234
1224 # Propagate variables to user namespace
1235 # Propagate variables to user namespace
1225 self.user_ns.update(vdict)
1236 self.user_ns.update(vdict)
1226
1237
1227 # And configure interactive visibility
1238 # And configure interactive visibility
1228 config_ns = self.user_ns_hidden
1239 config_ns = self.user_ns_hidden
1229 if interactive:
1240 if interactive:
1230 for name, val in vdict.iteritems():
1241 for name, val in vdict.iteritems():
1231 config_ns.pop(name, None)
1242 config_ns.pop(name, None)
1232 else:
1243 else:
1233 for name,val in vdict.iteritems():
1244 for name,val in vdict.iteritems():
1234 config_ns[name] = val
1245 config_ns[name] = val
1235
1246
1236 #-------------------------------------------------------------------------
1247 #-------------------------------------------------------------------------
1237 # Things related to object introspection
1248 # Things related to object introspection
1238 #-------------------------------------------------------------------------
1249 #-------------------------------------------------------------------------
1239
1250
1240 def _ofind(self, oname, namespaces=None):
1251 def _ofind(self, oname, namespaces=None):
1241 """Find an object in the available namespaces.
1252 """Find an object in the available namespaces.
1242
1253
1243 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1254 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1244
1255
1245 Has special code to detect magic functions.
1256 Has special code to detect magic functions.
1246 """
1257 """
1247 #oname = oname.strip()
1258 #oname = oname.strip()
1248 #print '1- oname: <%r>' % oname # dbg
1259 #print '1- oname: <%r>' % oname # dbg
1249 try:
1260 try:
1250 oname = oname.strip().encode('ascii')
1261 oname = oname.strip().encode('ascii')
1251 #print '2- oname: <%r>' % oname # dbg
1262 #print '2- oname: <%r>' % oname # dbg
1252 except UnicodeEncodeError:
1263 except UnicodeEncodeError:
1253 print 'Python identifiers can only contain ascii characters.'
1264 print 'Python identifiers can only contain ascii characters.'
1254 return dict(found=False)
1265 return dict(found=False)
1255
1266
1256 alias_ns = None
1267 alias_ns = None
1257 if namespaces is None:
1268 if namespaces is None:
1258 # Namespaces to search in:
1269 # Namespaces to search in:
1259 # Put them in a list. The order is important so that we
1270 # Put them in a list. The order is important so that we
1260 # find things in the same order that Python finds them.
1271 # find things in the same order that Python finds them.
1261 namespaces = [ ('Interactive', self.user_ns),
1272 namespaces = [ ('Interactive', self.user_ns),
1262 ('IPython internal', self.internal_ns),
1273 ('IPython internal', self.internal_ns),
1263 ('Python builtin', __builtin__.__dict__),
1274 ('Python builtin', __builtin__.__dict__),
1264 ('Alias', self.alias_manager.alias_table),
1275 ('Alias', self.alias_manager.alias_table),
1265 ]
1276 ]
1266 alias_ns = self.alias_manager.alias_table
1277 alias_ns = self.alias_manager.alias_table
1267
1278
1268 # initialize results to 'null'
1279 # initialize results to 'null'
1269 found = False; obj = None; ospace = None; ds = None;
1280 found = False; obj = None; ospace = None; ds = None;
1270 ismagic = False; isalias = False; parent = None
1281 ismagic = False; isalias = False; parent = None
1271
1282
1272 # We need to special-case 'print', which as of python2.6 registers as a
1283 # We need to special-case 'print', which as of python2.6 registers as a
1273 # function but should only be treated as one if print_function was
1284 # function but should only be treated as one if print_function was
1274 # loaded with a future import. In this case, just bail.
1285 # loaded with a future import. In this case, just bail.
1275 if (oname == 'print' and not (self.compile.compiler_flags &
1286 if (oname == 'print' and not (self.compile.compiler_flags &
1276 __future__.CO_FUTURE_PRINT_FUNCTION)):
1287 __future__.CO_FUTURE_PRINT_FUNCTION)):
1277 return {'found':found, 'obj':obj, 'namespace':ospace,
1288 return {'found':found, 'obj':obj, 'namespace':ospace,
1278 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1279
1290
1280 # Look for the given name by splitting it in parts. If the head is
1291 # Look for the given name by splitting it in parts. If the head is
1281 # found, then we look for all the remaining parts as members, and only
1292 # found, then we look for all the remaining parts as members, and only
1282 # declare success if we can find them all.
1293 # declare success if we can find them all.
1283 oname_parts = oname.split('.')
1294 oname_parts = oname.split('.')
1284 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1295 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1285 for nsname,ns in namespaces:
1296 for nsname,ns in namespaces:
1286 try:
1297 try:
1287 obj = ns[oname_head]
1298 obj = ns[oname_head]
1288 except KeyError:
1299 except KeyError:
1289 continue
1300 continue
1290 else:
1301 else:
1291 #print 'oname_rest:', oname_rest # dbg
1302 #print 'oname_rest:', oname_rest # dbg
1292 for part in oname_rest:
1303 for part in oname_rest:
1293 try:
1304 try:
1294 parent = obj
1305 parent = obj
1295 obj = getattr(obj,part)
1306 obj = getattr(obj,part)
1296 except:
1307 except:
1297 # Blanket except b/c some badly implemented objects
1308 # Blanket except b/c some badly implemented objects
1298 # allow __getattr__ to raise exceptions other than
1309 # allow __getattr__ to raise exceptions other than
1299 # AttributeError, which then crashes IPython.
1310 # AttributeError, which then crashes IPython.
1300 break
1311 break
1301 else:
1312 else:
1302 # If we finish the for loop (no break), we got all members
1313 # If we finish the for loop (no break), we got all members
1303 found = True
1314 found = True
1304 ospace = nsname
1315 ospace = nsname
1305 if ns == alias_ns:
1316 if ns == alias_ns:
1306 isalias = True
1317 isalias = True
1307 break # namespace loop
1318 break # namespace loop
1308
1319
1309 # Try to see if it's magic
1320 # Try to see if it's magic
1310 if not found:
1321 if not found:
1311 if oname.startswith(ESC_MAGIC):
1322 if oname.startswith(ESC_MAGIC):
1312 oname = oname[1:]
1323 oname = oname[1:]
1313 obj = getattr(self,'magic_'+oname,None)
1324 obj = getattr(self,'magic_'+oname,None)
1314 if obj is not None:
1325 if obj is not None:
1315 found = True
1326 found = True
1316 ospace = 'IPython internal'
1327 ospace = 'IPython internal'
1317 ismagic = True
1328 ismagic = True
1318
1329
1319 # Last try: special-case some literals like '', [], {}, etc:
1330 # Last try: special-case some literals like '', [], {}, etc:
1320 if not found and oname_head in ["''",'""','[]','{}','()']:
1331 if not found and oname_head in ["''",'""','[]','{}','()']:
1321 obj = eval(oname_head)
1332 obj = eval(oname_head)
1322 found = True
1333 found = True
1323 ospace = 'Interactive'
1334 ospace = 'Interactive'
1324
1335
1325 return {'found':found, 'obj':obj, 'namespace':ospace,
1336 return {'found':found, 'obj':obj, 'namespace':ospace,
1326 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1337 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1327
1338
1328 def _ofind_property(self, oname, info):
1339 def _ofind_property(self, oname, info):
1329 """Second part of object finding, to look for property details."""
1340 """Second part of object finding, to look for property details."""
1330 if info.found:
1341 if info.found:
1331 # Get the docstring of the class property if it exists.
1342 # Get the docstring of the class property if it exists.
1332 path = oname.split('.')
1343 path = oname.split('.')
1333 root = '.'.join(path[:-1])
1344 root = '.'.join(path[:-1])
1334 if info.parent is not None:
1345 if info.parent is not None:
1335 try:
1346 try:
1336 target = getattr(info.parent, '__class__')
1347 target = getattr(info.parent, '__class__')
1337 # The object belongs to a class instance.
1348 # The object belongs to a class instance.
1338 try:
1349 try:
1339 target = getattr(target, path[-1])
1350 target = getattr(target, path[-1])
1340 # The class defines the object.
1351 # The class defines the object.
1341 if isinstance(target, property):
1352 if isinstance(target, property):
1342 oname = root + '.__class__.' + path[-1]
1353 oname = root + '.__class__.' + path[-1]
1343 info = Struct(self._ofind(oname))
1354 info = Struct(self._ofind(oname))
1344 except AttributeError: pass
1355 except AttributeError: pass
1345 except AttributeError: pass
1356 except AttributeError: pass
1346
1357
1347 # We return either the new info or the unmodified input if the object
1358 # We return either the new info or the unmodified input if the object
1348 # hadn't been found
1359 # hadn't been found
1349 return info
1360 return info
1350
1361
1351 def _object_find(self, oname, namespaces=None):
1362 def _object_find(self, oname, namespaces=None):
1352 """Find an object and return a struct with info about it."""
1363 """Find an object and return a struct with info about it."""
1353 inf = Struct(self._ofind(oname, namespaces))
1364 inf = Struct(self._ofind(oname, namespaces))
1354 return Struct(self._ofind_property(oname, inf))
1365 return Struct(self._ofind_property(oname, inf))
1355
1366
1356 def _inspect(self, meth, oname, namespaces=None, **kw):
1367 def _inspect(self, meth, oname, namespaces=None, **kw):
1357 """Generic interface to the inspector system.
1368 """Generic interface to the inspector system.
1358
1369
1359 This function is meant to be called by pdef, pdoc & friends."""
1370 This function is meant to be called by pdef, pdoc & friends."""
1360 info = self._object_find(oname)
1371 info = self._object_find(oname)
1361 if info.found:
1372 if info.found:
1362 pmethod = getattr(self.inspector, meth)
1373 pmethod = getattr(self.inspector, meth)
1363 formatter = format_screen if info.ismagic else None
1374 formatter = format_screen if info.ismagic else None
1364 if meth == 'pdoc':
1375 if meth == 'pdoc':
1365 pmethod(info.obj, oname, formatter)
1376 pmethod(info.obj, oname, formatter)
1366 elif meth == 'pinfo':
1377 elif meth == 'pinfo':
1367 pmethod(info.obj, oname, formatter, info, **kw)
1378 pmethod(info.obj, oname, formatter, info, **kw)
1368 else:
1379 else:
1369 pmethod(info.obj, oname)
1380 pmethod(info.obj, oname)
1370 else:
1381 else:
1371 print 'Object `%s` not found.' % oname
1382 print 'Object `%s` not found.' % oname
1372 return 'not found' # so callers can take other action
1383 return 'not found' # so callers can take other action
1373
1384
1374 def object_inspect(self, oname):
1385 def object_inspect(self, oname):
1375 with self.builtin_trap:
1386 with self.builtin_trap:
1376 info = self._object_find(oname)
1387 info = self._object_find(oname)
1377 if info.found:
1388 if info.found:
1378 return self.inspector.info(info.obj, oname, info=info)
1389 return self.inspector.info(info.obj, oname, info=info)
1379 else:
1390 else:
1380 return oinspect.object_info(name=oname, found=False)
1391 return oinspect.object_info(name=oname, found=False)
1381
1392
1382 #-------------------------------------------------------------------------
1393 #-------------------------------------------------------------------------
1383 # Things related to history management
1394 # Things related to history management
1384 #-------------------------------------------------------------------------
1395 #-------------------------------------------------------------------------
1385
1396
1386 def init_history(self):
1397 def init_history(self):
1387 """Sets up the command history, and starts regular autosaves."""
1398 """Sets up the command history, and starts regular autosaves."""
1388 self.history_manager = HistoryManager(shell=self, config=self.config)
1399 self.history_manager = HistoryManager(shell=self, config=self.config)
1389
1400
1390 #-------------------------------------------------------------------------
1401 #-------------------------------------------------------------------------
1391 # Things related to exception handling and tracebacks (not debugging)
1402 # Things related to exception handling and tracebacks (not debugging)
1392 #-------------------------------------------------------------------------
1403 #-------------------------------------------------------------------------
1393
1404
1394 def init_traceback_handlers(self, custom_exceptions):
1405 def init_traceback_handlers(self, custom_exceptions):
1395 # Syntax error handler.
1406 # Syntax error handler.
1396 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1407 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1397
1408
1398 # The interactive one is initialized with an offset, meaning we always
1409 # The interactive one is initialized with an offset, meaning we always
1399 # want to remove the topmost item in the traceback, which is our own
1410 # want to remove the topmost item in the traceback, which is our own
1400 # internal code. Valid modes: ['Plain','Context','Verbose']
1411 # internal code. Valid modes: ['Plain','Context','Verbose']
1401 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1412 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1402 color_scheme='NoColor',
1413 color_scheme='NoColor',
1403 tb_offset = 1,
1414 tb_offset = 1,
1404 check_cache=self.compile.check_cache)
1415 check_cache=self.compile.check_cache)
1405
1416
1406 # The instance will store a pointer to the system-wide exception hook,
1417 # The instance will store a pointer to the system-wide exception hook,
1407 # so that runtime code (such as magics) can access it. This is because
1418 # so that runtime code (such as magics) can access it. This is because
1408 # during the read-eval loop, it may get temporarily overwritten.
1419 # during the read-eval loop, it may get temporarily overwritten.
1409 self.sys_excepthook = sys.excepthook
1420 self.sys_excepthook = sys.excepthook
1410
1421
1411 # and add any custom exception handlers the user may have specified
1422 # and add any custom exception handlers the user may have specified
1412 self.set_custom_exc(*custom_exceptions)
1423 self.set_custom_exc(*custom_exceptions)
1413
1424
1414 # Set the exception mode
1425 # Set the exception mode
1415 self.InteractiveTB.set_mode(mode=self.xmode)
1426 self.InteractiveTB.set_mode(mode=self.xmode)
1416
1427
1417 def set_custom_exc(self, exc_tuple, handler):
1428 def set_custom_exc(self, exc_tuple, handler):
1418 """set_custom_exc(exc_tuple,handler)
1429 """set_custom_exc(exc_tuple,handler)
1419
1430
1420 Set a custom exception handler, which will be called if any of the
1431 Set a custom exception handler, which will be called if any of the
1421 exceptions in exc_tuple occur in the mainloop (specifically, in the
1432 exceptions in exc_tuple occur in the mainloop (specifically, in the
1422 run_code() method.
1433 run_code() method.
1423
1434
1424 Inputs:
1435 Inputs:
1425
1436
1426 - exc_tuple: a *tuple* of valid exceptions to call the defined
1437 - exc_tuple: a *tuple* of valid exceptions to call the defined
1427 handler for. It is very important that you use a tuple, and NOT A
1438 handler for. It is very important that you use a tuple, and NOT A
1428 LIST here, because of the way Python's except statement works. If
1439 LIST here, because of the way Python's except statement works. If
1429 you only want to trap a single exception, use a singleton tuple:
1440 you only want to trap a single exception, use a singleton tuple:
1430
1441
1431 exc_tuple == (MyCustomException,)
1442 exc_tuple == (MyCustomException,)
1432
1443
1433 - handler: this must be defined as a function with the following
1444 - handler: this must be defined as a function with the following
1434 basic interface::
1445 basic interface::
1435
1446
1436 def my_handler(self, etype, value, tb, tb_offset=None)
1447 def my_handler(self, etype, value, tb, tb_offset=None)
1437 ...
1448 ...
1438 # The return value must be
1449 # The return value must be
1439 return structured_traceback
1450 return structured_traceback
1440
1451
1441 This will be made into an instance method (via types.MethodType)
1452 This will be made into an instance method (via types.MethodType)
1442 of IPython itself, and it will be called if any of the exceptions
1453 of IPython itself, and it will be called if any of the exceptions
1443 listed in the exc_tuple are caught. If the handler is None, an
1454 listed in the exc_tuple are caught. If the handler is None, an
1444 internal basic one is used, which just prints basic info.
1455 internal basic one is used, which just prints basic info.
1445
1456
1446 WARNING: by putting in your own exception handler into IPython's main
1457 WARNING: by putting in your own exception handler into IPython's main
1447 execution loop, you run a very good chance of nasty crashes. This
1458 execution loop, you run a very good chance of nasty crashes. This
1448 facility should only be used if you really know what you are doing."""
1459 facility should only be used if you really know what you are doing."""
1449
1460
1450 assert type(exc_tuple)==type(()) , \
1461 assert type(exc_tuple)==type(()) , \
1451 "The custom exceptions must be given AS A TUPLE."
1462 "The custom exceptions must be given AS A TUPLE."
1452
1463
1453 def dummy_handler(self,etype,value,tb):
1464 def dummy_handler(self,etype,value,tb):
1454 print '*** Simple custom exception handler ***'
1465 print '*** Simple custom exception handler ***'
1455 print 'Exception type :',etype
1466 print 'Exception type :',etype
1456 print 'Exception value:',value
1467 print 'Exception value:',value
1457 print 'Traceback :',tb
1468 print 'Traceback :',tb
1458 #print 'Source code :','\n'.join(self.buffer)
1469 #print 'Source code :','\n'.join(self.buffer)
1459
1470
1460 if handler is None: handler = dummy_handler
1471 if handler is None: handler = dummy_handler
1461
1472
1462 self.CustomTB = types.MethodType(handler,self)
1473 self.CustomTB = types.MethodType(handler,self)
1463 self.custom_exceptions = exc_tuple
1474 self.custom_exceptions = exc_tuple
1464
1475
1465 def excepthook(self, etype, value, tb):
1476 def excepthook(self, etype, value, tb):
1466 """One more defense for GUI apps that call sys.excepthook.
1477 """One more defense for GUI apps that call sys.excepthook.
1467
1478
1468 GUI frameworks like wxPython trap exceptions and call
1479 GUI frameworks like wxPython trap exceptions and call
1469 sys.excepthook themselves. I guess this is a feature that
1480 sys.excepthook themselves. I guess this is a feature that
1470 enables them to keep running after exceptions that would
1481 enables them to keep running after exceptions that would
1471 otherwise kill their mainloop. This is a bother for IPython
1482 otherwise kill their mainloop. This is a bother for IPython
1472 which excepts to catch all of the program exceptions with a try:
1483 which excepts to catch all of the program exceptions with a try:
1473 except: statement.
1484 except: statement.
1474
1485
1475 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1486 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1476 any app directly invokes sys.excepthook, it will look to the user like
1487 any app directly invokes sys.excepthook, it will look to the user like
1477 IPython crashed. In order to work around this, we can disable the
1488 IPython crashed. In order to work around this, we can disable the
1478 CrashHandler and replace it with this excepthook instead, which prints a
1489 CrashHandler and replace it with this excepthook instead, which prints a
1479 regular traceback using our InteractiveTB. In this fashion, apps which
1490 regular traceback using our InteractiveTB. In this fashion, apps which
1480 call sys.excepthook will generate a regular-looking exception from
1491 call sys.excepthook will generate a regular-looking exception from
1481 IPython, and the CrashHandler will only be triggered by real IPython
1492 IPython, and the CrashHandler will only be triggered by real IPython
1482 crashes.
1493 crashes.
1483
1494
1484 This hook should be used sparingly, only in places which are not likely
1495 This hook should be used sparingly, only in places which are not likely
1485 to be true IPython errors.
1496 to be true IPython errors.
1486 """
1497 """
1487 self.showtraceback((etype,value,tb),tb_offset=0)
1498 self.showtraceback((etype,value,tb),tb_offset=0)
1488
1499
1489 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1500 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1490 exception_only=False):
1501 exception_only=False):
1491 """Display the exception that just occurred.
1502 """Display the exception that just occurred.
1492
1503
1493 If nothing is known about the exception, this is the method which
1504 If nothing is known about the exception, this is the method which
1494 should be used throughout the code for presenting user tracebacks,
1505 should be used throughout the code for presenting user tracebacks,
1495 rather than directly invoking the InteractiveTB object.
1506 rather than directly invoking the InteractiveTB object.
1496
1507
1497 A specific showsyntaxerror() also exists, but this method can take
1508 A specific showsyntaxerror() also exists, but this method can take
1498 care of calling it if needed, so unless you are explicitly catching a
1509 care of calling it if needed, so unless you are explicitly catching a
1499 SyntaxError exception, don't try to analyze the stack manually and
1510 SyntaxError exception, don't try to analyze the stack manually and
1500 simply call this method."""
1511 simply call this method."""
1501
1512
1502 try:
1513 try:
1503 if exc_tuple is None:
1514 if exc_tuple is None:
1504 etype, value, tb = sys.exc_info()
1515 etype, value, tb = sys.exc_info()
1505 else:
1516 else:
1506 etype, value, tb = exc_tuple
1517 etype, value, tb = exc_tuple
1507
1518
1508 if etype is None:
1519 if etype is None:
1509 if hasattr(sys, 'last_type'):
1520 if hasattr(sys, 'last_type'):
1510 etype, value, tb = sys.last_type, sys.last_value, \
1521 etype, value, tb = sys.last_type, sys.last_value, \
1511 sys.last_traceback
1522 sys.last_traceback
1512 else:
1523 else:
1513 self.write_err('No traceback available to show.\n')
1524 self.write_err('No traceback available to show.\n')
1514 return
1525 return
1515
1526
1516 if etype is SyntaxError:
1527 if etype is SyntaxError:
1517 # Though this won't be called by syntax errors in the input
1528 # Though this won't be called by syntax errors in the input
1518 # line, there may be SyntaxError cases whith imported code.
1529 # line, there may be SyntaxError cases whith imported code.
1519 self.showsyntaxerror(filename)
1530 self.showsyntaxerror(filename)
1520 elif etype is UsageError:
1531 elif etype is UsageError:
1521 print "UsageError:", value
1532 print "UsageError:", value
1522 else:
1533 else:
1523 # WARNING: these variables are somewhat deprecated and not
1534 # WARNING: these variables are somewhat deprecated and not
1524 # necessarily safe to use in a threaded environment, but tools
1535 # necessarily safe to use in a threaded environment, but tools
1525 # like pdb depend on their existence, so let's set them. If we
1536 # like pdb depend on their existence, so let's set them. If we
1526 # find problems in the field, we'll need to revisit their use.
1537 # find problems in the field, we'll need to revisit their use.
1527 sys.last_type = etype
1538 sys.last_type = etype
1528 sys.last_value = value
1539 sys.last_value = value
1529 sys.last_traceback = tb
1540 sys.last_traceback = tb
1530 if etype in self.custom_exceptions:
1541 if etype in self.custom_exceptions:
1531 # FIXME: Old custom traceback objects may just return a
1542 # FIXME: Old custom traceback objects may just return a
1532 # string, in that case we just put it into a list
1543 # string, in that case we just put it into a list
1533 stb = self.CustomTB(etype, value, tb, tb_offset)
1544 stb = self.CustomTB(etype, value, tb, tb_offset)
1534 if isinstance(ctb, basestring):
1545 if isinstance(ctb, basestring):
1535 stb = [stb]
1546 stb = [stb]
1536 else:
1547 else:
1537 if exception_only:
1548 if exception_only:
1538 stb = ['An exception has occurred, use %tb to see '
1549 stb = ['An exception has occurred, use %tb to see '
1539 'the full traceback.\n']
1550 'the full traceback.\n']
1540 stb.extend(self.InteractiveTB.get_exception_only(etype,
1551 stb.extend(self.InteractiveTB.get_exception_only(etype,
1541 value))
1552 value))
1542 else:
1553 else:
1543 stb = self.InteractiveTB.structured_traceback(etype,
1554 stb = self.InteractiveTB.structured_traceback(etype,
1544 value, tb, tb_offset=tb_offset)
1555 value, tb, tb_offset=tb_offset)
1545
1556
1546 if self.call_pdb:
1557 if self.call_pdb:
1547 # drop into debugger
1558 # drop into debugger
1548 self.debugger(force=True)
1559 self.debugger(force=True)
1549
1560
1550 # Actually show the traceback
1561 # Actually show the traceback
1551 self._showtraceback(etype, value, stb)
1562 self._showtraceback(etype, value, stb)
1552
1563
1553 except KeyboardInterrupt:
1564 except KeyboardInterrupt:
1554 self.write_err("\nKeyboardInterrupt\n")
1565 self.write_err("\nKeyboardInterrupt\n")
1555
1566
1556 def _showtraceback(self, etype, evalue, stb):
1567 def _showtraceback(self, etype, evalue, stb):
1557 """Actually show a traceback.
1568 """Actually show a traceback.
1558
1569
1559 Subclasses may override this method to put the traceback on a different
1570 Subclasses may override this method to put the traceback on a different
1560 place, like a side channel.
1571 place, like a side channel.
1561 """
1572 """
1562 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1573 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1563
1574
1564 def showsyntaxerror(self, filename=None):
1575 def showsyntaxerror(self, filename=None):
1565 """Display the syntax error that just occurred.
1576 """Display the syntax error that just occurred.
1566
1577
1567 This doesn't display a stack trace because there isn't one.
1578 This doesn't display a stack trace because there isn't one.
1568
1579
1569 If a filename is given, it is stuffed in the exception instead
1580 If a filename is given, it is stuffed in the exception instead
1570 of what was there before (because Python's parser always uses
1581 of what was there before (because Python's parser always uses
1571 "<string>" when reading from a string).
1582 "<string>" when reading from a string).
1572 """
1583 """
1573 etype, value, last_traceback = sys.exc_info()
1584 etype, value, last_traceback = sys.exc_info()
1574
1585
1575 # See note about these variables in showtraceback() above
1586 # See note about these variables in showtraceback() above
1576 sys.last_type = etype
1587 sys.last_type = etype
1577 sys.last_value = value
1588 sys.last_value = value
1578 sys.last_traceback = last_traceback
1589 sys.last_traceback = last_traceback
1579
1590
1580 if filename and etype is SyntaxError:
1591 if filename and etype is SyntaxError:
1581 # Work hard to stuff the correct filename in the exception
1592 # Work hard to stuff the correct filename in the exception
1582 try:
1593 try:
1583 msg, (dummy_filename, lineno, offset, line) = value
1594 msg, (dummy_filename, lineno, offset, line) = value
1584 except:
1595 except:
1585 # Not the format we expect; leave it alone
1596 # Not the format we expect; leave it alone
1586 pass
1597 pass
1587 else:
1598 else:
1588 # Stuff in the right filename
1599 # Stuff in the right filename
1589 try:
1600 try:
1590 # Assume SyntaxError is a class exception
1601 # Assume SyntaxError is a class exception
1591 value = SyntaxError(msg, (filename, lineno, offset, line))
1602 value = SyntaxError(msg, (filename, lineno, offset, line))
1592 except:
1603 except:
1593 # If that failed, assume SyntaxError is a string
1604 # If that failed, assume SyntaxError is a string
1594 value = msg, (filename, lineno, offset, line)
1605 value = msg, (filename, lineno, offset, line)
1595 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1606 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1596 self._showtraceback(etype, value, stb)
1607 self._showtraceback(etype, value, stb)
1597
1608
1598 #-------------------------------------------------------------------------
1609 #-------------------------------------------------------------------------
1599 # Things related to readline
1610 # Things related to readline
1600 #-------------------------------------------------------------------------
1611 #-------------------------------------------------------------------------
1601
1612
1602 def init_readline(self):
1613 def init_readline(self):
1603 """Command history completion/saving/reloading."""
1614 """Command history completion/saving/reloading."""
1604
1615
1605 if self.readline_use:
1616 if self.readline_use:
1606 import IPython.utils.rlineimpl as readline
1617 import IPython.utils.rlineimpl as readline
1607
1618
1608 self.rl_next_input = None
1619 self.rl_next_input = None
1609 self.rl_do_indent = False
1620 self.rl_do_indent = False
1610
1621
1611 if not self.readline_use or not readline.have_readline:
1622 if not self.readline_use or not readline.have_readline:
1612 self.has_readline = False
1623 self.has_readline = False
1613 self.readline = None
1624 self.readline = None
1614 # Set a number of methods that depend on readline to be no-op
1625 # Set a number of methods that depend on readline to be no-op
1615 self.set_readline_completer = no_op
1626 self.set_readline_completer = no_op
1616 self.set_custom_completer = no_op
1627 self.set_custom_completer = no_op
1617 self.set_completer_frame = no_op
1628 self.set_completer_frame = no_op
1618 warn('Readline services not available or not loaded.')
1629 warn('Readline services not available or not loaded.')
1619 else:
1630 else:
1620 self.has_readline = True
1631 self.has_readline = True
1621 self.readline = readline
1632 self.readline = readline
1622 sys.modules['readline'] = readline
1633 sys.modules['readline'] = readline
1623
1634
1624 # Platform-specific configuration
1635 # Platform-specific configuration
1625 if os.name == 'nt':
1636 if os.name == 'nt':
1626 # FIXME - check with Frederick to see if we can harmonize
1637 # FIXME - check with Frederick to see if we can harmonize
1627 # naming conventions with pyreadline to avoid this
1638 # naming conventions with pyreadline to avoid this
1628 # platform-dependent check
1639 # platform-dependent check
1629 self.readline_startup_hook = readline.set_pre_input_hook
1640 self.readline_startup_hook = readline.set_pre_input_hook
1630 else:
1641 else:
1631 self.readline_startup_hook = readline.set_startup_hook
1642 self.readline_startup_hook = readline.set_startup_hook
1632
1643
1633 # Load user's initrc file (readline config)
1644 # Load user's initrc file (readline config)
1634 # Or if libedit is used, load editrc.
1645 # Or if libedit is used, load editrc.
1635 inputrc_name = os.environ.get('INPUTRC')
1646 inputrc_name = os.environ.get('INPUTRC')
1636 if inputrc_name is None:
1647 if inputrc_name is None:
1637 home_dir = get_home_dir()
1648 home_dir = get_home_dir()
1638 if home_dir is not None:
1649 if home_dir is not None:
1639 inputrc_name = '.inputrc'
1650 inputrc_name = '.inputrc'
1640 if readline.uses_libedit:
1651 if readline.uses_libedit:
1641 inputrc_name = '.editrc'
1652 inputrc_name = '.editrc'
1642 inputrc_name = os.path.join(home_dir, inputrc_name)
1653 inputrc_name = os.path.join(home_dir, inputrc_name)
1643 if os.path.isfile(inputrc_name):
1654 if os.path.isfile(inputrc_name):
1644 try:
1655 try:
1645 readline.read_init_file(inputrc_name)
1656 readline.read_init_file(inputrc_name)
1646 except:
1657 except:
1647 warn('Problems reading readline initialization file <%s>'
1658 warn('Problems reading readline initialization file <%s>'
1648 % inputrc_name)
1659 % inputrc_name)
1649
1660
1650 # Configure readline according to user's prefs
1661 # Configure readline according to user's prefs
1651 # This is only done if GNU readline is being used. If libedit
1662 # This is only done if GNU readline is being used. If libedit
1652 # is being used (as on Leopard) the readline config is
1663 # is being used (as on Leopard) the readline config is
1653 # not run as the syntax for libedit is different.
1664 # not run as the syntax for libedit is different.
1654 if not readline.uses_libedit:
1665 if not readline.uses_libedit:
1655 for rlcommand in self.readline_parse_and_bind:
1666 for rlcommand in self.readline_parse_and_bind:
1656 #print "loading rl:",rlcommand # dbg
1667 #print "loading rl:",rlcommand # dbg
1657 readline.parse_and_bind(rlcommand)
1668 readline.parse_and_bind(rlcommand)
1658
1669
1659 # Remove some chars from the delimiters list. If we encounter
1670 # Remove some chars from the delimiters list. If we encounter
1660 # unicode chars, discard them.
1671 # unicode chars, discard them.
1661 delims = readline.get_completer_delims().encode("ascii", "ignore")
1672 delims = readline.get_completer_delims().encode("ascii", "ignore")
1662 delims = delims.translate(None, self.readline_remove_delims)
1673 delims = delims.translate(None, self.readline_remove_delims)
1663 delims = delims.replace(ESC_MAGIC, '')
1674 delims = delims.replace(ESC_MAGIC, '')
1664 readline.set_completer_delims(delims)
1675 readline.set_completer_delims(delims)
1665 # otherwise we end up with a monster history after a while:
1676 # otherwise we end up with a monster history after a while:
1666 readline.set_history_length(self.history_length)
1677 readline.set_history_length(self.history_length)
1667
1678
1668 self.refill_readline_hist()
1679 self.refill_readline_hist()
1669 self.readline_no_record = ReadlineNoRecord(self)
1680 self.readline_no_record = ReadlineNoRecord(self)
1670
1681
1671 # Configure auto-indent for all platforms
1682 # Configure auto-indent for all platforms
1672 self.set_autoindent(self.autoindent)
1683 self.set_autoindent(self.autoindent)
1673
1684
1674 def refill_readline_hist(self):
1685 def refill_readline_hist(self):
1675 # Load the last 1000 lines from history
1686 # Load the last 1000 lines from history
1676 self.readline.clear_history()
1687 self.readline.clear_history()
1677 stdin_encoding = sys.stdin.encoding or "utf-8"
1688 stdin_encoding = sys.stdin.encoding or "utf-8"
1678 for _, _, cell in self.history_manager.get_tail(1000,
1689 for _, _, cell in self.history_manager.get_tail(1000,
1679 include_latest=True):
1690 include_latest=True):
1680 if cell.strip(): # Ignore blank lines
1691 if cell.strip(): # Ignore blank lines
1681 for line in cell.splitlines():
1692 for line in cell.splitlines():
1682 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1693 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1683
1694
1684 def set_next_input(self, s):
1695 def set_next_input(self, s):
1685 """ Sets the 'default' input string for the next command line.
1696 """ Sets the 'default' input string for the next command line.
1686
1697
1687 Requires readline.
1698 Requires readline.
1688
1699
1689 Example:
1700 Example:
1690
1701
1691 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1702 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1692 [D:\ipython]|2> Hello Word_ # cursor is here
1703 [D:\ipython]|2> Hello Word_ # cursor is here
1693 """
1704 """
1694
1705
1695 self.rl_next_input = s
1706 self.rl_next_input = s
1696
1707
1697 # Maybe move this to the terminal subclass?
1708 # Maybe move this to the terminal subclass?
1698 def pre_readline(self):
1709 def pre_readline(self):
1699 """readline hook to be used at the start of each line.
1710 """readline hook to be used at the start of each line.
1700
1711
1701 Currently it handles auto-indent only."""
1712 Currently it handles auto-indent only."""
1702
1713
1703 if self.rl_do_indent:
1714 if self.rl_do_indent:
1704 self.readline.insert_text(self._indent_current_str())
1715 self.readline.insert_text(self._indent_current_str())
1705 if self.rl_next_input is not None:
1716 if self.rl_next_input is not None:
1706 self.readline.insert_text(self.rl_next_input)
1717 self.readline.insert_text(self.rl_next_input)
1707 self.rl_next_input = None
1718 self.rl_next_input = None
1708
1719
1709 def _indent_current_str(self):
1720 def _indent_current_str(self):
1710 """return the current level of indentation as a string"""
1721 """return the current level of indentation as a string"""
1711 return self.input_splitter.indent_spaces * ' '
1722 return self.input_splitter.indent_spaces * ' '
1712
1723
1713 #-------------------------------------------------------------------------
1724 #-------------------------------------------------------------------------
1714 # Things related to text completion
1725 # Things related to text completion
1715 #-------------------------------------------------------------------------
1726 #-------------------------------------------------------------------------
1716
1727
1717 def init_completer(self):
1728 def init_completer(self):
1718 """Initialize the completion machinery.
1729 """Initialize the completion machinery.
1719
1730
1720 This creates completion machinery that can be used by client code,
1731 This creates completion machinery that can be used by client code,
1721 either interactively in-process (typically triggered by the readline
1732 either interactively in-process (typically triggered by the readline
1722 library), programatically (such as in test suites) or out-of-prcess
1733 library), programatically (such as in test suites) or out-of-prcess
1723 (typically over the network by remote frontends).
1734 (typically over the network by remote frontends).
1724 """
1735 """
1725 from IPython.core.completer import IPCompleter
1736 from IPython.core.completer import IPCompleter
1726 from IPython.core.completerlib import (module_completer,
1737 from IPython.core.completerlib import (module_completer,
1727 magic_run_completer, cd_completer)
1738 magic_run_completer, cd_completer)
1728
1739
1729 self.Completer = IPCompleter(self,
1740 self.Completer = IPCompleter(self,
1730 self.user_ns,
1741 self.user_ns,
1731 self.user_global_ns,
1742 self.user_global_ns,
1732 self.readline_omit__names,
1743 self.readline_omit__names,
1733 self.alias_manager.alias_table,
1744 self.alias_manager.alias_table,
1734 self.has_readline)
1745 self.has_readline)
1735
1746
1736 # Add custom completers to the basic ones built into IPCompleter
1747 # Add custom completers to the basic ones built into IPCompleter
1737 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1748 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1738 self.strdispatchers['complete_command'] = sdisp
1749 self.strdispatchers['complete_command'] = sdisp
1739 self.Completer.custom_completers = sdisp
1750 self.Completer.custom_completers = sdisp
1740
1751
1741 self.set_hook('complete_command', module_completer, str_key = 'import')
1752 self.set_hook('complete_command', module_completer, str_key = 'import')
1742 self.set_hook('complete_command', module_completer, str_key = 'from')
1753 self.set_hook('complete_command', module_completer, str_key = 'from')
1743 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1754 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1744 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1755 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1745
1756
1746 # Only configure readline if we truly are using readline. IPython can
1757 # Only configure readline if we truly are using readline. IPython can
1747 # do tab-completion over the network, in GUIs, etc, where readline
1758 # do tab-completion over the network, in GUIs, etc, where readline
1748 # itself may be absent
1759 # itself may be absent
1749 if self.has_readline:
1760 if self.has_readline:
1750 self.set_readline_completer()
1761 self.set_readline_completer()
1751
1762
1752 def complete(self, text, line=None, cursor_pos=None):
1763 def complete(self, text, line=None, cursor_pos=None):
1753 """Return the completed text and a list of completions.
1764 """Return the completed text and a list of completions.
1754
1765
1755 Parameters
1766 Parameters
1756 ----------
1767 ----------
1757
1768
1758 text : string
1769 text : string
1759 A string of text to be completed on. It can be given as empty and
1770 A string of text to be completed on. It can be given as empty and
1760 instead a line/position pair are given. In this case, the
1771 instead a line/position pair are given. In this case, the
1761 completer itself will split the line like readline does.
1772 completer itself will split the line like readline does.
1762
1773
1763 line : string, optional
1774 line : string, optional
1764 The complete line that text is part of.
1775 The complete line that text is part of.
1765
1776
1766 cursor_pos : int, optional
1777 cursor_pos : int, optional
1767 The position of the cursor on the input line.
1778 The position of the cursor on the input line.
1768
1779
1769 Returns
1780 Returns
1770 -------
1781 -------
1771 text : string
1782 text : string
1772 The actual text that was completed.
1783 The actual text that was completed.
1773
1784
1774 matches : list
1785 matches : list
1775 A sorted list with all possible completions.
1786 A sorted list with all possible completions.
1776
1787
1777 The optional arguments allow the completion to take more context into
1788 The optional arguments allow the completion to take more context into
1778 account, and are part of the low-level completion API.
1789 account, and are part of the low-level completion API.
1779
1790
1780 This is a wrapper around the completion mechanism, similar to what
1791 This is a wrapper around the completion mechanism, similar to what
1781 readline does at the command line when the TAB key is hit. By
1792 readline does at the command line when the TAB key is hit. By
1782 exposing it as a method, it can be used by other non-readline
1793 exposing it as a method, it can be used by other non-readline
1783 environments (such as GUIs) for text completion.
1794 environments (such as GUIs) for text completion.
1784
1795
1785 Simple usage example:
1796 Simple usage example:
1786
1797
1787 In [1]: x = 'hello'
1798 In [1]: x = 'hello'
1788
1799
1789 In [2]: _ip.complete('x.l')
1800 In [2]: _ip.complete('x.l')
1790 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1801 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1791 """
1802 """
1792
1803
1793 # Inject names into __builtin__ so we can complete on the added names.
1804 # Inject names into __builtin__ so we can complete on the added names.
1794 with self.builtin_trap:
1805 with self.builtin_trap:
1795 return self.Completer.complete(text, line, cursor_pos)
1806 return self.Completer.complete(text, line, cursor_pos)
1796
1807
1797 def set_custom_completer(self, completer, pos=0):
1808 def set_custom_completer(self, completer, pos=0):
1798 """Adds a new custom completer function.
1809 """Adds a new custom completer function.
1799
1810
1800 The position argument (defaults to 0) is the index in the completers
1811 The position argument (defaults to 0) is the index in the completers
1801 list where you want the completer to be inserted."""
1812 list where you want the completer to be inserted."""
1802
1813
1803 newcomp = types.MethodType(completer,self.Completer)
1814 newcomp = types.MethodType(completer,self.Completer)
1804 self.Completer.matchers.insert(pos,newcomp)
1815 self.Completer.matchers.insert(pos,newcomp)
1805
1816
1806 def set_readline_completer(self):
1817 def set_readline_completer(self):
1807 """Reset readline's completer to be our own."""
1818 """Reset readline's completer to be our own."""
1808 self.readline.set_completer(self.Completer.rlcomplete)
1819 self.readline.set_completer(self.Completer.rlcomplete)
1809
1820
1810 def set_completer_frame(self, frame=None):
1821 def set_completer_frame(self, frame=None):
1811 """Set the frame of the completer."""
1822 """Set the frame of the completer."""
1812 if frame:
1823 if frame:
1813 self.Completer.namespace = frame.f_locals
1824 self.Completer.namespace = frame.f_locals
1814 self.Completer.global_namespace = frame.f_globals
1825 self.Completer.global_namespace = frame.f_globals
1815 else:
1826 else:
1816 self.Completer.namespace = self.user_ns
1827 self.Completer.namespace = self.user_ns
1817 self.Completer.global_namespace = self.user_global_ns
1828 self.Completer.global_namespace = self.user_global_ns
1818
1829
1819 #-------------------------------------------------------------------------
1830 #-------------------------------------------------------------------------
1820 # Things related to magics
1831 # Things related to magics
1821 #-------------------------------------------------------------------------
1832 #-------------------------------------------------------------------------
1822
1833
1823 def init_magics(self):
1834 def init_magics(self):
1824 # FIXME: Move the color initialization to the DisplayHook, which
1835 # FIXME: Move the color initialization to the DisplayHook, which
1825 # should be split into a prompt manager and displayhook. We probably
1836 # should be split into a prompt manager and displayhook. We probably
1826 # even need a centralize colors management object.
1837 # even need a centralize colors management object.
1827 self.magic_colors(self.colors)
1838 self.magic_colors(self.colors)
1828 # History was moved to a separate module
1839 # History was moved to a separate module
1829 from . import history
1840 from . import history
1830 history.init_ipython(self)
1841 history.init_ipython(self)
1831
1842
1832 def magic(self,arg_s):
1843 def magic(self,arg_s):
1833 """Call a magic function by name.
1844 """Call a magic function by name.
1834
1845
1835 Input: a string containing the name of the magic function to call and
1846 Input: a string containing the name of the magic function to call and
1836 any additional arguments to be passed to the magic.
1847 any additional arguments to be passed to the magic.
1837
1848
1838 magic('name -opt foo bar') is equivalent to typing at the ipython
1849 magic('name -opt foo bar') is equivalent to typing at the ipython
1839 prompt:
1850 prompt:
1840
1851
1841 In[1]: %name -opt foo bar
1852 In[1]: %name -opt foo bar
1842
1853
1843 To call a magic without arguments, simply use magic('name').
1854 To call a magic without arguments, simply use magic('name').
1844
1855
1845 This provides a proper Python function to call IPython's magics in any
1856 This provides a proper Python function to call IPython's magics in any
1846 valid Python code you can type at the interpreter, including loops and
1857 valid Python code you can type at the interpreter, including loops and
1847 compound statements.
1858 compound statements.
1848 """
1859 """
1849 args = arg_s.split(' ',1)
1860 args = arg_s.split(' ',1)
1850 magic_name = args[0]
1861 magic_name = args[0]
1851 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1862 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1852
1863
1853 try:
1864 try:
1854 magic_args = args[1]
1865 magic_args = args[1]
1855 except IndexError:
1866 except IndexError:
1856 magic_args = ''
1867 magic_args = ''
1857 fn = getattr(self,'magic_'+magic_name,None)
1868 fn = getattr(self,'magic_'+magic_name,None)
1858 if fn is None:
1869 if fn is None:
1859 error("Magic function `%s` not found." % magic_name)
1870 error("Magic function `%s` not found." % magic_name)
1860 else:
1871 else:
1861 magic_args = self.var_expand(magic_args,1)
1872 magic_args = self.var_expand(magic_args,1)
1862 # Grab local namespace if we need it:
1873 # Grab local namespace if we need it:
1863 if getattr(fn, "needs_local_scope", False):
1874 if getattr(fn, "needs_local_scope", False):
1864 self._magic_locals = sys._getframe(1).f_locals
1875 self._magic_locals = sys._getframe(1).f_locals
1865 with self.builtin_trap:
1876 with self.builtin_trap:
1866 result = fn(magic_args)
1877 result = fn(magic_args)
1867 # Ensure we're not keeping object references around:
1878 # Ensure we're not keeping object references around:
1868 self._magic_locals = {}
1879 self._magic_locals = {}
1869 return result
1880 return result
1870
1881
1871 def define_magic(self, magicname, func):
1882 def define_magic(self, magicname, func):
1872 """Expose own function as magic function for ipython
1883 """Expose own function as magic function for ipython
1873
1884
1874 def foo_impl(self,parameter_s=''):
1885 def foo_impl(self,parameter_s=''):
1875 'My very own magic!. (Use docstrings, IPython reads them).'
1886 'My very own magic!. (Use docstrings, IPython reads them).'
1876 print 'Magic function. Passed parameter is between < >:'
1887 print 'Magic function. Passed parameter is between < >:'
1877 print '<%s>' % parameter_s
1888 print '<%s>' % parameter_s
1878 print 'The self object is:',self
1889 print 'The self object is:',self
1879
1890
1880 self.define_magic('foo',foo_impl)
1891 self.define_magic('foo',foo_impl)
1881 """
1892 """
1882
1893
1883 import new
1894 import new
1884 im = types.MethodType(func,self)
1895 im = types.MethodType(func,self)
1885 old = getattr(self, "magic_" + magicname, None)
1896 old = getattr(self, "magic_" + magicname, None)
1886 setattr(self, "magic_" + magicname, im)
1897 setattr(self, "magic_" + magicname, im)
1887 return old
1898 return old
1888
1899
1889 #-------------------------------------------------------------------------
1900 #-------------------------------------------------------------------------
1890 # Things related to macros
1901 # Things related to macros
1891 #-------------------------------------------------------------------------
1902 #-------------------------------------------------------------------------
1892
1903
1893 def define_macro(self, name, themacro):
1904 def define_macro(self, name, themacro):
1894 """Define a new macro
1905 """Define a new macro
1895
1906
1896 Parameters
1907 Parameters
1897 ----------
1908 ----------
1898 name : str
1909 name : str
1899 The name of the macro.
1910 The name of the macro.
1900 themacro : str or Macro
1911 themacro : str or Macro
1901 The action to do upon invoking the macro. If a string, a new
1912 The action to do upon invoking the macro. If a string, a new
1902 Macro object is created by passing the string to it.
1913 Macro object is created by passing the string to it.
1903 """
1914 """
1904
1915
1905 from IPython.core import macro
1916 from IPython.core import macro
1906
1917
1907 if isinstance(themacro, basestring):
1918 if isinstance(themacro, basestring):
1908 themacro = macro.Macro(themacro)
1919 themacro = macro.Macro(themacro)
1909 if not isinstance(themacro, macro.Macro):
1920 if not isinstance(themacro, macro.Macro):
1910 raise ValueError('A macro must be a string or a Macro instance.')
1921 raise ValueError('A macro must be a string or a Macro instance.')
1911 self.user_ns[name] = themacro
1922 self.user_ns[name] = themacro
1912
1923
1913 #-------------------------------------------------------------------------
1924 #-------------------------------------------------------------------------
1914 # Things related to the running of system commands
1925 # Things related to the running of system commands
1915 #-------------------------------------------------------------------------
1926 #-------------------------------------------------------------------------
1916
1927
1917 def system_piped(self, cmd):
1928 def system_piped(self, cmd):
1918 """Call the given cmd in a subprocess, piping stdout/err
1929 """Call the given cmd in a subprocess, piping stdout/err
1919
1930
1920 Parameters
1931 Parameters
1921 ----------
1932 ----------
1922 cmd : str
1933 cmd : str
1923 Command to execute (can not end in '&', as background processes are
1934 Command to execute (can not end in '&', as background processes are
1924 not supported. Should not be a command that expects input
1935 not supported. Should not be a command that expects input
1925 other than simple text.
1936 other than simple text.
1926 """
1937 """
1927 if cmd.rstrip().endswith('&'):
1938 if cmd.rstrip().endswith('&'):
1928 # this is *far* from a rigorous test
1939 # this is *far* from a rigorous test
1929 # We do not support backgrounding processes because we either use
1940 # We do not support backgrounding processes because we either use
1930 # pexpect or pipes to read from. Users can always just call
1941 # pexpect or pipes to read from. Users can always just call
1931 # os.system() or use ip.system=ip.system_raw
1942 # os.system() or use ip.system=ip.system_raw
1932 # if they really want a background process.
1943 # if they really want a background process.
1933 raise OSError("Background processes not supported.")
1944 raise OSError("Background processes not supported.")
1934
1945
1935 # we explicitly do NOT return the subprocess status code, because
1946 # we explicitly do NOT return the subprocess status code, because
1936 # a non-None value would trigger :func:`sys.displayhook` calls.
1947 # a non-None value would trigger :func:`sys.displayhook` calls.
1937 # Instead, we store the exit_code in user_ns.
1948 # Instead, we store the exit_code in user_ns.
1938 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1949 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1939
1950
1940 def system_raw(self, cmd):
1951 def system_raw(self, cmd):
1941 """Call the given cmd in a subprocess using os.system
1952 """Call the given cmd in a subprocess using os.system
1942
1953
1943 Parameters
1954 Parameters
1944 ----------
1955 ----------
1945 cmd : str
1956 cmd : str
1946 Command to execute.
1957 Command to execute.
1947 """
1958 """
1948 # We explicitly do NOT return the subprocess status code, because
1959 # We explicitly do NOT return the subprocess status code, because
1949 # a non-None value would trigger :func:`sys.displayhook` calls.
1960 # a non-None value would trigger :func:`sys.displayhook` calls.
1950 # Instead, we store the exit_code in user_ns.
1961 # Instead, we store the exit_code in user_ns.
1951 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1962 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1952
1963
1953 # use piped system by default, because it is better behaved
1964 # use piped system by default, because it is better behaved
1954 system = system_piped
1965 system = system_piped
1955
1966
1956 def getoutput(self, cmd, split=True):
1967 def getoutput(self, cmd, split=True):
1957 """Get output (possibly including stderr) from a subprocess.
1968 """Get output (possibly including stderr) from a subprocess.
1958
1969
1959 Parameters
1970 Parameters
1960 ----------
1971 ----------
1961 cmd : str
1972 cmd : str
1962 Command to execute (can not end in '&', as background processes are
1973 Command to execute (can not end in '&', as background processes are
1963 not supported.
1974 not supported.
1964 split : bool, optional
1975 split : bool, optional
1965
1976
1966 If True, split the output into an IPython SList. Otherwise, an
1977 If True, split the output into an IPython SList. Otherwise, an
1967 IPython LSString is returned. These are objects similar to normal
1978 IPython LSString is returned. These are objects similar to normal
1968 lists and strings, with a few convenience attributes for easier
1979 lists and strings, with a few convenience attributes for easier
1969 manipulation of line-based output. You can use '?' on them for
1980 manipulation of line-based output. You can use '?' on them for
1970 details.
1981 details.
1971 """
1982 """
1972 if cmd.rstrip().endswith('&'):
1983 if cmd.rstrip().endswith('&'):
1973 # this is *far* from a rigorous test
1984 # this is *far* from a rigorous test
1974 raise OSError("Background processes not supported.")
1985 raise OSError("Background processes not supported.")
1975 out = getoutput(self.var_expand(cmd, depth=2))
1986 out = getoutput(self.var_expand(cmd, depth=2))
1976 if split:
1987 if split:
1977 out = SList(out.splitlines())
1988 out = SList(out.splitlines())
1978 else:
1989 else:
1979 out = LSString(out)
1990 out = LSString(out)
1980 return out
1991 return out
1981
1992
1982 #-------------------------------------------------------------------------
1993 #-------------------------------------------------------------------------
1983 # Things related to aliases
1994 # Things related to aliases
1984 #-------------------------------------------------------------------------
1995 #-------------------------------------------------------------------------
1985
1996
1986 def init_alias(self):
1997 def init_alias(self):
1987 self.alias_manager = AliasManager(shell=self, config=self.config)
1998 self.alias_manager = AliasManager(shell=self, config=self.config)
1988 self.ns_table['alias'] = self.alias_manager.alias_table,
1999 self.ns_table['alias'] = self.alias_manager.alias_table,
1989
2000
1990 #-------------------------------------------------------------------------
2001 #-------------------------------------------------------------------------
1991 # Things related to extensions and plugins
2002 # Things related to extensions and plugins
1992 #-------------------------------------------------------------------------
2003 #-------------------------------------------------------------------------
1993
2004
1994 def init_extension_manager(self):
2005 def init_extension_manager(self):
1995 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2006 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1996
2007
1997 def init_plugin_manager(self):
2008 def init_plugin_manager(self):
1998 self.plugin_manager = PluginManager(config=self.config)
2009 self.plugin_manager = PluginManager(config=self.config)
1999
2010
2000 #-------------------------------------------------------------------------
2011 #-------------------------------------------------------------------------
2001 # Things related to payloads
2012 # Things related to payloads
2002 #-------------------------------------------------------------------------
2013 #-------------------------------------------------------------------------
2003
2014
2004 def init_payload(self):
2015 def init_payload(self):
2005 self.payload_manager = PayloadManager(config=self.config)
2016 self.payload_manager = PayloadManager(config=self.config)
2006
2017
2007 #-------------------------------------------------------------------------
2018 #-------------------------------------------------------------------------
2008 # Things related to the prefilter
2019 # Things related to the prefilter
2009 #-------------------------------------------------------------------------
2020 #-------------------------------------------------------------------------
2010
2021
2011 def init_prefilter(self):
2022 def init_prefilter(self):
2012 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2023 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2013 # Ultimately this will be refactored in the new interpreter code, but
2024 # Ultimately this will be refactored in the new interpreter code, but
2014 # for now, we should expose the main prefilter method (there's legacy
2025 # for now, we should expose the main prefilter method (there's legacy
2015 # code out there that may rely on this).
2026 # code out there that may rely on this).
2016 self.prefilter = self.prefilter_manager.prefilter_lines
2027 self.prefilter = self.prefilter_manager.prefilter_lines
2017
2028
2018 def auto_rewrite_input(self, cmd):
2029 def auto_rewrite_input(self, cmd):
2019 """Print to the screen the rewritten form of the user's command.
2030 """Print to the screen the rewritten form of the user's command.
2020
2031
2021 This shows visual feedback by rewriting input lines that cause
2032 This shows visual feedback by rewriting input lines that cause
2022 automatic calling to kick in, like::
2033 automatic calling to kick in, like::
2023
2034
2024 /f x
2035 /f x
2025
2036
2026 into::
2037 into::
2027
2038
2028 ------> f(x)
2039 ------> f(x)
2029
2040
2030 after the user's input prompt. This helps the user understand that the
2041 after the user's input prompt. This helps the user understand that the
2031 input line was transformed automatically by IPython.
2042 input line was transformed automatically by IPython.
2032 """
2043 """
2033 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2044 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2034
2045
2035 try:
2046 try:
2036 # plain ascii works better w/ pyreadline, on some machines, so
2047 # plain ascii works better w/ pyreadline, on some machines, so
2037 # we use it and only print uncolored rewrite if we have unicode
2048 # we use it and only print uncolored rewrite if we have unicode
2038 rw = str(rw)
2049 rw = str(rw)
2039 print >> io.stdout, rw
2050 print >> io.stdout, rw
2040 except UnicodeEncodeError:
2051 except UnicodeEncodeError:
2041 print "------> " + cmd
2052 print "------> " + cmd
2042
2053
2043 #-------------------------------------------------------------------------
2054 #-------------------------------------------------------------------------
2044 # Things related to extracting values/expressions from kernel and user_ns
2055 # Things related to extracting values/expressions from kernel and user_ns
2045 #-------------------------------------------------------------------------
2056 #-------------------------------------------------------------------------
2046
2057
2047 def _simple_error(self):
2058 def _simple_error(self):
2048 etype, value = sys.exc_info()[:2]
2059 etype, value = sys.exc_info()[:2]
2049 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2060 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2050
2061
2051 def user_variables(self, names):
2062 def user_variables(self, names):
2052 """Get a list of variable names from the user's namespace.
2063 """Get a list of variable names from the user's namespace.
2053
2064
2054 Parameters
2065 Parameters
2055 ----------
2066 ----------
2056 names : list of strings
2067 names : list of strings
2057 A list of names of variables to be read from the user namespace.
2068 A list of names of variables to be read from the user namespace.
2058
2069
2059 Returns
2070 Returns
2060 -------
2071 -------
2061 A dict, keyed by the input names and with the repr() of each value.
2072 A dict, keyed by the input names and with the repr() of each value.
2062 """
2073 """
2063 out = {}
2074 out = {}
2064 user_ns = self.user_ns
2075 user_ns = self.user_ns
2065 for varname in names:
2076 for varname in names:
2066 try:
2077 try:
2067 value = repr(user_ns[varname])
2078 value = repr(user_ns[varname])
2068 except:
2079 except:
2069 value = self._simple_error()
2080 value = self._simple_error()
2070 out[varname] = value
2081 out[varname] = value
2071 return out
2082 return out
2072
2083
2073 def user_expressions(self, expressions):
2084 def user_expressions(self, expressions):
2074 """Evaluate a dict of expressions in the user's namespace.
2085 """Evaluate a dict of expressions in the user's namespace.
2075
2086
2076 Parameters
2087 Parameters
2077 ----------
2088 ----------
2078 expressions : dict
2089 expressions : dict
2079 A dict with string keys and string values. The expression values
2090 A dict with string keys and string values. The expression values
2080 should be valid Python expressions, each of which will be evaluated
2091 should be valid Python expressions, each of which will be evaluated
2081 in the user namespace.
2092 in the user namespace.
2082
2093
2083 Returns
2094 Returns
2084 -------
2095 -------
2085 A dict, keyed like the input expressions dict, with the repr() of each
2096 A dict, keyed like the input expressions dict, with the repr() of each
2086 value.
2097 value.
2087 """
2098 """
2088 out = {}
2099 out = {}
2089 user_ns = self.user_ns
2100 user_ns = self.user_ns
2090 global_ns = self.user_global_ns
2101 global_ns = self.user_global_ns
2091 for key, expr in expressions.iteritems():
2102 for key, expr in expressions.iteritems():
2092 try:
2103 try:
2093 value = repr(eval(expr, global_ns, user_ns))
2104 value = repr(eval(expr, global_ns, user_ns))
2094 except:
2105 except:
2095 value = self._simple_error()
2106 value = self._simple_error()
2096 out[key] = value
2107 out[key] = value
2097 return out
2108 return out
2098
2109
2099 #-------------------------------------------------------------------------
2110 #-------------------------------------------------------------------------
2100 # Things related to the running of code
2111 # Things related to the running of code
2101 #-------------------------------------------------------------------------
2112 #-------------------------------------------------------------------------
2102
2113
2103 def ex(self, cmd):
2114 def ex(self, cmd):
2104 """Execute a normal python statement in user namespace."""
2115 """Execute a normal python statement in user namespace."""
2105 with self.builtin_trap:
2116 with self.builtin_trap:
2106 exec cmd in self.user_global_ns, self.user_ns
2117 exec cmd in self.user_global_ns, self.user_ns
2107
2118
2108 def ev(self, expr):
2119 def ev(self, expr):
2109 """Evaluate python expression expr in user namespace.
2120 """Evaluate python expression expr in user namespace.
2110
2121
2111 Returns the result of evaluation
2122 Returns the result of evaluation
2112 """
2123 """
2113 with self.builtin_trap:
2124 with self.builtin_trap:
2114 return eval(expr, self.user_global_ns, self.user_ns)
2125 return eval(expr, self.user_global_ns, self.user_ns)
2115
2126
2116 def safe_execfile(self, fname, *where, **kw):
2127 def safe_execfile(self, fname, *where, **kw):
2117 """A safe version of the builtin execfile().
2128 """A safe version of the builtin execfile().
2118
2129
2119 This version will never throw an exception, but instead print
2130 This version will never throw an exception, but instead print
2120 helpful error messages to the screen. This only works on pure
2131 helpful error messages to the screen. This only works on pure
2121 Python files with the .py extension.
2132 Python files with the .py extension.
2122
2133
2123 Parameters
2134 Parameters
2124 ----------
2135 ----------
2125 fname : string
2136 fname : string
2126 The name of the file to be executed.
2137 The name of the file to be executed.
2127 where : tuple
2138 where : tuple
2128 One or two namespaces, passed to execfile() as (globals,locals).
2139 One or two namespaces, passed to execfile() as (globals,locals).
2129 If only one is given, it is passed as both.
2140 If only one is given, it is passed as both.
2130 exit_ignore : bool (False)
2141 exit_ignore : bool (False)
2131 If True, then silence SystemExit for non-zero status (it is always
2142 If True, then silence SystemExit for non-zero status (it is always
2132 silenced for zero status, as it is so common).
2143 silenced for zero status, as it is so common).
2133 """
2144 """
2134 kw.setdefault('exit_ignore', False)
2145 kw.setdefault('exit_ignore', False)
2135
2146
2136 fname = os.path.abspath(os.path.expanduser(fname))
2147 fname = os.path.abspath(os.path.expanduser(fname))
2137 # Make sure we have a .py file
2148 # Make sure we have a .py file
2138 if not fname.endswith('.py'):
2149 if not fname.endswith('.py'):
2139 warn('File must end with .py to be run using execfile: <%s>' % fname)
2150 warn('File must end with .py to be run using execfile: <%s>' % fname)
2140
2151
2141 # Make sure we can open the file
2152 # Make sure we can open the file
2142 try:
2153 try:
2143 with open(fname) as thefile:
2154 with open(fname) as thefile:
2144 pass
2155 pass
2145 except:
2156 except:
2146 warn('Could not open file <%s> for safe execution.' % fname)
2157 warn('Could not open file <%s> for safe execution.' % fname)
2147 return
2158 return
2148
2159
2149 # Find things also in current directory. This is needed to mimic the
2160 # Find things also in current directory. This is needed to mimic the
2150 # behavior of running a script from the system command line, where
2161 # behavior of running a script from the system command line, where
2151 # Python inserts the script's directory into sys.path
2162 # Python inserts the script's directory into sys.path
2152 dname = os.path.dirname(fname)
2163 dname = os.path.dirname(fname)
2153
2164
2154 if isinstance(fname, unicode):
2165 if isinstance(fname, unicode):
2155 # execfile uses default encoding instead of filesystem encoding
2166 # execfile uses default encoding instead of filesystem encoding
2156 # so unicode filenames will fail
2167 # so unicode filenames will fail
2157 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2168 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2158
2169
2159 with prepended_to_syspath(dname):
2170 with prepended_to_syspath(dname):
2160 try:
2171 try:
2161 execfile(fname,*where)
2172 execfile(fname,*where)
2162 except SystemExit, status:
2173 except SystemExit, status:
2163 # If the call was made with 0 or None exit status (sys.exit(0)
2174 # If the call was made with 0 or None exit status (sys.exit(0)
2164 # or sys.exit() ), don't bother showing a traceback, as both of
2175 # or sys.exit() ), don't bother showing a traceback, as both of
2165 # these are considered normal by the OS:
2176 # these are considered normal by the OS:
2166 # > python -c'import sys;sys.exit(0)'; echo $?
2177 # > python -c'import sys;sys.exit(0)'; echo $?
2167 # 0
2178 # 0
2168 # > python -c'import sys;sys.exit()'; echo $?
2179 # > python -c'import sys;sys.exit()'; echo $?
2169 # 0
2180 # 0
2170 # For other exit status, we show the exception unless
2181 # For other exit status, we show the exception unless
2171 # explicitly silenced, but only in short form.
2182 # explicitly silenced, but only in short form.
2172 if status.code not in (0, None) and not kw['exit_ignore']:
2183 if status.code not in (0, None) and not kw['exit_ignore']:
2173 self.showtraceback(exception_only=True)
2184 self.showtraceback(exception_only=True)
2174 except:
2185 except:
2175 self.showtraceback()
2186 self.showtraceback()
2176
2187
2177 def safe_execfile_ipy(self, fname):
2188 def safe_execfile_ipy(self, fname):
2178 """Like safe_execfile, but for .ipy files with IPython syntax.
2189 """Like safe_execfile, but for .ipy files with IPython syntax.
2179
2190
2180 Parameters
2191 Parameters
2181 ----------
2192 ----------
2182 fname : str
2193 fname : str
2183 The name of the file to execute. The filename must have a
2194 The name of the file to execute. The filename must have a
2184 .ipy extension.
2195 .ipy extension.
2185 """
2196 """
2186 fname = os.path.abspath(os.path.expanduser(fname))
2197 fname = os.path.abspath(os.path.expanduser(fname))
2187
2198
2188 # Make sure we have a .py file
2199 # Make sure we have a .py file
2189 if not fname.endswith('.ipy'):
2200 if not fname.endswith('.ipy'):
2190 warn('File must end with .py to be run using execfile: <%s>' % fname)
2201 warn('File must end with .py to be run using execfile: <%s>' % fname)
2191
2202
2192 # Make sure we can open the file
2203 # Make sure we can open the file
2193 try:
2204 try:
2194 with open(fname) as thefile:
2205 with open(fname) as thefile:
2195 pass
2206 pass
2196 except:
2207 except:
2197 warn('Could not open file <%s> for safe execution.' % fname)
2208 warn('Could not open file <%s> for safe execution.' % fname)
2198 return
2209 return
2199
2210
2200 # Find things also in current directory. This is needed to mimic the
2211 # Find things also in current directory. This is needed to mimic the
2201 # behavior of running a script from the system command line, where
2212 # behavior of running a script from the system command line, where
2202 # Python inserts the script's directory into sys.path
2213 # Python inserts the script's directory into sys.path
2203 dname = os.path.dirname(fname)
2214 dname = os.path.dirname(fname)
2204
2215
2205 with prepended_to_syspath(dname):
2216 with prepended_to_syspath(dname):
2206 try:
2217 try:
2207 with open(fname) as thefile:
2218 with open(fname) as thefile:
2208 # self.run_cell currently captures all exceptions
2219 # self.run_cell currently captures all exceptions
2209 # raised in user code. It would be nice if there were
2220 # raised in user code. It would be nice if there were
2210 # versions of runlines, execfile that did raise, so
2221 # versions of runlines, execfile that did raise, so
2211 # we could catch the errors.
2222 # we could catch the errors.
2212 self.run_cell(thefile.read(), store_history=False)
2223 self.run_cell(thefile.read(), store_history=False)
2213 except:
2224 except:
2214 self.showtraceback()
2225 self.showtraceback()
2215 warn('Unknown failure executing file: <%s>' % fname)
2226 warn('Unknown failure executing file: <%s>' % fname)
2216
2227
2217 def run_cell(self, raw_cell, store_history=True):
2228 def run_cell(self, raw_cell, store_history=True):
2218 """Run a complete IPython cell.
2229 """Run a complete IPython cell.
2219
2230
2220 Parameters
2231 Parameters
2221 ----------
2232 ----------
2222 raw_cell : str
2233 raw_cell : str
2223 The code (including IPython code such as %magic functions) to run.
2234 The code (including IPython code such as %magic functions) to run.
2224 store_history : bool
2235 store_history : bool
2225 If True, the raw and translated cell will be stored in IPython's
2236 If True, the raw and translated cell will be stored in IPython's
2226 history. For user code calling back into IPython's machinery, this
2237 history. For user code calling back into IPython's machinery, this
2227 should be set to False.
2238 should be set to False.
2228 """
2239 """
2229 if (not raw_cell) or raw_cell.isspace():
2240 if (not raw_cell) or raw_cell.isspace():
2230 return
2241 return
2231
2242
2232 for line in raw_cell.splitlines():
2243 for line in raw_cell.splitlines():
2233 self.input_splitter.push(line)
2244 self.input_splitter.push(line)
2234 cell = self.input_splitter.source_reset()
2245 cell = self.input_splitter.source_reset()
2235
2246
2236 with self.builtin_trap:
2247 with self.builtin_trap:
2237 prefilter_failed = False
2248 prefilter_failed = False
2238 if len(cell.splitlines()) == 1:
2249 if len(cell.splitlines()) == 1:
2239 try:
2250 try:
2240 # use prefilter_lines to handle trailing newlines
2251 # use prefilter_lines to handle trailing newlines
2241 # restore trailing newline for ast.parse
2252 # restore trailing newline for ast.parse
2242 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2253 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2243 except AliasError as e:
2254 except AliasError as e:
2244 error(e)
2255 error(e)
2245 prefilter_failed=True
2256 prefilter_failed=True
2246 except Exception:
2257 except Exception:
2247 # don't allow prefilter errors to crash IPython
2258 # don't allow prefilter errors to crash IPython
2248 self.showtraceback()
2259 self.showtraceback()
2249 prefilter_failed = True
2260 prefilter_failed = True
2250
2261
2251 # Store raw and processed history
2262 # Store raw and processed history
2252 if store_history:
2263 if store_history:
2253 self.history_manager.store_inputs(self.execution_count,
2264 self.history_manager.store_inputs(self.execution_count,
2254 cell, raw_cell)
2265 cell, raw_cell)
2255
2266
2256 self.logger.log(cell, raw_cell)
2267 self.logger.log(cell, raw_cell)
2257
2268
2258 if not prefilter_failed:
2269 if not prefilter_failed:
2259 # don't run if prefilter failed
2270 # don't run if prefilter failed
2260 cell_name = self.compile.cache(cell, self.execution_count)
2271 cell_name = self.compile.cache(cell, self.execution_count)
2261
2272
2262 with self.display_trap:
2273 with self.display_trap:
2263 try:
2274 try:
2264 code_ast = ast.parse(cell, filename=cell_name)
2275 code_ast = ast.parse(cell, filename=cell_name)
2265 except (OverflowError, SyntaxError, ValueError, TypeError,
2276 except (OverflowError, SyntaxError, ValueError, TypeError,
2266 MemoryError):
2277 MemoryError):
2267 self.showsyntaxerror()
2278 self.showsyntaxerror()
2268 self.execution_count += 1
2279 self.execution_count += 1
2269 return None
2280 return None
2270
2281
2271 self.run_ast_nodes(code_ast.body, cell_name,
2282 self.run_ast_nodes(code_ast.body, cell_name,
2272 interactivity="last_expr")
2283 interactivity="last_expr")
2273
2284
2274 # Execute any registered post-execution functions.
2285 # Execute any registered post-execution functions.
2275 for func, status in self._post_execute.iteritems():
2286 for func, status in self._post_execute.iteritems():
2276 if not status:
2287 if not status:
2277 continue
2288 continue
2278 try:
2289 try:
2279 func()
2290 func()
2280 except:
2291 except:
2281 self.showtraceback()
2292 self.showtraceback()
2282 # Deactivate failing function
2293 # Deactivate failing function
2283 self._post_execute[func] = False
2294 self._post_execute[func] = False
2284
2295
2285 if store_history:
2296 if store_history:
2286 # Write output to the database. Does nothing unless
2297 # Write output to the database. Does nothing unless
2287 # history output logging is enabled.
2298 # history output logging is enabled.
2288 self.history_manager.store_output(self.execution_count)
2299 self.history_manager.store_output(self.execution_count)
2289 # Each cell is a *single* input, regardless of how many lines it has
2300 # Each cell is a *single* input, regardless of how many lines it has
2290 self.execution_count += 1
2301 self.execution_count += 1
2291
2302
2292 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2303 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2293 """Run a sequence of AST nodes. The execution mode depends on the
2304 """Run a sequence of AST nodes. The execution mode depends on the
2294 interactivity parameter.
2305 interactivity parameter.
2295
2306
2296 Parameters
2307 Parameters
2297 ----------
2308 ----------
2298 nodelist : list
2309 nodelist : list
2299 A sequence of AST nodes to run.
2310 A sequence of AST nodes to run.
2300 cell_name : str
2311 cell_name : str
2301 Will be passed to the compiler as the filename of the cell. Typically
2312 Will be passed to the compiler as the filename of the cell. Typically
2302 the value returned by ip.compile.cache(cell).
2313 the value returned by ip.compile.cache(cell).
2303 interactivity : str
2314 interactivity : str
2304 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2315 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2305 run interactively (displaying output from expressions). 'last_expr'
2316 run interactively (displaying output from expressions). 'last_expr'
2306 will run the last node interactively only if it is an expression (i.e.
2317 will run the last node interactively only if it is an expression (i.e.
2307 expressions in loops or other blocks are not displayed. Other values
2318 expressions in loops or other blocks are not displayed. Other values
2308 for this parameter will raise a ValueError.
2319 for this parameter will raise a ValueError.
2309 """
2320 """
2310 if not nodelist:
2321 if not nodelist:
2311 return
2322 return
2312
2323
2313 if interactivity == 'last_expr':
2324 if interactivity == 'last_expr':
2314 if isinstance(nodelist[-1], ast.Expr):
2325 if isinstance(nodelist[-1], ast.Expr):
2315 interactivity = "last"
2326 interactivity = "last"
2316 else:
2327 else:
2317 interactivity = "none"
2328 interactivity = "none"
2318
2329
2319 if interactivity == 'none':
2330 if interactivity == 'none':
2320 to_run_exec, to_run_interactive = nodelist, []
2331 to_run_exec, to_run_interactive = nodelist, []
2321 elif interactivity == 'last':
2332 elif interactivity == 'last':
2322 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2333 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2323 elif interactivity == 'all':
2334 elif interactivity == 'all':
2324 to_run_exec, to_run_interactive = [], nodelist
2335 to_run_exec, to_run_interactive = [], nodelist
2325 else:
2336 else:
2326 raise ValueError("Interactivity was %r" % interactivity)
2337 raise ValueError("Interactivity was %r" % interactivity)
2327
2338
2328 exec_count = self.execution_count
2339 exec_count = self.execution_count
2329
2340
2330 for i, node in enumerate(to_run_exec):
2341 for i, node in enumerate(to_run_exec):
2331 mod = ast.Module([node])
2342 mod = ast.Module([node])
2332 code = self.compile(mod, cell_name, "exec")
2343 code = self.compile(mod, cell_name, "exec")
2333 if self.run_code(code):
2344 if self.run_code(code):
2334 return True
2345 return True
2335
2346
2336 for i, node in enumerate(to_run_interactive):
2347 for i, node in enumerate(to_run_interactive):
2337 mod = ast.Interactive([node])
2348 mod = ast.Interactive([node])
2338 code = self.compile(mod, cell_name, "single")
2349 code = self.compile(mod, cell_name, "single")
2339 if self.run_code(code):
2350 if self.run_code(code):
2340 return True
2351 return True
2341
2352
2342 return False
2353 return False
2343
2354
2344 def run_code(self, code_obj):
2355 def run_code(self, code_obj):
2345 """Execute a code object.
2356 """Execute a code object.
2346
2357
2347 When an exception occurs, self.showtraceback() is called to display a
2358 When an exception occurs, self.showtraceback() is called to display a
2348 traceback.
2359 traceback.
2349
2360
2350 Parameters
2361 Parameters
2351 ----------
2362 ----------
2352 code_obj : code object
2363 code_obj : code object
2353 A compiled code object, to be executed
2364 A compiled code object, to be executed
2354 post_execute : bool [default: True]
2365 post_execute : bool [default: True]
2355 whether to call post_execute hooks after this particular execution.
2366 whether to call post_execute hooks after this particular execution.
2356
2367
2357 Returns
2368 Returns
2358 -------
2369 -------
2359 False : successful execution.
2370 False : successful execution.
2360 True : an error occurred.
2371 True : an error occurred.
2361 """
2372 """
2362
2373
2363 # Set our own excepthook in case the user code tries to call it
2374 # Set our own excepthook in case the user code tries to call it
2364 # directly, so that the IPython crash handler doesn't get triggered
2375 # directly, so that the IPython crash handler doesn't get triggered
2365 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2376 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2366
2377
2367 # we save the original sys.excepthook in the instance, in case config
2378 # we save the original sys.excepthook in the instance, in case config
2368 # code (such as magics) needs access to it.
2379 # code (such as magics) needs access to it.
2369 self.sys_excepthook = old_excepthook
2380 self.sys_excepthook = old_excepthook
2370 outflag = 1 # happens in more places, so it's easier as default
2381 outflag = 1 # happens in more places, so it's easier as default
2371 try:
2382 try:
2372 try:
2383 try:
2373 self.hooks.pre_run_code_hook()
2384 self.hooks.pre_run_code_hook()
2374 #rprint('Running code', repr(code_obj)) # dbg
2385 #rprint('Running code', repr(code_obj)) # dbg
2375 exec code_obj in self.user_global_ns, self.user_ns
2386 exec code_obj in self.user_global_ns, self.user_ns
2376 finally:
2387 finally:
2377 # Reset our crash handler in place
2388 # Reset our crash handler in place
2378 sys.excepthook = old_excepthook
2389 sys.excepthook = old_excepthook
2379 except SystemExit:
2390 except SystemExit:
2380 self.showtraceback(exception_only=True)
2391 self.showtraceback(exception_only=True)
2381 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2392 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2382 except self.custom_exceptions:
2393 except self.custom_exceptions:
2383 etype,value,tb = sys.exc_info()
2394 etype,value,tb = sys.exc_info()
2384 self.CustomTB(etype,value,tb)
2395 self.CustomTB(etype,value,tb)
2385 except:
2396 except:
2386 self.showtraceback()
2397 self.showtraceback()
2387 else:
2398 else:
2388 outflag = 0
2399 outflag = 0
2389 if softspace(sys.stdout, 0):
2400 if softspace(sys.stdout, 0):
2390 print
2401 print
2391
2402
2392 return outflag
2403 return outflag
2393
2404
2394 # For backwards compatibility
2405 # For backwards compatibility
2395 runcode = run_code
2406 runcode = run_code
2396
2407
2397 #-------------------------------------------------------------------------
2408 #-------------------------------------------------------------------------
2398 # Things related to GUI support and pylab
2409 # Things related to GUI support and pylab
2399 #-------------------------------------------------------------------------
2410 #-------------------------------------------------------------------------
2400
2411
2401 def enable_pylab(self, gui=None):
2412 def enable_pylab(self, gui=None):
2402 raise NotImplementedError('Implement enable_pylab in a subclass')
2413 raise NotImplementedError('Implement enable_pylab in a subclass')
2403
2414
2404 #-------------------------------------------------------------------------
2415 #-------------------------------------------------------------------------
2405 # Utilities
2416 # Utilities
2406 #-------------------------------------------------------------------------
2417 #-------------------------------------------------------------------------
2407
2418
2408 def var_expand(self,cmd,depth=0):
2419 def var_expand(self,cmd,depth=0):
2409 """Expand python variables in a string.
2420 """Expand python variables in a string.
2410
2421
2411 The depth argument indicates how many frames above the caller should
2422 The depth argument indicates how many frames above the caller should
2412 be walked to look for the local namespace where to expand variables.
2423 be walked to look for the local namespace where to expand variables.
2413
2424
2414 The global namespace for expansion is always the user's interactive
2425 The global namespace for expansion is always the user's interactive
2415 namespace.
2426 namespace.
2416 """
2427 """
2417 res = ItplNS(cmd, self.user_ns, # globals
2428 res = ItplNS(cmd, self.user_ns, # globals
2418 # Skip our own frame in searching for locals:
2429 # Skip our own frame in searching for locals:
2419 sys._getframe(depth+1).f_locals # locals
2430 sys._getframe(depth+1).f_locals # locals
2420 )
2431 )
2421 return str(res).decode(res.codec)
2432 return str(res).decode(res.codec)
2422
2433
2423 def mktempfile(self, data=None, prefix='ipython_edit_'):
2434 def mktempfile(self, data=None, prefix='ipython_edit_'):
2424 """Make a new tempfile and return its filename.
2435 """Make a new tempfile and return its filename.
2425
2436
2426 This makes a call to tempfile.mktemp, but it registers the created
2437 This makes a call to tempfile.mktemp, but it registers the created
2427 filename internally so ipython cleans it up at exit time.
2438 filename internally so ipython cleans it up at exit time.
2428
2439
2429 Optional inputs:
2440 Optional inputs:
2430
2441
2431 - data(None): if data is given, it gets written out to the temp file
2442 - data(None): if data is given, it gets written out to the temp file
2432 immediately, and the file is closed again."""
2443 immediately, and the file is closed again."""
2433
2444
2434 filename = tempfile.mktemp('.py', prefix)
2445 filename = tempfile.mktemp('.py', prefix)
2435 self.tempfiles.append(filename)
2446 self.tempfiles.append(filename)
2436
2447
2437 if data:
2448 if data:
2438 tmp_file = open(filename,'w')
2449 tmp_file = open(filename,'w')
2439 tmp_file.write(data)
2450 tmp_file.write(data)
2440 tmp_file.close()
2451 tmp_file.close()
2441 return filename
2452 return filename
2442
2453
2443 # TODO: This should be removed when Term is refactored.
2454 # TODO: This should be removed when Term is refactored.
2444 def write(self,data):
2455 def write(self,data):
2445 """Write a string to the default output"""
2456 """Write a string to the default output"""
2446 io.stdout.write(data)
2457 io.stdout.write(data)
2447
2458
2448 # TODO: This should be removed when Term is refactored.
2459 # TODO: This should be removed when Term is refactored.
2449 def write_err(self,data):
2460 def write_err(self,data):
2450 """Write a string to the default error output"""
2461 """Write a string to the default error output"""
2451 io.stderr.write(data)
2462 io.stderr.write(data)
2452
2463
2453 def ask_yes_no(self,prompt,default=True):
2464 def ask_yes_no(self,prompt,default=True):
2454 if self.quiet:
2465 if self.quiet:
2455 return True
2466 return True
2456 return ask_yes_no(prompt,default)
2467 return ask_yes_no(prompt,default)
2457
2468
2458 def show_usage(self):
2469 def show_usage(self):
2459 """Show a usage message"""
2470 """Show a usage message"""
2460 page.page(IPython.core.usage.interactive_usage)
2471 page.page(IPython.core.usage.interactive_usage)
2461
2472
2462 def find_user_code(self, target, raw=True):
2473 def find_user_code(self, target, raw=True):
2463 """Get a code string from history, file, or a string or macro.
2474 """Get a code string from history, file, or a string or macro.
2464
2475
2465 This is mainly used by magic functions.
2476 This is mainly used by magic functions.
2466
2477
2467 Parameters
2478 Parameters
2468 ----------
2479 ----------
2469 target : str
2480 target : str
2470 A string specifying code to retrieve. This will be tried respectively
2481 A string specifying code to retrieve. This will be tried respectively
2471 as: ranges of input history (see %history for syntax), a filename, or
2482 as: ranges of input history (see %history for syntax), a filename, or
2472 an expression evaluating to a string or Macro in the user namespace.
2483 an expression evaluating to a string or Macro in the user namespace.
2473 raw : bool
2484 raw : bool
2474 If true (default), retrieve raw history. Has no effect on the other
2485 If true (default), retrieve raw history. Has no effect on the other
2475 retrieval mechanisms.
2486 retrieval mechanisms.
2476
2487
2477 Returns
2488 Returns
2478 -------
2489 -------
2479 A string of code.
2490 A string of code.
2480
2491
2481 ValueError is raised if nothing is found, and TypeError if it evaluates
2492 ValueError is raised if nothing is found, and TypeError if it evaluates
2482 to an object of another type. In each case, .args[0] is a printable
2493 to an object of another type. In each case, .args[0] is a printable
2483 message.
2494 message.
2484 """
2495 """
2485 code = self.extract_input_lines(target, raw=raw) # Grab history
2496 code = self.extract_input_lines(target, raw=raw) # Grab history
2486 if code:
2497 if code:
2487 return code
2498 return code
2488 if os.path.isfile(target): # Read file
2499 if os.path.isfile(target): # Read file
2489 return open(target, "r").read()
2500 return open(target, "r").read()
2490
2501
2491 try: # User namespace
2502 try: # User namespace
2492 codeobj = eval(target, self.user_ns)
2503 codeobj = eval(target, self.user_ns)
2493 except Exception:
2504 except Exception:
2494 raise ValueError(("'%s' was not found in history, as a file, nor in"
2505 raise ValueError(("'%s' was not found in history, as a file, nor in"
2495 " the user namespace.") % target)
2506 " the user namespace.") % target)
2496 if isinstance(codeobj, basestring):
2507 if isinstance(codeobj, basestring):
2497 return codeobj
2508 return codeobj
2498 elif isinstance(codeobj, Macro):
2509 elif isinstance(codeobj, Macro):
2499 return codeobj.value
2510 return codeobj.value
2500
2511
2501 raise TypeError("%s is neither a string nor a macro." % target,
2512 raise TypeError("%s is neither a string nor a macro." % target,
2502 codeobj)
2513 codeobj)
2503
2514
2504 #-------------------------------------------------------------------------
2515 #-------------------------------------------------------------------------
2505 # Things related to IPython exiting
2516 # Things related to IPython exiting
2506 #-------------------------------------------------------------------------
2517 #-------------------------------------------------------------------------
2507 def atexit_operations(self):
2518 def atexit_operations(self):
2508 """This will be executed at the time of exit.
2519 """This will be executed at the time of exit.
2509
2520
2510 Cleanup operations and saving of persistent data that is done
2521 Cleanup operations and saving of persistent data that is done
2511 unconditionally by IPython should be performed here.
2522 unconditionally by IPython should be performed here.
2512
2523
2513 For things that may depend on startup flags or platform specifics (such
2524 For things that may depend on startup flags or platform specifics (such
2514 as having readline or not), register a separate atexit function in the
2525 as having readline or not), register a separate atexit function in the
2515 code that has the appropriate information, rather than trying to
2526 code that has the appropriate information, rather than trying to
2516 clutter
2527 clutter
2517 """
2528 """
2518 # Cleanup all tempfiles left around
2529 # Cleanup all tempfiles left around
2519 for tfile in self.tempfiles:
2530 for tfile in self.tempfiles:
2520 try:
2531 try:
2521 os.unlink(tfile)
2532 os.unlink(tfile)
2522 except OSError:
2533 except OSError:
2523 pass
2534 pass
2524
2535
2525 # Close the history session (this stores the end time and line count)
2536 # Close the history session (this stores the end time and line count)
2526 self.history_manager.end_session()
2537 self.history_manager.end_session()
2527
2538
2528 # Clear all user namespaces to release all references cleanly.
2539 # Clear all user namespaces to release all references cleanly.
2529 self.reset(new_session=False)
2540 self.reset(new_session=False)
2530
2541
2531 # Run user hooks
2542 # Run user hooks
2532 self.hooks.shutdown_hook()
2543 self.hooks.shutdown_hook()
2533
2544
2534 def cleanup(self):
2545 def cleanup(self):
2535 self.restore_sys_module_state()
2546 self.restore_sys_module_state()
2536
2547
2537
2548
2538 class InteractiveShellABC(object):
2549 class InteractiveShellABC(object):
2539 """An abstract base class for InteractiveShell."""
2550 """An abstract base class for InteractiveShell."""
2540 __metaclass__ = abc.ABCMeta
2551 __metaclass__ = abc.ABCMeta
2541
2552
2542 InteractiveShellABC.register(InteractiveShell)
2553 InteractiveShellABC.register(InteractiveShell)
@@ -1,3518 +1,3504 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 from cStringIO import StringIO
28 from cStringIO import StringIO
29 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
30 from pprint import pformat
30 from pprint import pformat
31 from xmlrpclib import ServerProxy
31 from xmlrpclib import ServerProxy
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 import IPython
44 import IPython
45 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.profiledir import ProfileDir
49 from IPython.core.macro import Macro
50 from IPython.core.macro import Macro
50 from IPython.core import page
51 from IPython.core import page
51 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.lib.pylabtools import mpl_runner
53 from IPython.lib.pylabtools import mpl_runner
53 from IPython.external.Itpl import itpl, printpl
54 from IPython.external.Itpl import itpl, printpl
54 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.path import get_py_filename
57 from IPython.utils.path import get_py_filename
57 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.terminal import set_term_title
59 from IPython.utils.terminal import set_term_title
59 from IPython.utils.text import LSString, SList, format_screen
60 from IPython.utils.text import LSString, SList, format_screen
60 from IPython.utils.timing import clock, clock2
61 from IPython.utils.timing import clock, clock2
61 from IPython.utils.warn import warn, error
62 from IPython.utils.warn import warn, error
62 from IPython.utils.ipstruct import Struct
63 from IPython.utils.ipstruct import Struct
63 import IPython.utils.generics
64 import IPython.utils.generics
64
65
65 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
66 # Utility functions
67 # Utility functions
67 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
68
69
69 def on_off(tag):
70 def on_off(tag):
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 return ['OFF','ON'][tag]
72 return ['OFF','ON'][tag]
72
73
73 class Bunch: pass
74 class Bunch: pass
74
75
75 def compress_dhist(dh):
76 def compress_dhist(dh):
76 head, tail = dh[:-10], dh[-10:]
77 head, tail = dh[:-10], dh[-10:]
77
78
78 newhead = []
79 newhead = []
79 done = set()
80 done = set()
80 for h in head:
81 for h in head:
81 if h in done:
82 if h in done:
82 continue
83 continue
83 newhead.append(h)
84 newhead.append(h)
84 done.add(h)
85 done.add(h)
85
86
86 return newhead + tail
87 return newhead + tail
87
88
88 def needs_local_scope(func):
89 def needs_local_scope(func):
89 """Decorator to mark magic functions which need to local scope to run."""
90 """Decorator to mark magic functions which need to local scope to run."""
90 func.needs_local_scope = True
91 func.needs_local_scope = True
91 return func
92 return func
92
93
93 # Used for exception handling in magic_edit
94 # Used for exception handling in magic_edit
94 class MacroToEdit(ValueError): pass
95 class MacroToEdit(ValueError): pass
95
96
96 #***************************************************************************
97 #***************************************************************************
97 # Main class implementing Magic functionality
98 # Main class implementing Magic functionality
98
99
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
103 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
106 # make Magic a configurable that InteractiveShell does not subclass.
106
107
107 class Magic:
108 class Magic:
108 """Magic functions for InteractiveShell.
109 """Magic functions for InteractiveShell.
109
110
110 Shell functions which can be reached as %function_name. All magic
111 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
112 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
113 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
114 vs. `%cd("../")`
114
115
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
117 at the command line, but it is is needed in the definition. """
117
118
118 # class globals
119 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121 'Automagic is ON, % prefix NOT needed for magic functions.']
121
122
122 #......................................................................
123 #......................................................................
123 # some utility functions
124 # some utility functions
124
125
125 def __init__(self,shell):
126 def __init__(self,shell):
126
127
127 self.options_table = {}
128 self.options_table = {}
128 if profile is None:
129 if profile is None:
129 self.magic_prun = self.profile_missing_notice
130 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
131 self.shell = shell
131
132
132 # namespace for holding state we may need
133 # namespace for holding state we may need
133 self._magic_state = Bunch()
134 self._magic_state = Bunch()
134
135
135 def profile_missing_notice(self, *args, **kwargs):
136 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
137 error("""\
137 The profile module could not be found. It has been removed from the standard
138 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
139 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
140 python-profiler package from non-free.""")
140
141
141 def default_option(self,fn,optstr):
142 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
143 """Make an entry in the options_table for fn, with value optstr"""
143
144
144 if fn not in self.lsmagic():
145 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
146 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
147 self.options_table[fn] = optstr
147
148
148 def lsmagic(self):
149 def lsmagic(self):
149 """Return a list of currently available magic functions.
150 """Return a list of currently available magic functions.
150
151
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
153 ['magic_ls','magic_cd',...]"""
153
154
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155 # FIXME. This needs a cleanup, in the way the magics list is built.
155
156
156 # magics in class definition
157 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
159 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
160 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
162 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
163 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
165 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
169 out = []
169 for fn in set(magics):
170 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
171 out.append(fn.replace('magic_','',1))
171 out.sort()
172 out.sort()
172 return out
173 return out
173
174
174 def extract_input_lines(self, range_str, raw=False):
175 def extract_input_lines(self, range_str, raw=False):
175 """Return as a string a set of input history slices.
176 """Return as a string a set of input history slices.
176
177
177 Inputs:
178 Inputs:
178
179
179 - range_str: the set of slices is given as a string, like
180 - range_str: the set of slices is given as a string, like
180 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 which get their arguments as strings. The number before the / is the
182 which get their arguments as strings. The number before the / is the
182 session number: ~n goes n back from the current session.
183 session number: ~n goes n back from the current session.
183
184
184 Optional inputs:
185 Optional inputs:
185
186
186 - raw(False): by default, the processed input is used. If this is
187 - raw(False): by default, the processed input is used. If this is
187 true, the raw input history is used instead.
188 true, the raw input history is used instead.
188
189
189 Note that slices can be called with two notations:
190 Note that slices can be called with two notations:
190
191
191 N:M -> standard python form, means including items N...(M-1).
192 N:M -> standard python form, means including items N...(M-1).
192
193
193 N-M -> include items N..M (closed endpoint)."""
194 N-M -> include items N..M (closed endpoint)."""
194 lines = self.shell.history_manager.\
195 lines = self.shell.history_manager.\
195 get_range_by_str(range_str, raw=raw)
196 get_range_by_str(range_str, raw=raw)
196 return "\n".join(x for _, _, x in lines)
197 return "\n".join(x for _, _, x in lines)
197
198
198 def arg_err(self,func):
199 def arg_err(self,func):
199 """Print docstring if incorrect arguments were passed"""
200 """Print docstring if incorrect arguments were passed"""
200 print 'Error in arguments:'
201 print 'Error in arguments:'
201 print oinspect.getdoc(func)
202 print oinspect.getdoc(func)
202
203
203 def format_latex(self,strng):
204 def format_latex(self,strng):
204 """Format a string for latex inclusion."""
205 """Format a string for latex inclusion."""
205
206
206 # Characters that need to be escaped for latex:
207 # Characters that need to be escaped for latex:
207 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 # Magic command names as headers:
209 # Magic command names as headers:
209 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 re.MULTILINE)
211 re.MULTILINE)
211 # Magic commands
212 # Magic commands
212 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 re.MULTILINE)
214 re.MULTILINE)
214 # Paragraph continue
215 # Paragraph continue
215 par_re = re.compile(r'\\$',re.MULTILINE)
216 par_re = re.compile(r'\\$',re.MULTILINE)
216
217
217 # The "\n" symbol
218 # The "\n" symbol
218 newline_re = re.compile(r'\\n')
219 newline_re = re.compile(r'\\n')
219
220
220 # Now build the string for output:
221 # Now build the string for output:
221 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 strng)
224 strng)
224 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 strng = par_re.sub(r'\\\\',strng)
226 strng = par_re.sub(r'\\\\',strng)
226 strng = escape_re.sub(r'\\\1',strng)
227 strng = escape_re.sub(r'\\\1',strng)
227 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 return strng
229 return strng
229
230
230 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 """Parse options passed to an argument string.
232 """Parse options passed to an argument string.
232
233
233 The interface is similar to that of getopt(), but it returns back a
234 The interface is similar to that of getopt(), but it returns back a
234 Struct with the options as keys and the stripped argument string still
235 Struct with the options as keys and the stripped argument string still
235 as a string.
236 as a string.
236
237
237 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 This allows us to easily expand variables, glob files, quote
239 This allows us to easily expand variables, glob files, quote
239 arguments, etc.
240 arguments, etc.
240
241
241 Options:
242 Options:
242 -mode: default 'string'. If given as 'list', the argument string is
243 -mode: default 'string'. If given as 'list', the argument string is
243 returned as a list (split on whitespace) instead of a string.
244 returned as a list (split on whitespace) instead of a string.
244
245
245 -list_all: put all option values in lists. Normally only options
246 -list_all: put all option values in lists. Normally only options
246 appearing more than once are put in a list.
247 appearing more than once are put in a list.
247
248
248 -posix (True): whether to split the input line in POSIX mode or not,
249 -posix (True): whether to split the input line in POSIX mode or not,
249 as per the conventions outlined in the shlex module from the
250 as per the conventions outlined in the shlex module from the
250 standard library."""
251 standard library."""
251
252
252 # inject default options at the beginning of the input line
253 # inject default options at the beginning of the input line
253 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255
256
256 mode = kw.get('mode','string')
257 mode = kw.get('mode','string')
257 if mode not in ['string','list']:
258 if mode not in ['string','list']:
258 raise ValueError,'incorrect mode given: %s' % mode
259 raise ValueError,'incorrect mode given: %s' % mode
259 # Get options
260 # Get options
260 list_all = kw.get('list_all',0)
261 list_all = kw.get('list_all',0)
261 posix = kw.get('posix', os.name == 'posix')
262 posix = kw.get('posix', os.name == 'posix')
262
263
263 # Check if we have more than one argument to warrant extra processing:
264 # Check if we have more than one argument to warrant extra processing:
264 odict = {} # Dictionary with options
265 odict = {} # Dictionary with options
265 args = arg_str.split()
266 args = arg_str.split()
266 if len(args) >= 1:
267 if len(args) >= 1:
267 # If the list of inputs only has 0 or 1 thing in it, there's no
268 # If the list of inputs only has 0 or 1 thing in it, there's no
268 # need to look for options
269 # need to look for options
269 argv = arg_split(arg_str,posix)
270 argv = arg_split(arg_str,posix)
270 # Do regular option processing
271 # Do regular option processing
271 try:
272 try:
272 opts,args = getopt(argv,opt_str,*long_opts)
273 opts,args = getopt(argv,opt_str,*long_opts)
273 except GetoptError,e:
274 except GetoptError,e:
274 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 " ".join(long_opts)))
276 " ".join(long_opts)))
276 for o,a in opts:
277 for o,a in opts:
277 if o.startswith('--'):
278 if o.startswith('--'):
278 o = o[2:]
279 o = o[2:]
279 else:
280 else:
280 o = o[1:]
281 o = o[1:]
281 try:
282 try:
282 odict[o].append(a)
283 odict[o].append(a)
283 except AttributeError:
284 except AttributeError:
284 odict[o] = [odict[o],a]
285 odict[o] = [odict[o],a]
285 except KeyError:
286 except KeyError:
286 if list_all:
287 if list_all:
287 odict[o] = [a]
288 odict[o] = [a]
288 else:
289 else:
289 odict[o] = a
290 odict[o] = a
290
291
291 # Prepare opts,args for return
292 # Prepare opts,args for return
292 opts = Struct(odict)
293 opts = Struct(odict)
293 if mode == 'string':
294 if mode == 'string':
294 args = ' '.join(args)
295 args = ' '.join(args)
295
296
296 return opts,args
297 return opts,args
297
298
298 #......................................................................
299 #......................................................................
299 # And now the actual magic functions
300 # And now the actual magic functions
300
301
301 # Functions for IPython shell work (vars,funcs, config, etc)
302 # Functions for IPython shell work (vars,funcs, config, etc)
302 def magic_lsmagic(self, parameter_s = ''):
303 def magic_lsmagic(self, parameter_s = ''):
303 """List currently available magic functions."""
304 """List currently available magic functions."""
304 mesc = ESC_MAGIC
305 mesc = ESC_MAGIC
305 print 'Available magic functions:\n'+mesc+\
306 print 'Available magic functions:\n'+mesc+\
306 (' '+mesc).join(self.lsmagic())
307 (' '+mesc).join(self.lsmagic())
307 print '\n' + Magic.auto_status[self.shell.automagic]
308 print '\n' + Magic.auto_status[self.shell.automagic]
308 return None
309 return None
309
310
310 def magic_magic(self, parameter_s = ''):
311 def magic_magic(self, parameter_s = ''):
311 """Print information about the magic function system.
312 """Print information about the magic function system.
312
313
313 Supported formats: -latex, -brief, -rest
314 Supported formats: -latex, -brief, -rest
314 """
315 """
315
316
316 mode = ''
317 mode = ''
317 try:
318 try:
318 if parameter_s.split()[0] == '-latex':
319 if parameter_s.split()[0] == '-latex':
319 mode = 'latex'
320 mode = 'latex'
320 if parameter_s.split()[0] == '-brief':
321 if parameter_s.split()[0] == '-brief':
321 mode = 'brief'
322 mode = 'brief'
322 if parameter_s.split()[0] == '-rest':
323 if parameter_s.split()[0] == '-rest':
323 mode = 'rest'
324 mode = 'rest'
324 rest_docs = []
325 rest_docs = []
325 except:
326 except:
326 pass
327 pass
327
328
328 magic_docs = []
329 magic_docs = []
329 for fname in self.lsmagic():
330 for fname in self.lsmagic():
330 mname = 'magic_' + fname
331 mname = 'magic_' + fname
331 for space in (Magic,self,self.__class__):
332 for space in (Magic,self,self.__class__):
332 try:
333 try:
333 fn = space.__dict__[mname]
334 fn = space.__dict__[mname]
334 except KeyError:
335 except KeyError:
335 pass
336 pass
336 else:
337 else:
337 break
338 break
338 if mode == 'brief':
339 if mode == 'brief':
339 # only first line
340 # only first line
340 if fn.__doc__:
341 if fn.__doc__:
341 fndoc = fn.__doc__.split('\n',1)[0]
342 fndoc = fn.__doc__.split('\n',1)[0]
342 else:
343 else:
343 fndoc = 'No documentation'
344 fndoc = 'No documentation'
344 else:
345 else:
345 if fn.__doc__:
346 if fn.__doc__:
346 fndoc = fn.__doc__.rstrip()
347 fndoc = fn.__doc__.rstrip()
347 else:
348 else:
348 fndoc = 'No documentation'
349 fndoc = 'No documentation'
349
350
350
351
351 if mode == 'rest':
352 if mode == 'rest':
352 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 fname,fndoc))
354 fname,fndoc))
354
355
355 else:
356 else:
356 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 fname,fndoc))
358 fname,fndoc))
358
359
359 magic_docs = ''.join(magic_docs)
360 magic_docs = ''.join(magic_docs)
360
361
361 if mode == 'rest':
362 if mode == 'rest':
362 return "".join(rest_docs)
363 return "".join(rest_docs)
363
364
364 if mode == 'latex':
365 if mode == 'latex':
365 print self.format_latex(magic_docs)
366 print self.format_latex(magic_docs)
366 return
367 return
367 else:
368 else:
368 magic_docs = format_screen(magic_docs)
369 magic_docs = format_screen(magic_docs)
369 if mode == 'brief':
370 if mode == 'brief':
370 return magic_docs
371 return magic_docs
371
372
372 outmsg = """
373 outmsg = """
373 IPython's 'magic' functions
374 IPython's 'magic' functions
374 ===========================
375 ===========================
375
376
376 The magic function system provides a series of functions which allow you to
377 The magic function system provides a series of functions which allow you to
377 control the behavior of IPython itself, plus a lot of system-type
378 control the behavior of IPython itself, plus a lot of system-type
378 features. All these functions are prefixed with a % character, but parameters
379 features. All these functions are prefixed with a % character, but parameters
379 are given without parentheses or quotes.
380 are given without parentheses or quotes.
380
381
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 %automagic function), you don't need to type in the % explicitly. By default,
383 %automagic function), you don't need to type in the % explicitly. By default,
383 IPython ships with automagic on, so you should only rarely need the % escape.
384 IPython ships with automagic on, so you should only rarely need the % escape.
384
385
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 to 'mydir', if it exists.
387 to 'mydir', if it exists.
387
388
388 You can define your own magic functions to extend the system. See the supplied
389 You can define your own magic functions to extend the system. See the supplied
389 ipythonrc and example-magic.py files for details (in your ipython
390 ipythonrc and example-magic.py files for details (in your ipython
390 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391
392
392 You can also define your own aliased names for magic functions. In your
393 You can also define your own aliased names for magic functions. In your
393 ipythonrc file, placing a line like:
394 ipythonrc file, placing a line like:
394
395
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396
397
397 will define %pf as a new name for %profile.
398 will define %pf as a new name for %profile.
398
399
399 You can also call magics in code using the magic() function, which IPython
400 You can also call magics in code using the magic() function, which IPython
400 automatically adds to the builtin namespace. Type 'magic?' for details.
401 automatically adds to the builtin namespace. Type 'magic?' for details.
401
402
402 For a list of the available magic functions, use %lsmagic. For a description
403 For a list of the available magic functions, use %lsmagic. For a description
403 of any of them, type %magic_name?, e.g. '%cd?'.
404 of any of them, type %magic_name?, e.g. '%cd?'.
404
405
405 Currently the magic system has the following functions:\n"""
406 Currently the magic system has the following functions:\n"""
406
407
407 mesc = ESC_MAGIC
408 mesc = ESC_MAGIC
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 "\n\n%s%s\n\n%s" % (outmsg,
410 "\n\n%s%s\n\n%s" % (outmsg,
410 magic_docs,mesc,mesc,
411 magic_docs,mesc,mesc,
411 (' '+mesc).join(self.lsmagic()),
412 (' '+mesc).join(self.lsmagic()),
412 Magic.auto_status[self.shell.automagic] ) )
413 Magic.auto_status[self.shell.automagic] ) )
413 page.page(outmsg)
414 page.page(outmsg)
414
415
415 def magic_automagic(self, parameter_s = ''):
416 def magic_automagic(self, parameter_s = ''):
416 """Make magic functions callable without having to type the initial %.
417 """Make magic functions callable without having to type the initial %.
417
418
418 Without argumentsl toggles on/off (when off, you must call it as
419 Without argumentsl toggles on/off (when off, you must call it as
419 %automagic, of course). With arguments it sets the value, and you can
420 %automagic, of course). With arguments it sets the value, and you can
420 use any of (case insensitive):
421 use any of (case insensitive):
421
422
422 - on,1,True: to activate
423 - on,1,True: to activate
423
424
424 - off,0,False: to deactivate.
425 - off,0,False: to deactivate.
425
426
426 Note that magic functions have lowest priority, so if there's a
427 Note that magic functions have lowest priority, so if there's a
427 variable whose name collides with that of a magic fn, automagic won't
428 variable whose name collides with that of a magic fn, automagic won't
428 work for that function (you get the variable instead). However, if you
429 work for that function (you get the variable instead). However, if you
429 delete the variable (del var), the previously shadowed magic function
430 delete the variable (del var), the previously shadowed magic function
430 becomes visible to automagic again."""
431 becomes visible to automagic again."""
431
432
432 arg = parameter_s.lower()
433 arg = parameter_s.lower()
433 if parameter_s in ('on','1','true'):
434 if parameter_s in ('on','1','true'):
434 self.shell.automagic = True
435 self.shell.automagic = True
435 elif parameter_s in ('off','0','false'):
436 elif parameter_s in ('off','0','false'):
436 self.shell.automagic = False
437 self.shell.automagic = False
437 else:
438 else:
438 self.shell.automagic = not self.shell.automagic
439 self.shell.automagic = not self.shell.automagic
439 print '\n' + Magic.auto_status[self.shell.automagic]
440 print '\n' + Magic.auto_status[self.shell.automagic]
440
441
441 @skip_doctest
442 @skip_doctest
442 def magic_autocall(self, parameter_s = ''):
443 def magic_autocall(self, parameter_s = ''):
443 """Make functions callable without having to type parentheses.
444 """Make functions callable without having to type parentheses.
444
445
445 Usage:
446 Usage:
446
447
447 %autocall [mode]
448 %autocall [mode]
448
449
449 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 value is toggled on and off (remembering the previous state).
451 value is toggled on and off (remembering the previous state).
451
452
452 In more detail, these values mean:
453 In more detail, these values mean:
453
454
454 0 -> fully disabled
455 0 -> fully disabled
455
456
456 1 -> active, but do not apply if there are no arguments on the line.
457 1 -> active, but do not apply if there are no arguments on the line.
457
458
458 In this mode, you get:
459 In this mode, you get:
459
460
460 In [1]: callable
461 In [1]: callable
461 Out[1]: <built-in function callable>
462 Out[1]: <built-in function callable>
462
463
463 In [2]: callable 'hello'
464 In [2]: callable 'hello'
464 ------> callable('hello')
465 ------> callable('hello')
465 Out[2]: False
466 Out[2]: False
466
467
467 2 -> Active always. Even if no arguments are present, the callable
468 2 -> Active always. Even if no arguments are present, the callable
468 object is called:
469 object is called:
469
470
470 In [2]: float
471 In [2]: float
471 ------> float()
472 ------> float()
472 Out[2]: 0.0
473 Out[2]: 0.0
473
474
474 Note that even with autocall off, you can still use '/' at the start of
475 Note that even with autocall off, you can still use '/' at the start of
475 a line to treat the first argument on the command line as a function
476 a line to treat the first argument on the command line as a function
476 and add parentheses to it:
477 and add parentheses to it:
477
478
478 In [8]: /str 43
479 In [8]: /str 43
479 ------> str(43)
480 ------> str(43)
480 Out[8]: '43'
481 Out[8]: '43'
481
482
482 # all-random (note for auto-testing)
483 # all-random (note for auto-testing)
483 """
484 """
484
485
485 if parameter_s:
486 if parameter_s:
486 arg = int(parameter_s)
487 arg = int(parameter_s)
487 else:
488 else:
488 arg = 'toggle'
489 arg = 'toggle'
489
490
490 if not arg in (0,1,2,'toggle'):
491 if not arg in (0,1,2,'toggle'):
491 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 return
493 return
493
494
494 if arg in (0,1,2):
495 if arg in (0,1,2):
495 self.shell.autocall = arg
496 self.shell.autocall = arg
496 else: # toggle
497 else: # toggle
497 if self.shell.autocall:
498 if self.shell.autocall:
498 self._magic_state.autocall_save = self.shell.autocall
499 self._magic_state.autocall_save = self.shell.autocall
499 self.shell.autocall = 0
500 self.shell.autocall = 0
500 else:
501 else:
501 try:
502 try:
502 self.shell.autocall = self._magic_state.autocall_save
503 self.shell.autocall = self._magic_state.autocall_save
503 except AttributeError:
504 except AttributeError:
504 self.shell.autocall = self._magic_state.autocall_save = 1
505 self.shell.autocall = self._magic_state.autocall_save = 1
505
506
506 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507
508
508
509
509 def magic_page(self, parameter_s=''):
510 def magic_page(self, parameter_s=''):
510 """Pretty print the object and display it through a pager.
511 """Pretty print the object and display it through a pager.
511
512
512 %page [options] OBJECT
513 %page [options] OBJECT
513
514
514 If no object is given, use _ (last output).
515 If no object is given, use _ (last output).
515
516
516 Options:
517 Options:
517
518
518 -r: page str(object), don't pretty-print it."""
519 -r: page str(object), don't pretty-print it."""
519
520
520 # After a function contributed by Olivier Aubert, slightly modified.
521 # After a function contributed by Olivier Aubert, slightly modified.
521
522
522 # Process options/args
523 # Process options/args
523 opts,args = self.parse_options(parameter_s,'r')
524 opts,args = self.parse_options(parameter_s,'r')
524 raw = 'r' in opts
525 raw = 'r' in opts
525
526
526 oname = args and args or '_'
527 oname = args and args or '_'
527 info = self._ofind(oname)
528 info = self._ofind(oname)
528 if info['found']:
529 if info['found']:
529 txt = (raw and str or pformat)( info['obj'] )
530 txt = (raw and str or pformat)( info['obj'] )
530 page.page(txt)
531 page.page(txt)
531 else:
532 else:
532 print 'Object `%s` not found' % oname
533 print 'Object `%s` not found' % oname
533
534
534 def magic_profile(self, parameter_s=''):
535 def magic_profile(self, parameter_s=''):
535 """Print your currently active IPython profile."""
536 """Print your currently active IPython profile."""
536 if self.shell.profile:
537 print self.shell.profile
537 printpl('Current IPython profile: $self.shell.profile.')
538 else:
539 print 'No profile active.'
540
538
541 def magic_pinfo(self, parameter_s='', namespaces=None):
539 def magic_pinfo(self, parameter_s='', namespaces=None):
542 """Provide detailed information about an object.
540 """Provide detailed information about an object.
543
541
544 '%pinfo object' is just a synonym for object? or ?object."""
542 '%pinfo object' is just a synonym for object? or ?object."""
545
543
546 #print 'pinfo par: <%s>' % parameter_s # dbg
544 #print 'pinfo par: <%s>' % parameter_s # dbg
547
545
548
546
549 # detail_level: 0 -> obj? , 1 -> obj??
547 # detail_level: 0 -> obj? , 1 -> obj??
550 detail_level = 0
548 detail_level = 0
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
549 # We need to detect if we got called as 'pinfo pinfo foo', which can
552 # happen if the user types 'pinfo foo?' at the cmd line.
550 # happen if the user types 'pinfo foo?' at the cmd line.
553 pinfo,qmark1,oname,qmark2 = \
551 pinfo,qmark1,oname,qmark2 = \
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
552 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
555 if pinfo or qmark1 or qmark2:
553 if pinfo or qmark1 or qmark2:
556 detail_level = 1
554 detail_level = 1
557 if "*" in oname:
555 if "*" in oname:
558 self.magic_psearch(oname)
556 self.magic_psearch(oname)
559 else:
557 else:
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
558 self.shell._inspect('pinfo', oname, detail_level=detail_level,
561 namespaces=namespaces)
559 namespaces=namespaces)
562
560
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
561 def magic_pinfo2(self, parameter_s='', namespaces=None):
564 """Provide extra detailed information about an object.
562 """Provide extra detailed information about an object.
565
563
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
564 '%pinfo2 object' is just a synonym for object?? or ??object."""
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
565 self.shell._inspect('pinfo', parameter_s, detail_level=1,
568 namespaces=namespaces)
566 namespaces=namespaces)
569
567
570 @skip_doctest
568 @skip_doctest
571 def magic_pdef(self, parameter_s='', namespaces=None):
569 def magic_pdef(self, parameter_s='', namespaces=None):
572 """Print the definition header for any callable object.
570 """Print the definition header for any callable object.
573
571
574 If the object is a class, print the constructor information.
572 If the object is a class, print the constructor information.
575
573
576 Examples
574 Examples
577 --------
575 --------
578 ::
576 ::
579
577
580 In [3]: %pdef urllib.urlopen
578 In [3]: %pdef urllib.urlopen
581 urllib.urlopen(url, data=None, proxies=None)
579 urllib.urlopen(url, data=None, proxies=None)
582 """
580 """
583 self._inspect('pdef',parameter_s, namespaces)
581 self._inspect('pdef',parameter_s, namespaces)
584
582
585 def magic_pdoc(self, parameter_s='', namespaces=None):
583 def magic_pdoc(self, parameter_s='', namespaces=None):
586 """Print the docstring for an object.
584 """Print the docstring for an object.
587
585
588 If the given object is a class, it will print both the class and the
586 If the given object is a class, it will print both the class and the
589 constructor docstrings."""
587 constructor docstrings."""
590 self._inspect('pdoc',parameter_s, namespaces)
588 self._inspect('pdoc',parameter_s, namespaces)
591
589
592 def magic_psource(self, parameter_s='', namespaces=None):
590 def magic_psource(self, parameter_s='', namespaces=None):
593 """Print (or run through pager) the source code for an object."""
591 """Print (or run through pager) the source code for an object."""
594 self._inspect('psource',parameter_s, namespaces)
592 self._inspect('psource',parameter_s, namespaces)
595
593
596 def magic_pfile(self, parameter_s=''):
594 def magic_pfile(self, parameter_s=''):
597 """Print (or run through pager) the file where an object is defined.
595 """Print (or run through pager) the file where an object is defined.
598
596
599 The file opens at the line where the object definition begins. IPython
597 The file opens at the line where the object definition begins. IPython
600 will honor the environment variable PAGER if set, and otherwise will
598 will honor the environment variable PAGER if set, and otherwise will
601 do its best to print the file in a convenient form.
599 do its best to print the file in a convenient form.
602
600
603 If the given argument is not an object currently defined, IPython will
601 If the given argument is not an object currently defined, IPython will
604 try to interpret it as a filename (automatically adding a .py extension
602 try to interpret it as a filename (automatically adding a .py extension
605 if needed). You can thus use %pfile as a syntax highlighting code
603 if needed). You can thus use %pfile as a syntax highlighting code
606 viewer."""
604 viewer."""
607
605
608 # first interpret argument as an object name
606 # first interpret argument as an object name
609 out = self._inspect('pfile',parameter_s)
607 out = self._inspect('pfile',parameter_s)
610 # if not, try the input as a filename
608 # if not, try the input as a filename
611 if out == 'not found':
609 if out == 'not found':
612 try:
610 try:
613 filename = get_py_filename(parameter_s)
611 filename = get_py_filename(parameter_s)
614 except IOError,msg:
612 except IOError,msg:
615 print msg
613 print msg
616 return
614 return
617 page.page(self.shell.inspector.format(file(filename).read()))
615 page.page(self.shell.inspector.format(file(filename).read()))
618
616
619 def magic_psearch(self, parameter_s=''):
617 def magic_psearch(self, parameter_s=''):
620 """Search for object in namespaces by wildcard.
618 """Search for object in namespaces by wildcard.
621
619
622 %psearch [options] PATTERN [OBJECT TYPE]
620 %psearch [options] PATTERN [OBJECT TYPE]
623
621
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
622 Note: ? can be used as a synonym for %psearch, at the beginning or at
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
623 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
626 rest of the command line must be unchanged (options come first), so
624 rest of the command line must be unchanged (options come first), so
627 for example the following forms are equivalent
625 for example the following forms are equivalent
628
626
629 %psearch -i a* function
627 %psearch -i a* function
630 -i a* function?
628 -i a* function?
631 ?-i a* function
629 ?-i a* function
632
630
633 Arguments:
631 Arguments:
634
632
635 PATTERN
633 PATTERN
636
634
637 where PATTERN is a string containing * as a wildcard similar to its
635 where PATTERN is a string containing * as a wildcard similar to its
638 use in a shell. The pattern is matched in all namespaces on the
636 use in a shell. The pattern is matched in all namespaces on the
639 search path. By default objects starting with a single _ are not
637 search path. By default objects starting with a single _ are not
640 matched, many IPython generated objects have a single
638 matched, many IPython generated objects have a single
641 underscore. The default is case insensitive matching. Matching is
639 underscore. The default is case insensitive matching. Matching is
642 also done on the attributes of objects and not only on the objects
640 also done on the attributes of objects and not only on the objects
643 in a module.
641 in a module.
644
642
645 [OBJECT TYPE]
643 [OBJECT TYPE]
646
644
647 Is the name of a python type from the types module. The name is
645 Is the name of a python type from the types module. The name is
648 given in lowercase without the ending type, ex. StringType is
646 given in lowercase without the ending type, ex. StringType is
649 written string. By adding a type here only objects matching the
647 written string. By adding a type here only objects matching the
650 given type are matched. Using all here makes the pattern match all
648 given type are matched. Using all here makes the pattern match all
651 types (this is the default).
649 types (this is the default).
652
650
653 Options:
651 Options:
654
652
655 -a: makes the pattern match even objects whose names start with a
653 -a: makes the pattern match even objects whose names start with a
656 single underscore. These names are normally ommitted from the
654 single underscore. These names are normally ommitted from the
657 search.
655 search.
658
656
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
657 -i/-c: make the pattern case insensitive/sensitive. If neither of
660 these options is given, the default is read from your ipythonrc
658 these options is given, the default is read from your ipythonrc
661 file. The option name which sets this value is
659 file. The option name which sets this value is
662 'wildcards_case_sensitive'. If this option is not specified in your
660 'wildcards_case_sensitive'. If this option is not specified in your
663 ipythonrc file, IPython's internal default is to do a case sensitive
661 ipythonrc file, IPython's internal default is to do a case sensitive
664 search.
662 search.
665
663
666 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
667 specifiy can be searched in any of the following namespaces:
665 specifiy can be searched in any of the following namespaces:
668 'builtin', 'user', 'user_global','internal', 'alias', where
666 'builtin', 'user', 'user_global','internal', 'alias', where
669 'builtin' and 'user' are the search defaults. Note that you should
667 'builtin' and 'user' are the search defaults. Note that you should
670 not use quotes when specifying namespaces.
668 not use quotes when specifying namespaces.
671
669
672 'Builtin' contains the python module builtin, 'user' contains all
670 'Builtin' contains the python module builtin, 'user' contains all
673 user data, 'alias' only contain the shell aliases and no python
671 user data, 'alias' only contain the shell aliases and no python
674 objects, 'internal' contains objects used by IPython. The
672 objects, 'internal' contains objects used by IPython. The
675 'user_global' namespace is only used by embedded IPython instances,
673 'user_global' namespace is only used by embedded IPython instances,
676 and it contains module-level globals. You can add namespaces to the
674 and it contains module-level globals. You can add namespaces to the
677 search with -s or exclude them with -e (these options can be given
675 search with -s or exclude them with -e (these options can be given
678 more than once).
676 more than once).
679
677
680 Examples:
678 Examples:
681
679
682 %psearch a* -> objects beginning with an a
680 %psearch a* -> objects beginning with an a
683 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
684 %psearch a* function -> all functions beginning with an a
682 %psearch a* function -> all functions beginning with an a
685 %psearch re.e* -> objects beginning with an e in module re
683 %psearch re.e* -> objects beginning with an e in module re
686 %psearch r*.e* -> objects that start with e in modules starting in r
684 %psearch r*.e* -> objects that start with e in modules starting in r
687 %psearch r*.* string -> all strings in modules beginning with r
685 %psearch r*.* string -> all strings in modules beginning with r
688
686
689 Case sensitve search:
687 Case sensitve search:
690
688
691 %psearch -c a* list all object beginning with lower case a
689 %psearch -c a* list all object beginning with lower case a
692
690
693 Show objects beginning with a single _:
691 Show objects beginning with a single _:
694
692
695 %psearch -a _* list objects beginning with a single underscore"""
693 %psearch -a _* list objects beginning with a single underscore"""
696 try:
694 try:
697 parameter_s = parameter_s.encode('ascii')
695 parameter_s = parameter_s.encode('ascii')
698 except UnicodeEncodeError:
696 except UnicodeEncodeError:
699 print 'Python identifiers can only contain ascii characters.'
697 print 'Python identifiers can only contain ascii characters.'
700 return
698 return
701
699
702 # default namespaces to be searched
700 # default namespaces to be searched
703 def_search = ['user','builtin']
701 def_search = ['user','builtin']
704
702
705 # Process options/args
703 # Process options/args
706 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 opt = opts.get
705 opt = opts.get
708 shell = self.shell
706 shell = self.shell
709 psearch = shell.inspector.psearch
707 psearch = shell.inspector.psearch
710
708
711 # select case options
709 # select case options
712 if opts.has_key('i'):
710 if opts.has_key('i'):
713 ignore_case = True
711 ignore_case = True
714 elif opts.has_key('c'):
712 elif opts.has_key('c'):
715 ignore_case = False
713 ignore_case = False
716 else:
714 else:
717 ignore_case = not shell.wildcards_case_sensitive
715 ignore_case = not shell.wildcards_case_sensitive
718
716
719 # Build list of namespaces to search from user options
717 # Build list of namespaces to search from user options
720 def_search.extend(opt('s',[]))
718 def_search.extend(opt('s',[]))
721 ns_exclude = ns_exclude=opt('e',[])
719 ns_exclude = ns_exclude=opt('e',[])
722 ns_search = [nm for nm in def_search if nm not in ns_exclude]
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723
721
724 # Call the actual search
722 # Call the actual search
725 try:
723 try:
726 psearch(args,shell.ns_table,ns_search,
724 psearch(args,shell.ns_table,ns_search,
727 show_all=opt('a'),ignore_case=ignore_case)
725 show_all=opt('a'),ignore_case=ignore_case)
728 except:
726 except:
729 shell.showtraceback()
727 shell.showtraceback()
730
728
731 @skip_doctest
729 @skip_doctest
732 def magic_who_ls(self, parameter_s=''):
730 def magic_who_ls(self, parameter_s=''):
733 """Return a sorted list of all interactive variables.
731 """Return a sorted list of all interactive variables.
734
732
735 If arguments are given, only variables of types matching these
733 If arguments are given, only variables of types matching these
736 arguments are returned.
734 arguments are returned.
737
735
738 Examples
736 Examples
739 --------
737 --------
740
738
741 Define two variables and list them with who_ls::
739 Define two variables and list them with who_ls::
742
740
743 In [1]: alpha = 123
741 In [1]: alpha = 123
744
742
745 In [2]: beta = 'test'
743 In [2]: beta = 'test'
746
744
747 In [3]: %who_ls
745 In [3]: %who_ls
748 Out[3]: ['alpha', 'beta']
746 Out[3]: ['alpha', 'beta']
749
747
750 In [4]: %who_ls int
748 In [4]: %who_ls int
751 Out[4]: ['alpha']
749 Out[4]: ['alpha']
752
750
753 In [5]: %who_ls str
751 In [5]: %who_ls str
754 Out[5]: ['beta']
752 Out[5]: ['beta']
755 """
753 """
756
754
757 user_ns = self.shell.user_ns
755 user_ns = self.shell.user_ns
758 internal_ns = self.shell.internal_ns
756 internal_ns = self.shell.internal_ns
759 user_ns_hidden = self.shell.user_ns_hidden
757 user_ns_hidden = self.shell.user_ns_hidden
760 out = [ i for i in user_ns
758 out = [ i for i in user_ns
761 if not i.startswith('_') \
759 if not i.startswith('_') \
762 and not (i in internal_ns or i in user_ns_hidden) ]
760 and not (i in internal_ns or i in user_ns_hidden) ]
763
761
764 typelist = parameter_s.split()
762 typelist = parameter_s.split()
765 if typelist:
763 if typelist:
766 typeset = set(typelist)
764 typeset = set(typelist)
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
768
766
769 out.sort()
767 out.sort()
770 return out
768 return out
771
769
772 @skip_doctest
770 @skip_doctest
773 def magic_who(self, parameter_s=''):
771 def magic_who(self, parameter_s=''):
774 """Print all interactive variables, with some minimal formatting.
772 """Print all interactive variables, with some minimal formatting.
775
773
776 If any arguments are given, only variables whose type matches one of
774 If any arguments are given, only variables whose type matches one of
777 these are printed. For example:
775 these are printed. For example:
778
776
779 %who function str
777 %who function str
780
778
781 will only list functions and strings, excluding all other types of
779 will only list functions and strings, excluding all other types of
782 variables. To find the proper type names, simply use type(var) at a
780 variables. To find the proper type names, simply use type(var) at a
783 command line to see how python prints type names. For example:
781 command line to see how python prints type names. For example:
784
782
785 In [1]: type('hello')\\
783 In [1]: type('hello')\\
786 Out[1]: <type 'str'>
784 Out[1]: <type 'str'>
787
785
788 indicates that the type name for strings is 'str'.
786 indicates that the type name for strings is 'str'.
789
787
790 %who always excludes executed names loaded through your configuration
788 %who always excludes executed names loaded through your configuration
791 file and things which are internal to IPython.
789 file and things which are internal to IPython.
792
790
793 This is deliberate, as typically you may load many modules and the
791 This is deliberate, as typically you may load many modules and the
794 purpose of %who is to show you only what you've manually defined.
792 purpose of %who is to show you only what you've manually defined.
795
793
796 Examples
794 Examples
797 --------
795 --------
798
796
799 Define two variables and list them with who::
797 Define two variables and list them with who::
800
798
801 In [1]: alpha = 123
799 In [1]: alpha = 123
802
800
803 In [2]: beta = 'test'
801 In [2]: beta = 'test'
804
802
805 In [3]: %who
803 In [3]: %who
806 alpha beta
804 alpha beta
807
805
808 In [4]: %who int
806 In [4]: %who int
809 alpha
807 alpha
810
808
811 In [5]: %who str
809 In [5]: %who str
812 beta
810 beta
813 """
811 """
814
812
815 varlist = self.magic_who_ls(parameter_s)
813 varlist = self.magic_who_ls(parameter_s)
816 if not varlist:
814 if not varlist:
817 if parameter_s:
815 if parameter_s:
818 print 'No variables match your requested type.'
816 print 'No variables match your requested type.'
819 else:
817 else:
820 print 'Interactive namespace is empty.'
818 print 'Interactive namespace is empty.'
821 return
819 return
822
820
823 # if we have variables, move on...
821 # if we have variables, move on...
824 count = 0
822 count = 0
825 for i in varlist:
823 for i in varlist:
826 print i+'\t',
824 print i+'\t',
827 count += 1
825 count += 1
828 if count > 8:
826 if count > 8:
829 count = 0
827 count = 0
830 print
828 print
831 print
829 print
832
830
833 @skip_doctest
831 @skip_doctest
834 def magic_whos(self, parameter_s=''):
832 def magic_whos(self, parameter_s=''):
835 """Like %who, but gives some extra information about each variable.
833 """Like %who, but gives some extra information about each variable.
836
834
837 The same type filtering of %who can be applied here.
835 The same type filtering of %who can be applied here.
838
836
839 For all variables, the type is printed. Additionally it prints:
837 For all variables, the type is printed. Additionally it prints:
840
838
841 - For {},[],(): their length.
839 - For {},[],(): their length.
842
840
843 - For numpy arrays, a summary with shape, number of
841 - For numpy arrays, a summary with shape, number of
844 elements, typecode and size in memory.
842 elements, typecode and size in memory.
845
843
846 - Everything else: a string representation, snipping their middle if
844 - Everything else: a string representation, snipping their middle if
847 too long.
845 too long.
848
846
849 Examples
847 Examples
850 --------
848 --------
851
849
852 Define two variables and list them with whos::
850 Define two variables and list them with whos::
853
851
854 In [1]: alpha = 123
852 In [1]: alpha = 123
855
853
856 In [2]: beta = 'test'
854 In [2]: beta = 'test'
857
855
858 In [3]: %whos
856 In [3]: %whos
859 Variable Type Data/Info
857 Variable Type Data/Info
860 --------------------------------
858 --------------------------------
861 alpha int 123
859 alpha int 123
862 beta str test
860 beta str test
863 """
861 """
864
862
865 varnames = self.magic_who_ls(parameter_s)
863 varnames = self.magic_who_ls(parameter_s)
866 if not varnames:
864 if not varnames:
867 if parameter_s:
865 if parameter_s:
868 print 'No variables match your requested type.'
866 print 'No variables match your requested type.'
869 else:
867 else:
870 print 'Interactive namespace is empty.'
868 print 'Interactive namespace is empty.'
871 return
869 return
872
870
873 # if we have variables, move on...
871 # if we have variables, move on...
874
872
875 # for these types, show len() instead of data:
873 # for these types, show len() instead of data:
876 seq_types = ['dict', 'list', 'tuple']
874 seq_types = ['dict', 'list', 'tuple']
877
875
878 # for numpy/Numeric arrays, display summary info
876 # for numpy/Numeric arrays, display summary info
879 try:
877 try:
880 import numpy
878 import numpy
881 except ImportError:
879 except ImportError:
882 ndarray_type = None
880 ndarray_type = None
883 else:
881 else:
884 ndarray_type = numpy.ndarray.__name__
882 ndarray_type = numpy.ndarray.__name__
885 try:
883 try:
886 import Numeric
884 import Numeric
887 except ImportError:
885 except ImportError:
888 array_type = None
886 array_type = None
889 else:
887 else:
890 array_type = Numeric.ArrayType.__name__
888 array_type = Numeric.ArrayType.__name__
891
889
892 # Find all variable names and types so we can figure out column sizes
890 # Find all variable names and types so we can figure out column sizes
893 def get_vars(i):
891 def get_vars(i):
894 return self.shell.user_ns[i]
892 return self.shell.user_ns[i]
895
893
896 # some types are well known and can be shorter
894 # some types are well known and can be shorter
897 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
898 def type_name(v):
896 def type_name(v):
899 tn = type(v).__name__
897 tn = type(v).__name__
900 return abbrevs.get(tn,tn)
898 return abbrevs.get(tn,tn)
901
899
902 varlist = map(get_vars,varnames)
900 varlist = map(get_vars,varnames)
903
901
904 typelist = []
902 typelist = []
905 for vv in varlist:
903 for vv in varlist:
906 tt = type_name(vv)
904 tt = type_name(vv)
907
905
908 if tt=='instance':
906 if tt=='instance':
909 typelist.append( abbrevs.get(str(vv.__class__),
907 typelist.append( abbrevs.get(str(vv.__class__),
910 str(vv.__class__)))
908 str(vv.__class__)))
911 else:
909 else:
912 typelist.append(tt)
910 typelist.append(tt)
913
911
914 # column labels and # of spaces as separator
912 # column labels and # of spaces as separator
915 varlabel = 'Variable'
913 varlabel = 'Variable'
916 typelabel = 'Type'
914 typelabel = 'Type'
917 datalabel = 'Data/Info'
915 datalabel = 'Data/Info'
918 colsep = 3
916 colsep = 3
919 # variable format strings
917 # variable format strings
920 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
918 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
921 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
919 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
922 aformat = "%s: %s elems, type `%s`, %s bytes"
920 aformat = "%s: %s elems, type `%s`, %s bytes"
923 # find the size of the columns to format the output nicely
921 # find the size of the columns to format the output nicely
924 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
922 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
925 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
923 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
926 # table header
924 # table header
927 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
925 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
928 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
926 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
929 # and the table itself
927 # and the table itself
930 kb = 1024
928 kb = 1024
931 Mb = 1048576 # kb**2
929 Mb = 1048576 # kb**2
932 for vname,var,vtype in zip(varnames,varlist,typelist):
930 for vname,var,vtype in zip(varnames,varlist,typelist):
933 print itpl(vformat),
931 print itpl(vformat),
934 if vtype in seq_types:
932 if vtype in seq_types:
935 print "n="+str(len(var))
933 print "n="+str(len(var))
936 elif vtype in [array_type,ndarray_type]:
934 elif vtype in [array_type,ndarray_type]:
937 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
935 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
938 if vtype==ndarray_type:
936 if vtype==ndarray_type:
939 # numpy
937 # numpy
940 vsize = var.size
938 vsize = var.size
941 vbytes = vsize*var.itemsize
939 vbytes = vsize*var.itemsize
942 vdtype = var.dtype
940 vdtype = var.dtype
943 else:
941 else:
944 # Numeric
942 # Numeric
945 vsize = Numeric.size(var)
943 vsize = Numeric.size(var)
946 vbytes = vsize*var.itemsize()
944 vbytes = vsize*var.itemsize()
947 vdtype = var.typecode()
945 vdtype = var.typecode()
948
946
949 if vbytes < 100000:
947 if vbytes < 100000:
950 print aformat % (vshape,vsize,vdtype,vbytes)
948 print aformat % (vshape,vsize,vdtype,vbytes)
951 else:
949 else:
952 print aformat % (vshape,vsize,vdtype,vbytes),
950 print aformat % (vshape,vsize,vdtype,vbytes),
953 if vbytes < Mb:
951 if vbytes < Mb:
954 print '(%s kb)' % (vbytes/kb,)
952 print '(%s kb)' % (vbytes/kb,)
955 else:
953 else:
956 print '(%s Mb)' % (vbytes/Mb,)
954 print '(%s Mb)' % (vbytes/Mb,)
957 else:
955 else:
958 try:
956 try:
959 vstr = str(var)
957 vstr = str(var)
960 except UnicodeEncodeError:
958 except UnicodeEncodeError:
961 vstr = unicode(var).encode(sys.getdefaultencoding(),
959 vstr = unicode(var).encode(sys.getdefaultencoding(),
962 'backslashreplace')
960 'backslashreplace')
963 vstr = vstr.replace('\n','\\n')
961 vstr = vstr.replace('\n','\\n')
964 if len(vstr) < 50:
962 if len(vstr) < 50:
965 print vstr
963 print vstr
966 else:
964 else:
967 printpl(vfmt_short)
965 printpl(vfmt_short)
968
966
969 def magic_reset(self, parameter_s=''):
967 def magic_reset(self, parameter_s=''):
970 """Resets the namespace by removing all names defined by the user.
968 """Resets the namespace by removing all names defined by the user.
971
969
972 Parameters
970 Parameters
973 ----------
971 ----------
974 -f : force reset without asking for confirmation.
972 -f : force reset without asking for confirmation.
975
973
976 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
974 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
977 References to objects may be kept. By default (without this option),
975 References to objects may be kept. By default (without this option),
978 we do a 'hard' reset, giving you a new session and removing all
976 we do a 'hard' reset, giving you a new session and removing all
979 references to objects from the current session.
977 references to objects from the current session.
980
978
981 Examples
979 Examples
982 --------
980 --------
983 In [6]: a = 1
981 In [6]: a = 1
984
982
985 In [7]: a
983 In [7]: a
986 Out[7]: 1
984 Out[7]: 1
987
985
988 In [8]: 'a' in _ip.user_ns
986 In [8]: 'a' in _ip.user_ns
989 Out[8]: True
987 Out[8]: True
990
988
991 In [9]: %reset -f
989 In [9]: %reset -f
992
990
993 In [1]: 'a' in _ip.user_ns
991 In [1]: 'a' in _ip.user_ns
994 Out[1]: False
992 Out[1]: False
995 """
993 """
996 opts, args = self.parse_options(parameter_s,'sf')
994 opts, args = self.parse_options(parameter_s,'sf')
997 if 'f' in opts:
995 if 'f' in opts:
998 ans = True
996 ans = True
999 else:
997 else:
1000 ans = self.shell.ask_yes_no(
998 ans = self.shell.ask_yes_no(
1001 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1002 if not ans:
1000 if not ans:
1003 print 'Nothing done.'
1001 print 'Nothing done.'
1004 return
1002 return
1005
1003
1006 if 's' in opts: # Soft reset
1004 if 's' in opts: # Soft reset
1007 user_ns = self.shell.user_ns
1005 user_ns = self.shell.user_ns
1008 for i in self.magic_who_ls():
1006 for i in self.magic_who_ls():
1009 del(user_ns[i])
1007 del(user_ns[i])
1010
1008
1011 else: # Hard reset
1009 else: # Hard reset
1012 self.shell.reset(new_session = False)
1010 self.shell.reset(new_session = False)
1013
1011
1014
1012
1015
1013
1016 def magic_reset_selective(self, parameter_s=''):
1014 def magic_reset_selective(self, parameter_s=''):
1017 """Resets the namespace by removing names defined by the user.
1015 """Resets the namespace by removing names defined by the user.
1018
1016
1019 Input/Output history are left around in case you need them.
1017 Input/Output history are left around in case you need them.
1020
1018
1021 %reset_selective [-f] regex
1019 %reset_selective [-f] regex
1022
1020
1023 No action is taken if regex is not included
1021 No action is taken if regex is not included
1024
1022
1025 Options
1023 Options
1026 -f : force reset without asking for confirmation.
1024 -f : force reset without asking for confirmation.
1027
1025
1028 Examples
1026 Examples
1029 --------
1027 --------
1030
1028
1031 We first fully reset the namespace so your output looks identical to
1029 We first fully reset the namespace so your output looks identical to
1032 this example for pedagogical reasons; in practice you do not need a
1030 this example for pedagogical reasons; in practice you do not need a
1033 full reset.
1031 full reset.
1034
1032
1035 In [1]: %reset -f
1033 In [1]: %reset -f
1036
1034
1037 Now, with a clean namespace we can make a few variables and use
1035 Now, with a clean namespace we can make a few variables and use
1038 %reset_selective to only delete names that match our regexp:
1036 %reset_selective to only delete names that match our regexp:
1039
1037
1040 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1038 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1041
1039
1042 In [3]: who_ls
1040 In [3]: who_ls
1043 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1041 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1044
1042
1045 In [4]: %reset_selective -f b[2-3]m
1043 In [4]: %reset_selective -f b[2-3]m
1046
1044
1047 In [5]: who_ls
1045 In [5]: who_ls
1048 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1046 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1049
1047
1050 In [6]: %reset_selective -f d
1048 In [6]: %reset_selective -f d
1051
1049
1052 In [7]: who_ls
1050 In [7]: who_ls
1053 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1051 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1054
1052
1055 In [8]: %reset_selective -f c
1053 In [8]: %reset_selective -f c
1056
1054
1057 In [9]: who_ls
1055 In [9]: who_ls
1058 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1056 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1059
1057
1060 In [10]: %reset_selective -f b
1058 In [10]: %reset_selective -f b
1061
1059
1062 In [11]: who_ls
1060 In [11]: who_ls
1063 Out[11]: ['a']
1061 Out[11]: ['a']
1064 """
1062 """
1065
1063
1066 opts, regex = self.parse_options(parameter_s,'f')
1064 opts, regex = self.parse_options(parameter_s,'f')
1067
1065
1068 if opts.has_key('f'):
1066 if opts.has_key('f'):
1069 ans = True
1067 ans = True
1070 else:
1068 else:
1071 ans = self.shell.ask_yes_no(
1069 ans = self.shell.ask_yes_no(
1072 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1070 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1073 if not ans:
1071 if not ans:
1074 print 'Nothing done.'
1072 print 'Nothing done.'
1075 return
1073 return
1076 user_ns = self.shell.user_ns
1074 user_ns = self.shell.user_ns
1077 if not regex:
1075 if not regex:
1078 print 'No regex pattern specified. Nothing done.'
1076 print 'No regex pattern specified. Nothing done.'
1079 return
1077 return
1080 else:
1078 else:
1081 try:
1079 try:
1082 m = re.compile(regex)
1080 m = re.compile(regex)
1083 except TypeError:
1081 except TypeError:
1084 raise TypeError('regex must be a string or compiled pattern')
1082 raise TypeError('regex must be a string or compiled pattern')
1085 for i in self.magic_who_ls():
1083 for i in self.magic_who_ls():
1086 if m.search(i):
1084 if m.search(i):
1087 del(user_ns[i])
1085 del(user_ns[i])
1088
1086
1089 def magic_xdel(self, parameter_s=''):
1087 def magic_xdel(self, parameter_s=''):
1090 """Delete a variable, trying to clear it from anywhere that
1088 """Delete a variable, trying to clear it from anywhere that
1091 IPython's machinery has references to it. By default, this uses
1089 IPython's machinery has references to it. By default, this uses
1092 the identity of the named object in the user namespace to remove
1090 the identity of the named object in the user namespace to remove
1093 references held under other names. The object is also removed
1091 references held under other names. The object is also removed
1094 from the output history.
1092 from the output history.
1095
1093
1096 Options
1094 Options
1097 -n : Delete the specified name from all namespaces, without
1095 -n : Delete the specified name from all namespaces, without
1098 checking their identity.
1096 checking their identity.
1099 """
1097 """
1100 opts, varname = self.parse_options(parameter_s,'n')
1098 opts, varname = self.parse_options(parameter_s,'n')
1101 try:
1099 try:
1102 self.shell.del_var(varname, ('n' in opts))
1100 self.shell.del_var(varname, ('n' in opts))
1103 except (NameError, ValueError) as e:
1101 except (NameError, ValueError) as e:
1104 print type(e).__name__ +": "+ str(e)
1102 print type(e).__name__ +": "+ str(e)
1105
1103
1106 def magic_logstart(self,parameter_s=''):
1104 def magic_logstart(self,parameter_s=''):
1107 """Start logging anywhere in a session.
1105 """Start logging anywhere in a session.
1108
1106
1109 %logstart [-o|-r|-t] [log_name [log_mode]]
1107 %logstart [-o|-r|-t] [log_name [log_mode]]
1110
1108
1111 If no name is given, it defaults to a file named 'ipython_log.py' in your
1109 If no name is given, it defaults to a file named 'ipython_log.py' in your
1112 current directory, in 'rotate' mode (see below).
1110 current directory, in 'rotate' mode (see below).
1113
1111
1114 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1112 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1115 history up to that point and then continues logging.
1113 history up to that point and then continues logging.
1116
1114
1117 %logstart takes a second optional parameter: logging mode. This can be one
1115 %logstart takes a second optional parameter: logging mode. This can be one
1118 of (note that the modes are given unquoted):\\
1116 of (note that the modes are given unquoted):\\
1119 append: well, that says it.\\
1117 append: well, that says it.\\
1120 backup: rename (if exists) to name~ and start name.\\
1118 backup: rename (if exists) to name~ and start name.\\
1121 global: single logfile in your home dir, appended to.\\
1119 global: single logfile in your home dir, appended to.\\
1122 over : overwrite existing log.\\
1120 over : overwrite existing log.\\
1123 rotate: create rotating logs name.1~, name.2~, etc.
1121 rotate: create rotating logs name.1~, name.2~, etc.
1124
1122
1125 Options:
1123 Options:
1126
1124
1127 -o: log also IPython's output. In this mode, all commands which
1125 -o: log also IPython's output. In this mode, all commands which
1128 generate an Out[NN] prompt are recorded to the logfile, right after
1126 generate an Out[NN] prompt are recorded to the logfile, right after
1129 their corresponding input line. The output lines are always
1127 their corresponding input line. The output lines are always
1130 prepended with a '#[Out]# ' marker, so that the log remains valid
1128 prepended with a '#[Out]# ' marker, so that the log remains valid
1131 Python code.
1129 Python code.
1132
1130
1133 Since this marker is always the same, filtering only the output from
1131 Since this marker is always the same, filtering only the output from
1134 a log is very easy, using for example a simple awk call:
1132 a log is very easy, using for example a simple awk call:
1135
1133
1136 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1134 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1137
1135
1138 -r: log 'raw' input. Normally, IPython's logs contain the processed
1136 -r: log 'raw' input. Normally, IPython's logs contain the processed
1139 input, so that user lines are logged in their final form, converted
1137 input, so that user lines are logged in their final form, converted
1140 into valid Python. For example, %Exit is logged as
1138 into valid Python. For example, %Exit is logged as
1141 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1139 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1142 exactly as typed, with no transformations applied.
1140 exactly as typed, with no transformations applied.
1143
1141
1144 -t: put timestamps before each input line logged (these are put in
1142 -t: put timestamps before each input line logged (these are put in
1145 comments)."""
1143 comments)."""
1146
1144
1147 opts,par = self.parse_options(parameter_s,'ort')
1145 opts,par = self.parse_options(parameter_s,'ort')
1148 log_output = 'o' in opts
1146 log_output = 'o' in opts
1149 log_raw_input = 'r' in opts
1147 log_raw_input = 'r' in opts
1150 timestamp = 't' in opts
1148 timestamp = 't' in opts
1151
1149
1152 logger = self.shell.logger
1150 logger = self.shell.logger
1153
1151
1154 # if no args are given, the defaults set in the logger constructor by
1152 # if no args are given, the defaults set in the logger constructor by
1155 # ipytohn remain valid
1153 # ipytohn remain valid
1156 if par:
1154 if par:
1157 try:
1155 try:
1158 logfname,logmode = par.split()
1156 logfname,logmode = par.split()
1159 except:
1157 except:
1160 logfname = par
1158 logfname = par
1161 logmode = 'backup'
1159 logmode = 'backup'
1162 else:
1160 else:
1163 logfname = logger.logfname
1161 logfname = logger.logfname
1164 logmode = logger.logmode
1162 logmode = logger.logmode
1165 # put logfname into rc struct as if it had been called on the command
1163 # put logfname into rc struct as if it had been called on the command
1166 # line, so it ends up saved in the log header Save it in case we need
1164 # line, so it ends up saved in the log header Save it in case we need
1167 # to restore it...
1165 # to restore it...
1168 old_logfile = self.shell.logfile
1166 old_logfile = self.shell.logfile
1169 if logfname:
1167 if logfname:
1170 logfname = os.path.expanduser(logfname)
1168 logfname = os.path.expanduser(logfname)
1171 self.shell.logfile = logfname
1169 self.shell.logfile = logfname
1172
1170
1173 loghead = '# IPython log file\n\n'
1171 loghead = '# IPython log file\n\n'
1174 try:
1172 try:
1175 started = logger.logstart(logfname,loghead,logmode,
1173 started = logger.logstart(logfname,loghead,logmode,
1176 log_output,timestamp,log_raw_input)
1174 log_output,timestamp,log_raw_input)
1177 except:
1175 except:
1178 self.shell.logfile = old_logfile
1176 self.shell.logfile = old_logfile
1179 warn("Couldn't start log: %s" % sys.exc_info()[1])
1177 warn("Couldn't start log: %s" % sys.exc_info()[1])
1180 else:
1178 else:
1181 # log input history up to this point, optionally interleaving
1179 # log input history up to this point, optionally interleaving
1182 # output if requested
1180 # output if requested
1183
1181
1184 if timestamp:
1182 if timestamp:
1185 # disable timestamping for the previous history, since we've
1183 # disable timestamping for the previous history, since we've
1186 # lost those already (no time machine here).
1184 # lost those already (no time machine here).
1187 logger.timestamp = False
1185 logger.timestamp = False
1188
1186
1189 if log_raw_input:
1187 if log_raw_input:
1190 input_hist = self.shell.history_manager.input_hist_raw
1188 input_hist = self.shell.history_manager.input_hist_raw
1191 else:
1189 else:
1192 input_hist = self.shell.history_manager.input_hist_parsed
1190 input_hist = self.shell.history_manager.input_hist_parsed
1193
1191
1194 if log_output:
1192 if log_output:
1195 log_write = logger.log_write
1193 log_write = logger.log_write
1196 output_hist = self.shell.history_manager.output_hist
1194 output_hist = self.shell.history_manager.output_hist
1197 for n in range(1,len(input_hist)-1):
1195 for n in range(1,len(input_hist)-1):
1198 log_write(input_hist[n].rstrip() + '\n')
1196 log_write(input_hist[n].rstrip() + '\n')
1199 if n in output_hist:
1197 if n in output_hist:
1200 log_write(repr(output_hist[n]),'output')
1198 log_write(repr(output_hist[n]),'output')
1201 else:
1199 else:
1202 logger.log_write('\n'.join(input_hist[1:]))
1200 logger.log_write('\n'.join(input_hist[1:]))
1203 logger.log_write('\n')
1201 logger.log_write('\n')
1204 if timestamp:
1202 if timestamp:
1205 # re-enable timestamping
1203 # re-enable timestamping
1206 logger.timestamp = True
1204 logger.timestamp = True
1207
1205
1208 print ('Activating auto-logging. '
1206 print ('Activating auto-logging. '
1209 'Current session state plus future input saved.')
1207 'Current session state plus future input saved.')
1210 logger.logstate()
1208 logger.logstate()
1211
1209
1212 def magic_logstop(self,parameter_s=''):
1210 def magic_logstop(self,parameter_s=''):
1213 """Fully stop logging and close log file.
1211 """Fully stop logging and close log file.
1214
1212
1215 In order to start logging again, a new %logstart call needs to be made,
1213 In order to start logging again, a new %logstart call needs to be made,
1216 possibly (though not necessarily) with a new filename, mode and other
1214 possibly (though not necessarily) with a new filename, mode and other
1217 options."""
1215 options."""
1218 self.logger.logstop()
1216 self.logger.logstop()
1219
1217
1220 def magic_logoff(self,parameter_s=''):
1218 def magic_logoff(self,parameter_s=''):
1221 """Temporarily stop logging.
1219 """Temporarily stop logging.
1222
1220
1223 You must have previously started logging."""
1221 You must have previously started logging."""
1224 self.shell.logger.switch_log(0)
1222 self.shell.logger.switch_log(0)
1225
1223
1226 def magic_logon(self,parameter_s=''):
1224 def magic_logon(self,parameter_s=''):
1227 """Restart logging.
1225 """Restart logging.
1228
1226
1229 This function is for restarting logging which you've temporarily
1227 This function is for restarting logging which you've temporarily
1230 stopped with %logoff. For starting logging for the first time, you
1228 stopped with %logoff. For starting logging for the first time, you
1231 must use the %logstart function, which allows you to specify an
1229 must use the %logstart function, which allows you to specify an
1232 optional log filename."""
1230 optional log filename."""
1233
1231
1234 self.shell.logger.switch_log(1)
1232 self.shell.logger.switch_log(1)
1235
1233
1236 def magic_logstate(self,parameter_s=''):
1234 def magic_logstate(self,parameter_s=''):
1237 """Print the status of the logging system."""
1235 """Print the status of the logging system."""
1238
1236
1239 self.shell.logger.logstate()
1237 self.shell.logger.logstate()
1240
1238
1241 def magic_pdb(self, parameter_s=''):
1239 def magic_pdb(self, parameter_s=''):
1242 """Control the automatic calling of the pdb interactive debugger.
1240 """Control the automatic calling of the pdb interactive debugger.
1243
1241
1244 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1242 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1245 argument it works as a toggle.
1243 argument it works as a toggle.
1246
1244
1247 When an exception is triggered, IPython can optionally call the
1245 When an exception is triggered, IPython can optionally call the
1248 interactive pdb debugger after the traceback printout. %pdb toggles
1246 interactive pdb debugger after the traceback printout. %pdb toggles
1249 this feature on and off.
1247 this feature on and off.
1250
1248
1251 The initial state of this feature is set in your ipythonrc
1249 The initial state of this feature is set in your ipythonrc
1252 configuration file (the variable is called 'pdb').
1250 configuration file (the variable is called 'pdb').
1253
1251
1254 If you want to just activate the debugger AFTER an exception has fired,
1252 If you want to just activate the debugger AFTER an exception has fired,
1255 without having to type '%pdb on' and rerunning your code, you can use
1253 without having to type '%pdb on' and rerunning your code, you can use
1256 the %debug magic."""
1254 the %debug magic."""
1257
1255
1258 par = parameter_s.strip().lower()
1256 par = parameter_s.strip().lower()
1259
1257
1260 if par:
1258 if par:
1261 try:
1259 try:
1262 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1260 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1263 except KeyError:
1261 except KeyError:
1264 print ('Incorrect argument. Use on/1, off/0, '
1262 print ('Incorrect argument. Use on/1, off/0, '
1265 'or nothing for a toggle.')
1263 'or nothing for a toggle.')
1266 return
1264 return
1267 else:
1265 else:
1268 # toggle
1266 # toggle
1269 new_pdb = not self.shell.call_pdb
1267 new_pdb = not self.shell.call_pdb
1270
1268
1271 # set on the shell
1269 # set on the shell
1272 self.shell.call_pdb = new_pdb
1270 self.shell.call_pdb = new_pdb
1273 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1271 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1274
1272
1275 def magic_debug(self, parameter_s=''):
1273 def magic_debug(self, parameter_s=''):
1276 """Activate the interactive debugger in post-mortem mode.
1274 """Activate the interactive debugger in post-mortem mode.
1277
1275
1278 If an exception has just occurred, this lets you inspect its stack
1276 If an exception has just occurred, this lets you inspect its stack
1279 frames interactively. Note that this will always work only on the last
1277 frames interactively. Note that this will always work only on the last
1280 traceback that occurred, so you must call this quickly after an
1278 traceback that occurred, so you must call this quickly after an
1281 exception that you wish to inspect has fired, because if another one
1279 exception that you wish to inspect has fired, because if another one
1282 occurs, it clobbers the previous one.
1280 occurs, it clobbers the previous one.
1283
1281
1284 If you want IPython to automatically do this on every exception, see
1282 If you want IPython to automatically do this on every exception, see
1285 the %pdb magic for more details.
1283 the %pdb magic for more details.
1286 """
1284 """
1287 self.shell.debugger(force=True)
1285 self.shell.debugger(force=True)
1288
1286
1289 @skip_doctest
1287 @skip_doctest
1290 def magic_prun(self, parameter_s ='',user_mode=1,
1288 def magic_prun(self, parameter_s ='',user_mode=1,
1291 opts=None,arg_lst=None,prog_ns=None):
1289 opts=None,arg_lst=None,prog_ns=None):
1292
1290
1293 """Run a statement through the python code profiler.
1291 """Run a statement through the python code profiler.
1294
1292
1295 Usage:
1293 Usage:
1296 %prun [options] statement
1294 %prun [options] statement
1297
1295
1298 The given statement (which doesn't require quote marks) is run via the
1296 The given statement (which doesn't require quote marks) is run via the
1299 python profiler in a manner similar to the profile.run() function.
1297 python profiler in a manner similar to the profile.run() function.
1300 Namespaces are internally managed to work correctly; profile.run
1298 Namespaces are internally managed to work correctly; profile.run
1301 cannot be used in IPython because it makes certain assumptions about
1299 cannot be used in IPython because it makes certain assumptions about
1302 namespaces which do not hold under IPython.
1300 namespaces which do not hold under IPython.
1303
1301
1304 Options:
1302 Options:
1305
1303
1306 -l <limit>: you can place restrictions on what or how much of the
1304 -l <limit>: you can place restrictions on what or how much of the
1307 profile gets printed. The limit value can be:
1305 profile gets printed. The limit value can be:
1308
1306
1309 * A string: only information for function names containing this string
1307 * A string: only information for function names containing this string
1310 is printed.
1308 is printed.
1311
1309
1312 * An integer: only these many lines are printed.
1310 * An integer: only these many lines are printed.
1313
1311
1314 * A float (between 0 and 1): this fraction of the report is printed
1312 * A float (between 0 and 1): this fraction of the report is printed
1315 (for example, use a limit of 0.4 to see the topmost 40% only).
1313 (for example, use a limit of 0.4 to see the topmost 40% only).
1316
1314
1317 You can combine several limits with repeated use of the option. For
1315 You can combine several limits with repeated use of the option. For
1318 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1316 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1319 information about class constructors.
1317 information about class constructors.
1320
1318
1321 -r: return the pstats.Stats object generated by the profiling. This
1319 -r: return the pstats.Stats object generated by the profiling. This
1322 object has all the information about the profile in it, and you can
1320 object has all the information about the profile in it, and you can
1323 later use it for further analysis or in other functions.
1321 later use it for further analysis or in other functions.
1324
1322
1325 -s <key>: sort profile by given key. You can provide more than one key
1323 -s <key>: sort profile by given key. You can provide more than one key
1326 by using the option several times: '-s key1 -s key2 -s key3...'. The
1324 by using the option several times: '-s key1 -s key2 -s key3...'. The
1327 default sorting key is 'time'.
1325 default sorting key is 'time'.
1328
1326
1329 The following is copied verbatim from the profile documentation
1327 The following is copied verbatim from the profile documentation
1330 referenced below:
1328 referenced below:
1331
1329
1332 When more than one key is provided, additional keys are used as
1330 When more than one key is provided, additional keys are used as
1333 secondary criteria when the there is equality in all keys selected
1331 secondary criteria when the there is equality in all keys selected
1334 before them.
1332 before them.
1335
1333
1336 Abbreviations can be used for any key names, as long as the
1334 Abbreviations can be used for any key names, as long as the
1337 abbreviation is unambiguous. The following are the keys currently
1335 abbreviation is unambiguous. The following are the keys currently
1338 defined:
1336 defined:
1339
1337
1340 Valid Arg Meaning
1338 Valid Arg Meaning
1341 "calls" call count
1339 "calls" call count
1342 "cumulative" cumulative time
1340 "cumulative" cumulative time
1343 "file" file name
1341 "file" file name
1344 "module" file name
1342 "module" file name
1345 "pcalls" primitive call count
1343 "pcalls" primitive call count
1346 "line" line number
1344 "line" line number
1347 "name" function name
1345 "name" function name
1348 "nfl" name/file/line
1346 "nfl" name/file/line
1349 "stdname" standard name
1347 "stdname" standard name
1350 "time" internal time
1348 "time" internal time
1351
1349
1352 Note that all sorts on statistics are in descending order (placing
1350 Note that all sorts on statistics are in descending order (placing
1353 most time consuming items first), where as name, file, and line number
1351 most time consuming items first), where as name, file, and line number
1354 searches are in ascending order (i.e., alphabetical). The subtle
1352 searches are in ascending order (i.e., alphabetical). The subtle
1355 distinction between "nfl" and "stdname" is that the standard name is a
1353 distinction between "nfl" and "stdname" is that the standard name is a
1356 sort of the name as printed, which means that the embedded line
1354 sort of the name as printed, which means that the embedded line
1357 numbers get compared in an odd way. For example, lines 3, 20, and 40
1355 numbers get compared in an odd way. For example, lines 3, 20, and 40
1358 would (if the file names were the same) appear in the string order
1356 would (if the file names were the same) appear in the string order
1359 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1357 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1360 line numbers. In fact, sort_stats("nfl") is the same as
1358 line numbers. In fact, sort_stats("nfl") is the same as
1361 sort_stats("name", "file", "line").
1359 sort_stats("name", "file", "line").
1362
1360
1363 -T <filename>: save profile results as shown on screen to a text
1361 -T <filename>: save profile results as shown on screen to a text
1364 file. The profile is still shown on screen.
1362 file. The profile is still shown on screen.
1365
1363
1366 -D <filename>: save (via dump_stats) profile statistics to given
1364 -D <filename>: save (via dump_stats) profile statistics to given
1367 filename. This data is in a format understod by the pstats module, and
1365 filename. This data is in a format understod by the pstats module, and
1368 is generated by a call to the dump_stats() method of profile
1366 is generated by a call to the dump_stats() method of profile
1369 objects. The profile is still shown on screen.
1367 objects. The profile is still shown on screen.
1370
1368
1371 If you want to run complete programs under the profiler's control, use
1369 If you want to run complete programs under the profiler's control, use
1372 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1370 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1373 contains profiler specific options as described here.
1371 contains profiler specific options as described here.
1374
1372
1375 You can read the complete documentation for the profile module with::
1373 You can read the complete documentation for the profile module with::
1376
1374
1377 In [1]: import profile; profile.help()
1375 In [1]: import profile; profile.help()
1378 """
1376 """
1379
1377
1380 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1378 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1381 # protect user quote marks
1379 # protect user quote marks
1382 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1380 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1383
1381
1384 if user_mode: # regular user call
1382 if user_mode: # regular user call
1385 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1383 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1386 list_all=1)
1384 list_all=1)
1387 namespace = self.shell.user_ns
1385 namespace = self.shell.user_ns
1388 else: # called to run a program by %run -p
1386 else: # called to run a program by %run -p
1389 try:
1387 try:
1390 filename = get_py_filename(arg_lst[0])
1388 filename = get_py_filename(arg_lst[0])
1391 except IOError,msg:
1389 except IOError,msg:
1392 error(msg)
1390 error(msg)
1393 return
1391 return
1394
1392
1395 arg_str = 'execfile(filename,prog_ns)'
1393 arg_str = 'execfile(filename,prog_ns)'
1396 namespace = locals()
1394 namespace = locals()
1397
1395
1398 opts.merge(opts_def)
1396 opts.merge(opts_def)
1399
1397
1400 prof = profile.Profile()
1398 prof = profile.Profile()
1401 try:
1399 try:
1402 prof = prof.runctx(arg_str,namespace,namespace)
1400 prof = prof.runctx(arg_str,namespace,namespace)
1403 sys_exit = ''
1401 sys_exit = ''
1404 except SystemExit:
1402 except SystemExit:
1405 sys_exit = """*** SystemExit exception caught in code being profiled."""
1403 sys_exit = """*** SystemExit exception caught in code being profiled."""
1406
1404
1407 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1405 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1408
1406
1409 lims = opts.l
1407 lims = opts.l
1410 if lims:
1408 if lims:
1411 lims = [] # rebuild lims with ints/floats/strings
1409 lims = [] # rebuild lims with ints/floats/strings
1412 for lim in opts.l:
1410 for lim in opts.l:
1413 try:
1411 try:
1414 lims.append(int(lim))
1412 lims.append(int(lim))
1415 except ValueError:
1413 except ValueError:
1416 try:
1414 try:
1417 lims.append(float(lim))
1415 lims.append(float(lim))
1418 except ValueError:
1416 except ValueError:
1419 lims.append(lim)
1417 lims.append(lim)
1420
1418
1421 # Trap output.
1419 # Trap output.
1422 stdout_trap = StringIO()
1420 stdout_trap = StringIO()
1423
1421
1424 if hasattr(stats,'stream'):
1422 if hasattr(stats,'stream'):
1425 # In newer versions of python, the stats object has a 'stream'
1423 # In newer versions of python, the stats object has a 'stream'
1426 # attribute to write into.
1424 # attribute to write into.
1427 stats.stream = stdout_trap
1425 stats.stream = stdout_trap
1428 stats.print_stats(*lims)
1426 stats.print_stats(*lims)
1429 else:
1427 else:
1430 # For older versions, we manually redirect stdout during printing
1428 # For older versions, we manually redirect stdout during printing
1431 sys_stdout = sys.stdout
1429 sys_stdout = sys.stdout
1432 try:
1430 try:
1433 sys.stdout = stdout_trap
1431 sys.stdout = stdout_trap
1434 stats.print_stats(*lims)
1432 stats.print_stats(*lims)
1435 finally:
1433 finally:
1436 sys.stdout = sys_stdout
1434 sys.stdout = sys_stdout
1437
1435
1438 output = stdout_trap.getvalue()
1436 output = stdout_trap.getvalue()
1439 output = output.rstrip()
1437 output = output.rstrip()
1440
1438
1441 page.page(output)
1439 page.page(output)
1442 print sys_exit,
1440 print sys_exit,
1443
1441
1444 dump_file = opts.D[0]
1442 dump_file = opts.D[0]
1445 text_file = opts.T[0]
1443 text_file = opts.T[0]
1446 if dump_file:
1444 if dump_file:
1447 prof.dump_stats(dump_file)
1445 prof.dump_stats(dump_file)
1448 print '\n*** Profile stats marshalled to file',\
1446 print '\n*** Profile stats marshalled to file',\
1449 `dump_file`+'.',sys_exit
1447 `dump_file`+'.',sys_exit
1450 if text_file:
1448 if text_file:
1451 pfile = file(text_file,'w')
1449 pfile = file(text_file,'w')
1452 pfile.write(output)
1450 pfile.write(output)
1453 pfile.close()
1451 pfile.close()
1454 print '\n*** Profile printout saved to text file',\
1452 print '\n*** Profile printout saved to text file',\
1455 `text_file`+'.',sys_exit
1453 `text_file`+'.',sys_exit
1456
1454
1457 if opts.has_key('r'):
1455 if opts.has_key('r'):
1458 return stats
1456 return stats
1459 else:
1457 else:
1460 return None
1458 return None
1461
1459
1462 @skip_doctest
1460 @skip_doctest
1463 def magic_run(self, parameter_s ='',runner=None,
1461 def magic_run(self, parameter_s ='',runner=None,
1464 file_finder=get_py_filename):
1462 file_finder=get_py_filename):
1465 """Run the named file inside IPython as a program.
1463 """Run the named file inside IPython as a program.
1466
1464
1467 Usage:\\
1465 Usage:\\
1468 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1466 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1469
1467
1470 Parameters after the filename are passed as command-line arguments to
1468 Parameters after the filename are passed as command-line arguments to
1471 the program (put in sys.argv). Then, control returns to IPython's
1469 the program (put in sys.argv). Then, control returns to IPython's
1472 prompt.
1470 prompt.
1473
1471
1474 This is similar to running at a system prompt:\\
1472 This is similar to running at a system prompt:\\
1475 $ python file args\\
1473 $ python file args\\
1476 but with the advantage of giving you IPython's tracebacks, and of
1474 but with the advantage of giving you IPython's tracebacks, and of
1477 loading all variables into your interactive namespace for further use
1475 loading all variables into your interactive namespace for further use
1478 (unless -p is used, see below).
1476 (unless -p is used, see below).
1479
1477
1480 The file is executed in a namespace initially consisting only of
1478 The file is executed in a namespace initially consisting only of
1481 __name__=='__main__' and sys.argv constructed as indicated. It thus
1479 __name__=='__main__' and sys.argv constructed as indicated. It thus
1482 sees its environment as if it were being run as a stand-alone program
1480 sees its environment as if it were being run as a stand-alone program
1483 (except for sharing global objects such as previously imported
1481 (except for sharing global objects such as previously imported
1484 modules). But after execution, the IPython interactive namespace gets
1482 modules). But after execution, the IPython interactive namespace gets
1485 updated with all variables defined in the program (except for __name__
1483 updated with all variables defined in the program (except for __name__
1486 and sys.argv). This allows for very convenient loading of code for
1484 and sys.argv). This allows for very convenient loading of code for
1487 interactive work, while giving each program a 'clean sheet' to run in.
1485 interactive work, while giving each program a 'clean sheet' to run in.
1488
1486
1489 Options:
1487 Options:
1490
1488
1491 -n: __name__ is NOT set to '__main__', but to the running file's name
1489 -n: __name__ is NOT set to '__main__', but to the running file's name
1492 without extension (as python does under import). This allows running
1490 without extension (as python does under import). This allows running
1493 scripts and reloading the definitions in them without calling code
1491 scripts and reloading the definitions in them without calling code
1494 protected by an ' if __name__ == "__main__" ' clause.
1492 protected by an ' if __name__ == "__main__" ' clause.
1495
1493
1496 -i: run the file in IPython's namespace instead of an empty one. This
1494 -i: run the file in IPython's namespace instead of an empty one. This
1497 is useful if you are experimenting with code written in a text editor
1495 is useful if you are experimenting with code written in a text editor
1498 which depends on variables defined interactively.
1496 which depends on variables defined interactively.
1499
1497
1500 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1498 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1501 being run. This is particularly useful if IPython is being used to
1499 being run. This is particularly useful if IPython is being used to
1502 run unittests, which always exit with a sys.exit() call. In such
1500 run unittests, which always exit with a sys.exit() call. In such
1503 cases you are interested in the output of the test results, not in
1501 cases you are interested in the output of the test results, not in
1504 seeing a traceback of the unittest module.
1502 seeing a traceback of the unittest module.
1505
1503
1506 -t: print timing information at the end of the run. IPython will give
1504 -t: print timing information at the end of the run. IPython will give
1507 you an estimated CPU time consumption for your script, which under
1505 you an estimated CPU time consumption for your script, which under
1508 Unix uses the resource module to avoid the wraparound problems of
1506 Unix uses the resource module to avoid the wraparound problems of
1509 time.clock(). Under Unix, an estimate of time spent on system tasks
1507 time.clock(). Under Unix, an estimate of time spent on system tasks
1510 is also given (for Windows platforms this is reported as 0.0).
1508 is also given (for Windows platforms this is reported as 0.0).
1511
1509
1512 If -t is given, an additional -N<N> option can be given, where <N>
1510 If -t is given, an additional -N<N> option can be given, where <N>
1513 must be an integer indicating how many times you want the script to
1511 must be an integer indicating how many times you want the script to
1514 run. The final timing report will include total and per run results.
1512 run. The final timing report will include total and per run results.
1515
1513
1516 For example (testing the script uniq_stable.py):
1514 For example (testing the script uniq_stable.py):
1517
1515
1518 In [1]: run -t uniq_stable
1516 In [1]: run -t uniq_stable
1519
1517
1520 IPython CPU timings (estimated):\\
1518 IPython CPU timings (estimated):\\
1521 User : 0.19597 s.\\
1519 User : 0.19597 s.\\
1522 System: 0.0 s.\\
1520 System: 0.0 s.\\
1523
1521
1524 In [2]: run -t -N5 uniq_stable
1522 In [2]: run -t -N5 uniq_stable
1525
1523
1526 IPython CPU timings (estimated):\\
1524 IPython CPU timings (estimated):\\
1527 Total runs performed: 5\\
1525 Total runs performed: 5\\
1528 Times : Total Per run\\
1526 Times : Total Per run\\
1529 User : 0.910862 s, 0.1821724 s.\\
1527 User : 0.910862 s, 0.1821724 s.\\
1530 System: 0.0 s, 0.0 s.
1528 System: 0.0 s, 0.0 s.
1531
1529
1532 -d: run your program under the control of pdb, the Python debugger.
1530 -d: run your program under the control of pdb, the Python debugger.
1533 This allows you to execute your program step by step, watch variables,
1531 This allows you to execute your program step by step, watch variables,
1534 etc. Internally, what IPython does is similar to calling:
1532 etc. Internally, what IPython does is similar to calling:
1535
1533
1536 pdb.run('execfile("YOURFILENAME")')
1534 pdb.run('execfile("YOURFILENAME")')
1537
1535
1538 with a breakpoint set on line 1 of your file. You can change the line
1536 with a breakpoint set on line 1 of your file. You can change the line
1539 number for this automatic breakpoint to be <N> by using the -bN option
1537 number for this automatic breakpoint to be <N> by using the -bN option
1540 (where N must be an integer). For example:
1538 (where N must be an integer). For example:
1541
1539
1542 %run -d -b40 myscript
1540 %run -d -b40 myscript
1543
1541
1544 will set the first breakpoint at line 40 in myscript.py. Note that
1542 will set the first breakpoint at line 40 in myscript.py. Note that
1545 the first breakpoint must be set on a line which actually does
1543 the first breakpoint must be set on a line which actually does
1546 something (not a comment or docstring) for it to stop execution.
1544 something (not a comment or docstring) for it to stop execution.
1547
1545
1548 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1546 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1549 first enter 'c' (without qoutes) to start execution up to the first
1547 first enter 'c' (without qoutes) to start execution up to the first
1550 breakpoint.
1548 breakpoint.
1551
1549
1552 Entering 'help' gives information about the use of the debugger. You
1550 Entering 'help' gives information about the use of the debugger. You
1553 can easily see pdb's full documentation with "import pdb;pdb.help()"
1551 can easily see pdb's full documentation with "import pdb;pdb.help()"
1554 at a prompt.
1552 at a prompt.
1555
1553
1556 -p: run program under the control of the Python profiler module (which
1554 -p: run program under the control of the Python profiler module (which
1557 prints a detailed report of execution times, function calls, etc).
1555 prints a detailed report of execution times, function calls, etc).
1558
1556
1559 You can pass other options after -p which affect the behavior of the
1557 You can pass other options after -p which affect the behavior of the
1560 profiler itself. See the docs for %prun for details.
1558 profiler itself. See the docs for %prun for details.
1561
1559
1562 In this mode, the program's variables do NOT propagate back to the
1560 In this mode, the program's variables do NOT propagate back to the
1563 IPython interactive namespace (because they remain in the namespace
1561 IPython interactive namespace (because they remain in the namespace
1564 where the profiler executes them).
1562 where the profiler executes them).
1565
1563
1566 Internally this triggers a call to %prun, see its documentation for
1564 Internally this triggers a call to %prun, see its documentation for
1567 details on the options available specifically for profiling.
1565 details on the options available specifically for profiling.
1568
1566
1569 There is one special usage for which the text above doesn't apply:
1567 There is one special usage for which the text above doesn't apply:
1570 if the filename ends with .ipy, the file is run as ipython script,
1568 if the filename ends with .ipy, the file is run as ipython script,
1571 just as if the commands were written on IPython prompt.
1569 just as if the commands were written on IPython prompt.
1572 """
1570 """
1573
1571
1574 # get arguments and set sys.argv for program to be run.
1572 # get arguments and set sys.argv for program to be run.
1575 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1573 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1576 mode='list',list_all=1)
1574 mode='list',list_all=1)
1577
1575
1578 try:
1576 try:
1579 filename = file_finder(arg_lst[0])
1577 filename = file_finder(arg_lst[0])
1580 except IndexError:
1578 except IndexError:
1581 warn('you must provide at least a filename.')
1579 warn('you must provide at least a filename.')
1582 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1580 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1583 return
1581 return
1584 except IOError,msg:
1582 except IOError,msg:
1585 error(msg)
1583 error(msg)
1586 return
1584 return
1587
1585
1588 if filename.lower().endswith('.ipy'):
1586 if filename.lower().endswith('.ipy'):
1589 self.shell.safe_execfile_ipy(filename)
1587 self.shell.safe_execfile_ipy(filename)
1590 return
1588 return
1591
1589
1592 # Control the response to exit() calls made by the script being run
1590 # Control the response to exit() calls made by the script being run
1593 exit_ignore = opts.has_key('e')
1591 exit_ignore = opts.has_key('e')
1594
1592
1595 # Make sure that the running script gets a proper sys.argv as if it
1593 # Make sure that the running script gets a proper sys.argv as if it
1596 # were run from a system shell.
1594 # were run from a system shell.
1597 save_argv = sys.argv # save it for later restoring
1595 save_argv = sys.argv # save it for later restoring
1598 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1596 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1599
1597
1600 if opts.has_key('i'):
1598 if opts.has_key('i'):
1601 # Run in user's interactive namespace
1599 # Run in user's interactive namespace
1602 prog_ns = self.shell.user_ns
1600 prog_ns = self.shell.user_ns
1603 __name__save = self.shell.user_ns['__name__']
1601 __name__save = self.shell.user_ns['__name__']
1604 prog_ns['__name__'] = '__main__'
1602 prog_ns['__name__'] = '__main__'
1605 main_mod = self.shell.new_main_mod(prog_ns)
1603 main_mod = self.shell.new_main_mod(prog_ns)
1606 else:
1604 else:
1607 # Run in a fresh, empty namespace
1605 # Run in a fresh, empty namespace
1608 if opts.has_key('n'):
1606 if opts.has_key('n'):
1609 name = os.path.splitext(os.path.basename(filename))[0]
1607 name = os.path.splitext(os.path.basename(filename))[0]
1610 else:
1608 else:
1611 name = '__main__'
1609 name = '__main__'
1612
1610
1613 main_mod = self.shell.new_main_mod()
1611 main_mod = self.shell.new_main_mod()
1614 prog_ns = main_mod.__dict__
1612 prog_ns = main_mod.__dict__
1615 prog_ns['__name__'] = name
1613 prog_ns['__name__'] = name
1616
1614
1617 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1615 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1618 # set the __file__ global in the script's namespace
1616 # set the __file__ global in the script's namespace
1619 prog_ns['__file__'] = filename
1617 prog_ns['__file__'] = filename
1620
1618
1621 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1619 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1622 # that, if we overwrite __main__, we replace it at the end
1620 # that, if we overwrite __main__, we replace it at the end
1623 main_mod_name = prog_ns['__name__']
1621 main_mod_name = prog_ns['__name__']
1624
1622
1625 if main_mod_name == '__main__':
1623 if main_mod_name == '__main__':
1626 restore_main = sys.modules['__main__']
1624 restore_main = sys.modules['__main__']
1627 else:
1625 else:
1628 restore_main = False
1626 restore_main = False
1629
1627
1630 # This needs to be undone at the end to prevent holding references to
1628 # This needs to be undone at the end to prevent holding references to
1631 # every single object ever created.
1629 # every single object ever created.
1632 sys.modules[main_mod_name] = main_mod
1630 sys.modules[main_mod_name] = main_mod
1633
1631
1634 try:
1632 try:
1635 stats = None
1633 stats = None
1636 with self.readline_no_record:
1634 with self.readline_no_record:
1637 if opts.has_key('p'):
1635 if opts.has_key('p'):
1638 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1636 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1639 else:
1637 else:
1640 if opts.has_key('d'):
1638 if opts.has_key('d'):
1641 deb = debugger.Pdb(self.shell.colors)
1639 deb = debugger.Pdb(self.shell.colors)
1642 # reset Breakpoint state, which is moronically kept
1640 # reset Breakpoint state, which is moronically kept
1643 # in a class
1641 # in a class
1644 bdb.Breakpoint.next = 1
1642 bdb.Breakpoint.next = 1
1645 bdb.Breakpoint.bplist = {}
1643 bdb.Breakpoint.bplist = {}
1646 bdb.Breakpoint.bpbynumber = [None]
1644 bdb.Breakpoint.bpbynumber = [None]
1647 # Set an initial breakpoint to stop execution
1645 # Set an initial breakpoint to stop execution
1648 maxtries = 10
1646 maxtries = 10
1649 bp = int(opts.get('b',[1])[0])
1647 bp = int(opts.get('b',[1])[0])
1650 checkline = deb.checkline(filename,bp)
1648 checkline = deb.checkline(filename,bp)
1651 if not checkline:
1649 if not checkline:
1652 for bp in range(bp+1,bp+maxtries+1):
1650 for bp in range(bp+1,bp+maxtries+1):
1653 if deb.checkline(filename,bp):
1651 if deb.checkline(filename,bp):
1654 break
1652 break
1655 else:
1653 else:
1656 msg = ("\nI failed to find a valid line to set "
1654 msg = ("\nI failed to find a valid line to set "
1657 "a breakpoint\n"
1655 "a breakpoint\n"
1658 "after trying up to line: %s.\n"
1656 "after trying up to line: %s.\n"
1659 "Please set a valid breakpoint manually "
1657 "Please set a valid breakpoint manually "
1660 "with the -b option." % bp)
1658 "with the -b option." % bp)
1661 error(msg)
1659 error(msg)
1662 return
1660 return
1663 # if we find a good linenumber, set the breakpoint
1661 # if we find a good linenumber, set the breakpoint
1664 deb.do_break('%s:%s' % (filename,bp))
1662 deb.do_break('%s:%s' % (filename,bp))
1665 # Start file run
1663 # Start file run
1666 print "NOTE: Enter 'c' at the",
1664 print "NOTE: Enter 'c' at the",
1667 print "%s prompt to start your script." % deb.prompt
1665 print "%s prompt to start your script." % deb.prompt
1668 try:
1666 try:
1669 deb.run('execfile("%s")' % filename,prog_ns)
1667 deb.run('execfile("%s")' % filename,prog_ns)
1670
1668
1671 except:
1669 except:
1672 etype, value, tb = sys.exc_info()
1670 etype, value, tb = sys.exc_info()
1673 # Skip three frames in the traceback: the %run one,
1671 # Skip three frames in the traceback: the %run one,
1674 # one inside bdb.py, and the command-line typed by the
1672 # one inside bdb.py, and the command-line typed by the
1675 # user (run by exec in pdb itself).
1673 # user (run by exec in pdb itself).
1676 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1674 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1677 else:
1675 else:
1678 if runner is None:
1676 if runner is None:
1679 runner = self.shell.safe_execfile
1677 runner = self.shell.safe_execfile
1680 if opts.has_key('t'):
1678 if opts.has_key('t'):
1681 # timed execution
1679 # timed execution
1682 try:
1680 try:
1683 nruns = int(opts['N'][0])
1681 nruns = int(opts['N'][0])
1684 if nruns < 1:
1682 if nruns < 1:
1685 error('Number of runs must be >=1')
1683 error('Number of runs must be >=1')
1686 return
1684 return
1687 except (KeyError):
1685 except (KeyError):
1688 nruns = 1
1686 nruns = 1
1689 if nruns == 1:
1687 if nruns == 1:
1690 t0 = clock2()
1688 t0 = clock2()
1691 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1692 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1693 t1 = clock2()
1691 t1 = clock2()
1694 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1695 t_sys = t1[1]-t0[1]
1693 t_sys = t1[1]-t0[1]
1696 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1697 print " User : %10s s." % t_usr
1695 print " User : %10s s." % t_usr
1698 print " System: %10s s." % t_sys
1696 print " System: %10s s." % t_sys
1699 else:
1697 else:
1700 runs = range(nruns)
1698 runs = range(nruns)
1701 t0 = clock2()
1699 t0 = clock2()
1702 for nr in runs:
1700 for nr in runs:
1703 runner(filename,prog_ns,prog_ns,
1701 runner(filename,prog_ns,prog_ns,
1704 exit_ignore=exit_ignore)
1702 exit_ignore=exit_ignore)
1705 t1 = clock2()
1703 t1 = clock2()
1706 t_usr = t1[0]-t0[0]
1704 t_usr = t1[0]-t0[0]
1707 t_sys = t1[1]-t0[1]
1705 t_sys = t1[1]-t0[1]
1708 print "\nIPython CPU timings (estimated):"
1706 print "\nIPython CPU timings (estimated):"
1709 print "Total runs performed:",nruns
1707 print "Total runs performed:",nruns
1710 print " Times : %10s %10s" % ('Total','Per run')
1708 print " Times : %10s %10s" % ('Total','Per run')
1711 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1709 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1712 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1710 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1713
1711
1714 else:
1712 else:
1715 # regular execution
1713 # regular execution
1716 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1714 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1717
1715
1718 if opts.has_key('i'):
1716 if opts.has_key('i'):
1719 self.shell.user_ns['__name__'] = __name__save
1717 self.shell.user_ns['__name__'] = __name__save
1720 else:
1718 else:
1721 # The shell MUST hold a reference to prog_ns so after %run
1719 # The shell MUST hold a reference to prog_ns so after %run
1722 # exits, the python deletion mechanism doesn't zero it out
1720 # exits, the python deletion mechanism doesn't zero it out
1723 # (leaving dangling references).
1721 # (leaving dangling references).
1724 self.shell.cache_main_mod(prog_ns,filename)
1722 self.shell.cache_main_mod(prog_ns,filename)
1725 # update IPython interactive namespace
1723 # update IPython interactive namespace
1726
1724
1727 # Some forms of read errors on the file may mean the
1725 # Some forms of read errors on the file may mean the
1728 # __name__ key was never set; using pop we don't have to
1726 # __name__ key was never set; using pop we don't have to
1729 # worry about a possible KeyError.
1727 # worry about a possible KeyError.
1730 prog_ns.pop('__name__', None)
1728 prog_ns.pop('__name__', None)
1731
1729
1732 self.shell.user_ns.update(prog_ns)
1730 self.shell.user_ns.update(prog_ns)
1733 finally:
1731 finally:
1734 # It's a bit of a mystery why, but __builtins__ can change from
1732 # It's a bit of a mystery why, but __builtins__ can change from
1735 # being a module to becoming a dict missing some key data after
1733 # being a module to becoming a dict missing some key data after
1736 # %run. As best I can see, this is NOT something IPython is doing
1734 # %run. As best I can see, this is NOT something IPython is doing
1737 # at all, and similar problems have been reported before:
1735 # at all, and similar problems have been reported before:
1738 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1736 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1739 # Since this seems to be done by the interpreter itself, the best
1737 # Since this seems to be done by the interpreter itself, the best
1740 # we can do is to at least restore __builtins__ for the user on
1738 # we can do is to at least restore __builtins__ for the user on
1741 # exit.
1739 # exit.
1742 self.shell.user_ns['__builtins__'] = __builtin__
1740 self.shell.user_ns['__builtins__'] = __builtin__
1743
1741
1744 # Ensure key global structures are restored
1742 # Ensure key global structures are restored
1745 sys.argv = save_argv
1743 sys.argv = save_argv
1746 if restore_main:
1744 if restore_main:
1747 sys.modules['__main__'] = restore_main
1745 sys.modules['__main__'] = restore_main
1748 else:
1746 else:
1749 # Remove from sys.modules the reference to main_mod we'd
1747 # Remove from sys.modules the reference to main_mod we'd
1750 # added. Otherwise it will trap references to objects
1748 # added. Otherwise it will trap references to objects
1751 # contained therein.
1749 # contained therein.
1752 del sys.modules[main_mod_name]
1750 del sys.modules[main_mod_name]
1753
1751
1754 return stats
1752 return stats
1755
1753
1756 @skip_doctest
1754 @skip_doctest
1757 def magic_timeit(self, parameter_s =''):
1755 def magic_timeit(self, parameter_s =''):
1758 """Time execution of a Python statement or expression
1756 """Time execution of a Python statement or expression
1759
1757
1760 Usage:\\
1758 Usage:\\
1761 %timeit [-n<N> -r<R> [-t|-c]] statement
1759 %timeit [-n<N> -r<R> [-t|-c]] statement
1762
1760
1763 Time execution of a Python statement or expression using the timeit
1761 Time execution of a Python statement or expression using the timeit
1764 module.
1762 module.
1765
1763
1766 Options:
1764 Options:
1767 -n<N>: execute the given statement <N> times in a loop. If this value
1765 -n<N>: execute the given statement <N> times in a loop. If this value
1768 is not given, a fitting value is chosen.
1766 is not given, a fitting value is chosen.
1769
1767
1770 -r<R>: repeat the loop iteration <R> times and take the best result.
1768 -r<R>: repeat the loop iteration <R> times and take the best result.
1771 Default: 3
1769 Default: 3
1772
1770
1773 -t: use time.time to measure the time, which is the default on Unix.
1771 -t: use time.time to measure the time, which is the default on Unix.
1774 This function measures wall time.
1772 This function measures wall time.
1775
1773
1776 -c: use time.clock to measure the time, which is the default on
1774 -c: use time.clock to measure the time, which is the default on
1777 Windows and measures wall time. On Unix, resource.getrusage is used
1775 Windows and measures wall time. On Unix, resource.getrusage is used
1778 instead and returns the CPU user time.
1776 instead and returns the CPU user time.
1779
1777
1780 -p<P>: use a precision of <P> digits to display the timing result.
1778 -p<P>: use a precision of <P> digits to display the timing result.
1781 Default: 3
1779 Default: 3
1782
1780
1783
1781
1784 Examples:
1782 Examples:
1785
1783
1786 In [1]: %timeit pass
1784 In [1]: %timeit pass
1787 10000000 loops, best of 3: 53.3 ns per loop
1785 10000000 loops, best of 3: 53.3 ns per loop
1788
1786
1789 In [2]: u = None
1787 In [2]: u = None
1790
1788
1791 In [3]: %timeit u is None
1789 In [3]: %timeit u is None
1792 10000000 loops, best of 3: 184 ns per loop
1790 10000000 loops, best of 3: 184 ns per loop
1793
1791
1794 In [4]: %timeit -r 4 u == None
1792 In [4]: %timeit -r 4 u == None
1795 1000000 loops, best of 4: 242 ns per loop
1793 1000000 loops, best of 4: 242 ns per loop
1796
1794
1797 In [5]: import time
1795 In [5]: import time
1798
1796
1799 In [6]: %timeit -n1 time.sleep(2)
1797 In [6]: %timeit -n1 time.sleep(2)
1800 1 loops, best of 3: 2 s per loop
1798 1 loops, best of 3: 2 s per loop
1801
1799
1802
1800
1803 The times reported by %timeit will be slightly higher than those
1801 The times reported by %timeit will be slightly higher than those
1804 reported by the timeit.py script when variables are accessed. This is
1802 reported by the timeit.py script when variables are accessed. This is
1805 due to the fact that %timeit executes the statement in the namespace
1803 due to the fact that %timeit executes the statement in the namespace
1806 of the shell, compared with timeit.py, which uses a single setup
1804 of the shell, compared with timeit.py, which uses a single setup
1807 statement to import function or create variables. Generally, the bias
1805 statement to import function or create variables. Generally, the bias
1808 does not matter as long as results from timeit.py are not mixed with
1806 does not matter as long as results from timeit.py are not mixed with
1809 those from %timeit."""
1807 those from %timeit."""
1810
1808
1811 import timeit
1809 import timeit
1812 import math
1810 import math
1813
1811
1814 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1812 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1815 # certain terminals. Until we figure out a robust way of
1813 # certain terminals. Until we figure out a robust way of
1816 # auto-detecting if the terminal can deal with it, use plain 'us' for
1814 # auto-detecting if the terminal can deal with it, use plain 'us' for
1817 # microseconds. I am really NOT happy about disabling the proper
1815 # microseconds. I am really NOT happy about disabling the proper
1818 # 'micro' prefix, but crashing is worse... If anyone knows what the
1816 # 'micro' prefix, but crashing is worse... If anyone knows what the
1819 # right solution for this is, I'm all ears...
1817 # right solution for this is, I'm all ears...
1820 #
1818 #
1821 # Note: using
1819 # Note: using
1822 #
1820 #
1823 # s = u'\xb5'
1821 # s = u'\xb5'
1824 # s.encode(sys.getdefaultencoding())
1822 # s.encode(sys.getdefaultencoding())
1825 #
1823 #
1826 # is not sufficient, as I've seen terminals where that fails but
1824 # is not sufficient, as I've seen terminals where that fails but
1827 # print s
1825 # print s
1828 #
1826 #
1829 # succeeds
1827 # succeeds
1830 #
1828 #
1831 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1829 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1832
1830
1833 #units = [u"s", u"ms",u'\xb5',"ns"]
1831 #units = [u"s", u"ms",u'\xb5',"ns"]
1834 units = [u"s", u"ms",u'us',"ns"]
1832 units = [u"s", u"ms",u'us',"ns"]
1835
1833
1836 scaling = [1, 1e3, 1e6, 1e9]
1834 scaling = [1, 1e3, 1e6, 1e9]
1837
1835
1838 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1836 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1839 posix=False)
1837 posix=False)
1840 if stmt == "":
1838 if stmt == "":
1841 return
1839 return
1842 timefunc = timeit.default_timer
1840 timefunc = timeit.default_timer
1843 number = int(getattr(opts, "n", 0))
1841 number = int(getattr(opts, "n", 0))
1844 repeat = int(getattr(opts, "r", timeit.default_repeat))
1842 repeat = int(getattr(opts, "r", timeit.default_repeat))
1845 precision = int(getattr(opts, "p", 3))
1843 precision = int(getattr(opts, "p", 3))
1846 if hasattr(opts, "t"):
1844 if hasattr(opts, "t"):
1847 timefunc = time.time
1845 timefunc = time.time
1848 if hasattr(opts, "c"):
1846 if hasattr(opts, "c"):
1849 timefunc = clock
1847 timefunc = clock
1850
1848
1851 timer = timeit.Timer(timer=timefunc)
1849 timer = timeit.Timer(timer=timefunc)
1852 # this code has tight coupling to the inner workings of timeit.Timer,
1850 # this code has tight coupling to the inner workings of timeit.Timer,
1853 # but is there a better way to achieve that the code stmt has access
1851 # but is there a better way to achieve that the code stmt has access
1854 # to the shell namespace?
1852 # to the shell namespace?
1855
1853
1856 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1854 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1857 'setup': "pass"}
1855 'setup': "pass"}
1858 # Track compilation time so it can be reported if too long
1856 # Track compilation time so it can be reported if too long
1859 # Minimum time above which compilation time will be reported
1857 # Minimum time above which compilation time will be reported
1860 tc_min = 0.1
1858 tc_min = 0.1
1861
1859
1862 t0 = clock()
1860 t0 = clock()
1863 code = compile(src, "<magic-timeit>", "exec")
1861 code = compile(src, "<magic-timeit>", "exec")
1864 tc = clock()-t0
1862 tc = clock()-t0
1865
1863
1866 ns = {}
1864 ns = {}
1867 exec code in self.shell.user_ns, ns
1865 exec code in self.shell.user_ns, ns
1868 timer.inner = ns["inner"]
1866 timer.inner = ns["inner"]
1869
1867
1870 if number == 0:
1868 if number == 0:
1871 # determine number so that 0.2 <= total time < 2.0
1869 # determine number so that 0.2 <= total time < 2.0
1872 number = 1
1870 number = 1
1873 for i in range(1, 10):
1871 for i in range(1, 10):
1874 if timer.timeit(number) >= 0.2:
1872 if timer.timeit(number) >= 0.2:
1875 break
1873 break
1876 number *= 10
1874 number *= 10
1877
1875
1878 best = min(timer.repeat(repeat, number)) / number
1876 best = min(timer.repeat(repeat, number)) / number
1879
1877
1880 if best > 0.0 and best < 1000.0:
1878 if best > 0.0 and best < 1000.0:
1881 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1879 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1882 elif best >= 1000.0:
1880 elif best >= 1000.0:
1883 order = 0
1881 order = 0
1884 else:
1882 else:
1885 order = 3
1883 order = 3
1886 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1884 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1887 precision,
1885 precision,
1888 best * scaling[order],
1886 best * scaling[order],
1889 units[order])
1887 units[order])
1890 if tc > tc_min:
1888 if tc > tc_min:
1891 print "Compiler time: %.2f s" % tc
1889 print "Compiler time: %.2f s" % tc
1892
1890
1893 @skip_doctest
1891 @skip_doctest
1894 @needs_local_scope
1892 @needs_local_scope
1895 def magic_time(self,parameter_s = ''):
1893 def magic_time(self,parameter_s = ''):
1896 """Time execution of a Python statement or expression.
1894 """Time execution of a Python statement or expression.
1897
1895
1898 The CPU and wall clock times are printed, and the value of the
1896 The CPU and wall clock times are printed, and the value of the
1899 expression (if any) is returned. Note that under Win32, system time
1897 expression (if any) is returned. Note that under Win32, system time
1900 is always reported as 0, since it can not be measured.
1898 is always reported as 0, since it can not be measured.
1901
1899
1902 This function provides very basic timing functionality. In Python
1900 This function provides very basic timing functionality. In Python
1903 2.3, the timeit module offers more control and sophistication, so this
1901 2.3, the timeit module offers more control and sophistication, so this
1904 could be rewritten to use it (patches welcome).
1902 could be rewritten to use it (patches welcome).
1905
1903
1906 Some examples:
1904 Some examples:
1907
1905
1908 In [1]: time 2**128
1906 In [1]: time 2**128
1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1910 Wall time: 0.00
1908 Wall time: 0.00
1911 Out[1]: 340282366920938463463374607431768211456L
1909 Out[1]: 340282366920938463463374607431768211456L
1912
1910
1913 In [2]: n = 1000000
1911 In [2]: n = 1000000
1914
1912
1915 In [3]: time sum(range(n))
1913 In [3]: time sum(range(n))
1916 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1914 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1917 Wall time: 1.37
1915 Wall time: 1.37
1918 Out[3]: 499999500000L
1916 Out[3]: 499999500000L
1919
1917
1920 In [4]: time print 'hello world'
1918 In [4]: time print 'hello world'
1921 hello world
1919 hello world
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 Wall time: 0.00
1921 Wall time: 0.00
1924
1922
1925 Note that the time needed by Python to compile the given expression
1923 Note that the time needed by Python to compile the given expression
1926 will be reported if it is more than 0.1s. In this example, the
1924 will be reported if it is more than 0.1s. In this example, the
1927 actual exponentiation is done by Python at compilation time, so while
1925 actual exponentiation is done by Python at compilation time, so while
1928 the expression can take a noticeable amount of time to compute, that
1926 the expression can take a noticeable amount of time to compute, that
1929 time is purely due to the compilation:
1927 time is purely due to the compilation:
1930
1928
1931 In [5]: time 3**9999;
1929 In [5]: time 3**9999;
1932 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1933 Wall time: 0.00 s
1931 Wall time: 0.00 s
1934
1932
1935 In [6]: time 3**999999;
1933 In [6]: time 3**999999;
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1934 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1937 Wall time: 0.00 s
1935 Wall time: 0.00 s
1938 Compiler : 0.78 s
1936 Compiler : 0.78 s
1939 """
1937 """
1940
1938
1941 # fail immediately if the given expression can't be compiled
1939 # fail immediately if the given expression can't be compiled
1942
1940
1943 expr = self.shell.prefilter(parameter_s,False)
1941 expr = self.shell.prefilter(parameter_s,False)
1944
1942
1945 # Minimum time above which compilation time will be reported
1943 # Minimum time above which compilation time will be reported
1946 tc_min = 0.1
1944 tc_min = 0.1
1947
1945
1948 try:
1946 try:
1949 mode = 'eval'
1947 mode = 'eval'
1950 t0 = clock()
1948 t0 = clock()
1951 code = compile(expr,'<timed eval>',mode)
1949 code = compile(expr,'<timed eval>',mode)
1952 tc = clock()-t0
1950 tc = clock()-t0
1953 except SyntaxError:
1951 except SyntaxError:
1954 mode = 'exec'
1952 mode = 'exec'
1955 t0 = clock()
1953 t0 = clock()
1956 code = compile(expr,'<timed exec>',mode)
1954 code = compile(expr,'<timed exec>',mode)
1957 tc = clock()-t0
1955 tc = clock()-t0
1958 # skew measurement as little as possible
1956 # skew measurement as little as possible
1959 glob = self.shell.user_ns
1957 glob = self.shell.user_ns
1960 locs = self._magic_locals
1958 locs = self._magic_locals
1961 clk = clock2
1959 clk = clock2
1962 wtime = time.time
1960 wtime = time.time
1963 # time execution
1961 # time execution
1964 wall_st = wtime()
1962 wall_st = wtime()
1965 if mode=='eval':
1963 if mode=='eval':
1966 st = clk()
1964 st = clk()
1967 out = eval(code, glob, locs)
1965 out = eval(code, glob, locs)
1968 end = clk()
1966 end = clk()
1969 else:
1967 else:
1970 st = clk()
1968 st = clk()
1971 exec code in glob, locs
1969 exec code in glob, locs
1972 end = clk()
1970 end = clk()
1973 out = None
1971 out = None
1974 wall_end = wtime()
1972 wall_end = wtime()
1975 # Compute actual times and report
1973 # Compute actual times and report
1976 wall_time = wall_end-wall_st
1974 wall_time = wall_end-wall_st
1977 cpu_user = end[0]-st[0]
1975 cpu_user = end[0]-st[0]
1978 cpu_sys = end[1]-st[1]
1976 cpu_sys = end[1]-st[1]
1979 cpu_tot = cpu_user+cpu_sys
1977 cpu_tot = cpu_user+cpu_sys
1980 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1978 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1981 (cpu_user,cpu_sys,cpu_tot)
1979 (cpu_user,cpu_sys,cpu_tot)
1982 print "Wall time: %.2f s" % wall_time
1980 print "Wall time: %.2f s" % wall_time
1983 if tc > tc_min:
1981 if tc > tc_min:
1984 print "Compiler : %.2f s" % tc
1982 print "Compiler : %.2f s" % tc
1985 return out
1983 return out
1986
1984
1987 @skip_doctest
1985 @skip_doctest
1988 def magic_macro(self,parameter_s = ''):
1986 def magic_macro(self,parameter_s = ''):
1989 """Define a macro for future re-execution. It accepts ranges of history,
1987 """Define a macro for future re-execution. It accepts ranges of history,
1990 filenames or string objects.
1988 filenames or string objects.
1991
1989
1992 Usage:\\
1990 Usage:\\
1993 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1991 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1994
1992
1995 Options:
1993 Options:
1996
1994
1997 -r: use 'raw' input. By default, the 'processed' history is used,
1995 -r: use 'raw' input. By default, the 'processed' history is used,
1998 so that magics are loaded in their transformed version to valid
1996 so that magics are loaded in their transformed version to valid
1999 Python. If this option is given, the raw input as typed as the
1997 Python. If this option is given, the raw input as typed as the
2000 command line is used instead.
1998 command line is used instead.
2001
1999
2002 This will define a global variable called `name` which is a string
2000 This will define a global variable called `name` which is a string
2003 made of joining the slices and lines you specify (n1,n2,... numbers
2001 made of joining the slices and lines you specify (n1,n2,... numbers
2004 above) from your input history into a single string. This variable
2002 above) from your input history into a single string. This variable
2005 acts like an automatic function which re-executes those lines as if
2003 acts like an automatic function which re-executes those lines as if
2006 you had typed them. You just type 'name' at the prompt and the code
2004 you had typed them. You just type 'name' at the prompt and the code
2007 executes.
2005 executes.
2008
2006
2009 The syntax for indicating input ranges is described in %history.
2007 The syntax for indicating input ranges is described in %history.
2010
2008
2011 Note: as a 'hidden' feature, you can also use traditional python slice
2009 Note: as a 'hidden' feature, you can also use traditional python slice
2012 notation, where N:M means numbers N through M-1.
2010 notation, where N:M means numbers N through M-1.
2013
2011
2014 For example, if your history contains (%hist prints it):
2012 For example, if your history contains (%hist prints it):
2015
2013
2016 44: x=1
2014 44: x=1
2017 45: y=3
2015 45: y=3
2018 46: z=x+y
2016 46: z=x+y
2019 47: print x
2017 47: print x
2020 48: a=5
2018 48: a=5
2021 49: print 'x',x,'y',y
2019 49: print 'x',x,'y',y
2022
2020
2023 you can create a macro with lines 44 through 47 (included) and line 49
2021 you can create a macro with lines 44 through 47 (included) and line 49
2024 called my_macro with:
2022 called my_macro with:
2025
2023
2026 In [55]: %macro my_macro 44-47 49
2024 In [55]: %macro my_macro 44-47 49
2027
2025
2028 Now, typing `my_macro` (without quotes) will re-execute all this code
2026 Now, typing `my_macro` (without quotes) will re-execute all this code
2029 in one pass.
2027 in one pass.
2030
2028
2031 You don't need to give the line-numbers in order, and any given line
2029 You don't need to give the line-numbers in order, and any given line
2032 number can appear multiple times. You can assemble macros with any
2030 number can appear multiple times. You can assemble macros with any
2033 lines from your input history in any order.
2031 lines from your input history in any order.
2034
2032
2035 The macro is a simple object which holds its value in an attribute,
2033 The macro is a simple object which holds its value in an attribute,
2036 but IPython's display system checks for macros and executes them as
2034 but IPython's display system checks for macros and executes them as
2037 code instead of printing them when you type their name.
2035 code instead of printing them when you type their name.
2038
2036
2039 You can view a macro's contents by explicitly printing it with:
2037 You can view a macro's contents by explicitly printing it with:
2040
2038
2041 'print macro_name'.
2039 'print macro_name'.
2042
2040
2043 """
2041 """
2044 opts,args = self.parse_options(parameter_s,'r',mode='list')
2042 opts,args = self.parse_options(parameter_s,'r',mode='list')
2045 if not args: # List existing macros
2043 if not args: # List existing macros
2046 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2044 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2047 isinstance(v, Macro))
2045 isinstance(v, Macro))
2048 if len(args) == 1:
2046 if len(args) == 1:
2049 raise UsageError(
2047 raise UsageError(
2050 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2048 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2051 name, codefrom = args[0], " ".join(args[1:])
2049 name, codefrom = args[0], " ".join(args[1:])
2052
2050
2053 #print 'rng',ranges # dbg
2051 #print 'rng',ranges # dbg
2054 try:
2052 try:
2055 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2053 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2056 except (ValueError, TypeError) as e:
2054 except (ValueError, TypeError) as e:
2057 print e.args[0]
2055 print e.args[0]
2058 return
2056 return
2059 macro = Macro(lines)
2057 macro = Macro(lines)
2060 self.shell.define_macro(name, macro)
2058 self.shell.define_macro(name, macro)
2061 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2062 print '=== Macro contents: ==='
2060 print '=== Macro contents: ==='
2063 print macro,
2061 print macro,
2064
2062
2065 def magic_save(self,parameter_s = ''):
2063 def magic_save(self,parameter_s = ''):
2066 """Save a set of lines or a macro to a given filename.
2064 """Save a set of lines or a macro to a given filename.
2067
2065
2068 Usage:\\
2066 Usage:\\
2069 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2067 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2070
2068
2071 Options:
2069 Options:
2072
2070
2073 -r: use 'raw' input. By default, the 'processed' history is used,
2071 -r: use 'raw' input. By default, the 'processed' history is used,
2074 so that magics are loaded in their transformed version to valid
2072 so that magics are loaded in their transformed version to valid
2075 Python. If this option is given, the raw input as typed as the
2073 Python. If this option is given, the raw input as typed as the
2076 command line is used instead.
2074 command line is used instead.
2077
2075
2078 This function uses the same syntax as %history for input ranges,
2076 This function uses the same syntax as %history for input ranges,
2079 then saves the lines to the filename you specify.
2077 then saves the lines to the filename you specify.
2080
2078
2081 It adds a '.py' extension to the file if you don't do so yourself, and
2079 It adds a '.py' extension to the file if you don't do so yourself, and
2082 it asks for confirmation before overwriting existing files."""
2080 it asks for confirmation before overwriting existing files."""
2083
2081
2084 opts,args = self.parse_options(parameter_s,'r',mode='list')
2082 opts,args = self.parse_options(parameter_s,'r',mode='list')
2085 fname, codefrom = args[0], " ".join(args[1:])
2083 fname, codefrom = args[0], " ".join(args[1:])
2086 if not fname.endswith('.py'):
2084 if not fname.endswith('.py'):
2087 fname += '.py'
2085 fname += '.py'
2088 if os.path.isfile(fname):
2086 if os.path.isfile(fname):
2089 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2087 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2090 if ans.lower() not in ['y','yes']:
2088 if ans.lower() not in ['y','yes']:
2091 print 'Operation cancelled.'
2089 print 'Operation cancelled.'
2092 return
2090 return
2093 try:
2091 try:
2094 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2092 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2095 except (TypeError, ValueError) as e:
2093 except (TypeError, ValueError) as e:
2096 print e.args[0]
2094 print e.args[0]
2097 return
2095 return
2098 if isinstance(cmds, unicode):
2096 if isinstance(cmds, unicode):
2099 cmds = cmds.encode("utf-8")
2097 cmds = cmds.encode("utf-8")
2100 with open(fname,'w') as f:
2098 with open(fname,'w') as f:
2101 f.write("# coding: utf-8\n")
2099 f.write("# coding: utf-8\n")
2102 f.write(cmds)
2100 f.write(cmds)
2103 print 'The following commands were written to file `%s`:' % fname
2101 print 'The following commands were written to file `%s`:' % fname
2104 print cmds
2102 print cmds
2105
2103
2106 def magic_pastebin(self, parameter_s = ''):
2104 def magic_pastebin(self, parameter_s = ''):
2107 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2105 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2108 try:
2106 try:
2109 code = self.shell.find_user_code(parameter_s)
2107 code = self.shell.find_user_code(parameter_s)
2110 except (ValueError, TypeError) as e:
2108 except (ValueError, TypeError) as e:
2111 print e.args[0]
2109 print e.args[0]
2112 return
2110 return
2113 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2111 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2114 id = pbserver.pastes.newPaste("python", code)
2112 id = pbserver.pastes.newPaste("python", code)
2115 return "http://paste.pocoo.org/show/" + id
2113 return "http://paste.pocoo.org/show/" + id
2116
2114
2117 def magic_loadpy(self, arg_s):
2115 def magic_loadpy(self, arg_s):
2118 """Load a .py python script into the GUI console.
2116 """Load a .py python script into the GUI console.
2119
2117
2120 This magic command can either take a local filename or a url::
2118 This magic command can either take a local filename or a url::
2121
2119
2122 %loadpy myscript.py
2120 %loadpy myscript.py
2123 %loadpy http://www.example.com/myscript.py
2121 %loadpy http://www.example.com/myscript.py
2124 """
2122 """
2125 if not arg_s.endswith('.py'):
2123 if not arg_s.endswith('.py'):
2126 raise ValueError('%%load only works with .py files: %s' % arg_s)
2124 raise ValueError('%%load only works with .py files: %s' % arg_s)
2127 if arg_s.startswith('http'):
2125 if arg_s.startswith('http'):
2128 import urllib2
2126 import urllib2
2129 response = urllib2.urlopen(arg_s)
2127 response = urllib2.urlopen(arg_s)
2130 content = response.read()
2128 content = response.read()
2131 else:
2129 else:
2132 content = open(arg_s).read()
2130 content = open(arg_s).read()
2133 self.set_next_input(content)
2131 self.set_next_input(content)
2134
2132
2135 def _find_edit_target(self, args, opts, last_call):
2133 def _find_edit_target(self, args, opts, last_call):
2136 """Utility method used by magic_edit to find what to edit."""
2134 """Utility method used by magic_edit to find what to edit."""
2137
2135
2138 def make_filename(arg):
2136 def make_filename(arg):
2139 "Make a filename from the given args"
2137 "Make a filename from the given args"
2140 try:
2138 try:
2141 filename = get_py_filename(arg)
2139 filename = get_py_filename(arg)
2142 except IOError:
2140 except IOError:
2143 # If it ends with .py but doesn't already exist, assume we want
2141 # If it ends with .py but doesn't already exist, assume we want
2144 # a new file.
2142 # a new file.
2145 if args.endswith('.py'):
2143 if args.endswith('.py'):
2146 filename = arg
2144 filename = arg
2147 else:
2145 else:
2148 filename = None
2146 filename = None
2149 return filename
2147 return filename
2150
2148
2151 # Set a few locals from the options for convenience:
2149 # Set a few locals from the options for convenience:
2152 opts_prev = 'p' in opts
2150 opts_prev = 'p' in opts
2153 opts_raw = 'r' in opts
2151 opts_raw = 'r' in opts
2154
2152
2155 # custom exceptions
2153 # custom exceptions
2156 class DataIsObject(Exception): pass
2154 class DataIsObject(Exception): pass
2157
2155
2158 # Default line number value
2156 # Default line number value
2159 lineno = opts.get('n',None)
2157 lineno = opts.get('n',None)
2160
2158
2161 if opts_prev:
2159 if opts_prev:
2162 args = '_%s' % last_call[0]
2160 args = '_%s' % last_call[0]
2163 if not self.shell.user_ns.has_key(args):
2161 if not self.shell.user_ns.has_key(args):
2164 args = last_call[1]
2162 args = last_call[1]
2165
2163
2166 # use last_call to remember the state of the previous call, but don't
2164 # use last_call to remember the state of the previous call, but don't
2167 # let it be clobbered by successive '-p' calls.
2165 # let it be clobbered by successive '-p' calls.
2168 try:
2166 try:
2169 last_call[0] = self.shell.displayhook.prompt_count
2167 last_call[0] = self.shell.displayhook.prompt_count
2170 if not opts_prev:
2168 if not opts_prev:
2171 last_call[1] = parameter_s
2169 last_call[1] = parameter_s
2172 except:
2170 except:
2173 pass
2171 pass
2174
2172
2175 # by default this is done with temp files, except when the given
2173 # by default this is done with temp files, except when the given
2176 # arg is a filename
2174 # arg is a filename
2177 use_temp = True
2175 use_temp = True
2178
2176
2179 data = ''
2177 data = ''
2180
2178
2181 # First, see if the arguments should be a filename.
2179 # First, see if the arguments should be a filename.
2182 filename = make_filename(args)
2180 filename = make_filename(args)
2183 if filename:
2181 if filename:
2184 use_temp = False
2182 use_temp = False
2185 elif args:
2183 elif args:
2186 # Mode where user specifies ranges of lines, like in %macro.
2184 # Mode where user specifies ranges of lines, like in %macro.
2187 data = self.extract_input_lines(args, opts_raw)
2185 data = self.extract_input_lines(args, opts_raw)
2188 if not data:
2186 if not data:
2189 try:
2187 try:
2190 # Load the parameter given as a variable. If not a string,
2188 # Load the parameter given as a variable. If not a string,
2191 # process it as an object instead (below)
2189 # process it as an object instead (below)
2192
2190
2193 #print '*** args',args,'type',type(args) # dbg
2191 #print '*** args',args,'type',type(args) # dbg
2194 data = eval(args, self.shell.user_ns)
2192 data = eval(args, self.shell.user_ns)
2195 if not isinstance(data, basestring):
2193 if not isinstance(data, basestring):
2196 raise DataIsObject
2194 raise DataIsObject
2197
2195
2198 except (NameError,SyntaxError):
2196 except (NameError,SyntaxError):
2199 # given argument is not a variable, try as a filename
2197 # given argument is not a variable, try as a filename
2200 filename = make_filename(args)
2198 filename = make_filename(args)
2201 if filename is None:
2199 if filename is None:
2202 warn("Argument given (%s) can't be found as a variable "
2200 warn("Argument given (%s) can't be found as a variable "
2203 "or as a filename." % args)
2201 "or as a filename." % args)
2204 return
2202 return
2205 use_temp = False
2203 use_temp = False
2206
2204
2207 except DataIsObject:
2205 except DataIsObject:
2208 # macros have a special edit function
2206 # macros have a special edit function
2209 if isinstance(data, Macro):
2207 if isinstance(data, Macro):
2210 raise MacroToEdit(data)
2208 raise MacroToEdit(data)
2211
2209
2212 # For objects, try to edit the file where they are defined
2210 # For objects, try to edit the file where they are defined
2213 try:
2211 try:
2214 filename = inspect.getabsfile(data)
2212 filename = inspect.getabsfile(data)
2215 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2213 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2216 # class created by %edit? Try to find source
2214 # class created by %edit? Try to find source
2217 # by looking for method definitions instead, the
2215 # by looking for method definitions instead, the
2218 # __module__ in those classes is FakeModule.
2216 # __module__ in those classes is FakeModule.
2219 attrs = [getattr(data, aname) for aname in dir(data)]
2217 attrs = [getattr(data, aname) for aname in dir(data)]
2220 for attr in attrs:
2218 for attr in attrs:
2221 if not inspect.ismethod(attr):
2219 if not inspect.ismethod(attr):
2222 continue
2220 continue
2223 filename = inspect.getabsfile(attr)
2221 filename = inspect.getabsfile(attr)
2224 if filename and 'fakemodule' not in filename.lower():
2222 if filename and 'fakemodule' not in filename.lower():
2225 # change the attribute to be the edit target instead
2223 # change the attribute to be the edit target instead
2226 data = attr
2224 data = attr
2227 break
2225 break
2228
2226
2229 datafile = 1
2227 datafile = 1
2230 except TypeError:
2228 except TypeError:
2231 filename = make_filename(args)
2229 filename = make_filename(args)
2232 datafile = 1
2230 datafile = 1
2233 warn('Could not find file where `%s` is defined.\n'
2231 warn('Could not find file where `%s` is defined.\n'
2234 'Opening a file named `%s`' % (args,filename))
2232 'Opening a file named `%s`' % (args,filename))
2235 # Now, make sure we can actually read the source (if it was in
2233 # Now, make sure we can actually read the source (if it was in
2236 # a temp file it's gone by now).
2234 # a temp file it's gone by now).
2237 if datafile:
2235 if datafile:
2238 try:
2236 try:
2239 if lineno is None:
2237 if lineno is None:
2240 lineno = inspect.getsourcelines(data)[1]
2238 lineno = inspect.getsourcelines(data)[1]
2241 except IOError:
2239 except IOError:
2242 filename = make_filename(args)
2240 filename = make_filename(args)
2243 if filename is None:
2241 if filename is None:
2244 warn('The file `%s` where `%s` was defined cannot '
2242 warn('The file `%s` where `%s` was defined cannot '
2245 'be read.' % (filename,data))
2243 'be read.' % (filename,data))
2246 return
2244 return
2247 use_temp = False
2245 use_temp = False
2248
2246
2249 if use_temp:
2247 if use_temp:
2250 filename = self.shell.mktempfile(data)
2248 filename = self.shell.mktempfile(data)
2251 print 'IPython will make a temporary file named:',filename
2249 print 'IPython will make a temporary file named:',filename
2252
2250
2253 return filename, lineno, use_temp
2251 return filename, lineno, use_temp
2254
2252
2255 def _edit_macro(self,mname,macro):
2253 def _edit_macro(self,mname,macro):
2256 """open an editor with the macro data in a file"""
2254 """open an editor with the macro data in a file"""
2257 filename = self.shell.mktempfile(macro.value)
2255 filename = self.shell.mktempfile(macro.value)
2258 self.shell.hooks.editor(filename)
2256 self.shell.hooks.editor(filename)
2259
2257
2260 # and make a new macro object, to replace the old one
2258 # and make a new macro object, to replace the old one
2261 mfile = open(filename)
2259 mfile = open(filename)
2262 mvalue = mfile.read()
2260 mvalue = mfile.read()
2263 mfile.close()
2261 mfile.close()
2264 self.shell.user_ns[mname] = Macro(mvalue)
2262 self.shell.user_ns[mname] = Macro(mvalue)
2265
2263
2266 def magic_ed(self,parameter_s=''):
2264 def magic_ed(self,parameter_s=''):
2267 """Alias to %edit."""
2265 """Alias to %edit."""
2268 return self.magic_edit(parameter_s)
2266 return self.magic_edit(parameter_s)
2269
2267
2270 @skip_doctest
2268 @skip_doctest
2271 def magic_edit(self,parameter_s='',last_call=['','']):
2269 def magic_edit(self,parameter_s='',last_call=['','']):
2272 """Bring up an editor and execute the resulting code.
2270 """Bring up an editor and execute the resulting code.
2273
2271
2274 Usage:
2272 Usage:
2275 %edit [options] [args]
2273 %edit [options] [args]
2276
2274
2277 %edit runs IPython's editor hook. The default version of this hook is
2275 %edit runs IPython's editor hook. The default version of this hook is
2278 set to call the __IPYTHON__.rc.editor command. This is read from your
2276 set to call the __IPYTHON__.rc.editor command. This is read from your
2279 environment variable $EDITOR. If this isn't found, it will default to
2277 environment variable $EDITOR. If this isn't found, it will default to
2280 vi under Linux/Unix and to notepad under Windows. See the end of this
2278 vi under Linux/Unix and to notepad under Windows. See the end of this
2281 docstring for how to change the editor hook.
2279 docstring for how to change the editor hook.
2282
2280
2283 You can also set the value of this editor via the command line option
2281 You can also set the value of this editor via the command line option
2284 '-editor' or in your ipythonrc file. This is useful if you wish to use
2282 '-editor' or in your ipythonrc file. This is useful if you wish to use
2285 specifically for IPython an editor different from your typical default
2283 specifically for IPython an editor different from your typical default
2286 (and for Windows users who typically don't set environment variables).
2284 (and for Windows users who typically don't set environment variables).
2287
2285
2288 This command allows you to conveniently edit multi-line code right in
2286 This command allows you to conveniently edit multi-line code right in
2289 your IPython session.
2287 your IPython session.
2290
2288
2291 If called without arguments, %edit opens up an empty editor with a
2289 If called without arguments, %edit opens up an empty editor with a
2292 temporary file and will execute the contents of this file when you
2290 temporary file and will execute the contents of this file when you
2293 close it (don't forget to save it!).
2291 close it (don't forget to save it!).
2294
2292
2295
2293
2296 Options:
2294 Options:
2297
2295
2298 -n <number>: open the editor at a specified line number. By default,
2296 -n <number>: open the editor at a specified line number. By default,
2299 the IPython editor hook uses the unix syntax 'editor +N filename', but
2297 the IPython editor hook uses the unix syntax 'editor +N filename', but
2300 you can configure this by providing your own modified hook if your
2298 you can configure this by providing your own modified hook if your
2301 favorite editor supports line-number specifications with a different
2299 favorite editor supports line-number specifications with a different
2302 syntax.
2300 syntax.
2303
2301
2304 -p: this will call the editor with the same data as the previous time
2302 -p: this will call the editor with the same data as the previous time
2305 it was used, regardless of how long ago (in your current session) it
2303 it was used, regardless of how long ago (in your current session) it
2306 was.
2304 was.
2307
2305
2308 -r: use 'raw' input. This option only applies to input taken from the
2306 -r: use 'raw' input. This option only applies to input taken from the
2309 user's history. By default, the 'processed' history is used, so that
2307 user's history. By default, the 'processed' history is used, so that
2310 magics are loaded in their transformed version to valid Python. If
2308 magics are loaded in their transformed version to valid Python. If
2311 this option is given, the raw input as typed as the command line is
2309 this option is given, the raw input as typed as the command line is
2312 used instead. When you exit the editor, it will be executed by
2310 used instead. When you exit the editor, it will be executed by
2313 IPython's own processor.
2311 IPython's own processor.
2314
2312
2315 -x: do not execute the edited code immediately upon exit. This is
2313 -x: do not execute the edited code immediately upon exit. This is
2316 mainly useful if you are editing programs which need to be called with
2314 mainly useful if you are editing programs which need to be called with
2317 command line arguments, which you can then do using %run.
2315 command line arguments, which you can then do using %run.
2318
2316
2319
2317
2320 Arguments:
2318 Arguments:
2321
2319
2322 If arguments are given, the following possibilites exist:
2320 If arguments are given, the following possibilites exist:
2323
2321
2324 - If the argument is a filename, IPython will load that into the
2322 - If the argument is a filename, IPython will load that into the
2325 editor. It will execute its contents with execfile() when you exit,
2323 editor. It will execute its contents with execfile() when you exit,
2326 loading any code in the file into your interactive namespace.
2324 loading any code in the file into your interactive namespace.
2327
2325
2328 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2326 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2329 The syntax is the same as in the %history magic.
2327 The syntax is the same as in the %history magic.
2330
2328
2331 - If the argument is a string variable, its contents are loaded
2329 - If the argument is a string variable, its contents are loaded
2332 into the editor. You can thus edit any string which contains
2330 into the editor. You can thus edit any string which contains
2333 python code (including the result of previous edits).
2331 python code (including the result of previous edits).
2334
2332
2335 - If the argument is the name of an object (other than a string),
2333 - If the argument is the name of an object (other than a string),
2336 IPython will try to locate the file where it was defined and open the
2334 IPython will try to locate the file where it was defined and open the
2337 editor at the point where it is defined. You can use `%edit function`
2335 editor at the point where it is defined. You can use `%edit function`
2338 to load an editor exactly at the point where 'function' is defined,
2336 to load an editor exactly at the point where 'function' is defined,
2339 edit it and have the file be executed automatically.
2337 edit it and have the file be executed automatically.
2340
2338
2341 If the object is a macro (see %macro for details), this opens up your
2339 If the object is a macro (see %macro for details), this opens up your
2342 specified editor with a temporary file containing the macro's data.
2340 specified editor with a temporary file containing the macro's data.
2343 Upon exit, the macro is reloaded with the contents of the file.
2341 Upon exit, the macro is reloaded with the contents of the file.
2344
2342
2345 Note: opening at an exact line is only supported under Unix, and some
2343 Note: opening at an exact line is only supported under Unix, and some
2346 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2344 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2347 '+NUMBER' parameter necessary for this feature. Good editors like
2345 '+NUMBER' parameter necessary for this feature. Good editors like
2348 (X)Emacs, vi, jed, pico and joe all do.
2346 (X)Emacs, vi, jed, pico and joe all do.
2349
2347
2350 After executing your code, %edit will return as output the code you
2348 After executing your code, %edit will return as output the code you
2351 typed in the editor (except when it was an existing file). This way
2349 typed in the editor (except when it was an existing file). This way
2352 you can reload the code in further invocations of %edit as a variable,
2350 you can reload the code in further invocations of %edit as a variable,
2353 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2351 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2354 the output.
2352 the output.
2355
2353
2356 Note that %edit is also available through the alias %ed.
2354 Note that %edit is also available through the alias %ed.
2357
2355
2358 This is an example of creating a simple function inside the editor and
2356 This is an example of creating a simple function inside the editor and
2359 then modifying it. First, start up the editor:
2357 then modifying it. First, start up the editor:
2360
2358
2361 In [1]: ed
2359 In [1]: ed
2362 Editing... done. Executing edited code...
2360 Editing... done. Executing edited code...
2363 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2361 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2364
2362
2365 We can then call the function foo():
2363 We can then call the function foo():
2366
2364
2367 In [2]: foo()
2365 In [2]: foo()
2368 foo() was defined in an editing session
2366 foo() was defined in an editing session
2369
2367
2370 Now we edit foo. IPython automatically loads the editor with the
2368 Now we edit foo. IPython automatically loads the editor with the
2371 (temporary) file where foo() was previously defined:
2369 (temporary) file where foo() was previously defined:
2372
2370
2373 In [3]: ed foo
2371 In [3]: ed foo
2374 Editing... done. Executing edited code...
2372 Editing... done. Executing edited code...
2375
2373
2376 And if we call foo() again we get the modified version:
2374 And if we call foo() again we get the modified version:
2377
2375
2378 In [4]: foo()
2376 In [4]: foo()
2379 foo() has now been changed!
2377 foo() has now been changed!
2380
2378
2381 Here is an example of how to edit a code snippet successive
2379 Here is an example of how to edit a code snippet successive
2382 times. First we call the editor:
2380 times. First we call the editor:
2383
2381
2384 In [5]: ed
2382 In [5]: ed
2385 Editing... done. Executing edited code...
2383 Editing... done. Executing edited code...
2386 hello
2384 hello
2387 Out[5]: "print 'hello'n"
2385 Out[5]: "print 'hello'n"
2388
2386
2389 Now we call it again with the previous output (stored in _):
2387 Now we call it again with the previous output (stored in _):
2390
2388
2391 In [6]: ed _
2389 In [6]: ed _
2392 Editing... done. Executing edited code...
2390 Editing... done. Executing edited code...
2393 hello world
2391 hello world
2394 Out[6]: "print 'hello world'n"
2392 Out[6]: "print 'hello world'n"
2395
2393
2396 Now we call it with the output #8 (stored in _8, also as Out[8]):
2394 Now we call it with the output #8 (stored in _8, also as Out[8]):
2397
2395
2398 In [7]: ed _8
2396 In [7]: ed _8
2399 Editing... done. Executing edited code...
2397 Editing... done. Executing edited code...
2400 hello again
2398 hello again
2401 Out[7]: "print 'hello again'n"
2399 Out[7]: "print 'hello again'n"
2402
2400
2403
2401
2404 Changing the default editor hook:
2402 Changing the default editor hook:
2405
2403
2406 If you wish to write your own editor hook, you can put it in a
2404 If you wish to write your own editor hook, you can put it in a
2407 configuration file which you load at startup time. The default hook
2405 configuration file which you load at startup time. The default hook
2408 is defined in the IPython.core.hooks module, and you can use that as a
2406 is defined in the IPython.core.hooks module, and you can use that as a
2409 starting example for further modifications. That file also has
2407 starting example for further modifications. That file also has
2410 general instructions on how to set a new hook for use once you've
2408 general instructions on how to set a new hook for use once you've
2411 defined it."""
2409 defined it."""
2412 opts,args = self.parse_options(parameter_s,'prxn:')
2410 opts,args = self.parse_options(parameter_s,'prxn:')
2413
2411
2414 try:
2412 try:
2415 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2413 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2416 except MacroToEdit as e:
2414 except MacroToEdit as e:
2417 self._edit_macro(args, e.args[0])
2415 self._edit_macro(args, e.args[0])
2418 return
2416 return
2419
2417
2420 # do actual editing here
2418 # do actual editing here
2421 print 'Editing...',
2419 print 'Editing...',
2422 sys.stdout.flush()
2420 sys.stdout.flush()
2423 try:
2421 try:
2424 # Quote filenames that may have spaces in them
2422 # Quote filenames that may have spaces in them
2425 if ' ' in filename:
2423 if ' ' in filename:
2426 filename = "'%s'" % filename
2424 filename = "'%s'" % filename
2427 self.shell.hooks.editor(filename,lineno)
2425 self.shell.hooks.editor(filename,lineno)
2428 except TryNext:
2426 except TryNext:
2429 warn('Could not open editor')
2427 warn('Could not open editor')
2430 return
2428 return
2431
2429
2432 # XXX TODO: should this be generalized for all string vars?
2430 # XXX TODO: should this be generalized for all string vars?
2433 # For now, this is special-cased to blocks created by cpaste
2431 # For now, this is special-cased to blocks created by cpaste
2434 if args.strip() == 'pasted_block':
2432 if args.strip() == 'pasted_block':
2435 self.shell.user_ns['pasted_block'] = file_read(filename)
2433 self.shell.user_ns['pasted_block'] = file_read(filename)
2436
2434
2437 if 'x' in opts: # -x prevents actual execution
2435 if 'x' in opts: # -x prevents actual execution
2438 print
2436 print
2439 else:
2437 else:
2440 print 'done. Executing edited code...'
2438 print 'done. Executing edited code...'
2441 if 'r' in opts: # Untranslated IPython code
2439 if 'r' in opts: # Untranslated IPython code
2442 self.shell.run_cell(file_read(filename),
2440 self.shell.run_cell(file_read(filename),
2443 store_history=False)
2441 store_history=False)
2444 else:
2442 else:
2445 self.shell.safe_execfile(filename,self.shell.user_ns,
2443 self.shell.safe_execfile(filename,self.shell.user_ns,
2446 self.shell.user_ns)
2444 self.shell.user_ns)
2447
2445
2448 if is_temp:
2446 if is_temp:
2449 try:
2447 try:
2450 return open(filename).read()
2448 return open(filename).read()
2451 except IOError,msg:
2449 except IOError,msg:
2452 if msg.filename == filename:
2450 if msg.filename == filename:
2453 warn('File not found. Did you forget to save?')
2451 warn('File not found. Did you forget to save?')
2454 return
2452 return
2455 else:
2453 else:
2456 self.shell.showtraceback()
2454 self.shell.showtraceback()
2457
2455
2458 def magic_xmode(self,parameter_s = ''):
2456 def magic_xmode(self,parameter_s = ''):
2459 """Switch modes for the exception handlers.
2457 """Switch modes for the exception handlers.
2460
2458
2461 Valid modes: Plain, Context and Verbose.
2459 Valid modes: Plain, Context and Verbose.
2462
2460
2463 If called without arguments, acts as a toggle."""
2461 If called without arguments, acts as a toggle."""
2464
2462
2465 def xmode_switch_err(name):
2463 def xmode_switch_err(name):
2466 warn('Error changing %s exception modes.\n%s' %
2464 warn('Error changing %s exception modes.\n%s' %
2467 (name,sys.exc_info()[1]))
2465 (name,sys.exc_info()[1]))
2468
2466
2469 shell = self.shell
2467 shell = self.shell
2470 new_mode = parameter_s.strip().capitalize()
2468 new_mode = parameter_s.strip().capitalize()
2471 try:
2469 try:
2472 shell.InteractiveTB.set_mode(mode=new_mode)
2470 shell.InteractiveTB.set_mode(mode=new_mode)
2473 print 'Exception reporting mode:',shell.InteractiveTB.mode
2471 print 'Exception reporting mode:',shell.InteractiveTB.mode
2474 except:
2472 except:
2475 xmode_switch_err('user')
2473 xmode_switch_err('user')
2476
2474
2477 def magic_colors(self,parameter_s = ''):
2475 def magic_colors(self,parameter_s = ''):
2478 """Switch color scheme for prompts, info system and exception handlers.
2476 """Switch color scheme for prompts, info system and exception handlers.
2479
2477
2480 Currently implemented schemes: NoColor, Linux, LightBG.
2478 Currently implemented schemes: NoColor, Linux, LightBG.
2481
2479
2482 Color scheme names are not case-sensitive.
2480 Color scheme names are not case-sensitive.
2483
2481
2484 Examples
2482 Examples
2485 --------
2483 --------
2486 To get a plain black and white terminal::
2484 To get a plain black and white terminal::
2487
2485
2488 %colors nocolor
2486 %colors nocolor
2489 """
2487 """
2490
2488
2491 def color_switch_err(name):
2489 def color_switch_err(name):
2492 warn('Error changing %s color schemes.\n%s' %
2490 warn('Error changing %s color schemes.\n%s' %
2493 (name,sys.exc_info()[1]))
2491 (name,sys.exc_info()[1]))
2494
2492
2495
2493
2496 new_scheme = parameter_s.strip()
2494 new_scheme = parameter_s.strip()
2497 if not new_scheme:
2495 if not new_scheme:
2498 raise UsageError(
2496 raise UsageError(
2499 "%colors: you must specify a color scheme. See '%colors?'")
2497 "%colors: you must specify a color scheme. See '%colors?'")
2500 return
2498 return
2501 # local shortcut
2499 # local shortcut
2502 shell = self.shell
2500 shell = self.shell
2503
2501
2504 import IPython.utils.rlineimpl as readline
2502 import IPython.utils.rlineimpl as readline
2505
2503
2506 if not readline.have_readline and sys.platform == "win32":
2504 if not readline.have_readline and sys.platform == "win32":
2507 msg = """\
2505 msg = """\
2508 Proper color support under MS Windows requires the pyreadline library.
2506 Proper color support under MS Windows requires the pyreadline library.
2509 You can find it at:
2507 You can find it at:
2510 http://ipython.scipy.org/moin/PyReadline/Intro
2508 http://ipython.scipy.org/moin/PyReadline/Intro
2511 Gary's readline needs the ctypes module, from:
2509 Gary's readline needs the ctypes module, from:
2512 http://starship.python.net/crew/theller/ctypes
2510 http://starship.python.net/crew/theller/ctypes
2513 (Note that ctypes is already part of Python versions 2.5 and newer).
2511 (Note that ctypes is already part of Python versions 2.5 and newer).
2514
2512
2515 Defaulting color scheme to 'NoColor'"""
2513 Defaulting color scheme to 'NoColor'"""
2516 new_scheme = 'NoColor'
2514 new_scheme = 'NoColor'
2517 warn(msg)
2515 warn(msg)
2518
2516
2519 # readline option is 0
2517 # readline option is 0
2520 if not shell.has_readline:
2518 if not shell.has_readline:
2521 new_scheme = 'NoColor'
2519 new_scheme = 'NoColor'
2522
2520
2523 # Set prompt colors
2521 # Set prompt colors
2524 try:
2522 try:
2525 shell.displayhook.set_colors(new_scheme)
2523 shell.displayhook.set_colors(new_scheme)
2526 except:
2524 except:
2527 color_switch_err('prompt')
2525 color_switch_err('prompt')
2528 else:
2526 else:
2529 shell.colors = \
2527 shell.colors = \
2530 shell.displayhook.color_table.active_scheme_name
2528 shell.displayhook.color_table.active_scheme_name
2531 # Set exception colors
2529 # Set exception colors
2532 try:
2530 try:
2533 shell.InteractiveTB.set_colors(scheme = new_scheme)
2531 shell.InteractiveTB.set_colors(scheme = new_scheme)
2534 shell.SyntaxTB.set_colors(scheme = new_scheme)
2532 shell.SyntaxTB.set_colors(scheme = new_scheme)
2535 except:
2533 except:
2536 color_switch_err('exception')
2534 color_switch_err('exception')
2537
2535
2538 # Set info (for 'object?') colors
2536 # Set info (for 'object?') colors
2539 if shell.color_info:
2537 if shell.color_info:
2540 try:
2538 try:
2541 shell.inspector.set_active_scheme(new_scheme)
2539 shell.inspector.set_active_scheme(new_scheme)
2542 except:
2540 except:
2543 color_switch_err('object inspector')
2541 color_switch_err('object inspector')
2544 else:
2542 else:
2545 shell.inspector.set_active_scheme('NoColor')
2543 shell.inspector.set_active_scheme('NoColor')
2546
2544
2547 def magic_pprint(self, parameter_s=''):
2545 def magic_pprint(self, parameter_s=''):
2548 """Toggle pretty printing on/off."""
2546 """Toggle pretty printing on/off."""
2549 ptformatter = self.shell.display_formatter.formatters['text/plain']
2547 ptformatter = self.shell.display_formatter.formatters['text/plain']
2550 ptformatter.pprint = bool(1 - ptformatter.pprint)
2548 ptformatter.pprint = bool(1 - ptformatter.pprint)
2551 print 'Pretty printing has been turned', \
2549 print 'Pretty printing has been turned', \
2552 ['OFF','ON'][ptformatter.pprint]
2550 ['OFF','ON'][ptformatter.pprint]
2553
2551
2554 #......................................................................
2552 #......................................................................
2555 # Functions to implement unix shell-type things
2553 # Functions to implement unix shell-type things
2556
2554
2557 @skip_doctest
2555 @skip_doctest
2558 def magic_alias(self, parameter_s = ''):
2556 def magic_alias(self, parameter_s = ''):
2559 """Define an alias for a system command.
2557 """Define an alias for a system command.
2560
2558
2561 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2559 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2562
2560
2563 Then, typing 'alias_name params' will execute the system command 'cmd
2561 Then, typing 'alias_name params' will execute the system command 'cmd
2564 params' (from your underlying operating system).
2562 params' (from your underlying operating system).
2565
2563
2566 Aliases have lower precedence than magic functions and Python normal
2564 Aliases have lower precedence than magic functions and Python normal
2567 variables, so if 'foo' is both a Python variable and an alias, the
2565 variables, so if 'foo' is both a Python variable and an alias, the
2568 alias can not be executed until 'del foo' removes the Python variable.
2566 alias can not be executed until 'del foo' removes the Python variable.
2569
2567
2570 You can use the %l specifier in an alias definition to represent the
2568 You can use the %l specifier in an alias definition to represent the
2571 whole line when the alias is called. For example:
2569 whole line when the alias is called. For example:
2572
2570
2573 In [2]: alias bracket echo "Input in brackets: <%l>"
2571 In [2]: alias bracket echo "Input in brackets: <%l>"
2574 In [3]: bracket hello world
2572 In [3]: bracket hello world
2575 Input in brackets: <hello world>
2573 Input in brackets: <hello world>
2576
2574
2577 You can also define aliases with parameters using %s specifiers (one
2575 You can also define aliases with parameters using %s specifiers (one
2578 per parameter):
2576 per parameter):
2579
2577
2580 In [1]: alias parts echo first %s second %s
2578 In [1]: alias parts echo first %s second %s
2581 In [2]: %parts A B
2579 In [2]: %parts A B
2582 first A second B
2580 first A second B
2583 In [3]: %parts A
2581 In [3]: %parts A
2584 Incorrect number of arguments: 2 expected.
2582 Incorrect number of arguments: 2 expected.
2585 parts is an alias to: 'echo first %s second %s'
2583 parts is an alias to: 'echo first %s second %s'
2586
2584
2587 Note that %l and %s are mutually exclusive. You can only use one or
2585 Note that %l and %s are mutually exclusive. You can only use one or
2588 the other in your aliases.
2586 the other in your aliases.
2589
2587
2590 Aliases expand Python variables just like system calls using ! or !!
2588 Aliases expand Python variables just like system calls using ! or !!
2591 do: all expressions prefixed with '$' get expanded. For details of
2589 do: all expressions prefixed with '$' get expanded. For details of
2592 the semantic rules, see PEP-215:
2590 the semantic rules, see PEP-215:
2593 http://www.python.org/peps/pep-0215.html. This is the library used by
2591 http://www.python.org/peps/pep-0215.html. This is the library used by
2594 IPython for variable expansion. If you want to access a true shell
2592 IPython for variable expansion. If you want to access a true shell
2595 variable, an extra $ is necessary to prevent its expansion by IPython:
2593 variable, an extra $ is necessary to prevent its expansion by IPython:
2596
2594
2597 In [6]: alias show echo
2595 In [6]: alias show echo
2598 In [7]: PATH='A Python string'
2596 In [7]: PATH='A Python string'
2599 In [8]: show $PATH
2597 In [8]: show $PATH
2600 A Python string
2598 A Python string
2601 In [9]: show $$PATH
2599 In [9]: show $$PATH
2602 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2600 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2603
2601
2604 You can use the alias facility to acess all of $PATH. See the %rehash
2602 You can use the alias facility to acess all of $PATH. See the %rehash
2605 and %rehashx functions, which automatically create aliases for the
2603 and %rehashx functions, which automatically create aliases for the
2606 contents of your $PATH.
2604 contents of your $PATH.
2607
2605
2608 If called with no parameters, %alias prints the current alias table."""
2606 If called with no parameters, %alias prints the current alias table."""
2609
2607
2610 par = parameter_s.strip()
2608 par = parameter_s.strip()
2611 if not par:
2609 if not par:
2612 stored = self.db.get('stored_aliases', {} )
2610 stored = self.db.get('stored_aliases', {} )
2613 aliases = sorted(self.shell.alias_manager.aliases)
2611 aliases = sorted(self.shell.alias_manager.aliases)
2614 # for k, v in stored:
2612 # for k, v in stored:
2615 # atab.append(k, v[0])
2613 # atab.append(k, v[0])
2616
2614
2617 print "Total number of aliases:", len(aliases)
2615 print "Total number of aliases:", len(aliases)
2618 sys.stdout.flush()
2616 sys.stdout.flush()
2619 return aliases
2617 return aliases
2620
2618
2621 # Now try to define a new one
2619 # Now try to define a new one
2622 try:
2620 try:
2623 alias,cmd = par.split(None, 1)
2621 alias,cmd = par.split(None, 1)
2624 except:
2622 except:
2625 print oinspect.getdoc(self.magic_alias)
2623 print oinspect.getdoc(self.magic_alias)
2626 else:
2624 else:
2627 self.shell.alias_manager.soft_define_alias(alias, cmd)
2625 self.shell.alias_manager.soft_define_alias(alias, cmd)
2628 # end magic_alias
2626 # end magic_alias
2629
2627
2630 def magic_unalias(self, parameter_s = ''):
2628 def magic_unalias(self, parameter_s = ''):
2631 """Remove an alias"""
2629 """Remove an alias"""
2632
2630
2633 aname = parameter_s.strip()
2631 aname = parameter_s.strip()
2634 self.shell.alias_manager.undefine_alias(aname)
2632 self.shell.alias_manager.undefine_alias(aname)
2635 stored = self.db.get('stored_aliases', {} )
2633 stored = self.db.get('stored_aliases', {} )
2636 if aname in stored:
2634 if aname in stored:
2637 print "Removing %stored alias",aname
2635 print "Removing %stored alias",aname
2638 del stored[aname]
2636 del stored[aname]
2639 self.db['stored_aliases'] = stored
2637 self.db['stored_aliases'] = stored
2640
2638
2641 def magic_rehashx(self, parameter_s = ''):
2639 def magic_rehashx(self, parameter_s = ''):
2642 """Update the alias table with all executable files in $PATH.
2640 """Update the alias table with all executable files in $PATH.
2643
2641
2644 This version explicitly checks that every entry in $PATH is a file
2642 This version explicitly checks that every entry in $PATH is a file
2645 with execute access (os.X_OK), so it is much slower than %rehash.
2643 with execute access (os.X_OK), so it is much slower than %rehash.
2646
2644
2647 Under Windows, it checks executability as a match agains a
2645 Under Windows, it checks executability as a match agains a
2648 '|'-separated string of extensions, stored in the IPython config
2646 '|'-separated string of extensions, stored in the IPython config
2649 variable win_exec_ext. This defaults to 'exe|com|bat'.
2647 variable win_exec_ext. This defaults to 'exe|com|bat'.
2650
2648
2651 This function also resets the root module cache of module completer,
2649 This function also resets the root module cache of module completer,
2652 used on slow filesystems.
2650 used on slow filesystems.
2653 """
2651 """
2654 from IPython.core.alias import InvalidAliasError
2652 from IPython.core.alias import InvalidAliasError
2655
2653
2656 # for the benefit of module completer in ipy_completers.py
2654 # for the benefit of module completer in ipy_completers.py
2657 del self.db['rootmodules']
2655 del self.db['rootmodules']
2658
2656
2659 path = [os.path.abspath(os.path.expanduser(p)) for p in
2657 path = [os.path.abspath(os.path.expanduser(p)) for p in
2660 os.environ.get('PATH','').split(os.pathsep)]
2658 os.environ.get('PATH','').split(os.pathsep)]
2661 path = filter(os.path.isdir,path)
2659 path = filter(os.path.isdir,path)
2662
2660
2663 syscmdlist = []
2661 syscmdlist = []
2664 # Now define isexec in a cross platform manner.
2662 # Now define isexec in a cross platform manner.
2665 if os.name == 'posix':
2663 if os.name == 'posix':
2666 isexec = lambda fname:os.path.isfile(fname) and \
2664 isexec = lambda fname:os.path.isfile(fname) and \
2667 os.access(fname,os.X_OK)
2665 os.access(fname,os.X_OK)
2668 else:
2666 else:
2669 try:
2667 try:
2670 winext = os.environ['pathext'].replace(';','|').replace('.','')
2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2671 except KeyError:
2669 except KeyError:
2672 winext = 'exe|com|bat|py'
2670 winext = 'exe|com|bat|py'
2673 if 'py' not in winext:
2671 if 'py' not in winext:
2674 winext += '|py'
2672 winext += '|py'
2675 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2676 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2677 savedir = os.getcwd()
2675 savedir = os.getcwd()
2678
2676
2679 # Now walk the paths looking for executables to alias.
2677 # Now walk the paths looking for executables to alias.
2680 try:
2678 try:
2681 # write the whole loop for posix/Windows so we don't have an if in
2679 # write the whole loop for posix/Windows so we don't have an if in
2682 # the innermost part
2680 # the innermost part
2683 if os.name == 'posix':
2681 if os.name == 'posix':
2684 for pdir in path:
2682 for pdir in path:
2685 os.chdir(pdir)
2683 os.chdir(pdir)
2686 for ff in os.listdir(pdir):
2684 for ff in os.listdir(pdir):
2687 if isexec(ff):
2685 if isexec(ff):
2688 try:
2686 try:
2689 # Removes dots from the name since ipython
2687 # Removes dots from the name since ipython
2690 # will assume names with dots to be python.
2688 # will assume names with dots to be python.
2691 self.shell.alias_manager.define_alias(
2689 self.shell.alias_manager.define_alias(
2692 ff.replace('.',''), ff)
2690 ff.replace('.',''), ff)
2693 except InvalidAliasError:
2691 except InvalidAliasError:
2694 pass
2692 pass
2695 else:
2693 else:
2696 syscmdlist.append(ff)
2694 syscmdlist.append(ff)
2697 else:
2695 else:
2698 no_alias = self.shell.alias_manager.no_alias
2696 no_alias = self.shell.alias_manager.no_alias
2699 for pdir in path:
2697 for pdir in path:
2700 os.chdir(pdir)
2698 os.chdir(pdir)
2701 for ff in os.listdir(pdir):
2699 for ff in os.listdir(pdir):
2702 base, ext = os.path.splitext(ff)
2700 base, ext = os.path.splitext(ff)
2703 if isexec(ff) and base.lower() not in no_alias:
2701 if isexec(ff) and base.lower() not in no_alias:
2704 if ext.lower() == '.exe':
2702 if ext.lower() == '.exe':
2705 ff = base
2703 ff = base
2706 try:
2704 try:
2707 # Removes dots from the name since ipython
2705 # Removes dots from the name since ipython
2708 # will assume names with dots to be python.
2706 # will assume names with dots to be python.
2709 self.shell.alias_manager.define_alias(
2707 self.shell.alias_manager.define_alias(
2710 base.lower().replace('.',''), ff)
2708 base.lower().replace('.',''), ff)
2711 except InvalidAliasError:
2709 except InvalidAliasError:
2712 pass
2710 pass
2713 syscmdlist.append(ff)
2711 syscmdlist.append(ff)
2714 db = self.db
2712 db = self.db
2715 db['syscmdlist'] = syscmdlist
2713 db['syscmdlist'] = syscmdlist
2716 finally:
2714 finally:
2717 os.chdir(savedir)
2715 os.chdir(savedir)
2718
2716
2719 @skip_doctest
2717 @skip_doctest
2720 def magic_pwd(self, parameter_s = ''):
2718 def magic_pwd(self, parameter_s = ''):
2721 """Return the current working directory path.
2719 """Return the current working directory path.
2722
2720
2723 Examples
2721 Examples
2724 --------
2722 --------
2725 ::
2723 ::
2726
2724
2727 In [9]: pwd
2725 In [9]: pwd
2728 Out[9]: '/home/tsuser/sprint/ipython'
2726 Out[9]: '/home/tsuser/sprint/ipython'
2729 """
2727 """
2730 return os.getcwd()
2728 return os.getcwd()
2731
2729
2732 @skip_doctest
2730 @skip_doctest
2733 def magic_cd(self, parameter_s=''):
2731 def magic_cd(self, parameter_s=''):
2734 """Change the current working directory.
2732 """Change the current working directory.
2735
2733
2736 This command automatically maintains an internal list of directories
2734 This command automatically maintains an internal list of directories
2737 you visit during your IPython session, in the variable _dh. The
2735 you visit during your IPython session, in the variable _dh. The
2738 command %dhist shows this history nicely formatted. You can also
2736 command %dhist shows this history nicely formatted. You can also
2739 do 'cd -<tab>' to see directory history conveniently.
2737 do 'cd -<tab>' to see directory history conveniently.
2740
2738
2741 Usage:
2739 Usage:
2742
2740
2743 cd 'dir': changes to directory 'dir'.
2741 cd 'dir': changes to directory 'dir'.
2744
2742
2745 cd -: changes to the last visited directory.
2743 cd -: changes to the last visited directory.
2746
2744
2747 cd -<n>: changes to the n-th directory in the directory history.
2745 cd -<n>: changes to the n-th directory in the directory history.
2748
2746
2749 cd --foo: change to directory that matches 'foo' in history
2747 cd --foo: change to directory that matches 'foo' in history
2750
2748
2751 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2749 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2752 (note: cd <bookmark_name> is enough if there is no
2750 (note: cd <bookmark_name> is enough if there is no
2753 directory <bookmark_name>, but a bookmark with the name exists.)
2751 directory <bookmark_name>, but a bookmark with the name exists.)
2754 'cd -b <tab>' allows you to tab-complete bookmark names.
2752 'cd -b <tab>' allows you to tab-complete bookmark names.
2755
2753
2756 Options:
2754 Options:
2757
2755
2758 -q: quiet. Do not print the working directory after the cd command is
2756 -q: quiet. Do not print the working directory after the cd command is
2759 executed. By default IPython's cd command does print this directory,
2757 executed. By default IPython's cd command does print this directory,
2760 since the default prompts do not display path information.
2758 since the default prompts do not display path information.
2761
2759
2762 Note that !cd doesn't work for this purpose because the shell where
2760 Note that !cd doesn't work for this purpose because the shell where
2763 !command runs is immediately discarded after executing 'command'.
2761 !command runs is immediately discarded after executing 'command'.
2764
2762
2765 Examples
2763 Examples
2766 --------
2764 --------
2767 ::
2765 ::
2768
2766
2769 In [10]: cd parent/child
2767 In [10]: cd parent/child
2770 /home/tsuser/parent/child
2768 /home/tsuser/parent/child
2771 """
2769 """
2772
2770
2773 parameter_s = parameter_s.strip()
2771 parameter_s = parameter_s.strip()
2774 #bkms = self.shell.persist.get("bookmarks",{})
2772 #bkms = self.shell.persist.get("bookmarks",{})
2775
2773
2776 oldcwd = os.getcwd()
2774 oldcwd = os.getcwd()
2777 numcd = re.match(r'(-)(\d+)$',parameter_s)
2775 numcd = re.match(r'(-)(\d+)$',parameter_s)
2778 # jump in directory history by number
2776 # jump in directory history by number
2779 if numcd:
2777 if numcd:
2780 nn = int(numcd.group(2))
2778 nn = int(numcd.group(2))
2781 try:
2779 try:
2782 ps = self.shell.user_ns['_dh'][nn]
2780 ps = self.shell.user_ns['_dh'][nn]
2783 except IndexError:
2781 except IndexError:
2784 print 'The requested directory does not exist in history.'
2782 print 'The requested directory does not exist in history.'
2785 return
2783 return
2786 else:
2784 else:
2787 opts = {}
2785 opts = {}
2788 elif parameter_s.startswith('--'):
2786 elif parameter_s.startswith('--'):
2789 ps = None
2787 ps = None
2790 fallback = None
2788 fallback = None
2791 pat = parameter_s[2:]
2789 pat = parameter_s[2:]
2792 dh = self.shell.user_ns['_dh']
2790 dh = self.shell.user_ns['_dh']
2793 # first search only by basename (last component)
2791 # first search only by basename (last component)
2794 for ent in reversed(dh):
2792 for ent in reversed(dh):
2795 if pat in os.path.basename(ent) and os.path.isdir(ent):
2793 if pat in os.path.basename(ent) and os.path.isdir(ent):
2796 ps = ent
2794 ps = ent
2797 break
2795 break
2798
2796
2799 if fallback is None and pat in ent and os.path.isdir(ent):
2797 if fallback is None and pat in ent and os.path.isdir(ent):
2800 fallback = ent
2798 fallback = ent
2801
2799
2802 # if we have no last part match, pick the first full path match
2800 # if we have no last part match, pick the first full path match
2803 if ps is None:
2801 if ps is None:
2804 ps = fallback
2802 ps = fallback
2805
2803
2806 if ps is None:
2804 if ps is None:
2807 print "No matching entry in directory history"
2805 print "No matching entry in directory history"
2808 return
2806 return
2809 else:
2807 else:
2810 opts = {}
2808 opts = {}
2811
2809
2812
2810
2813 else:
2811 else:
2814 #turn all non-space-escaping backslashes to slashes,
2812 #turn all non-space-escaping backslashes to slashes,
2815 # for c:\windows\directory\names\
2813 # for c:\windows\directory\names\
2816 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2814 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2817 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2815 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2818 # jump to previous
2816 # jump to previous
2819 if ps == '-':
2817 if ps == '-':
2820 try:
2818 try:
2821 ps = self.shell.user_ns['_dh'][-2]
2819 ps = self.shell.user_ns['_dh'][-2]
2822 except IndexError:
2820 except IndexError:
2823 raise UsageError('%cd -: No previous directory to change to.')
2821 raise UsageError('%cd -: No previous directory to change to.')
2824 # jump to bookmark if needed
2822 # jump to bookmark if needed
2825 else:
2823 else:
2826 if not os.path.isdir(ps) or opts.has_key('b'):
2824 if not os.path.isdir(ps) or opts.has_key('b'):
2827 bkms = self.db.get('bookmarks', {})
2825 bkms = self.db.get('bookmarks', {})
2828
2826
2829 if bkms.has_key(ps):
2827 if bkms.has_key(ps):
2830 target = bkms[ps]
2828 target = bkms[ps]
2831 print '(bookmark:%s) -> %s' % (ps,target)
2829 print '(bookmark:%s) -> %s' % (ps,target)
2832 ps = target
2830 ps = target
2833 else:
2831 else:
2834 if opts.has_key('b'):
2832 if opts.has_key('b'):
2835 raise UsageError("Bookmark '%s' not found. "
2833 raise UsageError("Bookmark '%s' not found. "
2836 "Use '%%bookmark -l' to see your bookmarks." % ps)
2834 "Use '%%bookmark -l' to see your bookmarks." % ps)
2837
2835
2838 # at this point ps should point to the target dir
2836 # at this point ps should point to the target dir
2839 if ps:
2837 if ps:
2840 try:
2838 try:
2841 os.chdir(os.path.expanduser(ps))
2839 os.chdir(os.path.expanduser(ps))
2842 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2840 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2843 set_term_title('IPython: ' + abbrev_cwd())
2841 set_term_title('IPython: ' + abbrev_cwd())
2844 except OSError:
2842 except OSError:
2845 print sys.exc_info()[1]
2843 print sys.exc_info()[1]
2846 else:
2844 else:
2847 cwd = os.getcwd()
2845 cwd = os.getcwd()
2848 dhist = self.shell.user_ns['_dh']
2846 dhist = self.shell.user_ns['_dh']
2849 if oldcwd != cwd:
2847 if oldcwd != cwd:
2850 dhist.append(cwd)
2848 dhist.append(cwd)
2851 self.db['dhist'] = compress_dhist(dhist)[-100:]
2849 self.db['dhist'] = compress_dhist(dhist)[-100:]
2852
2850
2853 else:
2851 else:
2854 os.chdir(self.shell.home_dir)
2852 os.chdir(self.shell.home_dir)
2855 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2853 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2856 set_term_title('IPython: ' + '~')
2854 set_term_title('IPython: ' + '~')
2857 cwd = os.getcwd()
2855 cwd = os.getcwd()
2858 dhist = self.shell.user_ns['_dh']
2856 dhist = self.shell.user_ns['_dh']
2859
2857
2860 if oldcwd != cwd:
2858 if oldcwd != cwd:
2861 dhist.append(cwd)
2859 dhist.append(cwd)
2862 self.db['dhist'] = compress_dhist(dhist)[-100:]
2860 self.db['dhist'] = compress_dhist(dhist)[-100:]
2863 if not 'q' in opts and self.shell.user_ns['_dh']:
2861 if not 'q' in opts and self.shell.user_ns['_dh']:
2864 print self.shell.user_ns['_dh'][-1]
2862 print self.shell.user_ns['_dh'][-1]
2865
2863
2866
2864
2867 def magic_env(self, parameter_s=''):
2865 def magic_env(self, parameter_s=''):
2868 """List environment variables."""
2866 """List environment variables."""
2869
2867
2870 return os.environ.data
2868 return os.environ.data
2871
2869
2872 def magic_pushd(self, parameter_s=''):
2870 def magic_pushd(self, parameter_s=''):
2873 """Place the current dir on stack and change directory.
2871 """Place the current dir on stack and change directory.
2874
2872
2875 Usage:\\
2873 Usage:\\
2876 %pushd ['dirname']
2874 %pushd ['dirname']
2877 """
2875 """
2878
2876
2879 dir_s = self.shell.dir_stack
2877 dir_s = self.shell.dir_stack
2880 tgt = os.path.expanduser(parameter_s)
2878 tgt = os.path.expanduser(parameter_s)
2881 cwd = os.getcwd().replace(self.home_dir,'~')
2879 cwd = os.getcwd().replace(self.home_dir,'~')
2882 if tgt:
2880 if tgt:
2883 self.magic_cd(parameter_s)
2881 self.magic_cd(parameter_s)
2884 dir_s.insert(0,cwd)
2882 dir_s.insert(0,cwd)
2885 return self.magic_dirs()
2883 return self.magic_dirs()
2886
2884
2887 def magic_popd(self, parameter_s=''):
2885 def magic_popd(self, parameter_s=''):
2888 """Change to directory popped off the top of the stack.
2886 """Change to directory popped off the top of the stack.
2889 """
2887 """
2890 if not self.shell.dir_stack:
2888 if not self.shell.dir_stack:
2891 raise UsageError("%popd on empty stack")
2889 raise UsageError("%popd on empty stack")
2892 top = self.shell.dir_stack.pop(0)
2890 top = self.shell.dir_stack.pop(0)
2893 self.magic_cd(top)
2891 self.magic_cd(top)
2894 print "popd ->",top
2892 print "popd ->",top
2895
2893
2896 def magic_dirs(self, parameter_s=''):
2894 def magic_dirs(self, parameter_s=''):
2897 """Return the current directory stack."""
2895 """Return the current directory stack."""
2898
2896
2899 return self.shell.dir_stack
2897 return self.shell.dir_stack
2900
2898
2901 def magic_dhist(self, parameter_s=''):
2899 def magic_dhist(self, parameter_s=''):
2902 """Print your history of visited directories.
2900 """Print your history of visited directories.
2903
2901
2904 %dhist -> print full history\\
2902 %dhist -> print full history\\
2905 %dhist n -> print last n entries only\\
2903 %dhist n -> print last n entries only\\
2906 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2904 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2907
2905
2908 This history is automatically maintained by the %cd command, and
2906 This history is automatically maintained by the %cd command, and
2909 always available as the global list variable _dh. You can use %cd -<n>
2907 always available as the global list variable _dh. You can use %cd -<n>
2910 to go to directory number <n>.
2908 to go to directory number <n>.
2911
2909
2912 Note that most of time, you should view directory history by entering
2910 Note that most of time, you should view directory history by entering
2913 cd -<TAB>.
2911 cd -<TAB>.
2914
2912
2915 """
2913 """
2916
2914
2917 dh = self.shell.user_ns['_dh']
2915 dh = self.shell.user_ns['_dh']
2918 if parameter_s:
2916 if parameter_s:
2919 try:
2917 try:
2920 args = map(int,parameter_s.split())
2918 args = map(int,parameter_s.split())
2921 except:
2919 except:
2922 self.arg_err(Magic.magic_dhist)
2920 self.arg_err(Magic.magic_dhist)
2923 return
2921 return
2924 if len(args) == 1:
2922 if len(args) == 1:
2925 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2923 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2926 elif len(args) == 2:
2924 elif len(args) == 2:
2927 ini,fin = args
2925 ini,fin = args
2928 else:
2926 else:
2929 self.arg_err(Magic.magic_dhist)
2927 self.arg_err(Magic.magic_dhist)
2930 return
2928 return
2931 else:
2929 else:
2932 ini,fin = 0,len(dh)
2930 ini,fin = 0,len(dh)
2933 nlprint(dh,
2931 nlprint(dh,
2934 header = 'Directory history (kept in _dh)',
2932 header = 'Directory history (kept in _dh)',
2935 start=ini,stop=fin)
2933 start=ini,stop=fin)
2936
2934
2937 @skip_doctest
2935 @skip_doctest
2938 def magic_sc(self, parameter_s=''):
2936 def magic_sc(self, parameter_s=''):
2939 """Shell capture - execute a shell command and capture its output.
2937 """Shell capture - execute a shell command and capture its output.
2940
2938
2941 DEPRECATED. Suboptimal, retained for backwards compatibility.
2939 DEPRECATED. Suboptimal, retained for backwards compatibility.
2942
2940
2943 You should use the form 'var = !command' instead. Example:
2941 You should use the form 'var = !command' instead. Example:
2944
2942
2945 "%sc -l myfiles = ls ~" should now be written as
2943 "%sc -l myfiles = ls ~" should now be written as
2946
2944
2947 "myfiles = !ls ~"
2945 "myfiles = !ls ~"
2948
2946
2949 myfiles.s, myfiles.l and myfiles.n still apply as documented
2947 myfiles.s, myfiles.l and myfiles.n still apply as documented
2950 below.
2948 below.
2951
2949
2952 --
2950 --
2953 %sc [options] varname=command
2951 %sc [options] varname=command
2954
2952
2955 IPython will run the given command using commands.getoutput(), and
2953 IPython will run the given command using commands.getoutput(), and
2956 will then update the user's interactive namespace with a variable
2954 will then update the user's interactive namespace with a variable
2957 called varname, containing the value of the call. Your command can
2955 called varname, containing the value of the call. Your command can
2958 contain shell wildcards, pipes, etc.
2956 contain shell wildcards, pipes, etc.
2959
2957
2960 The '=' sign in the syntax is mandatory, and the variable name you
2958 The '=' sign in the syntax is mandatory, and the variable name you
2961 supply must follow Python's standard conventions for valid names.
2959 supply must follow Python's standard conventions for valid names.
2962
2960
2963 (A special format without variable name exists for internal use)
2961 (A special format without variable name exists for internal use)
2964
2962
2965 Options:
2963 Options:
2966
2964
2967 -l: list output. Split the output on newlines into a list before
2965 -l: list output. Split the output on newlines into a list before
2968 assigning it to the given variable. By default the output is stored
2966 assigning it to the given variable. By default the output is stored
2969 as a single string.
2967 as a single string.
2970
2968
2971 -v: verbose. Print the contents of the variable.
2969 -v: verbose. Print the contents of the variable.
2972
2970
2973 In most cases you should not need to split as a list, because the
2971 In most cases you should not need to split as a list, because the
2974 returned value is a special type of string which can automatically
2972 returned value is a special type of string which can automatically
2975 provide its contents either as a list (split on newlines) or as a
2973 provide its contents either as a list (split on newlines) or as a
2976 space-separated string. These are convenient, respectively, either
2974 space-separated string. These are convenient, respectively, either
2977 for sequential processing or to be passed to a shell command.
2975 for sequential processing or to be passed to a shell command.
2978
2976
2979 For example:
2977 For example:
2980
2978
2981 # all-random
2979 # all-random
2982
2980
2983 # Capture into variable a
2981 # Capture into variable a
2984 In [1]: sc a=ls *py
2982 In [1]: sc a=ls *py
2985
2983
2986 # a is a string with embedded newlines
2984 # a is a string with embedded newlines
2987 In [2]: a
2985 In [2]: a
2988 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2986 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2989
2987
2990 # which can be seen as a list:
2988 # which can be seen as a list:
2991 In [3]: a.l
2989 In [3]: a.l
2992 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2990 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2993
2991
2994 # or as a whitespace-separated string:
2992 # or as a whitespace-separated string:
2995 In [4]: a.s
2993 In [4]: a.s
2996 Out[4]: 'setup.py win32_manual_post_install.py'
2994 Out[4]: 'setup.py win32_manual_post_install.py'
2997
2995
2998 # a.s is useful to pass as a single command line:
2996 # a.s is useful to pass as a single command line:
2999 In [5]: !wc -l $a.s
2997 In [5]: !wc -l $a.s
3000 146 setup.py
2998 146 setup.py
3001 130 win32_manual_post_install.py
2999 130 win32_manual_post_install.py
3002 276 total
3000 276 total
3003
3001
3004 # while the list form is useful to loop over:
3002 # while the list form is useful to loop over:
3005 In [6]: for f in a.l:
3003 In [6]: for f in a.l:
3006 ...: !wc -l $f
3004 ...: !wc -l $f
3007 ...:
3005 ...:
3008 146 setup.py
3006 146 setup.py
3009 130 win32_manual_post_install.py
3007 130 win32_manual_post_install.py
3010
3008
3011 Similiarly, the lists returned by the -l option are also special, in
3009 Similiarly, the lists returned by the -l option are also special, in
3012 the sense that you can equally invoke the .s attribute on them to
3010 the sense that you can equally invoke the .s attribute on them to
3013 automatically get a whitespace-separated string from their contents:
3011 automatically get a whitespace-separated string from their contents:
3014
3012
3015 In [7]: sc -l b=ls *py
3013 In [7]: sc -l b=ls *py
3016
3014
3017 In [8]: b
3015 In [8]: b
3018 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3016 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3019
3017
3020 In [9]: b.s
3018 In [9]: b.s
3021 Out[9]: 'setup.py win32_manual_post_install.py'
3019 Out[9]: 'setup.py win32_manual_post_install.py'
3022
3020
3023 In summary, both the lists and strings used for ouptut capture have
3021 In summary, both the lists and strings used for ouptut capture have
3024 the following special attributes:
3022 the following special attributes:
3025
3023
3026 .l (or .list) : value as list.
3024 .l (or .list) : value as list.
3027 .n (or .nlstr): value as newline-separated string.
3025 .n (or .nlstr): value as newline-separated string.
3028 .s (or .spstr): value as space-separated string.
3026 .s (or .spstr): value as space-separated string.
3029 """
3027 """
3030
3028
3031 opts,args = self.parse_options(parameter_s,'lv')
3029 opts,args = self.parse_options(parameter_s,'lv')
3032 # Try to get a variable name and command to run
3030 # Try to get a variable name and command to run
3033 try:
3031 try:
3034 # the variable name must be obtained from the parse_options
3032 # the variable name must be obtained from the parse_options
3035 # output, which uses shlex.split to strip options out.
3033 # output, which uses shlex.split to strip options out.
3036 var,_ = args.split('=',1)
3034 var,_ = args.split('=',1)
3037 var = var.strip()
3035 var = var.strip()
3038 # But the the command has to be extracted from the original input
3036 # But the the command has to be extracted from the original input
3039 # parameter_s, not on what parse_options returns, to avoid the
3037 # parameter_s, not on what parse_options returns, to avoid the
3040 # quote stripping which shlex.split performs on it.
3038 # quote stripping which shlex.split performs on it.
3041 _,cmd = parameter_s.split('=',1)
3039 _,cmd = parameter_s.split('=',1)
3042 except ValueError:
3040 except ValueError:
3043 var,cmd = '',''
3041 var,cmd = '',''
3044 # If all looks ok, proceed
3042 # If all looks ok, proceed
3045 split = 'l' in opts
3043 split = 'l' in opts
3046 out = self.shell.getoutput(cmd, split=split)
3044 out = self.shell.getoutput(cmd, split=split)
3047 if opts.has_key('v'):
3045 if opts.has_key('v'):
3048 print '%s ==\n%s' % (var,pformat(out))
3046 print '%s ==\n%s' % (var,pformat(out))
3049 if var:
3047 if var:
3050 self.shell.user_ns.update({var:out})
3048 self.shell.user_ns.update({var:out})
3051 else:
3049 else:
3052 return out
3050 return out
3053
3051
3054 def magic_sx(self, parameter_s=''):
3052 def magic_sx(self, parameter_s=''):
3055 """Shell execute - run a shell command and capture its output.
3053 """Shell execute - run a shell command and capture its output.
3056
3054
3057 %sx command
3055 %sx command
3058
3056
3059 IPython will run the given command using commands.getoutput(), and
3057 IPython will run the given command using commands.getoutput(), and
3060 return the result formatted as a list (split on '\\n'). Since the
3058 return the result formatted as a list (split on '\\n'). Since the
3061 output is _returned_, it will be stored in ipython's regular output
3059 output is _returned_, it will be stored in ipython's regular output
3062 cache Out[N] and in the '_N' automatic variables.
3060 cache Out[N] and in the '_N' automatic variables.
3063
3061
3064 Notes:
3062 Notes:
3065
3063
3066 1) If an input line begins with '!!', then %sx is automatically
3064 1) If an input line begins with '!!', then %sx is automatically
3067 invoked. That is, while:
3065 invoked. That is, while:
3068 !ls
3066 !ls
3069 causes ipython to simply issue system('ls'), typing
3067 causes ipython to simply issue system('ls'), typing
3070 !!ls
3068 !!ls
3071 is a shorthand equivalent to:
3069 is a shorthand equivalent to:
3072 %sx ls
3070 %sx ls
3073
3071
3074 2) %sx differs from %sc in that %sx automatically splits into a list,
3072 2) %sx differs from %sc in that %sx automatically splits into a list,
3075 like '%sc -l'. The reason for this is to make it as easy as possible
3073 like '%sc -l'. The reason for this is to make it as easy as possible
3076 to process line-oriented shell output via further python commands.
3074 to process line-oriented shell output via further python commands.
3077 %sc is meant to provide much finer control, but requires more
3075 %sc is meant to provide much finer control, but requires more
3078 typing.
3076 typing.
3079
3077
3080 3) Just like %sc -l, this is a list with special attributes:
3078 3) Just like %sc -l, this is a list with special attributes:
3081
3079
3082 .l (or .list) : value as list.
3080 .l (or .list) : value as list.
3083 .n (or .nlstr): value as newline-separated string.
3081 .n (or .nlstr): value as newline-separated string.
3084 .s (or .spstr): value as whitespace-separated string.
3082 .s (or .spstr): value as whitespace-separated string.
3085
3083
3086 This is very useful when trying to use such lists as arguments to
3084 This is very useful when trying to use such lists as arguments to
3087 system commands."""
3085 system commands."""
3088
3086
3089 if parameter_s:
3087 if parameter_s:
3090 return self.shell.getoutput(parameter_s)
3088 return self.shell.getoutput(parameter_s)
3091
3089
3092
3090
3093 def magic_bookmark(self, parameter_s=''):
3091 def magic_bookmark(self, parameter_s=''):
3094 """Manage IPython's bookmark system.
3092 """Manage IPython's bookmark system.
3095
3093
3096 %bookmark <name> - set bookmark to current dir
3094 %bookmark <name> - set bookmark to current dir
3097 %bookmark <name> <dir> - set bookmark to <dir>
3095 %bookmark <name> <dir> - set bookmark to <dir>
3098 %bookmark -l - list all bookmarks
3096 %bookmark -l - list all bookmarks
3099 %bookmark -d <name> - remove bookmark
3097 %bookmark -d <name> - remove bookmark
3100 %bookmark -r - remove all bookmarks
3098 %bookmark -r - remove all bookmarks
3101
3099
3102 You can later on access a bookmarked folder with:
3100 You can later on access a bookmarked folder with:
3103 %cd -b <name>
3101 %cd -b <name>
3104 or simply '%cd <name>' if there is no directory called <name> AND
3102 or simply '%cd <name>' if there is no directory called <name> AND
3105 there is such a bookmark defined.
3103 there is such a bookmark defined.
3106
3104
3107 Your bookmarks persist through IPython sessions, but they are
3105 Your bookmarks persist through IPython sessions, but they are
3108 associated with each profile."""
3106 associated with each profile."""
3109
3107
3110 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3108 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3111 if len(args) > 2:
3109 if len(args) > 2:
3112 raise UsageError("%bookmark: too many arguments")
3110 raise UsageError("%bookmark: too many arguments")
3113
3111
3114 bkms = self.db.get('bookmarks',{})
3112 bkms = self.db.get('bookmarks',{})
3115
3113
3116 if opts.has_key('d'):
3114 if opts.has_key('d'):
3117 try:
3115 try:
3118 todel = args[0]
3116 todel = args[0]
3119 except IndexError:
3117 except IndexError:
3120 raise UsageError(
3118 raise UsageError(
3121 "%bookmark -d: must provide a bookmark to delete")
3119 "%bookmark -d: must provide a bookmark to delete")
3122 else:
3120 else:
3123 try:
3121 try:
3124 del bkms[todel]
3122 del bkms[todel]
3125 except KeyError:
3123 except KeyError:
3126 raise UsageError(
3124 raise UsageError(
3127 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3125 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3128
3126
3129 elif opts.has_key('r'):
3127 elif opts.has_key('r'):
3130 bkms = {}
3128 bkms = {}
3131 elif opts.has_key('l'):
3129 elif opts.has_key('l'):
3132 bks = bkms.keys()
3130 bks = bkms.keys()
3133 bks.sort()
3131 bks.sort()
3134 if bks:
3132 if bks:
3135 size = max(map(len,bks))
3133 size = max(map(len,bks))
3136 else:
3134 else:
3137 size = 0
3135 size = 0
3138 fmt = '%-'+str(size)+'s -> %s'
3136 fmt = '%-'+str(size)+'s -> %s'
3139 print 'Current bookmarks:'
3137 print 'Current bookmarks:'
3140 for bk in bks:
3138 for bk in bks:
3141 print fmt % (bk,bkms[bk])
3139 print fmt % (bk,bkms[bk])
3142 else:
3140 else:
3143 if not args:
3141 if not args:
3144 raise UsageError("%bookmark: You must specify the bookmark name")
3142 raise UsageError("%bookmark: You must specify the bookmark name")
3145 elif len(args)==1:
3143 elif len(args)==1:
3146 bkms[args[0]] = os.getcwd()
3144 bkms[args[0]] = os.getcwd()
3147 elif len(args)==2:
3145 elif len(args)==2:
3148 bkms[args[0]] = args[1]
3146 bkms[args[0]] = args[1]
3149 self.db['bookmarks'] = bkms
3147 self.db['bookmarks'] = bkms
3150
3148
3151 def magic_pycat(self, parameter_s=''):
3149 def magic_pycat(self, parameter_s=''):
3152 """Show a syntax-highlighted file through a pager.
3150 """Show a syntax-highlighted file through a pager.
3153
3151
3154 This magic is similar to the cat utility, but it will assume the file
3152 This magic is similar to the cat utility, but it will assume the file
3155 to be Python source and will show it with syntax highlighting. """
3153 to be Python source and will show it with syntax highlighting. """
3156
3154
3157 try:
3155 try:
3158 filename = get_py_filename(parameter_s)
3156 filename = get_py_filename(parameter_s)
3159 cont = file_read(filename)
3157 cont = file_read(filename)
3160 except IOError:
3158 except IOError:
3161 try:
3159 try:
3162 cont = eval(parameter_s,self.user_ns)
3160 cont = eval(parameter_s,self.user_ns)
3163 except NameError:
3161 except NameError:
3164 cont = None
3162 cont = None
3165 if cont is None:
3163 if cont is None:
3166 print "Error: no such file or variable"
3164 print "Error: no such file or variable"
3167 return
3165 return
3168
3166
3169 page.page(self.shell.pycolorize(cont))
3167 page.page(self.shell.pycolorize(cont))
3170
3168
3171 def _rerun_pasted(self):
3169 def _rerun_pasted(self):
3172 """ Rerun a previously pasted command.
3170 """ Rerun a previously pasted command.
3173 """
3171 """
3174 b = self.user_ns.get('pasted_block', None)
3172 b = self.user_ns.get('pasted_block', None)
3175 if b is None:
3173 if b is None:
3176 raise UsageError('No previous pasted block available')
3174 raise UsageError('No previous pasted block available')
3177 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3175 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3178 exec b in self.user_ns
3176 exec b in self.user_ns
3179
3177
3180 def _get_pasted_lines(self, sentinel):
3178 def _get_pasted_lines(self, sentinel):
3181 """ Yield pasted lines until the user enters the given sentinel value.
3179 """ Yield pasted lines until the user enters the given sentinel value.
3182 """
3180 """
3183 from IPython.core import interactiveshell
3181 from IPython.core import interactiveshell
3184 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3182 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3185 while True:
3183 while True:
3186 l = interactiveshell.raw_input_original(':')
3184 l = interactiveshell.raw_input_original(':')
3187 if l == sentinel:
3185 if l == sentinel:
3188 return
3186 return
3189 else:
3187 else:
3190 yield l
3188 yield l
3191
3189
3192 def _strip_pasted_lines_for_code(self, raw_lines):
3190 def _strip_pasted_lines_for_code(self, raw_lines):
3193 """ Strip non-code parts of a sequence of lines to return a block of
3191 """ Strip non-code parts of a sequence of lines to return a block of
3194 code.
3192 code.
3195 """
3193 """
3196 # Regular expressions that declare text we strip from the input:
3194 # Regular expressions that declare text we strip from the input:
3197 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3195 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3198 r'^\s*(\s?>)+', # Python input prompt
3196 r'^\s*(\s?>)+', # Python input prompt
3199 r'^\s*\.{3,}', # Continuation prompts
3197 r'^\s*\.{3,}', # Continuation prompts
3200 r'^\++',
3198 r'^\++',
3201 ]
3199 ]
3202
3200
3203 strip_from_start = map(re.compile,strip_re)
3201 strip_from_start = map(re.compile,strip_re)
3204
3202
3205 lines = []
3203 lines = []
3206 for l in raw_lines:
3204 for l in raw_lines:
3207 for pat in strip_from_start:
3205 for pat in strip_from_start:
3208 l = pat.sub('',l)
3206 l = pat.sub('',l)
3209 lines.append(l)
3207 lines.append(l)
3210
3208
3211 block = "\n".join(lines) + '\n'
3209 block = "\n".join(lines) + '\n'
3212 #print "block:\n",block
3210 #print "block:\n",block
3213 return block
3211 return block
3214
3212
3215 def _execute_block(self, block, par):
3213 def _execute_block(self, block, par):
3216 """ Execute a block, or store it in a variable, per the user's request.
3214 """ Execute a block, or store it in a variable, per the user's request.
3217 """
3215 """
3218 if not par:
3216 if not par:
3219 b = textwrap.dedent(block)
3217 b = textwrap.dedent(block)
3220 self.user_ns['pasted_block'] = b
3218 self.user_ns['pasted_block'] = b
3221 exec b in self.user_ns
3219 exec b in self.user_ns
3222 else:
3220 else:
3223 self.user_ns[par] = SList(block.splitlines())
3221 self.user_ns[par] = SList(block.splitlines())
3224 print "Block assigned to '%s'" % par
3222 print "Block assigned to '%s'" % par
3225
3223
3226 def magic_quickref(self,arg):
3224 def magic_quickref(self,arg):
3227 """ Show a quick reference sheet """
3225 """ Show a quick reference sheet """
3228 import IPython.core.usage
3226 import IPython.core.usage
3229 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3227 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3230
3228
3231 page.page(qr)
3229 page.page(qr)
3232
3230
3233 def magic_doctest_mode(self,parameter_s=''):
3231 def magic_doctest_mode(self,parameter_s=''):
3234 """Toggle doctest mode on and off.
3232 """Toggle doctest mode on and off.
3235
3233
3236 This mode is intended to make IPython behave as much as possible like a
3234 This mode is intended to make IPython behave as much as possible like a
3237 plain Python shell, from the perspective of how its prompts, exceptions
3235 plain Python shell, from the perspective of how its prompts, exceptions
3238 and output look. This makes it easy to copy and paste parts of a
3236 and output look. This makes it easy to copy and paste parts of a
3239 session into doctests. It does so by:
3237 session into doctests. It does so by:
3240
3238
3241 - Changing the prompts to the classic ``>>>`` ones.
3239 - Changing the prompts to the classic ``>>>`` ones.
3242 - Changing the exception reporting mode to 'Plain'.
3240 - Changing the exception reporting mode to 'Plain'.
3243 - Disabling pretty-printing of output.
3241 - Disabling pretty-printing of output.
3244
3242
3245 Note that IPython also supports the pasting of code snippets that have
3243 Note that IPython also supports the pasting of code snippets that have
3246 leading '>>>' and '...' prompts in them. This means that you can paste
3244 leading '>>>' and '...' prompts in them. This means that you can paste
3247 doctests from files or docstrings (even if they have leading
3245 doctests from files or docstrings (even if they have leading
3248 whitespace), and the code will execute correctly. You can then use
3246 whitespace), and the code will execute correctly. You can then use
3249 '%history -t' to see the translated history; this will give you the
3247 '%history -t' to see the translated history; this will give you the
3250 input after removal of all the leading prompts and whitespace, which
3248 input after removal of all the leading prompts and whitespace, which
3251 can be pasted back into an editor.
3249 can be pasted back into an editor.
3252
3250
3253 With these features, you can switch into this mode easily whenever you
3251 With these features, you can switch into this mode easily whenever you
3254 need to do testing and changes to doctests, without having to leave
3252 need to do testing and changes to doctests, without having to leave
3255 your existing IPython session.
3253 your existing IPython session.
3256 """
3254 """
3257
3255
3258 from IPython.utils.ipstruct import Struct
3256 from IPython.utils.ipstruct import Struct
3259
3257
3260 # Shorthands
3258 # Shorthands
3261 shell = self.shell
3259 shell = self.shell
3262 oc = shell.displayhook
3260 oc = shell.displayhook
3263 meta = shell.meta
3261 meta = shell.meta
3264 disp_formatter = self.shell.display_formatter
3262 disp_formatter = self.shell.display_formatter
3265 ptformatter = disp_formatter.formatters['text/plain']
3263 ptformatter = disp_formatter.formatters['text/plain']
3266 # dstore is a data store kept in the instance metadata bag to track any
3264 # dstore is a data store kept in the instance metadata bag to track any
3267 # changes we make, so we can undo them later.
3265 # changes we make, so we can undo them later.
3268 dstore = meta.setdefault('doctest_mode',Struct())
3266 dstore = meta.setdefault('doctest_mode',Struct())
3269 save_dstore = dstore.setdefault
3267 save_dstore = dstore.setdefault
3270
3268
3271 # save a few values we'll need to recover later
3269 # save a few values we'll need to recover later
3272 mode = save_dstore('mode',False)
3270 mode = save_dstore('mode',False)
3273 save_dstore('rc_pprint',ptformatter.pprint)
3271 save_dstore('rc_pprint',ptformatter.pprint)
3274 save_dstore('xmode',shell.InteractiveTB.mode)
3272 save_dstore('xmode',shell.InteractiveTB.mode)
3275 save_dstore('rc_separate_out',shell.separate_out)
3273 save_dstore('rc_separate_out',shell.separate_out)
3276 save_dstore('rc_separate_out2',shell.separate_out2)
3274 save_dstore('rc_separate_out2',shell.separate_out2)
3277 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3275 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3278 save_dstore('rc_separate_in',shell.separate_in)
3276 save_dstore('rc_separate_in',shell.separate_in)
3279 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3277 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3280
3278
3281 if mode == False:
3279 if mode == False:
3282 # turn on
3280 # turn on
3283 oc.prompt1.p_template = '>>> '
3281 oc.prompt1.p_template = '>>> '
3284 oc.prompt2.p_template = '... '
3282 oc.prompt2.p_template = '... '
3285 oc.prompt_out.p_template = ''
3283 oc.prompt_out.p_template = ''
3286
3284
3287 # Prompt separators like plain python
3285 # Prompt separators like plain python
3288 oc.input_sep = oc.prompt1.sep = ''
3286 oc.input_sep = oc.prompt1.sep = ''
3289 oc.output_sep = ''
3287 oc.output_sep = ''
3290 oc.output_sep2 = ''
3288 oc.output_sep2 = ''
3291
3289
3292 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3290 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3293 oc.prompt_out.pad_left = False
3291 oc.prompt_out.pad_left = False
3294
3292
3295 ptformatter.pprint = False
3293 ptformatter.pprint = False
3296 disp_formatter.plain_text_only = True
3294 disp_formatter.plain_text_only = True
3297
3295
3298 shell.magic_xmode('Plain')
3296 shell.magic_xmode('Plain')
3299 else:
3297 else:
3300 # turn off
3298 # turn off
3301 oc.prompt1.p_template = shell.prompt_in1
3299 oc.prompt1.p_template = shell.prompt_in1
3302 oc.prompt2.p_template = shell.prompt_in2
3300 oc.prompt2.p_template = shell.prompt_in2
3303 oc.prompt_out.p_template = shell.prompt_out
3301 oc.prompt_out.p_template = shell.prompt_out
3304
3302
3305 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3303 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3306
3304
3307 oc.output_sep = dstore.rc_separate_out
3305 oc.output_sep = dstore.rc_separate_out
3308 oc.output_sep2 = dstore.rc_separate_out2
3306 oc.output_sep2 = dstore.rc_separate_out2
3309
3307
3310 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3308 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3311 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3309 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3312
3310
3313 ptformatter.pprint = dstore.rc_pprint
3311 ptformatter.pprint = dstore.rc_pprint
3314 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3312 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3315
3313
3316 shell.magic_xmode(dstore.xmode)
3314 shell.magic_xmode(dstore.xmode)
3317
3315
3318 # Store new mode and inform
3316 # Store new mode and inform
3319 dstore.mode = bool(1-int(mode))
3317 dstore.mode = bool(1-int(mode))
3320 mode_label = ['OFF','ON'][dstore.mode]
3318 mode_label = ['OFF','ON'][dstore.mode]
3321 print 'Doctest mode is:', mode_label
3319 print 'Doctest mode is:', mode_label
3322
3320
3323 def magic_gui(self, parameter_s=''):
3321 def magic_gui(self, parameter_s=''):
3324 """Enable or disable IPython GUI event loop integration.
3322 """Enable or disable IPython GUI event loop integration.
3325
3323
3326 %gui [GUINAME]
3324 %gui [GUINAME]
3327
3325
3328 This magic replaces IPython's threaded shells that were activated
3326 This magic replaces IPython's threaded shells that were activated
3329 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3327 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3330 can now be enabled, disabled and changed at runtime and keyboard
3328 can now be enabled, disabled and changed at runtime and keyboard
3331 interrupts should work without any problems. The following toolkits
3329 interrupts should work without any problems. The following toolkits
3332 are supported: wxPython, PyQt4, PyGTK, and Tk::
3330 are supported: wxPython, PyQt4, PyGTK, and Tk::
3333
3331
3334 %gui wx # enable wxPython event loop integration
3332 %gui wx # enable wxPython event loop integration
3335 %gui qt4|qt # enable PyQt4 event loop integration
3333 %gui qt4|qt # enable PyQt4 event loop integration
3336 %gui gtk # enable PyGTK event loop integration
3334 %gui gtk # enable PyGTK event loop integration
3337 %gui tk # enable Tk event loop integration
3335 %gui tk # enable Tk event loop integration
3338 %gui # disable all event loop integration
3336 %gui # disable all event loop integration
3339
3337
3340 WARNING: after any of these has been called you can simply create
3338 WARNING: after any of these has been called you can simply create
3341 an application object, but DO NOT start the event loop yourself, as
3339 an application object, but DO NOT start the event loop yourself, as
3342 we have already handled that.
3340 we have already handled that.
3343 """
3341 """
3344 from IPython.lib.inputhook import enable_gui
3342 from IPython.lib.inputhook import enable_gui
3345 opts, arg = self.parse_options(parameter_s, '')
3343 opts, arg = self.parse_options(parameter_s, '')
3346 if arg=='': arg = None
3344 if arg=='': arg = None
3347 return enable_gui(arg)
3345 return enable_gui(arg)
3348
3346
3349 def magic_load_ext(self, module_str):
3347 def magic_load_ext(self, module_str):
3350 """Load an IPython extension by its module name."""
3348 """Load an IPython extension by its module name."""
3351 return self.extension_manager.load_extension(module_str)
3349 return self.extension_manager.load_extension(module_str)
3352
3350
3353 def magic_unload_ext(self, module_str):
3351 def magic_unload_ext(self, module_str):
3354 """Unload an IPython extension by its module name."""
3352 """Unload an IPython extension by its module name."""
3355 self.extension_manager.unload_extension(module_str)
3353 self.extension_manager.unload_extension(module_str)
3356
3354
3357 def magic_reload_ext(self, module_str):
3355 def magic_reload_ext(self, module_str):
3358 """Reload an IPython extension by its module name."""
3356 """Reload an IPython extension by its module name."""
3359 self.extension_manager.reload_extension(module_str)
3357 self.extension_manager.reload_extension(module_str)
3360
3358
3361 @skip_doctest
3359 @skip_doctest
3362 def magic_install_profiles(self, s):
3360 def magic_install_profiles(self, s):
3363 """Install the default IPython profiles into the .ipython dir.
3361 """Install the default IPython profiles into the .ipython dir.
3364
3362
3365 If the default profiles have already been installed, they will not
3363 If the default profiles have already been installed, they will not
3366 be overwritten. You can force overwriting them by using the ``-o``
3364 be overwritten. You can force overwriting them by using the ``-o``
3367 option::
3365 option::
3368
3366
3369 In [1]: %install_profiles -o
3367 In [1]: %install_profiles -o
3370 """
3368 """
3371 if '-o' in s:
3369 if '-o' in s:
3372 overwrite = True
3370 overwrite = True
3373 else:
3371 else:
3374 overwrite = False
3372 overwrite = False
3375 from IPython.config import profile
3373 from IPython.config import profile
3376 profile_dir = os.path.split(profile.__file__)[0]
3374 profile_dir = os.path.dirname(profile.__file__)
3377 ipython_dir = self.ipython_dir
3375 ipython_dir = self.ipython_dir
3378 files = os.listdir(profile_dir)
3376 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3379
3377 for src in os.listdir(profile_dir):
3380 to_install = []
3378 if src.startswith('profile_'):
3381 for f in files:
3379 name = src.replace('profile_', '')
3382 if f.startswith('ipython_config'):
3380 print " %s"%name
3383 src = os.path.join(profile_dir, f)
3381 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3384 dst = os.path.join(ipython_dir, f)
3382 pd.copy_config_file('ipython_config.py', path=src,
3385 if (not os.path.isfile(dst)) or overwrite:
3383 overwrite=overwrite)
3386 to_install.append((f, src, dst))
3387 if len(to_install)>0:
3388 print "Installing profiles to: ", ipython_dir
3389 for (f, src, dst) in to_install:
3390 shutil.copy(src, dst)
3391 print " %s" % f
3392
3384
3393 @skip_doctest
3385 @skip_doctest
3394 def magic_install_default_config(self, s):
3386 def magic_install_default_config(self, s):
3395 """Install IPython's default config file into the .ipython dir.
3387 """Install IPython's default config file into the .ipython dir.
3396
3388
3397 If the default config file (:file:`ipython_config.py`) is already
3389 If the default config file (:file:`ipython_config.py`) is already
3398 installed, it will not be overwritten. You can force overwriting
3390 installed, it will not be overwritten. You can force overwriting
3399 by using the ``-o`` option::
3391 by using the ``-o`` option::
3400
3392
3401 In [1]: %install_default_config
3393 In [1]: %install_default_config
3402 """
3394 """
3403 if '-o' in s:
3395 if '-o' in s:
3404 overwrite = True
3396 overwrite = True
3405 else:
3397 else:
3406 overwrite = False
3398 overwrite = False
3407 from IPython.config import default
3399 pd = self.shell.profile_dir
3408 config_dir = os.path.split(default.__file__)[0]
3400 print "Installing default config file in: %s" % pd.location
3409 ipython_dir = self.ipython_dir
3401 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3410 default_config_file_name = 'ipython_config.py'
3411 src = os.path.join(config_dir, default_config_file_name)
3412 dst = os.path.join(ipython_dir, default_config_file_name)
3413 if (not os.path.isfile(dst)) or overwrite:
3414 shutil.copy(src, dst)
3415 print "Installing default config file: %s" % dst
3416
3402
3417 # Pylab support: simple wrappers that activate pylab, load gui input
3403 # Pylab support: simple wrappers that activate pylab, load gui input
3418 # handling and modify slightly %run
3404 # handling and modify slightly %run
3419
3405
3420 @skip_doctest
3406 @skip_doctest
3421 def _pylab_magic_run(self, parameter_s=''):
3407 def _pylab_magic_run(self, parameter_s=''):
3422 Magic.magic_run(self, parameter_s,
3408 Magic.magic_run(self, parameter_s,
3423 runner=mpl_runner(self.shell.safe_execfile))
3409 runner=mpl_runner(self.shell.safe_execfile))
3424
3410
3425 _pylab_magic_run.__doc__ = magic_run.__doc__
3411 _pylab_magic_run.__doc__ = magic_run.__doc__
3426
3412
3427 @skip_doctest
3413 @skip_doctest
3428 def magic_pylab(self, s):
3414 def magic_pylab(self, s):
3429 """Load numpy and matplotlib to work interactively.
3415 """Load numpy and matplotlib to work interactively.
3430
3416
3431 %pylab [GUINAME]
3417 %pylab [GUINAME]
3432
3418
3433 This function lets you activate pylab (matplotlib, numpy and
3419 This function lets you activate pylab (matplotlib, numpy and
3434 interactive support) at any point during an IPython session.
3420 interactive support) at any point during an IPython session.
3435
3421
3436 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3422 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3437 pylab and mlab, as well as all names from numpy and pylab.
3423 pylab and mlab, as well as all names from numpy and pylab.
3438
3424
3439 Parameters
3425 Parameters
3440 ----------
3426 ----------
3441 guiname : optional
3427 guiname : optional
3442 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3428 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3443 'tk'). If given, the corresponding Matplotlib backend is used,
3429 'tk'). If given, the corresponding Matplotlib backend is used,
3444 otherwise matplotlib's default (which you can override in your
3430 otherwise matplotlib's default (which you can override in your
3445 matplotlib config file) is used.
3431 matplotlib config file) is used.
3446
3432
3447 Examples
3433 Examples
3448 --------
3434 --------
3449 In this case, where the MPL default is TkAgg:
3435 In this case, where the MPL default is TkAgg:
3450 In [2]: %pylab
3436 In [2]: %pylab
3451
3437
3452 Welcome to pylab, a matplotlib-based Python environment.
3438 Welcome to pylab, a matplotlib-based Python environment.
3453 Backend in use: TkAgg
3439 Backend in use: TkAgg
3454 For more information, type 'help(pylab)'.
3440 For more information, type 'help(pylab)'.
3455
3441
3456 But you can explicitly request a different backend:
3442 But you can explicitly request a different backend:
3457 In [3]: %pylab qt
3443 In [3]: %pylab qt
3458
3444
3459 Welcome to pylab, a matplotlib-based Python environment.
3445 Welcome to pylab, a matplotlib-based Python environment.
3460 Backend in use: Qt4Agg
3446 Backend in use: Qt4Agg
3461 For more information, type 'help(pylab)'.
3447 For more information, type 'help(pylab)'.
3462 """
3448 """
3463 self.shell.enable_pylab(s)
3449 self.shell.enable_pylab(s)
3464
3450
3465 def magic_tb(self, s):
3451 def magic_tb(self, s):
3466 """Print the last traceback with the currently active exception mode.
3452 """Print the last traceback with the currently active exception mode.
3467
3453
3468 See %xmode for changing exception reporting modes."""
3454 See %xmode for changing exception reporting modes."""
3469 self.shell.showtraceback()
3455 self.shell.showtraceback()
3470
3456
3471 @skip_doctest
3457 @skip_doctest
3472 def magic_precision(self, s=''):
3458 def magic_precision(self, s=''):
3473 """Set floating point precision for pretty printing.
3459 """Set floating point precision for pretty printing.
3474
3460
3475 Can set either integer precision or a format string.
3461 Can set either integer precision or a format string.
3476
3462
3477 If numpy has been imported and precision is an int,
3463 If numpy has been imported and precision is an int,
3478 numpy display precision will also be set, via ``numpy.set_printoptions``.
3464 numpy display precision will also be set, via ``numpy.set_printoptions``.
3479
3465
3480 If no argument is given, defaults will be restored.
3466 If no argument is given, defaults will be restored.
3481
3467
3482 Examples
3468 Examples
3483 --------
3469 --------
3484 ::
3470 ::
3485
3471
3486 In [1]: from math import pi
3472 In [1]: from math import pi
3487
3473
3488 In [2]: %precision 3
3474 In [2]: %precision 3
3489 Out[2]: '%.3f'
3475 Out[2]: '%.3f'
3490
3476
3491 In [3]: pi
3477 In [3]: pi
3492 Out[3]: 3.142
3478 Out[3]: 3.142
3493
3479
3494 In [4]: %precision %i
3480 In [4]: %precision %i
3495 Out[4]: '%i'
3481 Out[4]: '%i'
3496
3482
3497 In [5]: pi
3483 In [5]: pi
3498 Out[5]: 3
3484 Out[5]: 3
3499
3485
3500 In [6]: %precision %e
3486 In [6]: %precision %e
3501 Out[6]: '%e'
3487 Out[6]: '%e'
3502
3488
3503 In [7]: pi**10
3489 In [7]: pi**10
3504 Out[7]: 9.364805e+04
3490 Out[7]: 9.364805e+04
3505
3491
3506 In [8]: %precision
3492 In [8]: %precision
3507 Out[8]: '%r'
3493 Out[8]: '%r'
3508
3494
3509 In [9]: pi**10
3495 In [9]: pi**10
3510 Out[9]: 93648.047476082982
3496 Out[9]: 93648.047476082982
3511
3497
3512 """
3498 """
3513
3499
3514 ptformatter = self.shell.display_formatter.formatters['text/plain']
3500 ptformatter = self.shell.display_formatter.formatters['text/plain']
3515 ptformatter.float_precision = s
3501 ptformatter.float_precision = s
3516 return ptformatter.float_format
3502 return ptformatter.float_format
3517
3503
3518 # end Magic
3504 # end Magic
@@ -1,71 +1,49 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for IPython.core.application"""
2 """Tests for IPython.core.application"""
3
3
4 import os
4 import os
5 import tempfile
5 import tempfile
6
6
7 from IPython.core.application import Application
7 from IPython.core.application import BaseIPythonApplication
8 from IPython.testing import decorators as testdec
8 from IPython.testing import decorators as testdec
9
9
10 @testdec.onlyif_unicode_paths
10 @testdec.onlyif_unicode_paths
11 def test_unicode_cwd():
11 def test_unicode_cwd():
12 """Check that IPython starts with non-ascii characters in the path."""
12 """Check that IPython starts with non-ascii characters in the path."""
13 wd = tempfile.mkdtemp(suffix=u"€")
13 wd = tempfile.mkdtemp(suffix=u"€")
14
14
15 old_wd = os.getcwdu()
15 old_wd = os.getcwdu()
16 os.chdir(wd)
16 os.chdir(wd)
17 #raise Exception(repr(os.getcwd()))
17 #raise Exception(repr(os.getcwd()))
18 try:
18 try:
19 app = Application()
19 app = BaseIPythonApplication()
20 # The lines below are copied from Application.initialize()
20 # The lines below are copied from Application.initialize()
21 app.create_default_config()
21 app.init_profile_dir()
22 app.log_default_config()
22 app.init_config_files()
23 app.set_default_config_log_level()
23 app.load_config_file(suppress_errors=False)
24
25 # Find resources needed for filesystem access, using information from
26 # the above two
27 app.find_ipython_dir()
28 app.find_resources()
29 app.find_config_file_name()
30 app.find_config_file_paths()
31
32 # File-based config
33 app.pre_load_file_config()
34 app.load_file_config(suppress_errors=False)
35 finally:
24 finally:
36 os.chdir(old_wd)
25 os.chdir(old_wd)
37
26
38 @testdec.onlyif_unicode_paths
27 @testdec.onlyif_unicode_paths
39 def test_unicode_ipdir():
28 def test_unicode_ipdir():
40 """Check that IPython starts with non-ascii characters in the IP dir."""
29 """Check that IPython starts with non-ascii characters in the IP dir."""
41 ipdir = tempfile.mkdtemp(suffix=u"€")
30 ipdir = tempfile.mkdtemp(suffix=u"€")
42
31
43 # Create the config file, so it tries to load it.
32 # Create the config file, so it tries to load it.
44 with open(os.path.join(ipdir, 'ipython_config.py'), "w") as f:
33 with open(os.path.join(ipdir, 'ipython_config.py'), "w") as f:
45 pass
34 pass
46
35
47 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
36 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
48 old_ipdir2 = os.environ.pop("IPYTHON_DIR", None)
37 old_ipdir2 = os.environ.pop("IPYTHON_DIR", None)
49 os.environ["IPYTHONDIR"] = ipdir.encode("utf-8")
38 os.environ["IPYTHONDIR"] = ipdir.encode("utf-8")
50 try:
39 try:
51 app = Application()
40 app = BaseIPythonApplication()
52 # The lines below are copied from Application.initialize()
41 # The lines below are copied from Application.initialize()
53 app.create_default_config()
42 app.init_profile_dir()
54 app.log_default_config()
43 app.init_config_files()
55 app.set_default_config_log_level()
44 app.load_config_file(suppress_errors=False)
56
57 # Find resources needed for filesystem access, using information from
58 # the above two
59 app.find_ipython_dir()
60 app.find_resources()
61 app.find_config_file_name()
62 app.find_config_file_paths()
63
64 # File-based config
65 app.pre_load_file_config()
66 app.load_file_config(suppress_errors=False)
67 finally:
45 finally:
68 if old_ipdir1:
46 if old_ipdir1:
69 os.environ["IPYTHONDIR"] = old_ipdir1
47 os.environ["IPYTHONDIR"] = old_ipdir1
70 if old_ipdir2:
48 if old_ipdir2:
71 os.environ["IPYTHONDIR"] = old_ipdir2
49 os.environ["IPYTHONDIR"] = old_ipdir2
@@ -1,294 +1,300 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Magic command interface for interactive parallel work."""
4 """Magic command interface for interactive parallel work."""
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import ast
17 import ast
18 import re
18 import re
19
19
20 from IPython.core.plugin import Plugin
20 from IPython.core.plugin import Plugin
21 from IPython.utils.traitlets import Bool, Any, Instance
21 from IPython.utils.traitlets import Bool, Any, Instance
22 from IPython.testing.skipdoctest import skip_doctest
22 from IPython.testing.skipdoctest import skip_doctest
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Definitions of magic functions for use with IPython
25 # Definitions of magic functions for use with IPython
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 NO_ACTIVE_VIEW = """
29 NO_ACTIVE_VIEW = """
30 Use activate() on a DirectView object to activate it for magics.
30 Use activate() on a DirectView object to activate it for magics.
31 """
31 """
32
32
33
33
34 class ParalleMagic(Plugin):
34 class ParalleMagic(Plugin):
35 """A component to manage the %result, %px and %autopx magics."""
35 """A component to manage the %result, %px and %autopx magics."""
36
36
37 active_view = Instance('IPython.parallel.client.view.DirectView')
37 active_view = Instance('IPython.parallel.client.view.DirectView')
38 verbose = Bool(False, config=True)
38 verbose = Bool(False, config=True)
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
40
40
41 def __init__(self, shell=None, config=None):
41 def __init__(self, shell=None, config=None):
42 super(ParalleMagic, self).__init__(shell=shell, config=config)
42 super(ParalleMagic, self).__init__(shell=shell, config=config)
43 self._define_magics()
43 self._define_magics()
44 # A flag showing if autopx is activated or not
44 # A flag showing if autopx is activated or not
45 self.autopx = False
45 self.autopx = False
46
46
47 def _define_magics(self):
47 def _define_magics(self):
48 """Define the magic functions."""
48 """Define the magic functions."""
49 self.shell.define_magic('result', self.magic_result)
49 self.shell.define_magic('result', self.magic_result)
50 self.shell.define_magic('px', self.magic_px)
50 self.shell.define_magic('px', self.magic_px)
51 self.shell.define_magic('autopx', self.magic_autopx)
51 self.shell.define_magic('autopx', self.magic_autopx)
52
52
53 @skip_doctest
53 @skip_doctest
54 def magic_result(self, ipself, parameter_s=''):
54 def magic_result(self, ipself, parameter_s=''):
55 """Print the result of command i on all engines..
55 """Print the result of command i on all engines..
56
56
57 To use this a :class:`DirectView` instance must be created
57 To use this a :class:`DirectView` instance must be created
58 and then activated by calling its :meth:`activate` method.
58 and then activated by calling its :meth:`activate` method.
59
59
60 Then you can do the following::
60 Then you can do the following::
61
61
62 In [23]: %result
62 In [23]: %result
63 Out[23]:
63 Out[23]:
64 <Results List>
64 <Results List>
65 [0] In [6]: a = 10
65 [0] In [6]: a = 10
66 [1] In [6]: a = 10
66 [1] In [6]: a = 10
67
67
68 In [22]: %result 6
68 In [22]: %result 6
69 Out[22]:
69 Out[22]:
70 <Results List>
70 <Results List>
71 [0] In [6]: a = 10
71 [0] In [6]: a = 10
72 [1] In [6]: a = 10
72 [1] In [6]: a = 10
73 """
73 """
74 if self.active_view is None:
74 if self.active_view is None:
75 print NO_ACTIVE_VIEW
75 print NO_ACTIVE_VIEW
76 return
76 return
77
77
78 try:
78 try:
79 index = int(parameter_s)
79 index = int(parameter_s)
80 except:
80 except:
81 index = None
81 index = None
82 result = self.active_view.get_result(index)
82 result = self.active_view.get_result(index)
83 return result
83 return result
84
84
85 @skip_doctest
85 @skip_doctest
86 def magic_px(self, ipself, parameter_s=''):
86 def magic_px(self, ipself, parameter_s=''):
87 """Executes the given python command in parallel.
87 """Executes the given python command in parallel.
88
88
89 To use this a :class:`DirectView` instance must be created
89 To use this a :class:`DirectView` instance must be created
90 and then activated by calling its :meth:`activate` method.
90 and then activated by calling its :meth:`activate` method.
91
91
92 Then you can do the following::
92 Then you can do the following::
93
93
94 In [24]: %px a = 5
94 In [24]: %px a = 5
95 Parallel execution on engines: all
95 Parallel execution on engine(s): all
96 Out[24]:
96 Out[24]:
97 <Results List>
97 <Results List>
98 [0] In [7]: a = 5
98 [0] In [7]: a = 5
99 [1] In [7]: a = 5
99 [1] In [7]: a = 5
100 """
100 """
101
101
102 if self.active_view is None:
102 if self.active_view is None:
103 print NO_ACTIVE_VIEW
103 print NO_ACTIVE_VIEW
104 return
104 return
105 print "Parallel execution on engines: %s" % self.active_view.targets
105 print "Parallel execution on engine(s): %s" % self.active_view.targets
106 result = self.active_view.execute(parameter_s, block=False)
106 result = self.active_view.execute(parameter_s, block=False)
107 if self.active_view.block:
107 if self.active_view.block:
108 result.get()
108 result.get()
109 self._maybe_display_output(result)
109 self._maybe_display_output(result)
110
110
111 @skip_doctest
111 @skip_doctest
112 def magic_autopx(self, ipself, parameter_s=''):
112 def magic_autopx(self, ipself, parameter_s=''):
113 """Toggles auto parallel mode.
113 """Toggles auto parallel mode.
114
114
115 To use this a :class:`DirectView` instance must be created
115 To use this a :class:`DirectView` instance must be created
116 and then activated by calling its :meth:`activate` method. Once this
116 and then activated by calling its :meth:`activate` method. Once this
117 is called, all commands typed at the command line are send to
117 is called, all commands typed at the command line are send to
118 the engines to be executed in parallel. To control which engine
118 the engines to be executed in parallel. To control which engine
119 are used, set the ``targets`` attributed of the multiengine client
119 are used, set the ``targets`` attributed of the multiengine client
120 before entering ``%autopx`` mode.
120 before entering ``%autopx`` mode.
121
121
122 Then you can do the following::
122 Then you can do the following::
123
123
124 In [25]: %autopx
124 In [25]: %autopx
125 %autopx to enabled
125 %autopx to enabled
126
126
127 In [26]: a = 10
127 In [26]: a = 10
128 Parallel execution on engines: [0,1,2,3]
128 Parallel execution on engine(s): [0,1,2,3]
129 In [27]: print a
129 In [27]: print a
130 Parallel execution on engines: [0,1,2,3]
130 Parallel execution on engine(s): [0,1,2,3]
131 [stdout:0] 10
131 [stdout:0] 10
132 [stdout:1] 10
132 [stdout:1] 10
133 [stdout:2] 10
133 [stdout:2] 10
134 [stdout:3] 10
134 [stdout:3] 10
135
135
136
136
137 In [27]: %autopx
137 In [27]: %autopx
138 %autopx disabled
138 %autopx disabled
139 """
139 """
140 if self.autopx:
140 if self.autopx:
141 self._disable_autopx()
141 self._disable_autopx()
142 else:
142 else:
143 self._enable_autopx()
143 self._enable_autopx()
144
144
145 def _enable_autopx(self):
145 def _enable_autopx(self):
146 """Enable %autopx mode by saving the original run_cell and installing
146 """Enable %autopx mode by saving the original run_cell and installing
147 pxrun_cell.
147 pxrun_cell.
148 """
148 """
149 if self.active_view is None:
149 if self.active_view is None:
150 print NO_ACTIVE_VIEW
150 print NO_ACTIVE_VIEW
151 return
151 return
152
152
153 # override run_cell and run_code
153 # override run_cell and run_code
154 self._original_run_cell = self.shell.run_cell
154 self._original_run_cell = self.shell.run_cell
155 self.shell.run_cell = self.pxrun_cell
155 self.shell.run_cell = self.pxrun_cell
156 self._original_run_code = self.shell.run_code
156 self._original_run_code = self.shell.run_code
157 self.shell.run_code = self.pxrun_code
157 self.shell.run_code = self.pxrun_code
158
158
159 self.autopx = True
159 self.autopx = True
160 print "%autopx enabled"
160 print "%autopx enabled"
161
161
162 def _disable_autopx(self):
162 def _disable_autopx(self):
163 """Disable %autopx by restoring the original InteractiveShell.run_cell.
163 """Disable %autopx by restoring the original InteractiveShell.run_cell.
164 """
164 """
165 if self.autopx:
165 if self.autopx:
166 self.shell.run_cell = self._original_run_cell
166 self.shell.run_cell = self._original_run_cell
167 self.shell.run_code = self._original_run_code
167 self.shell.run_code = self._original_run_code
168 self.autopx = False
168 self.autopx = False
169 print "%autopx disabled"
169 print "%autopx disabled"
170
170
171 def _maybe_display_output(self, result):
171 def _maybe_display_output(self, result):
172 """Maybe display the output of a parallel result.
172 """Maybe display the output of a parallel result.
173
173
174 If self.active_view.block is True, wait for the result
174 If self.active_view.block is True, wait for the result
175 and display the result. Otherwise, this is a noop.
175 and display the result. Otherwise, this is a noop.
176 """
176 """
177 if isinstance(result.stdout, basestring):
178 # single result
179 stdouts = [result.stdout.rstrip()]
180 else:
181 stdouts = [s.rstrip() for s in result.stdout]
182
177 targets = self.active_view.targets
183 targets = self.active_view.targets
178 if isinstance(targets, int):
184 if isinstance(targets, int):
179 targets = [targets]
185 targets = [targets]
180 if targets == 'all':
186 elif targets == 'all':
181 targets = self.active_view.client.ids
187 targets = self.active_view.client.ids
182 stdout = [s.rstrip() for s in result.stdout]
188
183 if any(stdout):
189 if any(stdouts):
184 for i,eid in enumerate(targets):
190 for eid,stdout in zip(targets, stdouts):
185 print '[stdout:%i]'%eid, stdout[i]
191 print '[stdout:%i]'%eid, stdout
186
192
187
193
188 def pxrun_cell(self, raw_cell, store_history=True):
194 def pxrun_cell(self, raw_cell, store_history=True):
189 """drop-in replacement for InteractiveShell.run_cell.
195 """drop-in replacement for InteractiveShell.run_cell.
190
196
191 This executes code remotely, instead of in the local namespace.
197 This executes code remotely, instead of in the local namespace.
192
198
193 See InteractiveShell.run_cell for details.
199 See InteractiveShell.run_cell for details.
194 """
200 """
195
201
196 if (not raw_cell) or raw_cell.isspace():
202 if (not raw_cell) or raw_cell.isspace():
197 return
203 return
198
204
199 ipself = self.shell
205 ipself = self.shell
200
206
201 with ipself.builtin_trap:
207 with ipself.builtin_trap:
202 cell = ipself.prefilter_manager.prefilter_lines(raw_cell)
208 cell = ipself.prefilter_manager.prefilter_lines(raw_cell)
203
209
204 # Store raw and processed history
210 # Store raw and processed history
205 if store_history:
211 if store_history:
206 ipself.history_manager.store_inputs(ipself.execution_count,
212 ipself.history_manager.store_inputs(ipself.execution_count,
207 cell, raw_cell)
213 cell, raw_cell)
208
214
209 # ipself.logger.log(cell, raw_cell)
215 # ipself.logger.log(cell, raw_cell)
210
216
211 cell_name = ipself.compile.cache(cell, ipself.execution_count)
217 cell_name = ipself.compile.cache(cell, ipself.execution_count)
212
218
213 try:
219 try:
214 code_ast = ast.parse(cell, filename=cell_name)
220 code_ast = ast.parse(cell, filename=cell_name)
215 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
221 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
216 # Case 1
222 # Case 1
217 ipself.showsyntaxerror()
223 ipself.showsyntaxerror()
218 ipself.execution_count += 1
224 ipself.execution_count += 1
219 return None
225 return None
220 except NameError:
226 except NameError:
221 # ignore name errors, because we don't know the remote keys
227 # ignore name errors, because we don't know the remote keys
222 pass
228 pass
223
229
224 if store_history:
230 if store_history:
225 # Write output to the database. Does nothing unless
231 # Write output to the database. Does nothing unless
226 # history output logging is enabled.
232 # history output logging is enabled.
227 ipself.history_manager.store_output(ipself.execution_count)
233 ipself.history_manager.store_output(ipself.execution_count)
228 # Each cell is a *single* input, regardless of how many lines it has
234 # Each cell is a *single* input, regardless of how many lines it has
229 ipself.execution_count += 1
235 ipself.execution_count += 1
230
236
231 if re.search(r'get_ipython\(\)\.magic\(u?"%?autopx', cell):
237 if re.search(r'get_ipython\(\)\.magic\(u?"%?autopx', cell):
232 self._disable_autopx()
238 self._disable_autopx()
233 return False
239 return False
234 else:
240 else:
235 try:
241 try:
236 result = self.active_view.execute(cell, block=False)
242 result = self.active_view.execute(cell, block=False)
237 except:
243 except:
238 ipself.showtraceback()
244 ipself.showtraceback()
239 return True
245 return True
240 else:
246 else:
241 if self.active_view.block:
247 if self.active_view.block:
242 try:
248 try:
243 result.get()
249 result.get()
244 except:
250 except:
245 self.shell.showtraceback()
251 self.shell.showtraceback()
246 return True
252 return True
247 else:
253 else:
248 self._maybe_display_output(result)
254 self._maybe_display_output(result)
249 return False
255 return False
250
256
251 def pxrun_code(self, code_obj):
257 def pxrun_code(self, code_obj):
252 """drop-in replacement for InteractiveShell.run_code.
258 """drop-in replacement for InteractiveShell.run_code.
253
259
254 This executes code remotely, instead of in the local namespace.
260 This executes code remotely, instead of in the local namespace.
255
261
256 See InteractiveShell.run_code for details.
262 See InteractiveShell.run_code for details.
257 """
263 """
258 ipself = self.shell
264 ipself = self.shell
259 # check code object for the autopx magic
265 # check code object for the autopx magic
260 if 'get_ipython' in code_obj.co_names and 'magic' in code_obj.co_names and \
266 if 'get_ipython' in code_obj.co_names and 'magic' in code_obj.co_names and \
261 any( [ isinstance(c, basestring) and 'autopx' in c for c in code_obj.co_consts ]):
267 any( [ isinstance(c, basestring) and 'autopx' in c for c in code_obj.co_consts ]):
262 self._disable_autopx()
268 self._disable_autopx()
263 return False
269 return False
264 else:
270 else:
265 try:
271 try:
266 result = self.active_view.execute(code_obj, block=False)
272 result = self.active_view.execute(code_obj, block=False)
267 except:
273 except:
268 ipself.showtraceback()
274 ipself.showtraceback()
269 return True
275 return True
270 else:
276 else:
271 if self.active_view.block:
277 if self.active_view.block:
272 try:
278 try:
273 result.get()
279 result.get()
274 except:
280 except:
275 self.shell.showtraceback()
281 self.shell.showtraceback()
276 return True
282 return True
277 else:
283 else:
278 self._maybe_display_output(result)
284 self._maybe_display_output(result)
279 return False
285 return False
280
286
281
287
282
288
283
289
284 _loaded = False
290 _loaded = False
285
291
286
292
287 def load_ipython_extension(ip):
293 def load_ipython_extension(ip):
288 """Load the extension in IPython."""
294 """Load the extension in IPython."""
289 global _loaded
295 global _loaded
290 if not _loaded:
296 if not _loaded:
291 plugin = ParalleMagic(shell=ip, config=ip.config)
297 plugin = ParalleMagic(shell=ip, config=ip.config)
292 ip.plugin_manager.register_plugin('parallelmagic', plugin)
298 ip.plugin_manager.register_plugin('parallelmagic', plugin)
293 _loaded = True
299 _loaded = True
294
300
@@ -1,109 +1,109 b''
1 """ Defines a convenient mix-in class for implementing Qt frontends.
1 """ Defines a convenient mix-in class for implementing Qt frontends.
2 """
2 """
3
3
4 class BaseFrontendMixin(object):
4 class BaseFrontendMixin(object):
5 """ A mix-in class for implementing Qt frontends.
5 """ A mix-in class for implementing Qt frontends.
6
6
7 To handle messages of a particular type, frontends need only define an
7 To handle messages of a particular type, frontends need only define an
8 appropriate handler method. For example, to handle 'stream' messaged, define
8 appropriate handler method. For example, to handle 'stream' messaged, define
9 a '_handle_stream(msg)' method.
9 a '_handle_stream(msg)' method.
10 """
10 """
11
11
12 #---------------------------------------------------------------------------
12 #---------------------------------------------------------------------------
13 # 'BaseFrontendMixin' concrete interface
13 # 'BaseFrontendMixin' concrete interface
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15
15
16 def _get_kernel_manager(self):
16 def _get_kernel_manager(self):
17 """ Returns the current kernel manager.
17 """ Returns the current kernel manager.
18 """
18 """
19 return self._kernel_manager
19 return self._kernel_manager
20
20
21 def _set_kernel_manager(self, kernel_manager):
21 def _set_kernel_manager(self, kernel_manager):
22 """ Disconnect from the current kernel manager (if any) and set a new
22 """ Disconnect from the current kernel manager (if any) and set a new
23 kernel manager.
23 kernel manager.
24 """
24 """
25 # Disconnect the old kernel manager, if necessary.
25 # Disconnect the old kernel manager, if necessary.
26 old_manager = self._kernel_manager
26 old_manager = self._kernel_manager
27 if old_manager is not None:
27 if old_manager is not None:
28 old_manager.started_channels.disconnect(self._started_channels)
28 old_manager.started_channels.disconnect(self._started_channels)
29 old_manager.stopped_channels.disconnect(self._stopped_channels)
29 old_manager.stopped_channels.disconnect(self._stopped_channels)
30
30
31 # Disconnect the old kernel manager's channels.
31 # Disconnect the old kernel manager's channels.
32 old_manager.sub_channel.message_received.disconnect(self._dispatch)
32 old_manager.sub_channel.message_received.disconnect(self._dispatch)
33 old_manager.xreq_channel.message_received.disconnect(self._dispatch)
33 old_manager.shell_channel.message_received.disconnect(self._dispatch)
34 old_manager.rep_channel.message_received.disconnect(self._dispatch)
34 old_manager.stdin_channel.message_received.disconnect(self._dispatch)
35 old_manager.hb_channel.kernel_died.disconnect(
35 old_manager.hb_channel.kernel_died.disconnect(
36 self._handle_kernel_died)
36 self._handle_kernel_died)
37
37
38 # Handle the case where the old kernel manager is still listening.
38 # Handle the case where the old kernel manager is still listening.
39 if old_manager.channels_running:
39 if old_manager.channels_running:
40 self._stopped_channels()
40 self._stopped_channels()
41
41
42 # Set the new kernel manager.
42 # Set the new kernel manager.
43 self._kernel_manager = kernel_manager
43 self._kernel_manager = kernel_manager
44 if kernel_manager is None:
44 if kernel_manager is None:
45 return
45 return
46
46
47 # Connect the new kernel manager.
47 # Connect the new kernel manager.
48 kernel_manager.started_channels.connect(self._started_channels)
48 kernel_manager.started_channels.connect(self._started_channels)
49 kernel_manager.stopped_channels.connect(self._stopped_channels)
49 kernel_manager.stopped_channels.connect(self._stopped_channels)
50
50
51 # Connect the new kernel manager's channels.
51 # Connect the new kernel manager's channels.
52 kernel_manager.sub_channel.message_received.connect(self._dispatch)
52 kernel_manager.sub_channel.message_received.connect(self._dispatch)
53 kernel_manager.xreq_channel.message_received.connect(self._dispatch)
53 kernel_manager.shell_channel.message_received.connect(self._dispatch)
54 kernel_manager.rep_channel.message_received.connect(self._dispatch)
54 kernel_manager.stdin_channel.message_received.connect(self._dispatch)
55 kernel_manager.hb_channel.kernel_died.connect(self._handle_kernel_died)
55 kernel_manager.hb_channel.kernel_died.connect(self._handle_kernel_died)
56
56
57 # Handle the case where the kernel manager started channels before
57 # Handle the case where the kernel manager started channels before
58 # we connected.
58 # we connected.
59 if kernel_manager.channels_running:
59 if kernel_manager.channels_running:
60 self._started_channels()
60 self._started_channels()
61
61
62 kernel_manager = property(_get_kernel_manager, _set_kernel_manager)
62 kernel_manager = property(_get_kernel_manager, _set_kernel_manager)
63
63
64 #---------------------------------------------------------------------------
64 #---------------------------------------------------------------------------
65 # 'BaseFrontendMixin' abstract interface
65 # 'BaseFrontendMixin' abstract interface
66 #---------------------------------------------------------------------------
66 #---------------------------------------------------------------------------
67
67
68 def _handle_kernel_died(self, since_last_heartbeat):
68 def _handle_kernel_died(self, since_last_heartbeat):
69 """ This is called when the ``kernel_died`` signal is emitted.
69 """ This is called when the ``kernel_died`` signal is emitted.
70
70
71 This method is called when the kernel heartbeat has not been
71 This method is called when the kernel heartbeat has not been
72 active for a certain amount of time. The typical action will be to
72 active for a certain amount of time. The typical action will be to
73 give the user the option of restarting the kernel.
73 give the user the option of restarting the kernel.
74
74
75 Parameters
75 Parameters
76 ----------
76 ----------
77 since_last_heartbeat : float
77 since_last_heartbeat : float
78 The time since the heartbeat was last received.
78 The time since the heartbeat was last received.
79 """
79 """
80
80
81 def _started_channels(self):
81 def _started_channels(self):
82 """ Called when the KernelManager channels have started listening or
82 """ Called when the KernelManager channels have started listening or
83 when the frontend is assigned an already listening KernelManager.
83 when the frontend is assigned an already listening KernelManager.
84 """
84 """
85
85
86 def _stopped_channels(self):
86 def _stopped_channels(self):
87 """ Called when the KernelManager channels have stopped listening or
87 """ Called when the KernelManager channels have stopped listening or
88 when a listening KernelManager is removed from the frontend.
88 when a listening KernelManager is removed from the frontend.
89 """
89 """
90
90
91 #---------------------------------------------------------------------------
91 #---------------------------------------------------------------------------
92 # 'BaseFrontendMixin' protected interface
92 # 'BaseFrontendMixin' protected interface
93 #---------------------------------------------------------------------------
93 #---------------------------------------------------------------------------
94
94
95 def _dispatch(self, msg):
95 def _dispatch(self, msg):
96 """ Calls the frontend handler associated with the message type of the
96 """ Calls the frontend handler associated with the message type of the
97 given message.
97 given message.
98 """
98 """
99 msg_type = msg['msg_type']
99 msg_type = msg['msg_type']
100 handler = getattr(self, '_handle_' + msg_type, None)
100 handler = getattr(self, '_handle_' + msg_type, None)
101 if handler:
101 if handler:
102 handler(msg)
102 handler(msg)
103
103
104 def _is_from_this_session(self, msg):
104 def _is_from_this_session(self, msg):
105 """ Returns whether a reply from the kernel originated from a request
105 """ Returns whether a reply from the kernel originated from a request
106 from this frontend.
106 from this frontend.
107 """
107 """
108 session = self._kernel_manager.session.session
108 session = self._kernel_manager.session.session
109 return msg['parent_header']['session'] == session
109 return msg['parent_header']['session'] == session
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/frontend/qt/console/ipythonqt.py to IPython/frontend/qt/console/qtconsoleapp.py
NO CONTENT: file renamed from IPython/frontend/qt/console/ipythonqt.py to IPython/frontend/qt/console/qtconsoleapp.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/parallel/tests/test_streamsession.py to IPython/zmq/tests/test_session.py
NO CONTENT: file renamed from IPython/parallel/tests/test_streamsession.py to IPython/zmq/tests/test_session.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now