##// END OF EJS Templates
More work on getting rid of ipmaker.
Brian Granger -
Show More
@@ -1,200 +1,203 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """A factory for creating configuration objects.
3 """A factory for creating configuration objects.
4 """
4 """
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 os
17 import os
18 import sys
18 import sys
19
19
20 from IPython.external import argparse
20 from IPython.external import argparse
21 from IPython.utils.ipstruct import Struct
21 from IPython.utils.ipstruct import Struct
22 from IPython.utils.genutils import filefind
22 from IPython.utils.genutils import filefind
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 class ConfigLoaderError(Exception):
29 class ConfigLoaderError(Exception):
30 pass
30 pass
31
31
32
32
33 class ConfigLoader(object):
33 class ConfigLoader(object):
34 """A object for loading configurations from just about anywhere.
34 """A object for loading configurations from just about anywhere.
35
35
36 The resulting configuration is packaged as a :class:`Struct`.
36 The resulting configuration is packaged as a :class:`Struct`.
37
37
38 Notes
38 Notes
39 -----
39 -----
40 A :class:`ConfigLoader` does one thing: load a config from a source
40 A :class:`ConfigLoader` does one thing: load a config from a source
41 (file, command line arguments) and returns the data as a :class:`Struct`.
41 (file, command line arguments) and returns the data as a :class:`Struct`.
42 There are lots of things that :class:`ConfigLoader` does not do. It does
42 There are lots of things that :class:`ConfigLoader` does not do. It does
43 not implement complex logic for finding config files. It does not handle
43 not implement complex logic for finding config files. It does not handle
44 default values or merge multiple configs. These things need to be
44 default values or merge multiple configs. These things need to be
45 handled elsewhere.
45 handled elsewhere.
46 """
46 """
47
47
48 def __init__(self):
48 def __init__(self):
49 """A base class for config loaders.
49 """A base class for config loaders.
50
50
51 Examples
51 Examples
52 --------
52 --------
53
53
54 >>> cl = ConfigLoader()
54 >>> cl = ConfigLoader()
55 >>> config = cl.load_config()
55 >>> config = cl.load_config()
56 >>> config
56 >>> config
57 {}
57 {}
58 """
58 """
59 self.clear()
59 self.clear()
60
60
61 def clear(self):
61 def clear(self):
62 self.config = Struct()
62 self.config = Struct()
63
63
64 def load_config(self):
64 def load_config(self):
65 """Load a config from somewhere, return a Struct.
65 """Load a config from somewhere, return a Struct.
66
66
67 Usually, this will cause self.config to be set and then returned.
67 Usually, this will cause self.config to be set and then returned.
68 """
68 """
69 return self.config
69 return self.config
70
70
71
71
72 class FileConfigLoader(ConfigLoader):
72 class FileConfigLoader(ConfigLoader):
73 """A base class for file based configurations.
73 """A base class for file based configurations.
74
74
75 As we add more file based config loaders, the common logic should go
75 As we add more file based config loaders, the common logic should go
76 here.
76 here.
77 """
77 """
78 pass
78 pass
79
79
80
80
81 class PyFileConfigLoader(FileConfigLoader):
81 class PyFileConfigLoader(FileConfigLoader):
82 """A config loader for pure python files.
82 """A config loader for pure python files.
83
83
84 This calls execfile on a plain python file and looks for attributes
84 This calls execfile on a plain python file and looks for attributes
85 that are all caps. These attribute are added to the config Struct.
85 that are all caps. These attribute are added to the config Struct.
86 """
86 """
87
87
88 def __init__(self, filename, path=None):
88 def __init__(self, filename, path=None):
89 """Build a config loader for a filename and path.
89 """Build a config loader for a filename and path.
90
90
91 Parameters
91 Parameters
92 ----------
92 ----------
93 filename : str
93 filename : str
94 The file name of the config file.
94 The file name of the config file.
95 path : str, list, tuple
95 path : str, list, tuple
96 The path to search for the config file on, or a sequence of
96 The path to search for the config file on, or a sequence of
97 paths to try in order.
97 paths to try in order.
98 """
98 """
99 super(PyFileConfigLoader, self).__init__()
99 super(PyFileConfigLoader, self).__init__()
100 self.filename = filename
100 self.filename = filename
101 self.path = path
101 self.path = path
102 self.full_filename = ''
102 self.full_filename = ''
103 self.data = None
103 self.data = None
104
104
105 def load_config(self):
105 def load_config(self):
106 """Load the config from a file and return it as a Struct."""
106 """Load the config from a file and return it as a Struct."""
107 self._find_file()
107 self._find_file()
108 self._read_file_as_dict()
108 self._read_file_as_dict()
109 self._convert_to_struct()
109 self._convert_to_struct()
110 return self.config
110 return self.config
111
111
112 def _find_file(self):
112 def _find_file(self):
113 """Try to find the file by searching the paths."""
113 """Try to find the file by searching the paths."""
114 self.full_filename = filefind(self.filename, self.path)
114 self.full_filename = filefind(self.filename, self.path)
115
115
116 def _read_file_as_dict(self):
116 def _read_file_as_dict(self):
117 self.data = {}
117 self.data = {}
118 execfile(self.full_filename, self.data)
118 execfile(self.full_filename, self.data)
119
119
120 def _convert_to_struct(self):
120 def _convert_to_struct(self):
121 if self.data is None:
121 if self.data is None:
122 ConfigLoaderError('self.data does not exist')
122 ConfigLoaderError('self.data does not exist')
123 for k, v in self.data.iteritems():
123 for k, v in self.data.iteritems():
124 if k == k.upper():
124 if k == k.upper():
125 self.config[k] = v
125 self.config[k] = v
126
126
127
127
128 class CommandLineConfigLoader(ConfigLoader):
128 class CommandLineConfigLoader(ConfigLoader):
129 """A config loader for command line arguments.
129 """A config loader for command line arguments.
130
130
131 As we add more command line based loaders, the common logic should go
131 As we add more command line based loaders, the common logic should go
132 here.
132 here.
133 """
133 """
134
134
135
135
136 class NoDefault(object): pass
136 class NoDefault(object): pass
137 NoDefault = NoDefault()
137 NoDefault = NoDefault()
138
138
139 class ArgParseConfigLoader(CommandLineConfigLoader):
139 class ArgParseConfigLoader(CommandLineConfigLoader):
140
140
141 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
141 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
142 arguments = ()
142 arguments = ()
143
143
144 def __init__(self, *args, **kw):
144 def __init__(self, *args, **kw):
145 """Create a config loader for use with argparse.
145 """Create a config loader for use with argparse.
146
146
147 The args and kwargs arguments here are passed onto the constructor
147 The args and kwargs arguments here are passed onto the constructor
148 of :class:`argparse.ArgumentParser`.
148 of :class:`argparse.ArgumentParser`.
149 """
149 """
150 super(CommandLineConfigLoader, self).__init__()
150 super(CommandLineConfigLoader, self).__init__()
151 self.args = args
151 self.args = args
152 self.kw = kw
152 self.kw = kw
153
153
154 def load_config(self, args=None):
154 def load_config(self, args=None):
155 """Parse command line arguments and return as a Struct."""
155 """Parse command line arguments and return as a Struct."""
156 self._create_parser()
156 self._create_parser()
157 self._parse_args(args)
157 self._parse_args(args)
158 self._convert_to_struct()
158 self._convert_to_struct()
159 return self.config
159 return self.config
160
160
161 def _create_parser(self):
161 def _create_parser(self):
162 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
162 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
163 self._add_arguments()
163 self._add_arguments()
164 self._add_other_arguments()
164 self._add_other_arguments()
165
165
166 def _add_other_arguments(self):
166 def _add_other_arguments(self):
167 pass
167 pass
168
168
169 def _add_arguments(self):
169 def _add_arguments(self):
170 for argument in self.arguments:
170 for argument in self.arguments:
171 if not argument[1].has_key('default'):
171 if not argument[1].has_key('default'):
172 argument[1]['default'] = NoDefault
172 argument[1]['default'] = NoDefault
173 self.parser.add_argument(*argument[0],**argument[1])
173 self.parser.add_argument(*argument[0],**argument[1])
174
174
175 def _parse_args(self, args=None):
175 def _parse_args(self, args=None):
176 """self.parser->self.parsed_data"""
176 """self.parser->self.parsed_data"""
177 if args is None:
177 if args is None:
178 self.parsed_data = self.parser.parse_args()
178 self.parsed_data = self.parser.parse_args()
179 else:
179 else:
180 self.parsed_data = self.parser.parse_args(args)
180 self.parsed_data = self.parser.parse_args(args)
181
181
182 def _convert_to_struct(self):
182 def _convert_to_struct(self):
183 """self.parsed_data->self.config"""
183 """self.parsed_data->self.config"""
184 self.config = Struct()
184 self.config = Struct()
185 for k, v in vars(self.parsed_data).items():
185 for k, v in vars(self.parsed_data).items():
186 if v is not NoDefault:
186 if v is not NoDefault:
187 setattr(self.config, k, v)
187 setattr(self.config, k, v)
188
188
189 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
189 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
190
190
191 def _add_other_arguments(self):
191 def _add_other_arguments(self):
192 self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str,
192 self.parser.add_argument('-ipythondir',dest='IPYTHONDIR',type=str,
193 help='set to override default location of IPYTHONDIR',
193 help='Set to override default location of IPYTHONDIR.',
194 default=NoDefault)
194 default=NoDefault)
195 self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str,
195 self.parser.add_argument('-p','-profile',dest='PROFILE',type=str,
196 help='the string name of the ipython profile to be used',
196 help='The string name of the ipython profile to be used.',
197 default=None)
197 default=NoDefault)
198 self.parser.add_argument('--debug',dest="DEBUG",action='store_true',
198 self.parser.add_argument('-debug',dest="DEBUG",action='store_true',
199 help='debug the application startup process',
199 help='Debug the application startup process.',
200 default=NoDefault)
201 self.parser.add_argument('-config_file',dest='CONFIG_FILE',type=str,
202 help='Set the config file name to override default.',
200 default=NoDefault)
203 default=NoDefault)
@@ -1,233 +1,241 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An application for IPython
4 An application for IPython
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import os
26 import os
27 import sys
27 import sys
28 import traceback
28 import traceback
29
29
30 from copy import deepcopy
30 from copy import deepcopy
31 from IPython.utils.ipstruct import Struct
31 from IPython.utils.ipstruct import Struct
32 from IPython.utils.genutils import get_ipython_dir, filefind
32 from IPython.utils.genutils import get_ipython_dir, filefind
33 from IPython.config.loader import (
33 from IPython.config.loader import (
34 IPythonArgParseConfigLoader,
34 IPythonArgParseConfigLoader,
35 PyFileConfigLoader
35 PyFileConfigLoader
36 )
36 )
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Classes and functions
39 # Classes and functions
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42
42
43 class ApplicationError(Exception):
43 class ApplicationError(Exception):
44 pass
44 pass
45
45
46
46
47 class Application(object):
47 class Application(object):
48 """Load a config, construct an app and run it.
48 """Load a config, construct an app and run it.
49 """
49 """
50
50
51 config_file_name = 'ipython_config.py'
51 config_file_name = 'ipython_config.py'
52 name = 'ipython'
52 name = 'ipython'
53 debug = False
53 debug = False
54
54
55 def __init__(self):
55 def __init__(self):
56 pass
56 pass
57
57
58 def start(self):
58 def start(self):
59 """Start the application."""
59 """Start the application."""
60 self.attempt(self.create_default_config)
60 self.attempt(self.create_default_config)
61 self.attempt(self.pre_load_command_line_config)
61 self.attempt(self.pre_load_command_line_config)
62 self.attempt(self.load_command_line_config, action='exit')
62 self.attempt(self.load_command_line_config, action='abort')
63 self.attempt(self.post_load_command_line_config)
63 self.attempt(self.post_load_command_line_config)
64 self.attempt(self.find_ipythondir)
64 self.attempt(self.find_ipythondir)
65 self.attempt(self.find_config_file_name)
65 self.attempt(self.find_config_file_name)
66 self.attempt(self.find_config_file_paths)
66 self.attempt(self.find_config_file_paths)
67 self.attempt(self.pre_load_file_config)
67 self.attempt(self.pre_load_file_config)
68 self.attempt(self.load_file_config)
68 self.attempt(self.load_file_config)
69 self.attempt(self.post_load_file_config)
69 self.attempt(self.post_load_file_config)
70 self.attempt(self.merge_configs)
70 self.attempt(self.merge_configs)
71 self.attempt(self.pre_construct)
71 self.attempt(self.pre_construct)
72 self.attempt(self.construct)
72 self.attempt(self.construct)
73 self.attempt(self.post_construct)
73 self.attempt(self.post_construct)
74 self.attempt(self.start_app)
74 self.attempt(self.start_app)
75
75
76 #-------------------------------------------------------------------------
76 #-------------------------------------------------------------------------
77 # Various stages of Application creation
77 # Various stages of Application creation
78 #-------------------------------------------------------------------------
78 #-------------------------------------------------------------------------
79
79
80 def create_default_config(self):
80 def create_default_config(self):
81 """Create defaults that can't be set elsewhere."""
81 """Create defaults that can't be set elsewhere."""
82 self.default_config = Struct()
82 self.default_config = Struct()
83 self.default_config.IPYTHONDIR = get_ipython_dir()
83 self.default_config.IPYTHONDIR = get_ipython_dir()
84
84
85 def create_command_line_config(self):
85 def create_command_line_config(self):
86 """Create and return a command line config loader."""
86 """Create and return a command line config loader."""
87 return IPythonArgParseConfigLoader(description=self.name)
87 return IPythonArgParseConfigLoader(description=self.name)
88
88
89 def pre_load_command_line_config(self):
89 def pre_load_command_line_config(self):
90 """Do actions just before loading the command line config."""
90 """Do actions just before loading the command line config."""
91 pass
91 pass
92
92
93 def load_command_line_config(self):
93 def load_command_line_config(self):
94 """Load the command line config.
94 """Load the command line config.
95
95
96 This method also sets ``self.debug``.
96 This method also sets ``self.debug``.
97 """
97 """
98
98
99 loader = self.create_command_line_config()
99 loader = self.create_command_line_config()
100 self.command_line_config = loader.load_config()
100 self.command_line_config = loader.load_config()
101 try:
101 try:
102 self.debug = self.command_line_config.DEBUG
102 self.debug = self.command_line_config.DEBUG
103 except AttributeError:
103 except AttributeError:
104 pass # use class default
104 pass # use class default
105 self.log("Default config loaded:", self.default_config)
105 self.log("Default config loaded:", self.default_config)
106 self.log("Command line config loaded:", self.command_line_config)
106 self.log("Command line config loaded:", self.command_line_config)
107
107
108 def post_load_command_line_config(self):
108 def post_load_command_line_config(self):
109 """Do actions just after loading the command line config."""
109 """Do actions just after loading the command line config."""
110 pass
110 pass
111
111
112 def find_ipythondir(self):
112 def find_ipythondir(self):
113 """Set the IPython directory.
113 """Set the IPython directory.
114
114
115 This sets ``self.ipythondir``, but the actual value that is passed
115 This sets ``self.ipythondir``, but the actual value that is passed
116 to the application is kept in either ``self.default_config`` or
116 to the application is kept in either ``self.default_config`` or
117 ``self.command_line_config``. This also added ``self.ipythondir`` to
117 ``self.command_line_config``. This also added ``self.ipythondir`` to
118 ``sys.path`` so config files there can be references by other config
118 ``sys.path`` so config files there can be references by other config
119 files.
119 files.
120 """
120 """
121
121
122 try:
122 try:
123 self.ipythondir = self.command_line_config.IPYTHONDIR
123 self.ipythondir = self.command_line_config.IPYTHONDIR
124 except AttributeError:
124 except AttributeError:
125 self.ipythondir = self.default_config.IPYTHONDIR
125 self.ipythondir = self.default_config.IPYTHONDIR
126 sys.path.append(os.path.abspath(self.ipythondir))
126 sys.path.append(os.path.abspath(self.ipythondir))
127 if not os.path.isdir(self.ipythondir):
127 if not os.path.isdir(self.ipythondir):
128 os.makedirs(self.ipythondir, mode = 0777)
128 os.makedirs(self.ipythondir, mode = 0777)
129 self.log("IPYTHONDIR set to: %s" % self.ipythondir)
129 self.log("IPYTHONDIR set to: %s" % self.ipythondir)
130
130
131 def find_config_file_name(self):
131 def find_config_file_name(self):
132 """Find the config file name for this application.
132 """Find the config file name for this application.
133
133
134 If a profile has been set at the command line, this will resolve
134 If a profile has been set at the command line, this will resolve
135 it. The search paths for the config file are set in
135 it. The search paths for the config file are set in
136 :meth:`find_config_file_paths` and then passed to the config file
136 :meth:`find_config_file_paths` and then passed to the config file
137 loader where they are resolved to an absolute path.
137 loader where they are resolved to an absolute path.
138 """
138 """
139
139
140 if self.command_line_config.PROFILE_NAME is not None:
140 try:
141 self.profile_name = self.command_line_config.PROFILE_NAME
141 self.config_file_name = self.command_line_config.CONFIG_FILE
142 except AttributeError:
143 pass
144
145 try:
146 self.profile_name = self.command_line_config.PROFILE
142 name_parts = self.config_file_name.split('.')
147 name_parts = self.config_file_name.split('.')
143 name_parts.insert(1, '_' + self.profile_name + '.')
148 name_parts.insert(1, '_' + self.profile_name + '.')
144 self.config_file_name = ''.join(name_parts)
149 self.config_file_name = ''.join(name_parts)
150 except AttributeError:
151 pass
145
152
146 def find_config_file_paths(self):
153 def find_config_file_paths(self):
147 """Set the search paths for resolving the config file."""
154 """Set the search paths for resolving the config file."""
148 self.config_file_paths = (os.getcwd(), self.ipythondir)
155 self.config_file_paths = (os.getcwd(), self.ipythondir)
149
156
150 def pre_load_file_config(self):
157 def pre_load_file_config(self):
151 """Do actions before the config file is loaded."""
158 """Do actions before the config file is loaded."""
152 pass
159 pass
153
160
154 def load_file_config(self):
161 def load_file_config(self):
155 """Load the config file.
162 """Load the config file.
156
163
157 This tries to load the config file from disk. If successful, the
164 This tries to load the config file from disk. If successful, the
158 ``CONFIG_FILE`` config variable is set to the resolved config file
165 ``CONFIG_FILE`` config variable is set to the resolved config file
159 location. If not successful, an empty config is used.
166 location. If not successful, an empty config is used.
160 """
167 """
161 loader = PyFileConfigLoader(self.config_file_name,
168 loader = PyFileConfigLoader(self.config_file_name,
162 self.config_file_paths)
169 self.config_file_paths)
163 try:
170 try:
164 self.file_config = loader.load_config()
171 self.file_config = loader.load_config()
165 self.file_config.CONFIG_FILE = loader.full_filename
172 self.file_config.CONFIG_FILE = loader.full_filename
166 except IOError:
173 except IOError:
167 self.log("Config file not found, skipping: %s" % \
174 self.log("Config file not found, skipping: %s" % \
168 self.config_file_name)
175 self.config_file_name)
169 self.file_config = Struct()
176 self.file_config = Struct()
170 else:
177 else:
171 self.log("Config file loaded: %s" % loader.full_filename)
178 self.log("Config file loaded: %s" % loader.full_filename,
179 self.file_config)
172
180
173 def post_load_file_config(self):
181 def post_load_file_config(self):
174 """Do actions after the config file is loaded."""
182 """Do actions after the config file is loaded."""
175 pass
183 pass
176
184
177 def merge_configs(self):
185 def merge_configs(self):
178 """Merge the default, command line and file config objects."""
186 """Merge the default, command line and file config objects."""
179 config = Struct()
187 config = Struct()
180 config.update(self.default_config)
188 config.update(self.default_config)
181 config.update(self.command_line_config)
182 config.update(self.file_config)
189 config.update(self.file_config)
190 config.update(self.command_line_config)
183 self.master_config = config
191 self.master_config = config
184 self.log("Master config created:", self.master_config)
192 self.log("Master config created:", self.master_config)
185
193
186 def pre_construct(self):
194 def pre_construct(self):
187 """Do actions after the config has been built, but before construct."""
195 """Do actions after the config has been built, but before construct."""
188 pass
196 pass
189
197
190 def construct(self):
198 def construct(self):
191 """Construct the main components that make up this app."""
199 """Construct the main components that make up this app."""
192 self.log("Constructing components for application...")
200 self.log("Constructing components for application...")
193
201
194 def post_construct(self):
202 def post_construct(self):
195 """Do actions after construct, but before starting the app."""
203 """Do actions after construct, but before starting the app."""
196 pass
204 pass
197
205
198 def start_app(self):
206 def start_app(self):
199 """Actually start the app."""
207 """Actually start the app."""
200 self.log("Starting application...")
208 self.log("Starting application...")
201
209
202 #-------------------------------------------------------------------------
210 #-------------------------------------------------------------------------
203 # Utility methods
211 # Utility methods
204 #-------------------------------------------------------------------------
212 #-------------------------------------------------------------------------
205
213
206 def abort(self):
214 def abort(self):
207 """Abort the starting of the application."""
215 """Abort the starting of the application."""
208 print "Aborting application: ", self.name
216 print "Aborting application: ", self.name
209 sys.exit(1)
217 sys.exit(1)
210
218
211 def exit(self):
219 def exit(self):
212 print "Exiting application: ", self.name
220 print "Exiting application: ", self.name
213 sys.exit(1)
221 sys.exit(1)
214
222
215 def attempt(self, func, action='abort'):
223 def attempt(self, func, action='abort'):
216 try:
224 try:
217 func()
225 func()
218 except:
226 except:
219 if action == 'abort':
227 if action == 'abort':
220 self.print_traceback()
228 self.print_traceback()
221 self.abort()
229 self.abort()
222 elif action == 'exit':
230 elif action == 'exit':
223 self.exit()
231 self.exit()
224
232
225 def print_traceback(self):
233 def print_traceback(self):
226 print "Error in appliction startup: ", self.name
234 print "Error in appliction startup: ", self.name
227 print
235 print
228 traceback.print_exc()
236 traceback.print_exc()
229
237
230 def log(self, *args):
238 def log(self, *args):
231 if self.debug:
239 if self.debug:
232 for arg in args:
240 for arg in args:
233 print "[%s] %s" % (self.name, arg) No newline at end of file
241 print "[%s] %s" % (self.name, arg)
@@ -1,65 +1,316 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The main IPython application object
4 The main IPython application object
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import os
27 import sys
28 import warnings
29
26 from IPython.core.application import Application
30 from IPython.core.application import Application
27 from IPython.core import release
31 from IPython.core import release
28 from IPython.core.iplib import InteractiveShell
32 from IPython.core.iplib import InteractiveShell
29 from IPython.config.loader import IPythonArgParseConfigLoader
33 from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault
34
35 from IPython.utils.ipstruct import Struct
36
37
38 #-----------------------------------------------------------------------------
39 # Utilities and helpers
40 #-----------------------------------------------------------------------------
41
30
42
31 ipython_desc = """
43 ipython_desc = """
32 A Python shell with automatic history (input and output), dynamic object
44 A Python shell with automatic history (input and output), dynamic object
33 introspection, easier configuration, command completion, access to the system
45 introspection, easier configuration, command completion, access to the system
34 shell and more.
46 shell and more.
35 """
47 """
36
48
49 def threaded_shell_warning():
50 msg = """
51
52 The IPython threaded shells and their associated command line
53 arguments (pylab/wthread/gthread/qthread/q4thread) have been
54 deprecated. See the %gui magic for information on the new interface.
55 """
56 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
57
58
59 #-----------------------------------------------------------------------------
60 # Main classes and functions
61 #-----------------------------------------------------------------------------
62
63 cl_args = (
64 (('-autocall',), dict(
65 type=int, dest='AUTOCALL', default=NoDefault,
66 help='Set the autocall value (0,1,2).')
67 ),
68 (('-autoindent',), dict(
69 action='store_true', dest='AUTOINDENT', default=NoDefault,
70 help='Turn on autoindenting.')
71 ),
72 (('-noautoindent',), dict(
73 action='store_false', dest='AUTOINDENT', default=NoDefault,
74 help='Turn off autoindenting.')
75 ),
76 (('-automagic',), dict(
77 action='store_true', dest='AUTOMAGIC', default=NoDefault,
78 help='Turn on the auto calling of magic commands.')
79 ),
80 (('-noautomagic',), dict(
81 action='store_false', dest='AUTOMAGIC', default=NoDefault,
82 help='Turn off the auto calling of magic commands.')
83 ),
84 (('-autoedit_syntax',), dict(
85 action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault,
86 help='Turn on auto editing of files with syntax errors.')
87 ),
88 (('-noautoedit_syntax',), dict(
89 action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault,
90 help='Turn off auto editing of files with syntax errors.')
91 ),
92 (('-banner',), dict(
93 action='store_true', dest='DISPLAY_BANNER', default=NoDefault,
94 help='Display a banner upon starting IPython.')
95 ),
96 (('-nobanner',), dict(
97 action='store_false', dest='DISPLAY_BANNER', default=NoDefault,
98 help="Don't display a banner upon starting IPython.")
99 ),
100 (('-c',), dict(
101 type=str, dest='C', default=NoDefault,
102 help="Execute the given command string.")
103 ),
104 (('-cache_size',), dict(
105 type=int, dest='CACHE_SIZE', default=NoDefault,
106 help="Set the size of the output cache.")
107 ),
108 (('-classic',), dict(
109 action='store_true', dest='CLASSIC', default=NoDefault,
110 help="Gives IPython a similar feel to the classic Python prompt.")
111 ),
112 (('-colors',), dict(
113 type=str, dest='COLORS', default=NoDefault,
114 help="Set the color scheme (NoColor, Linux, and LightBG).")
115 ),
116 (('-color_info',), dict(
117 action='store_true', dest='COLOR_INFO', default=NoDefault,
118 help="Enable using colors for info related things.")
119 ),
120 (('-nocolor_info',), dict(
121 action='store_false', dest='COLOR_INFO', default=NoDefault,
122 help="Disable using colors for info related things.")
123 ),
124 (('-confirm_exit',), dict(
125 action='store_true', dest='CONFIRM_EXIT', default=NoDefault,
126 help="Prompt the user when existing.")
127 ),
128 (('-noconfirm_exit',), dict(
129 action='store_false', dest='CONFIRM_EXIT', default=NoDefault,
130 help="Don't prompt the user when existing.")
131 ),
132 (('-deep_reload',), dict(
133 action='store_true', dest='DEEP_RELOAD', default=NoDefault,
134 help="Enable deep (recursive) reloading by default.")
135 ),
136 (('-nodeep_reload',), dict(
137 action='store_false', dest='DEEP_RELOAD', default=NoDefault,
138 help="Disable deep (recursive) reloading by default.")
139 ),
140 (('-editor',), dict(
141 type=str, dest='EDITOR', default=NoDefault,
142 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).")
143 ),
144 (('-log','-l'), dict(
145 action='store_true', dest='LOGSTART', default=NoDefault,
146 help="Start logging to the default file (./ipython_log.py).")
147 ),
148 (('-logfile','-lf'), dict(
149 type=str, dest='LOGFILE', default=NoDefault,
150 help="Specify the name of your logfile.")
151 ),
152 (('-logplay','-lp'), dict(
153 type=str, dest='LOGPLAY', default=NoDefault,
154 help="Re-play a log file and then append to it.")
155 ),
156 (('-pdb',), dict(
157 action='store_true', dest='PDB', default=NoDefault,
158 help="Enable auto calling the pdb debugger after every exception.")
159 ),
160 (('-nopdb',), dict(
161 action='store_false', dest='PDB', default=NoDefault,
162 help="Disable auto calling the pdb debugger after every exception.")
163 ),
164 (('-pprint',), dict(
165 action='store_true', dest='PPRINT', default=NoDefault,
166 help="Enable auto pretty printing of results.")
167 ),
168 (('-nopprint',), dict(
169 action='store_false', dest='PPRINT', default=NoDefault,
170 help="Disable auto auto pretty printing of results.")
171 ),
172 (('-prompt_in1','-pi1'), dict(
173 type=str, dest='PROMPT_IN1', default=NoDefault,
174 help="Set the main input prompt ('In [\#]: ')")
175 ),
176 (('-prompt_in2','-pi2'), dict(
177 type=str, dest='PROMPT_IN2', default=NoDefault,
178 help="Set the secondary input prompt (' .\D.: ')")
179 ),
180 (('-prompt_out','-po'), dict(
181 type=str, dest='PROMPT_OUT', default=NoDefault,
182 help="Set the output prompt ('Out[\#]:')")
183 ),
184 (('-quick',), dict(
185 action='store_true', dest='QUICK', default=NoDefault,
186 help="Enable quick startup with no config files.")
187 ),
188 (('-readline',), dict(
189 action='store_true', dest='READLINE_USE', default=NoDefault,
190 help="Enable readline for command line usage.")
191 ),
192 (('-noreadline',), dict(
193 action='store_false', dest='READLINE_USE', default=NoDefault,
194 help="Disable readline for command line usage.")
195 ),
196 (('-screen_length','-sl'), dict(
197 type=int, dest='SCREEN_LENGTH', default=NoDefault,
198 help='Number of lines on screen, used to control printing of long strings.')
199 ),
200 (('-separate_in','-si'), dict(
201 type=str, dest='SEPARATE_IN', default=NoDefault,
202 help="Separator before input prompts. Default '\n'.")
203 ),
204 (('-separate_out','-so'), dict(
205 type=str, dest='SEPARATE_OUT', default=NoDefault,
206 help="Separator before output prompts. Default 0 (nothing).")
207 ),
208 (('-separate_out2','-so2'), dict(
209 type=str, dest='SEPARATE_OUT2', default=NoDefault,
210 help="Separator after output prompts. Default 0 (nonight).")
211 ),
212 (('-nosep',), dict(
213 action='store_true', dest='NOSEP', default=NoDefault,
214 help="Eliminate all spacing between prompts.")
215 ),
216 (('-xmode',), dict(
217 type=str, dest='XMODE', default=NoDefault,
218 help="Exception mode ('Plain','Context','Verbose')")
219 ),
220 )
221
222
37 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
223 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
38 arguments = (
224
39 ()
225 arguments = cl_args
40 )
226
41
227
42 class IPythonApp(Application):
228 class IPythonApp(Application):
43 name = 'ipython'
229 name = 'ipython'
44 config_file_name = 'ipython_config.py'
230 config_file_name = 'ipython_config.py'
45
231
46 def create_command_line_config(self):
232 def create_command_line_config(self):
47 """Create and return a command line config loader."""
233 """Create and return a command line config loader."""
48 return IPythonAppCLConfigLoader(
234 return IPythonAppCLConfigLoader(
49 description=ipython_desc,
235 description=ipython_desc,
50 version=release.version)
236 version=release.version)
51
237
238 def post_load_command_line_config(self):
239 """Do actions after loading cl config."""
240 clc = self.command_line_config
241
242 # This needs to be set here, the rest are set in pre_construct.
243 if hasattr(clc, 'CLASSIC'):
244 if clc.CLASSIC: clc.QUICK = 1
245
246 # Display the deprecation warnings about threaded shells
247 # if opts_all.pylab == 1: threaded_shell_warning()
248 # if opts_all.wthread == 1: threaded_shell_warning()
249 # if opts_all.qthread == 1: threaded_shell_warning()
250 # if opts_all.q4thread == 1: threaded_shell_warning()
251 # if opts_all.gthread == 1: threaded_shell_warning()
252
253 def load_file_config(self):
254 if hasattr(self.command_line_config, 'QUICK'):
255 if self.command_line_config.QUICK:
256 self.file_config = Struct()
257 return
258 super(IPythonApp, self).load_file_config()
259
260 def post_load_file_config(self):
261 """Logic goes here."""
262
263 def pre_construct(self):
264 config = self.master_config
265
266 if hasattr(config, 'CLASSIC'):
267 if config.CLASSIC:
268 config.QUICK = 1
269 config.CACHE_SIZE = 0
270 config.PPRINT = 0
271 config.PROMPT_IN1 = '>>> '
272 config.PROMPT_IN2 = '... '
273 config.PROMPT_OUT = ''
274 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
275 config.COLORS = 'NoColor'
276 config.XMODE = 'Plain'
277
278 # All this should be moved to traitlet handlers in InteractiveShell
279 if hasattr(config, 'NOSEP'):
280 if config.NOSEP:
281 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
282
283 if hasattr(config, 'SEPARATE_IN'):
284 if config.SEPARATE_IN == '0': config.SEPARATE_IN = ''
285 config.SEPARATE_IN = config.SEPARATE_IN.replace('\\n','\n')
286
287 if hasattr(config, 'SEPARATE_OUT'):
288 if config.SEPARATE_OUT == '0': config.SEPARATE_OUT = ''
289 config.SEPARATE_OUT = config.SEPARATE_OUT.replace('\\n','\n')
290
291 if hasattr(config, 'SEPARATE_OUT'):
292 if config.SEPARATE_OUT2 == '0': config.SEPARATE_OUT2 = ''
293 config.SEPARATE_OUT2 = config.SEPARATE_OUT2.replace('\\n','\n')
294
52 def construct(self):
295 def construct(self):
296 # I am a little hesitant to put these into InteractiveShell itself.
297 # But that might be the place for them
298 sys.path.insert(0, '')
299 # add personal ipythondir to sys.path so that users can put things in
300 # there for customization
301 sys.path.append(os.path.abspath(self.ipythondir))
302
303 # Create an InteractiveShell instance
53 self.shell = InteractiveShell(
304 self.shell = InteractiveShell(
54 name='__IP',
305 name='__IP',
55 parent=None,
306 parent=None,
56 config=self.master_config
307 config=self.master_config
57 )
308 )
58
309
59 def start_app(self):
310 def start_app(self):
60 self.shell.mainloop()
311 self.shell.mainloop()
61
312
62
313
63 if __name__ == '__main__':
314 if __name__ == '__main__':
64 app = IPythonApp()
315 app = IPythonApp()
65 app.start() No newline at end of file
316 app.start()
@@ -1,2737 +1,2809 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import __main__
19 import __main__
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import bdb
22 import bdb
23 import codeop
23 import codeop
24 import exceptions
24 import exceptions
25 import glob
25 import glob
26 import keyword
26 import keyword
27 import new
27 import new
28 import os
28 import os
29 import re
29 import re
30 import shutil
30 import shutil
31 import string
31 import string
32 import sys
32 import sys
33 import tempfile
33 import tempfile
34
34
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
37 from IPython.core import ipapi
37 from IPython.core import ipapi
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import history as ipcorehist
39 from IPython.core import history as ipcorehist
40 from IPython.core import prefilter
40 from IPython.core import prefilter
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.logger import Logger
42 from IPython.core.logger import Logger
43 from IPython.core.magic import Magic
43 from IPython.core.magic import Magic
44 from IPython.core.prompts import CachedOutput
44 from IPython.core.prompts import CachedOutput
45 from IPython.core.component import Component
45 from IPython.core.component import Component
46 from IPython.core.oldusersetup import user_setup
46 from IPython.core.oldusersetup import user_setup
47 from IPython.core.usage import interactive_usage, banner_parts
47 from IPython.core.usage import interactive_usage, default_banner
48
48
49 from IPython.extensions import pickleshare
49 from IPython.extensions import pickleshare
50 from IPython.external.Itpl import ItplNS
50 from IPython.external.Itpl import ItplNS
51 from IPython.lib.backgroundjobs import BackgroundJobManager
51 from IPython.lib.backgroundjobs import BackgroundJobManager
52 from IPython.utils.ipstruct import Struct
52 from IPython.utils.ipstruct import Struct
53 from IPython.utils import PyColorize
53 from IPython.utils import PyColorize
54 from IPython.utils.genutils import *
54 from IPython.utils.genutils import *
55 from IPython.utils.strdispatch import StrDispatch
55 from IPython.utils.strdispatch import StrDispatch
56
56
57 from IPython.utils.traitlets import (
57 from IPython.utils.traitlets import (
58 Int, Float, Str, Bool
58 Int, Float, Str, CBool, CaselessStrEnum, Enum
59 )
59 )
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 # Globals
62 # Globals
63 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
64
64
65
65
66 # store the builtin raw_input globally, and use this always, in case user code
66 # store the builtin raw_input globally, and use this always, in case user code
67 # overwrites it (like wx.py.PyShell does)
67 # overwrites it (like wx.py.PyShell does)
68 raw_input_original = raw_input
68 raw_input_original = raw_input
69
69
70 # compiled regexps for autoindent management
70 # compiled regexps for autoindent management
71 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
71 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
72
72
73
73
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75 # Utilities
75 # Utilities
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77
77
78
78
79 ini_spaces_re = re.compile(r'^(\s+)')
79 ini_spaces_re = re.compile(r'^(\s+)')
80
80
81
81
82 def num_ini_spaces(strng):
82 def num_ini_spaces(strng):
83 """Return the number of initial spaces in a string"""
83 """Return the number of initial spaces in a string"""
84
84
85 ini_spaces = ini_spaces_re.match(strng)
85 ini_spaces = ini_spaces_re.match(strng)
86 if ini_spaces:
86 if ini_spaces:
87 return ini_spaces.end()
87 return ini_spaces.end()
88 else:
88 else:
89 return 0
89 return 0
90
90
91
91
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107
107
108 class SpaceInInput(exceptions.Exception): pass
108 class SpaceInInput(exceptions.Exception): pass
109
109
110 class Bunch: pass
110 class Bunch: pass
111
111
112 class Undefined: pass
112 class Undefined: pass
113
113
114 class Quitter(object):
114 class Quitter(object):
115 """Simple class to handle exit, similar to Python 2.5's.
115 """Simple class to handle exit, similar to Python 2.5's.
116
116
117 It handles exiting in an ipython-safe manner, which the one in Python 2.5
117 It handles exiting in an ipython-safe manner, which the one in Python 2.5
118 doesn't do (obviously, since it doesn't know about ipython)."""
118 doesn't do (obviously, since it doesn't know about ipython)."""
119
119
120 def __init__(self,shell,name):
120 def __init__(self,shell,name):
121 self.shell = shell
121 self.shell = shell
122 self.name = name
122 self.name = name
123
123
124 def __repr__(self):
124 def __repr__(self):
125 return 'Type %s() to exit.' % self.name
125 return 'Type %s() to exit.' % self.name
126 __str__ = __repr__
126 __str__ = __repr__
127
127
128 def __call__(self):
128 def __call__(self):
129 self.shell.exit()
129 self.shell.exit()
130
130
131 class InputList(list):
131 class InputList(list):
132 """Class to store user input.
132 """Class to store user input.
133
133
134 It's basically a list, but slices return a string instead of a list, thus
134 It's basically a list, but slices return a string instead of a list, thus
135 allowing things like (assuming 'In' is an instance):
135 allowing things like (assuming 'In' is an instance):
136
136
137 exec In[4:7]
137 exec In[4:7]
138
138
139 or
139 or
140
140
141 exec In[5:9] + In[14] + In[21:25]"""
141 exec In[5:9] + In[14] + In[21:25]"""
142
142
143 def __getslice__(self,i,j):
143 def __getslice__(self,i,j):
144 return ''.join(list.__getslice__(self,i,j))
144 return ''.join(list.__getslice__(self,i,j))
145
145
146 class SyntaxTB(ultratb.ListTB):
146 class SyntaxTB(ultratb.ListTB):
147 """Extension which holds some state: the last exception value"""
147 """Extension which holds some state: the last exception value"""
148
148
149 def __init__(self,color_scheme = 'NoColor'):
149 def __init__(self,color_scheme = 'NoColor'):
150 ultratb.ListTB.__init__(self,color_scheme)
150 ultratb.ListTB.__init__(self,color_scheme)
151 self.last_syntax_error = None
151 self.last_syntax_error = None
152
152
153 def __call__(self, etype, value, elist):
153 def __call__(self, etype, value, elist):
154 self.last_syntax_error = value
154 self.last_syntax_error = value
155 ultratb.ListTB.__call__(self,etype,value,elist)
155 ultratb.ListTB.__call__(self,etype,value,elist)
156
156
157 def clear_err_state(self):
157 def clear_err_state(self):
158 """Return the current error state and clear it"""
158 """Return the current error state and clear it"""
159 e = self.last_syntax_error
159 e = self.last_syntax_error
160 self.last_syntax_error = None
160 self.last_syntax_error = None
161 return e
161 return e
162
162
163 def get_default_editor():
164 try:
165 ed = os.environ['EDITOR']
166 except KeyError:
167 if os.name == 'posix':
168 ed = 'vi' # the only one guaranteed to be there!
169 else:
170 ed = 'notepad' # same in Windows!
171 return ed
163
172
164 #-----------------------------------------------------------------------------
173 #-----------------------------------------------------------------------------
165 # Main IPython class
174 # Main IPython class
166 #-----------------------------------------------------------------------------
175 #-----------------------------------------------------------------------------
167
176
168 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
169 # until a full rewrite is made. I've cleaned all cross-class uses of
178 # until a full rewrite is made. I've cleaned all cross-class uses of
170 # attributes and methods, but too much user code out there relies on the
179 # attributes and methods, but too much user code out there relies on the
171 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
172 #
181 #
173 # But at least now, all the pieces have been separated and we could, in
182 # But at least now, all the pieces have been separated and we could, in
174 # principle, stop using the mixin. This will ease the transition to the
183 # principle, stop using the mixin. This will ease the transition to the
175 # chainsaw branch.
184 # chainsaw branch.
176
185
177 # For reference, the following is the list of 'self.foo' uses in the Magic
186 # For reference, the following is the list of 'self.foo' uses in the Magic
178 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
179 # class, to prevent clashes.
188 # class, to prevent clashes.
180
189
181 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
182 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
183 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
184 # 'self.value']
193 # 'self.value']
185
194
186 class InteractiveShell(Component, Magic):
195 class InteractiveShell(Component, Magic):
187 """An enhanced console for Python."""
196 """An enhanced console for Python."""
188
197
189 alias = []
198 alias = []
190 autocall = Bool(True)
199 autocall = Enum((0,1,2), config_key='AUTOCALL')
191 autoedit_syntax = Bool(False)
200 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
192 autoindent = Bool(False)
201 autoindent = CBool(True, config_key='AUTOINDENT')
193 automagic = Bool(True)
202 automagic = CBool(True, config_key='AUTOMAGIC')
194 autoexec = []
203 autoexec = []
195 display_banner = Bool(True)
204 display_banner = CBool(True, config_key='DISPLAY_BANNER')
196 banner = Str('')
205 banner = Str('')
197 c = Str('')
206 banner1 = Str(default_banner, config_key='BANNER1')
198 cache_size = Int(1000)
207 banner2 = Str('', config_key='BANNER2')
199 classic = Bool(False)
208 c = Str('', config_key='C')
200 color_info = Int(0)
209 cache_size = Int(1000, config_key='CACHE_SIZE')
201 colors = Str('LightBG')
210 classic = CBool(False, config_key='CLASSIC')
202 confirm_exit = Bool(True)
211 color_info = CBool(True, config_key='COLOR_INFO')
203 debug = Bool(False)
212 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
204 deep_reload = Bool(False)
213 default_value='LightBG', config_key='COLORS')
205 embedded = Bool(False)
214 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
206 editor = Str('0')
215 debug = CBool(False)
216 deep_reload = CBool(False, config_key='DEEP_RELOAD')
217 embedded = CBool(False)
218 editor = Str(get_default_editor(), config_key='EDITOR')
207 filename = Str("<ipython console>")
219 filename = Str("<ipython console>")
208 help = Bool(False)
220 help = CBool(False)
209 interactive = Bool(False)
221 interactive = CBool(False)
210 logstart = Bool(False, config_key='LOGSTART')
222 logstart = CBool(False, config_key='LOGSTART')
211 logfile = Str('')
223 logfile = Str('', config_key='LOGFILE')
212 logplay = Str('')
224 logplay = Str('', config_key='LOGPLAY')
213 messages = Bool(True)
225 multi_line_specials = CBool(True)
214 multi_line_specials = Bool(True)
215 nosep = Bool(False)
216 object_info_string_level = Int(0)
226 object_info_string_level = Int(0)
217 pager = Str('less')
227 pager = Str('less')
218 pdb = Bool(False)
228 pdb = CBool(False, config_key='PDB')
219 pprint = Bool(True)
229 pprint = CBool(True, config_key='PPRINT')
220 profile = Str('')
230 profile = Str('', config_key='PROFILE')
221 prompt_in1 = Str('In [\\#]: ')
231 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
222 prompt_in2 = Str(' .\\D.: ')
232 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
223 prompt_out = Str('Out[\\#]: ')
233 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
224 prompts_pad_left = Bool(True)
234 prompts_pad_left = CBool(True)
225 pydb = Bool(False)
235 pydb = CBool(False)
226 quick = Bool(False)
236 quiet = CBool(False)
227 quiet = Bool(False)
237
228
238 readline_use = CBool(True, config_key='READLINE_USE')
229 readline_use = Bool(True)
239 readline_merge_completions = CBool(True)
230 readline_merge_completions = Bool(True)
231 readline_omit__names = Int(0)
240 readline_omit__names = Int(0)
232 readline_remove_delims = '-/~'
241 readline_remove_delims = '-/~'
233 readline_parse_and_bind = [
242 readline_parse_and_bind = [
234 'tab: complete',
243 'tab: complete',
235 '"\C-l": possible-completions',
244 '"\C-l": possible-completions',
236 'set show-all-if-ambiguous on',
245 'set show-all-if-ambiguous on',
237 '"\C-o": tab-insert',
246 '"\C-o": tab-insert',
238 '"\M-i": " "',
247 '"\M-i": " "',
239 '"\M-o": "\d\d\d\d"',
248 '"\M-o": "\d\d\d\d"',
240 '"\M-I": "\d\d\d\d"',
249 '"\M-I": "\d\d\d\d"',
241 '"\C-r": reverse-search-history',
250 '"\C-r": reverse-search-history',
242 '"\C-s": forward-search-history',
251 '"\C-s": forward-search-history',
243 '"\C-p": history-search-backward',
252 '"\C-p": history-search-backward',
244 '"\C-n": history-search-forward',
253 '"\C-n": history-search-forward',
245 '"\e[A": history-search-backward',
254 '"\e[A": history-search-backward',
246 '"\e[B": history-search-forward',
255 '"\e[B": history-search-forward',
247 '"\C-k": kill-line',
256 '"\C-k": kill-line',
248 '"\C-u": unix-line-discard',
257 '"\C-u": unix-line-discard',
249 ]
258 ]
250
259
251 screen_length = Int(0)
260 screen_length = Int(0, config_key='SCREEN_LENGTH')
252 separate_in = Str('\n')
261 separate_in = Str('\n', config_key='SEPARATE_IN')
253 separate_out = Str('')
262 separate_out = Str('', config_key='SEPARATE_OUT')
254 separate_out2 = Str('')
263 separate_out2 = Str('', config_key='SEPARATE_OUT2')
255 system_header = Str('IPython system call: ')
264 system_header = Str('IPython system call: ')
256 system_verbose = Bool(False)
265 system_verbose = CBool(False)
257 term_title = Bool(True)
266 term_title = CBool(True)
258 wildcards_case_sensitive = Bool(True)
267 wildcards_case_sensitive = CBool(True)
259 xmode = Str('Context')
268 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
260 magic_docstrings = Bool(False)
269 default_value='Context', config_key='XMODE')
270 magic_docstrings = CBool(False)
261
271
262 # class attribute to indicate whether the class supports threads or not.
272 # class attribute to indicate whether the class supports threads or not.
263 # Subclasses with thread support should override this as needed.
273 # Subclasses with thread support should override this as needed.
264 isthreaded = False
274 isthreaded = False
265
275
266 def __init__(self, name, parent=None, config=None, usage=None,
276 def __init__(self, name, parent=None, config=None, usage=None,
267 user_ns=None, user_global_ns=None, banner2='',
277 user_ns=None, user_global_ns=None,
278 banner1='', banner2='',
268 custom_exceptions=((),None), embedded=False):
279 custom_exceptions=((),None), embedded=False):
269
280
281 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
283 # Ideally, from here on out, the config should only be used when
284 # passing it to children components.
270 super(InteractiveShell, self).__init__(parent, config=config, name=name)
285 super(InteractiveShell, self).__init__(parent, config=config, name=name)
271
286
272 self.init_instance_attrs()
287 self.init_instance_attrs()
273 self.init_usage(usage)
288 self.init_usage(usage)
274 self.init_banner(banner2)
289 self.init_banner(banner1, banner2)
275 self.init_embedded(embedded)
290 self.init_embedded(embedded)
276 self.init_create_namespaces(user_ns, user_global_ns)
291 self.init_create_namespaces(user_ns, user_global_ns)
277 self.init_history()
292 self.init_history()
278 self.init_encoding()
293 self.init_encoding()
279 self.init_handlers()
294 self.init_handlers()
280
295
281 Magic.__init__(self, self)
296 Magic.__init__(self, self)
282
297
283 self.init_syntax_highlighting()
298 self.init_syntax_highlighting()
284 self.init_hooks()
299 self.init_hooks()
285 self.init_pushd_popd_magic()
300 self.init_pushd_popd_magic()
286 self.init_traceback_handlers(custom_exceptions)
301 self.init_traceback_handlers(custom_exceptions)
287
302
288 # Produce a public API instance
303 # Produce a public API instance
289 self.api = ipapi.IPApi(self)
304 self.api = ipapi.IPApi(self)
290
305
291 self.init_namespaces()
306 self.init_namespaces()
292 self.init_logger()
307 self.init_logger()
293 self.init_aliases()
308 self.init_aliases()
294 self.init_builtins()
309 self.init_builtins()
310
311 # pre_config_initialization
295 self.init_shadow_hist()
312 self.init_shadow_hist()
313
314 # The next section should contain averything that was in ipmaker.
296 self.init_logstart()
315 self.init_logstart()
297 self.post_config_initialization()
316
317 # The following was in post_config_initialization
318 self.init_inspector()
319 self.init_readline()
320 self.init_prompts()
321 self.init_displayhook()
322 self.init_reload_doctest()
323 self.init_magics()
324 self.init_pdb()
325 self.hooks.late_startup_hook()
326 self.init_exec_commands()
327
328 #-------------------------------------------------------------------------
329 # Traitlet changed handlers
330 #-------------------------------------------------------------------------
331
332 def _banner1_changed(self):
333 self.compute_banner()
334
335 def _banner2_changed(self):
336 self.compute_banner()
337
338 @property
339 def usable_screen_length(self):
340 if self.screen_length == 0:
341 return 0
342 else:
343 num_lines_bot = self.separate_in.count('\n')+1
344 return self.screen_length - num_lines_bot
345
346 #-------------------------------------------------------------------------
347 # init_* methods called by __init__
348 #-------------------------------------------------------------------------
298
349
299 def init_instance_attrs(self):
350 def init_instance_attrs(self):
300 self.jobs = BackgroundJobManager()
351 self.jobs = BackgroundJobManager()
301 self.more = False
352 self.more = False
302
353
303 # command compiler
354 # command compiler
304 self.compile = codeop.CommandCompiler()
355 self.compile = codeop.CommandCompiler()
305
356
306 # User input buffer
357 # User input buffer
307 self.buffer = []
358 self.buffer = []
308
359
309 # Make an empty namespace, which extension writers can rely on both
360 # Make an empty namespace, which extension writers can rely on both
310 # existing and NEVER being used by ipython itself. This gives them a
361 # existing and NEVER being used by ipython itself. This gives them a
311 # convenient location for storing additional information and state
362 # convenient location for storing additional information and state
312 # their extensions may require, without fear of collisions with other
363 # their extensions may require, without fear of collisions with other
313 # ipython names that may develop later.
364 # ipython names that may develop later.
314 self.meta = Struct()
365 self.meta = Struct()
315
366
316 # Object variable to store code object waiting execution. This is
367 # Object variable to store code object waiting execution. This is
317 # used mainly by the multithreaded shells, but it can come in handy in
368 # used mainly by the multithreaded shells, but it can come in handy in
318 # other situations. No need to use a Queue here, since it's a single
369 # other situations. No need to use a Queue here, since it's a single
319 # item which gets cleared once run.
370 # item which gets cleared once run.
320 self.code_to_run = None
371 self.code_to_run = None
321
372
322 # Flag to mark unconditional exit
373 # Flag to mark unconditional exit
323 self.exit_now = False
374 self.exit_now = False
324
375
325 # Temporary files used for various purposes. Deleted at exit.
376 # Temporary files used for various purposes. Deleted at exit.
326 self.tempfiles = []
377 self.tempfiles = []
327
378
328 # Keep track of readline usage (later set by init_readline)
379 # Keep track of readline usage (later set by init_readline)
329 self.has_readline = False
380 self.has_readline = False
330
381
331 # keep track of where we started running (mainly for crash post-mortem)
382 # keep track of where we started running (mainly for crash post-mortem)
332 # This is not being used anywhere currently.
383 # This is not being used anywhere currently.
333 self.starting_dir = os.getcwd()
384 self.starting_dir = os.getcwd()
334
385
335 # Indentation management
386 # Indentation management
336 self.indent_current_nsp = 0
387 self.indent_current_nsp = 0
337
388
338 def init_usage(self, usage=None):
389 def init_usage(self, usage=None):
339 if usage is None:
390 if usage is None:
340 self.usage = interactive_usage
391 self.usage = interactive_usage
341 else:
392 else:
342 self.usage = usage
393 self.usage = usage
343
394
344 def init_banner(self, banner2):
395 def init_banner(self, banner1, banner2):
345 if self.c: # regular python doesn't print the banner with -c
396 if self.c: # regular python doesn't print the banner with -c
346 self.display_banner = False
397 self.display_banner = False
347 bp = banner_parts
398 if banner1:
399 self.banner1 = banner1
400 if banner2:
401 self.banner2 = banner2
402 self.compute_banner()
403
404 def compute_banner(self):
405 self.banner = self.banner1 + '\n'
348 if self.profile:
406 if self.profile:
349 bp.append('IPython profile: %s\n' % self.profile)
407 self.banner += '\nIPython profile: %s\n' % self.profile
350 if banner2 is not None:
408 if self.banner2:
351 bp.append(banner2)
409 self.banner += '\n' + self.banner2 + '\n'
352 self.banner = '\n'.join(bp)
353
410
354 def init_embedded(self, embedded):
411 def init_embedded(self, embedded):
355 # We need to know whether the instance is meant for embedding, since
412 # We need to know whether the instance is meant for embedding, since
356 # global/local namespaces need to be handled differently in that case
413 # global/local namespaces need to be handled differently in that case
357 self.embedded = embedded
414 self.embedded = embedded
358 if embedded:
415 if embedded:
359 # Control variable so users can, from within the embedded instance,
416 # Control variable so users can, from within the embedded instance,
360 # permanently deactivate it.
417 # permanently deactivate it.
361 self.embedded_active = True
418 self.embedded_active = True
362
419
363 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
420 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
364 # Create the namespace where the user will operate. user_ns is
421 # Create the namespace where the user will operate. user_ns is
365 # normally the only one used, and it is passed to the exec calls as
422 # normally the only one used, and it is passed to the exec calls as
366 # the locals argument. But we do carry a user_global_ns namespace
423 # the locals argument. But we do carry a user_global_ns namespace
367 # given as the exec 'globals' argument, This is useful in embedding
424 # given as the exec 'globals' argument, This is useful in embedding
368 # situations where the ipython shell opens in a context where the
425 # situations where the ipython shell opens in a context where the
369 # distinction between locals and globals is meaningful. For
426 # distinction between locals and globals is meaningful. For
370 # non-embedded contexts, it is just the same object as the user_ns dict.
427 # non-embedded contexts, it is just the same object as the user_ns dict.
371
428
372 # FIXME. For some strange reason, __builtins__ is showing up at user
429 # FIXME. For some strange reason, __builtins__ is showing up at user
373 # level as a dict instead of a module. This is a manual fix, but I
430 # level as a dict instead of a module. This is a manual fix, but I
374 # should really track down where the problem is coming from. Alex
431 # should really track down where the problem is coming from. Alex
375 # Schmolck reported this problem first.
432 # Schmolck reported this problem first.
376
433
377 # A useful post by Alex Martelli on this topic:
434 # A useful post by Alex Martelli on this topic:
378 # Re: inconsistent value from __builtins__
435 # Re: inconsistent value from __builtins__
379 # Von: Alex Martelli <aleaxit@yahoo.com>
436 # Von: Alex Martelli <aleaxit@yahoo.com>
380 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
437 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
381 # Gruppen: comp.lang.python
438 # Gruppen: comp.lang.python
382
439
383 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
440 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
384 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
441 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
385 # > <type 'dict'>
442 # > <type 'dict'>
386 # > >>> print type(__builtins__)
443 # > >>> print type(__builtins__)
387 # > <type 'module'>
444 # > <type 'module'>
388 # > Is this difference in return value intentional?
445 # > Is this difference in return value intentional?
389
446
390 # Well, it's documented that '__builtins__' can be either a dictionary
447 # Well, it's documented that '__builtins__' can be either a dictionary
391 # or a module, and it's been that way for a long time. Whether it's
448 # or a module, and it's been that way for a long time. Whether it's
392 # intentional (or sensible), I don't know. In any case, the idea is
449 # intentional (or sensible), I don't know. In any case, the idea is
393 # that if you need to access the built-in namespace directly, you
450 # that if you need to access the built-in namespace directly, you
394 # should start with "import __builtin__" (note, no 's') which will
451 # should start with "import __builtin__" (note, no 's') which will
395 # definitely give you a module. Yeah, it's somewhat confusing:-(.
452 # definitely give you a module. Yeah, it's somewhat confusing:-(.
396
453
397 # These routines return properly built dicts as needed by the rest of
454 # These routines return properly built dicts as needed by the rest of
398 # the code, and can also be used by extension writers to generate
455 # the code, and can also be used by extension writers to generate
399 # properly initialized namespaces.
456 # properly initialized namespaces.
400 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
457 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
401 user_global_ns)
458 user_global_ns)
402
459
403 # Assign namespaces
460 # Assign namespaces
404 # This is the namespace where all normal user variables live
461 # This is the namespace where all normal user variables live
405 self.user_ns = user_ns
462 self.user_ns = user_ns
406 self.user_global_ns = user_global_ns
463 self.user_global_ns = user_global_ns
407
464
408 # An auxiliary namespace that checks what parts of the user_ns were
465 # An auxiliary namespace that checks what parts of the user_ns were
409 # loaded at startup, so we can list later only variables defined in
466 # loaded at startup, so we can list later only variables defined in
410 # actual interactive use. Since it is always a subset of user_ns, it
467 # actual interactive use. Since it is always a subset of user_ns, it
411 # doesn't need to be seaparately tracked in the ns_table
468 # doesn't need to be seaparately tracked in the ns_table
412 self.user_config_ns = {}
469 self.user_config_ns = {}
413
470
414 # A namespace to keep track of internal data structures to prevent
471 # A namespace to keep track of internal data structures to prevent
415 # them from cluttering user-visible stuff. Will be updated later
472 # them from cluttering user-visible stuff. Will be updated later
416 self.internal_ns = {}
473 self.internal_ns = {}
417
474
418 # Namespace of system aliases. Each entry in the alias
475 # Namespace of system aliases. Each entry in the alias
419 # table must be a 2-tuple of the form (N,name), where N is the number
476 # table must be a 2-tuple of the form (N,name), where N is the number
420 # of positional arguments of the alias.
477 # of positional arguments of the alias.
421 self.alias_table = {}
478 self.alias_table = {}
422
479
423 # Now that FakeModule produces a real module, we've run into a nasty
480 # Now that FakeModule produces a real module, we've run into a nasty
424 # problem: after script execution (via %run), the module where the user
481 # problem: after script execution (via %run), the module where the user
425 # code ran is deleted. Now that this object is a true module (needed
482 # code ran is deleted. Now that this object is a true module (needed
426 # so docetst and other tools work correctly), the Python module
483 # so docetst and other tools work correctly), the Python module
427 # teardown mechanism runs over it, and sets to None every variable
484 # teardown mechanism runs over it, and sets to None every variable
428 # present in that module. Top-level references to objects from the
485 # present in that module. Top-level references to objects from the
429 # script survive, because the user_ns is updated with them. However,
486 # script survive, because the user_ns is updated with them. However,
430 # calling functions defined in the script that use other things from
487 # calling functions defined in the script that use other things from
431 # the script will fail, because the function's closure had references
488 # the script will fail, because the function's closure had references
432 # to the original objects, which are now all None. So we must protect
489 # to the original objects, which are now all None. So we must protect
433 # these modules from deletion by keeping a cache.
490 # these modules from deletion by keeping a cache.
434 #
491 #
435 # To avoid keeping stale modules around (we only need the one from the
492 # To avoid keeping stale modules around (we only need the one from the
436 # last run), we use a dict keyed with the full path to the script, so
493 # last run), we use a dict keyed with the full path to the script, so
437 # only the last version of the module is held in the cache. Note,
494 # only the last version of the module is held in the cache. Note,
438 # however, that we must cache the module *namespace contents* (their
495 # however, that we must cache the module *namespace contents* (their
439 # __dict__). Because if we try to cache the actual modules, old ones
496 # __dict__). Because if we try to cache the actual modules, old ones
440 # (uncached) could be destroyed while still holding references (such as
497 # (uncached) could be destroyed while still holding references (such as
441 # those held by GUI objects that tend to be long-lived)>
498 # those held by GUI objects that tend to be long-lived)>
442 #
499 #
443 # The %reset command will flush this cache. See the cache_main_mod()
500 # The %reset command will flush this cache. See the cache_main_mod()
444 # and clear_main_mod_cache() methods for details on use.
501 # and clear_main_mod_cache() methods for details on use.
445
502
446 # This is the cache used for 'main' namespaces
503 # This is the cache used for 'main' namespaces
447 self._main_ns_cache = {}
504 self._main_ns_cache = {}
448 # And this is the single instance of FakeModule whose __dict__ we keep
505 # And this is the single instance of FakeModule whose __dict__ we keep
449 # copying and clearing for reuse on each %run
506 # copying and clearing for reuse on each %run
450 self._user_main_module = FakeModule()
507 self._user_main_module = FakeModule()
451
508
452 # A table holding all the namespaces IPython deals with, so that
509 # A table holding all the namespaces IPython deals with, so that
453 # introspection facilities can search easily.
510 # introspection facilities can search easily.
454 self.ns_table = {'user':user_ns,
511 self.ns_table = {'user':user_ns,
455 'user_global':user_global_ns,
512 'user_global':user_global_ns,
456 'alias':self.alias_table,
513 'alias':self.alias_table,
457 'internal':self.internal_ns,
514 'internal':self.internal_ns,
458 'builtin':__builtin__.__dict__
515 'builtin':__builtin__.__dict__
459 }
516 }
460
517
461 # Similarly, track all namespaces where references can be held and that
518 # Similarly, track all namespaces where references can be held and that
462 # we can safely clear (so it can NOT include builtin). This one can be
519 # we can safely clear (so it can NOT include builtin). This one can be
463 # a simple list.
520 # a simple list.
464 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
521 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
465 self.alias_table, self.internal_ns,
522 self.alias_table, self.internal_ns,
466 self._main_ns_cache ]
523 self._main_ns_cache ]
467
524
468 # We need to insert into sys.modules something that looks like a
525 # We need to insert into sys.modules something that looks like a
469 # module but which accesses the IPython namespace, for shelve and
526 # module but which accesses the IPython namespace, for shelve and
470 # pickle to work interactively. Normally they rely on getting
527 # pickle to work interactively. Normally they rely on getting
471 # everything out of __main__, but for embedding purposes each IPython
528 # everything out of __main__, but for embedding purposes each IPython
472 # instance has its own private namespace, so we can't go shoving
529 # instance has its own private namespace, so we can't go shoving
473 # everything into __main__.
530 # everything into __main__.
474
531
475 # note, however, that we should only do this for non-embedded
532 # note, however, that we should only do this for non-embedded
476 # ipythons, which really mimic the __main__.__dict__ with their own
533 # ipythons, which really mimic the __main__.__dict__ with their own
477 # namespace. Embedded instances, on the other hand, should not do
534 # namespace. Embedded instances, on the other hand, should not do
478 # this because they need to manage the user local/global namespaces
535 # this because they need to manage the user local/global namespaces
479 # only, but they live within a 'normal' __main__ (meaning, they
536 # only, but they live within a 'normal' __main__ (meaning, they
480 # shouldn't overtake the execution environment of the script they're
537 # shouldn't overtake the execution environment of the script they're
481 # embedded in).
538 # embedded in).
482
539
483 if not self.embedded:
540 if not self.embedded:
484 try:
541 try:
485 main_name = self.user_ns['__name__']
542 main_name = self.user_ns['__name__']
486 except KeyError:
543 except KeyError:
487 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
544 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
488 else:
545 else:
489 sys.modules[main_name] = FakeModule(self.user_ns)
546 sys.modules[main_name] = FakeModule(self.user_ns)
490
547
491 def init_history(self):
548 def init_history(self):
492 # List of input with multi-line handling.
549 # List of input with multi-line handling.
493 self.input_hist = InputList()
550 self.input_hist = InputList()
494 # This one will hold the 'raw' input history, without any
551 # This one will hold the 'raw' input history, without any
495 # pre-processing. This will allow users to retrieve the input just as
552 # pre-processing. This will allow users to retrieve the input just as
496 # it was exactly typed in by the user, with %hist -r.
553 # it was exactly typed in by the user, with %hist -r.
497 self.input_hist_raw = InputList()
554 self.input_hist_raw = InputList()
498
555
499 # list of visited directories
556 # list of visited directories
500 try:
557 try:
501 self.dir_hist = [os.getcwd()]
558 self.dir_hist = [os.getcwd()]
502 except OSError:
559 except OSError:
503 self.dir_hist = []
560 self.dir_hist = []
504
561
505 # dict of output history
562 # dict of output history
506 self.output_hist = {}
563 self.output_hist = {}
507
564
508 # Now the history file
565 # Now the history file
509 try:
566 try:
510 histfname = 'history-%s' % self.config.PROFILE
567 histfname = 'history-%s' % self.config.PROFILE
511 except AttributeError:
568 except AttributeError:
512 histfname = 'history'
569 histfname = 'history'
513 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
570 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
514
571
572 # Fill the history zero entry, user counter starts at 1
573 self.input_hist.append('\n')
574 self.input_hist_raw.append('\n')
575
515 def init_encoding(self):
576 def init_encoding(self):
516 # Get system encoding at startup time. Certain terminals (like Emacs
577 # Get system encoding at startup time. Certain terminals (like Emacs
517 # under Win32 have it set to None, and we need to have a known valid
578 # under Win32 have it set to None, and we need to have a known valid
518 # encoding to use in the raw_input() method
579 # encoding to use in the raw_input() method
519 try:
580 try:
520 self.stdin_encoding = sys.stdin.encoding or 'ascii'
581 self.stdin_encoding = sys.stdin.encoding or 'ascii'
521 except AttributeError:
582 except AttributeError:
522 self.stdin_encoding = 'ascii'
583 self.stdin_encoding = 'ascii'
523
584
524 def init_handlers(self):
585 def init_handlers(self):
525 # escapes for automatic behavior on the command line
586 # escapes for automatic behavior on the command line
526 self.ESC_SHELL = '!'
587 self.ESC_SHELL = '!'
527 self.ESC_SH_CAP = '!!'
588 self.ESC_SH_CAP = '!!'
528 self.ESC_HELP = '?'
589 self.ESC_HELP = '?'
529 self.ESC_MAGIC = '%'
590 self.ESC_MAGIC = '%'
530 self.ESC_QUOTE = ','
591 self.ESC_QUOTE = ','
531 self.ESC_QUOTE2 = ';'
592 self.ESC_QUOTE2 = ';'
532 self.ESC_PAREN = '/'
593 self.ESC_PAREN = '/'
533
594
534 # And their associated handlers
595 # And their associated handlers
535 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
596 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
536 self.ESC_QUOTE : self.handle_auto,
597 self.ESC_QUOTE : self.handle_auto,
537 self.ESC_QUOTE2 : self.handle_auto,
598 self.ESC_QUOTE2 : self.handle_auto,
538 self.ESC_MAGIC : self.handle_magic,
599 self.ESC_MAGIC : self.handle_magic,
539 self.ESC_HELP : self.handle_help,
600 self.ESC_HELP : self.handle_help,
540 self.ESC_SHELL : self.handle_shell_escape,
601 self.ESC_SHELL : self.handle_shell_escape,
541 self.ESC_SH_CAP : self.handle_shell_escape,
602 self.ESC_SH_CAP : self.handle_shell_escape,
542 }
603 }
543
604
544 def init_syntax_highlighting(self):
605 def init_syntax_highlighting(self):
545 # Python source parser/formatter for syntax highlighting
606 # Python source parser/formatter for syntax highlighting
546 pyformat = PyColorize.Parser().format
607 pyformat = PyColorize.Parser().format
547 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
608 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
548
609
549 def init_hooks(self):
610 def init_hooks(self):
550 # hooks holds pointers used for user-side customizations
611 # hooks holds pointers used for user-side customizations
551 self.hooks = Struct()
612 self.hooks = Struct()
552
613
553 self.strdispatchers = {}
614 self.strdispatchers = {}
554
615
555 # Set all default hooks, defined in the IPython.hooks module.
616 # Set all default hooks, defined in the IPython.hooks module.
556 import IPython.core.hooks
617 import IPython.core.hooks
557 hooks = IPython.core.hooks
618 hooks = IPython.core.hooks
558 for hook_name in hooks.__all__:
619 for hook_name in hooks.__all__:
559 # default hooks have priority 100, i.e. low; user hooks should have
620 # default hooks have priority 100, i.e. low; user hooks should have
560 # 0-100 priority
621 # 0-100 priority
561 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
622 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
562
623
563 def init_pushd_popd_magic(self):
624 def init_pushd_popd_magic(self):
564 # for pushd/popd management
625 # for pushd/popd management
565 try:
626 try:
566 self.home_dir = get_home_dir()
627 self.home_dir = get_home_dir()
567 except HomeDirError, msg:
628 except HomeDirError, msg:
568 fatal(msg)
629 fatal(msg)
569
630
570 self.dir_stack = []
631 self.dir_stack = []
571
632
572 def init_traceback_handlers(self, custom_exceptions):
633 def init_traceback_handlers(self, custom_exceptions):
573 # Syntax error handler.
634 # Syntax error handler.
574 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
635 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
575
636
576 # The interactive one is initialized with an offset, meaning we always
637 # The interactive one is initialized with an offset, meaning we always
577 # want to remove the topmost item in the traceback, which is our own
638 # want to remove the topmost item in the traceback, which is our own
578 # internal code. Valid modes: ['Plain','Context','Verbose']
639 # internal code. Valid modes: ['Plain','Context','Verbose']
579 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
640 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
580 color_scheme='NoColor',
641 color_scheme='NoColor',
581 tb_offset = 1)
642 tb_offset = 1)
582
643
583 # IPython itself shouldn't crash. This will produce a detailed
644 # IPython itself shouldn't crash. This will produce a detailed
584 # post-mortem if it does. But we only install the crash handler for
645 # post-mortem if it does. But we only install the crash handler for
585 # non-threaded shells, the threaded ones use a normal verbose reporter
646 # non-threaded shells, the threaded ones use a normal verbose reporter
586 # and lose the crash handler. This is because exceptions in the main
647 # and lose the crash handler. This is because exceptions in the main
587 # thread (such as in GUI code) propagate directly to sys.excepthook,
648 # thread (such as in GUI code) propagate directly to sys.excepthook,
588 # and there's no point in printing crash dumps for every user exception.
649 # and there's no point in printing crash dumps for every user exception.
589 if self.isthreaded:
650 if self.isthreaded:
590 ipCrashHandler = ultratb.FormattedTB()
651 ipCrashHandler = ultratb.FormattedTB()
591 else:
652 else:
592 from IPython.core import crashhandler
653 from IPython.core import crashhandler
593 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
654 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
594 self.set_crash_handler(ipCrashHandler)
655 self.set_crash_handler(ipCrashHandler)
595
656
596 # and add any custom exception handlers the user may have specified
657 # and add any custom exception handlers the user may have specified
597 self.set_custom_exc(*custom_exceptions)
658 self.set_custom_exc(*custom_exceptions)
598
659
599 def init_logger(self):
660 def init_logger(self):
600 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
661 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
601 # local shortcut, this is used a LOT
662 # local shortcut, this is used a LOT
602 self.log = self.logger.log
663 self.log = self.logger.log
603 # template for logfile headers. It gets resolved at runtime by the
664 # template for logfile headers. It gets resolved at runtime by the
604 # logstart method.
665 # logstart method.
605 self.loghead_tpl = \
666 self.loghead_tpl = \
606 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
667 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
607 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
668 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
608 #log# opts = %s
669 #log# opts = %s
609 #log# args = %s
670 #log# args = %s
610 #log# It is safe to make manual edits below here.
671 #log# It is safe to make manual edits below here.
611 #log#-----------------------------------------------------------------------
672 #log#-----------------------------------------------------------------------
612 """
673 """
613
674
614 def init_logstart(self):
675 def init_logstart(self):
615 if self.logplay:
676 if self.logplay:
616 IP.magic_logstart(self.logplay + ' append')
677 self.magic_logstart(self.logplay + ' append')
617 elif self.logfile:
678 elif self.logfile:
618 IP.magic_logstart(self.logfile)
679 self.magic_logstart(self.logfile)
619 elif self.logstart:
680 elif self.logstart:
620 self.magic_logstart()
681 self.magic_logstart()
621
682
622 def init_aliases(self):
683 def init_aliases(self):
623 # dict of things NOT to alias (keywords, builtins and some magics)
684 # dict of things NOT to alias (keywords, builtins and some magics)
624 no_alias = {}
685 no_alias = {}
625 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
686 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
626 for key in keyword.kwlist + no_alias_magics:
687 for key in keyword.kwlist + no_alias_magics:
627 no_alias[key] = 1
688 no_alias[key] = 1
628 no_alias.update(__builtin__.__dict__)
689 no_alias.update(__builtin__.__dict__)
629 self.no_alias = no_alias
690 self.no_alias = no_alias
630
691
631 # Make some aliases automatically
692 # Make some aliases automatically
632 # Prepare list of shell aliases to auto-define
693 # Prepare list of shell aliases to auto-define
633 if os.name == 'posix':
694 if os.name == 'posix':
634 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
695 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
635 'mv mv -i','rm rm -i','cp cp -i',
696 'mv mv -i','rm rm -i','cp cp -i',
636 'cat cat','less less','clear clear',
697 'cat cat','less less','clear clear',
637 # a better ls
698 # a better ls
638 'ls ls -F',
699 'ls ls -F',
639 # long ls
700 # long ls
640 'll ls -lF')
701 'll ls -lF')
641 # Extra ls aliases with color, which need special treatment on BSD
702 # Extra ls aliases with color, which need special treatment on BSD
642 # variants
703 # variants
643 ls_extra = ( # color ls
704 ls_extra = ( # color ls
644 'lc ls -F -o --color',
705 'lc ls -F -o --color',
645 # ls normal files only
706 # ls normal files only
646 'lf ls -F -o --color %l | grep ^-',
707 'lf ls -F -o --color %l | grep ^-',
647 # ls symbolic links
708 # ls symbolic links
648 'lk ls -F -o --color %l | grep ^l',
709 'lk ls -F -o --color %l | grep ^l',
649 # directories or links to directories,
710 # directories or links to directories,
650 'ldir ls -F -o --color %l | grep /$',
711 'ldir ls -F -o --color %l | grep /$',
651 # things which are executable
712 # things which are executable
652 'lx ls -F -o --color %l | grep ^-..x',
713 'lx ls -F -o --color %l | grep ^-..x',
653 )
714 )
654 # The BSDs don't ship GNU ls, so they don't understand the
715 # The BSDs don't ship GNU ls, so they don't understand the
655 # --color switch out of the box
716 # --color switch out of the box
656 if 'bsd' in sys.platform:
717 if 'bsd' in sys.platform:
657 ls_extra = ( # ls normal files only
718 ls_extra = ( # ls normal files only
658 'lf ls -lF | grep ^-',
719 'lf ls -lF | grep ^-',
659 # ls symbolic links
720 # ls symbolic links
660 'lk ls -lF | grep ^l',
721 'lk ls -lF | grep ^l',
661 # directories or links to directories,
722 # directories or links to directories,
662 'ldir ls -lF | grep /$',
723 'ldir ls -lF | grep /$',
663 # things which are executable
724 # things which are executable
664 'lx ls -lF | grep ^-..x',
725 'lx ls -lF | grep ^-..x',
665 )
726 )
666 auto_alias = auto_alias + ls_extra
727 auto_alias = auto_alias + ls_extra
667 elif os.name in ['nt','dos']:
728 elif os.name in ['nt','dos']:
668 auto_alias = ('ls dir /on',
729 auto_alias = ('ls dir /on',
669 'ddir dir /ad /on', 'ldir dir /ad /on',
730 'ddir dir /ad /on', 'ldir dir /ad /on',
670 'mkdir mkdir','rmdir rmdir','echo echo',
731 'mkdir mkdir','rmdir rmdir','echo echo',
671 'ren ren','cls cls','copy copy')
732 'ren ren','cls cls','copy copy')
672 else:
733 else:
673 auto_alias = ()
734 auto_alias = ()
674 self.auto_alias = [s.split(None,1) for s in auto_alias]
735 self.auto_alias = [s.split(None,1) for s in auto_alias]
675
736
676 # Load default aliases
737 # Load default aliases
677 for alias, cmd in self.auto_alias:
738 for alias, cmd in self.auto_alias:
678 self.define_alias(alias,cmd)
739 self.define_alias(alias,cmd)
679
740
680 # Load user aliases
741 # Load user aliases
681 for alias in self.alias:
742 for alias in self.alias:
682 self.magic_alias(alias)
743 self.magic_alias(alias)
683
744
684 def init_builtins(self):
745 def init_builtins(self):
685 # track which builtins we add, so we can clean up later
746 # track which builtins we add, so we can clean up later
686 self.builtins_added = {}
747 self.builtins_added = {}
687 # This method will add the necessary builtins for operation, but
748 # This method will add the necessary builtins for operation, but
688 # tracking what it did via the builtins_added dict.
749 # tracking what it did via the builtins_added dict.
689
750
690 #TODO: remove this, redundant
751 #TODO: remove this, redundant. I don't understand why this is
752 # redundant?
691 self.add_builtins()
753 self.add_builtins()
692
754
693 def init_shadow_hist(self):
755 def init_shadow_hist(self):
694 try:
756 try:
695 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
757 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
696 except exceptions.UnicodeDecodeError:
758 except exceptions.UnicodeDecodeError:
697 print "Your ipythondir can't be decoded to unicode!"
759 print "Your ipythondir can't be decoded to unicode!"
698 print "Please set HOME environment variable to something that"
760 print "Please set HOME environment variable to something that"
699 print r"only has ASCII characters, e.g. c:\home"
761 print r"only has ASCII characters, e.g. c:\home"
700 print "Now it is", self.config.IPYTHONDIR
762 print "Now it is", self.config.IPYTHONDIR
701 sys.exit()
763 sys.exit()
702 self.shadowhist = ipcorehist.ShadowHist(self.db)
764 self.shadowhist = ipcorehist.ShadowHist(self.db)
703
765
704 def post_config_initialization(self):
766 def init_inspector(self):
705 """Post configuration init method
706
707 This is called after the configuration files have been processed to
708 'finalize' the initialization."""
709
710 # Object inspector
767 # Object inspector
711 self.inspector = oinspect.Inspector(oinspect.InspectColors,
768 self.inspector = oinspect.Inspector(oinspect.InspectColors,
712 PyColorize.ANSICodeColors,
769 PyColorize.ANSICodeColors,
713 'NoColor',
770 'NoColor',
714 self.object_info_string_level)
771 self.object_info_string_level)
715
772
773 def init_readline(self):
774 """Command history completion/saving/reloading."""
775
716 self.rl_next_input = None
776 self.rl_next_input = None
717 self.rl_do_indent = False
777 self.rl_do_indent = False
718 # Load readline proper
719 if self.readline_use:
720 self.init_readline()
721
778
779 if not self.readline_use:
780 return
781
782 import IPython.utils.rlineimpl as readline
783
784 if not readline.have_readline:
785 self.has_readline = 0
786 self.readline = None
787 # no point in bugging windows users with this every time:
788 warn('Readline services not available on this platform.')
789 else:
790 sys.modules['readline'] = readline
791 import atexit
792 from IPython.core.completer import IPCompleter
793 self.Completer = IPCompleter(self,
794 self.user_ns,
795 self.user_global_ns,
796 self.readline_omit__names,
797 self.alias_table)
798 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
799 self.strdispatchers['complete_command'] = sdisp
800 self.Completer.custom_completers = sdisp
801 # Platform-specific configuration
802 if os.name == 'nt':
803 self.readline_startup_hook = readline.set_pre_input_hook
804 else:
805 self.readline_startup_hook = readline.set_startup_hook
806
807 # Load user's initrc file (readline config)
808 # Or if libedit is used, load editrc.
809 inputrc_name = os.environ.get('INPUTRC')
810 if inputrc_name is None:
811 home_dir = get_home_dir()
812 if home_dir is not None:
813 inputrc_name = '.inputrc'
814 if readline.uses_libedit:
815 inputrc_name = '.editrc'
816 inputrc_name = os.path.join(home_dir, inputrc_name)
817 if os.path.isfile(inputrc_name):
818 try:
819 readline.read_init_file(inputrc_name)
820 except:
821 warn('Problems reading readline initialization file <%s>'
822 % inputrc_name)
823
824 self.has_readline = 1
825 self.readline = readline
826 # save this in sys so embedded copies can restore it properly
827 sys.ipcompleter = self.Completer.complete
828 self.set_completer()
829
830 # Configure readline according to user's prefs
831 # This is only done if GNU readline is being used. If libedit
832 # is being used (as on Leopard) the readline config is
833 # not run as the syntax for libedit is different.
834 if not readline.uses_libedit:
835 for rlcommand in self.readline_parse_and_bind:
836 #print "loading rl:",rlcommand # dbg
837 readline.parse_and_bind(rlcommand)
838
839 # Remove some chars from the delimiters list. If we encounter
840 # unicode chars, discard them.
841 delims = readline.get_completer_delims().encode("ascii", "ignore")
842 delims = delims.translate(string._idmap,
843 self.readline_remove_delims)
844 readline.set_completer_delims(delims)
845 # otherwise we end up with a monster history after a while:
846 readline.set_history_length(1000)
847 try:
848 #print '*** Reading readline history' # dbg
849 readline.read_history_file(self.histfile)
850 except IOError:
851 pass # It doesn't exist yet.
852
853 atexit.register(self.atexit_operations)
854 del atexit
855
856 # Configure auto-indent for all platforms
857 self.set_autoindent(self.autoindent)
858
859 def init_prompts(self):
722 # Initialize cache, set in/out prompts and printing system
860 # Initialize cache, set in/out prompts and printing system
723 self.outputcache = CachedOutput(self,
861 self.outputcache = CachedOutput(self,
724 self.cache_size,
862 self.cache_size,
725 self.pprint,
863 self.pprint,
726 input_sep = self.separate_in,
864 input_sep = self.separate_in,
727 output_sep = self.separate_out,
865 output_sep = self.separate_out,
728 output_sep2 = self.separate_out2,
866 output_sep2 = self.separate_out2,
729 ps1 = self.prompt_in1,
867 ps1 = self.prompt_in1,
730 ps2 = self.prompt_in2,
868 ps2 = self.prompt_in2,
731 ps_out = self.prompt_out,
869 ps_out = self.prompt_out,
732 pad_left = self.prompts_pad_left)
870 pad_left = self.prompts_pad_left)
733
871
734 # user may have over-ridden the default print hook:
872 # user may have over-ridden the default print hook:
735 try:
873 try:
736 self.outputcache.__class__.display = self.hooks.display
874 self.outputcache.__class__.display = self.hooks.display
737 except AttributeError:
875 except AttributeError:
738 pass
876 pass
739
877
878 def init_displayhook(self):
740 # I don't like assigning globally to sys, because it means when
879 # I don't like assigning globally to sys, because it means when
741 # embedding instances, each embedded instance overrides the previous
880 # embedding instances, each embedded instance overrides the previous
742 # choice. But sys.displayhook seems to be called internally by exec,
881 # choice. But sys.displayhook seems to be called internally by exec,
743 # so I don't see a way around it. We first save the original and then
882 # so I don't see a way around it. We first save the original and then
744 # overwrite it.
883 # overwrite it.
745 self.sys_displayhook = sys.displayhook
884 self.sys_displayhook = sys.displayhook
746 sys.displayhook = self.outputcache
885 sys.displayhook = self.outputcache
747
886
887 def init_reload_doctest(self):
748 # Do a proper resetting of doctest, including the necessary displayhook
888 # Do a proper resetting of doctest, including the necessary displayhook
749 # monkeypatching
889 # monkeypatching
750 try:
890 try:
751 doctest_reload()
891 doctest_reload()
752 except ImportError:
892 except ImportError:
753 warn("doctest module does not exist.")
893 warn("doctest module does not exist.")
754
894
895 def init_magics(self):
755 # Set user colors (don't do it in the constructor above so that it
896 # Set user colors (don't do it in the constructor above so that it
756 # doesn't crash if colors option is invalid)
897 # doesn't crash if colors option is invalid)
757 self.magic_colors(self.colors)
898 self.magic_colors(self.colors)
758
899
900 def init_pdb(self):
759 # Set calling of pdb on exceptions
901 # Set calling of pdb on exceptions
902 # self.call_pdb is a property
760 self.call_pdb = self.pdb
903 self.call_pdb = self.pdb
761
904
762
905 def init_exec_commands(self):
763
764 self.hooks.late_startup_hook()
765
766 for cmd in self.autoexec:
906 for cmd in self.autoexec:
767 #print "autoexec>",cmd #dbg
907 #print "autoexec>",cmd #dbg
768 self.api.runlines(cmd)
908 self.api.runlines(cmd)
769
909
770 batchrun = False
910 batchrun = False
771 if self.config.has_key('EXECFILE'):
911 if self.config.has_key('EXECFILE'):
772 for batchfile in [path(arg) for arg in self.config.EXECFILE
912 for batchfile in [path(arg) for arg in self.config.EXECFILE
773 if arg.lower().endswith('.ipy')]:
913 if arg.lower().endswith('.ipy')]:
774 if not batchfile.isfile():
914 if not batchfile.isfile():
775 print "No such batch file:", batchfile
915 print "No such batch file:", batchfile
776 continue
916 continue
777 self.api.runlines(batchfile.text())
917 self.api.runlines(batchfile.text())
778 batchrun = True
918 batchrun = True
779 # without -i option, exit after running the batch file
919 # without -i option, exit after running the batch file
780 if batchrun and not self.interactive:
920 if batchrun and not self.interactive:
781 self.ask_exit()
921 self.ask_exit()
782
922
783 def init_namespaces(self):
923 def init_namespaces(self):
784 """Initialize all user-visible namespaces to their minimum defaults.
924 """Initialize all user-visible namespaces to their minimum defaults.
785
925
786 Certain history lists are also initialized here, as they effectively
926 Certain history lists are also initialized here, as they effectively
787 act as user namespaces.
927 act as user namespaces.
788
928
789 Notes
929 Notes
790 -----
930 -----
791 All data structures here are only filled in, they are NOT reset by this
931 All data structures here are only filled in, they are NOT reset by this
792 method. If they were not empty before, data will simply be added to
932 method. If they were not empty before, data will simply be added to
793 therm.
933 therm.
794 """
934 """
795 # The user namespace MUST have a pointer to the shell itself.
935 # The user namespace MUST have a pointer to the shell itself.
796 self.user_ns[self.name] = self
936 self.user_ns[self.name] = self
797
937
798 # Store the public api instance
938 # Store the public api instance
799 self.user_ns['_ip'] = self.api
939 self.user_ns['_ip'] = self.api
800
940
801 # make global variables for user access to the histories
941 # make global variables for user access to the histories
802 self.user_ns['_ih'] = self.input_hist
942 self.user_ns['_ih'] = self.input_hist
803 self.user_ns['_oh'] = self.output_hist
943 self.user_ns['_oh'] = self.output_hist
804 self.user_ns['_dh'] = self.dir_hist
944 self.user_ns['_dh'] = self.dir_hist
805
945
806 # user aliases to input and output histories
946 # user aliases to input and output histories
807 self.user_ns['In'] = self.input_hist
947 self.user_ns['In'] = self.input_hist
808 self.user_ns['Out'] = self.output_hist
948 self.user_ns['Out'] = self.output_hist
809
949
810 self.user_ns['_sh'] = shadowns
950 self.user_ns['_sh'] = shadowns
811
951
812 # Fill the history zero entry, user counter starts at 1
952 # Put 'help' in the user namespace
813 self.input_hist.append('\n')
953 try:
814 self.input_hist_raw.append('\n')
954 from site import _Helper
955 self.user_ns['help'] = _Helper()
956 except ImportError:
957 warn('help() not available - check site.py')
815
958
816 def add_builtins(self):
959 def add_builtins(self):
817 """Store ipython references into the builtin namespace.
960 """Store ipython references into the builtin namespace.
818
961
819 Some parts of ipython operate via builtins injected here, which hold a
962 Some parts of ipython operate via builtins injected here, which hold a
820 reference to IPython itself."""
963 reference to IPython itself."""
821
964
822 # Install our own quitter instead of the builtins.
965 # Install our own quitter instead of the builtins.
823 # This used to be in the __init__ method, but this is a better
966 # This used to be in the __init__ method, but this is a better
824 # place for it. These can be incorporated to the logic below
967 # place for it. These can be incorporated to the logic below
825 # when it is refactored.
968 # when it is refactored.
826 __builtin__.exit = Quitter(self,'exit')
969 __builtin__.exit = Quitter(self,'exit')
827 __builtin__.quit = Quitter(self,'quit')
970 __builtin__.quit = Quitter(self,'quit')
971
972 # Recursive reload
973 try:
974 from IPython.lib import deepreload
975 if self.deep_reload:
976 __builtin__.reload = deepreload.reload
977 else:
978 __builtin__.dreload = deepreload.reload
979 del deepreload
980 except ImportError:
981 pass
828
982
829 # TODO: deprecate all of these, they are unsafe. Why though?
983 # TODO: deprecate all of these, they are unsafe. Why though?
830 builtins_new = dict(__IPYTHON__ = self,
984 builtins_new = dict(__IPYTHON__ = self,
831 ip_set_hook = self.set_hook,
985 ip_set_hook = self.set_hook,
832 jobs = self.jobs,
986 jobs = self.jobs,
833 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
987 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
834 ipalias = wrap_deprecated(self.ipalias),
988 ipalias = wrap_deprecated(self.ipalias),
835 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
989 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
836 #_ip = self.api
990 #_ip = self.api
837 )
991 )
838 for biname,bival in builtins_new.items():
992 for biname,bival in builtins_new.items():
839 try:
993 try:
840 # store the orignal value so we can restore it
994 # store the orignal value so we can restore it
841 self.builtins_added[biname] = __builtin__.__dict__[biname]
995 self.builtins_added[biname] = __builtin__.__dict__[biname]
842 except KeyError:
996 except KeyError:
843 # or mark that it wasn't defined, and we'll just delete it at
997 # or mark that it wasn't defined, and we'll just delete it at
844 # cleanup
998 # cleanup
845 self.builtins_added[biname] = Undefined
999 self.builtins_added[biname] = Undefined
846 __builtin__.__dict__[biname] = bival
1000 __builtin__.__dict__[biname] = bival
847
1001
848 # Keep in the builtins a flag for when IPython is active. We set it
1002 # Keep in the builtins a flag for when IPython is active. We set it
849 # with setdefault so that multiple nested IPythons don't clobber one
1003 # with setdefault so that multiple nested IPythons don't clobber one
850 # another. Each will increase its value by one upon being activated,
1004 # another. Each will increase its value by one upon being activated,
851 # which also gives us a way to determine the nesting level.
1005 # which also gives us a way to determine the nesting level.
852 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1006 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
853
1007
854 def clean_builtins(self):
1008 def clean_builtins(self):
855 """Remove any builtins which might have been added by add_builtins, or
1009 """Remove any builtins which might have been added by add_builtins, or
856 restore overwritten ones to their previous values."""
1010 restore overwritten ones to their previous values."""
857 for biname,bival in self.builtins_added.items():
1011 for biname,bival in self.builtins_added.items():
858 if bival is Undefined:
1012 if bival is Undefined:
859 del __builtin__.__dict__[biname]
1013 del __builtin__.__dict__[biname]
860 else:
1014 else:
861 __builtin__.__dict__[biname] = bival
1015 __builtin__.__dict__[biname] = bival
862 self.builtins_added.clear()
1016 self.builtins_added.clear()
863
1017
864 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1018 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
865 """set_hook(name,hook) -> sets an internal IPython hook.
1019 """set_hook(name,hook) -> sets an internal IPython hook.
866
1020
867 IPython exposes some of its internal API as user-modifiable hooks. By
1021 IPython exposes some of its internal API as user-modifiable hooks. By
868 adding your function to one of these hooks, you can modify IPython's
1022 adding your function to one of these hooks, you can modify IPython's
869 behavior to call at runtime your own routines."""
1023 behavior to call at runtime your own routines."""
870
1024
871 # At some point in the future, this should validate the hook before it
1025 # At some point in the future, this should validate the hook before it
872 # accepts it. Probably at least check that the hook takes the number
1026 # accepts it. Probably at least check that the hook takes the number
873 # of args it's supposed to.
1027 # of args it's supposed to.
874
1028
875 f = new.instancemethod(hook,self,self.__class__)
1029 f = new.instancemethod(hook,self,self.__class__)
876
1030
877 # check if the hook is for strdispatcher first
1031 # check if the hook is for strdispatcher first
878 if str_key is not None:
1032 if str_key is not None:
879 sdp = self.strdispatchers.get(name, StrDispatch())
1033 sdp = self.strdispatchers.get(name, StrDispatch())
880 sdp.add_s(str_key, f, priority )
1034 sdp.add_s(str_key, f, priority )
881 self.strdispatchers[name] = sdp
1035 self.strdispatchers[name] = sdp
882 return
1036 return
883 if re_key is not None:
1037 if re_key is not None:
884 sdp = self.strdispatchers.get(name, StrDispatch())
1038 sdp = self.strdispatchers.get(name, StrDispatch())
885 sdp.add_re(re.compile(re_key), f, priority )
1039 sdp.add_re(re.compile(re_key), f, priority )
886 self.strdispatchers[name] = sdp
1040 self.strdispatchers[name] = sdp
887 return
1041 return
888
1042
889 dp = getattr(self.hooks, name, None)
1043 dp = getattr(self.hooks, name, None)
890 if name not in IPython.core.hooks.__all__:
1044 if name not in IPython.core.hooks.__all__:
891 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1045 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
892 if not dp:
1046 if not dp:
893 dp = IPython.core.hooks.CommandChainDispatcher()
1047 dp = IPython.core.hooks.CommandChainDispatcher()
894
1048
895 try:
1049 try:
896 dp.add(f,priority)
1050 dp.add(f,priority)
897 except AttributeError:
1051 except AttributeError:
898 # it was not commandchain, plain old func - replace
1052 # it was not commandchain, plain old func - replace
899 dp = f
1053 dp = f
900
1054
901 setattr(self.hooks,name, dp)
1055 setattr(self.hooks,name, dp)
902
1056
903
1057
904 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1058 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
905
1059
906 def set_crash_handler(self,crashHandler):
1060 def set_crash_handler(self,crashHandler):
907 """Set the IPython crash handler.
1061 """Set the IPython crash handler.
908
1062
909 This must be a callable with a signature suitable for use as
1063 This must be a callable with a signature suitable for use as
910 sys.excepthook."""
1064 sys.excepthook."""
911
1065
912 # Install the given crash handler as the Python exception hook
1066 # Install the given crash handler as the Python exception hook
913 sys.excepthook = crashHandler
1067 sys.excepthook = crashHandler
914
1068
915 # The instance will store a pointer to this, so that runtime code
1069 # The instance will store a pointer to this, so that runtime code
916 # (such as magics) can access it. This is because during the
1070 # (such as magics) can access it. This is because during the
917 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1071 # read-eval loop, it gets temporarily overwritten (to deal with GUI
918 # frameworks).
1072 # frameworks).
919 self.sys_excepthook = sys.excepthook
1073 self.sys_excepthook = sys.excepthook
920
1074
921
1075
922 def set_custom_exc(self,exc_tuple,handler):
1076 def set_custom_exc(self,exc_tuple,handler):
923 """set_custom_exc(exc_tuple,handler)
1077 """set_custom_exc(exc_tuple,handler)
924
1078
925 Set a custom exception handler, which will be called if any of the
1079 Set a custom exception handler, which will be called if any of the
926 exceptions in exc_tuple occur in the mainloop (specifically, in the
1080 exceptions in exc_tuple occur in the mainloop (specifically, in the
927 runcode() method.
1081 runcode() method.
928
1082
929 Inputs:
1083 Inputs:
930
1084
931 - exc_tuple: a *tuple* of valid exceptions to call the defined
1085 - exc_tuple: a *tuple* of valid exceptions to call the defined
932 handler for. It is very important that you use a tuple, and NOT A
1086 handler for. It is very important that you use a tuple, and NOT A
933 LIST here, because of the way Python's except statement works. If
1087 LIST here, because of the way Python's except statement works. If
934 you only want to trap a single exception, use a singleton tuple:
1088 you only want to trap a single exception, use a singleton tuple:
935
1089
936 exc_tuple == (MyCustomException,)
1090 exc_tuple == (MyCustomException,)
937
1091
938 - handler: this must be defined as a function with the following
1092 - handler: this must be defined as a function with the following
939 basic interface: def my_handler(self,etype,value,tb).
1093 basic interface: def my_handler(self,etype,value,tb).
940
1094
941 This will be made into an instance method (via new.instancemethod)
1095 This will be made into an instance method (via new.instancemethod)
942 of IPython itself, and it will be called if any of the exceptions
1096 of IPython itself, and it will be called if any of the exceptions
943 listed in the exc_tuple are caught. If the handler is None, an
1097 listed in the exc_tuple are caught. If the handler is None, an
944 internal basic one is used, which just prints basic info.
1098 internal basic one is used, which just prints basic info.
945
1099
946 WARNING: by putting in your own exception handler into IPython's main
1100 WARNING: by putting in your own exception handler into IPython's main
947 execution loop, you run a very good chance of nasty crashes. This
1101 execution loop, you run a very good chance of nasty crashes. This
948 facility should only be used if you really know what you are doing."""
1102 facility should only be used if you really know what you are doing."""
949
1103
950 assert type(exc_tuple)==type(()) , \
1104 assert type(exc_tuple)==type(()) , \
951 "The custom exceptions must be given AS A TUPLE."
1105 "The custom exceptions must be given AS A TUPLE."
952
1106
953 def dummy_handler(self,etype,value,tb):
1107 def dummy_handler(self,etype,value,tb):
954 print '*** Simple custom exception handler ***'
1108 print '*** Simple custom exception handler ***'
955 print 'Exception type :',etype
1109 print 'Exception type :',etype
956 print 'Exception value:',value
1110 print 'Exception value:',value
957 print 'Traceback :',tb
1111 print 'Traceback :',tb
958 print 'Source code :','\n'.join(self.buffer)
1112 print 'Source code :','\n'.join(self.buffer)
959
1113
960 if handler is None: handler = dummy_handler
1114 if handler is None: handler = dummy_handler
961
1115
962 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1116 self.CustomTB = new.instancemethod(handler,self,self.__class__)
963 self.custom_exceptions = exc_tuple
1117 self.custom_exceptions = exc_tuple
964
1118
965 def set_custom_completer(self,completer,pos=0):
1119 def set_custom_completer(self,completer,pos=0):
966 """set_custom_completer(completer,pos=0)
1120 """set_custom_completer(completer,pos=0)
967
1121
968 Adds a new custom completer function.
1122 Adds a new custom completer function.
969
1123
970 The position argument (defaults to 0) is the index in the completers
1124 The position argument (defaults to 0) is the index in the completers
971 list where you want the completer to be inserted."""
1125 list where you want the completer to be inserted."""
972
1126
973 newcomp = new.instancemethod(completer,self.Completer,
1127 newcomp = new.instancemethod(completer,self.Completer,
974 self.Completer.__class__)
1128 self.Completer.__class__)
975 self.Completer.matchers.insert(pos,newcomp)
1129 self.Completer.matchers.insert(pos,newcomp)
976
1130
977 def set_completer(self):
1131 def set_completer(self):
978 """reset readline's completer to be our own."""
1132 """reset readline's completer to be our own."""
979 self.readline.set_completer(self.Completer.complete)
1133 self.readline.set_completer(self.Completer.complete)
980
1134
981 def _get_call_pdb(self):
1135 def _get_call_pdb(self):
982 return self._call_pdb
1136 return self._call_pdb
983
1137
984 def _set_call_pdb(self,val):
1138 def _set_call_pdb(self,val):
985
1139
986 if val not in (0,1,False,True):
1140 if val not in (0,1,False,True):
987 raise ValueError,'new call_pdb value must be boolean'
1141 raise ValueError,'new call_pdb value must be boolean'
988
1142
989 # store value in instance
1143 # store value in instance
990 self._call_pdb = val
1144 self._call_pdb = val
991
1145
992 # notify the actual exception handlers
1146 # notify the actual exception handlers
993 self.InteractiveTB.call_pdb = val
1147 self.InteractiveTB.call_pdb = val
994 if self.isthreaded:
1148 if self.isthreaded:
995 try:
1149 try:
996 self.sys_excepthook.call_pdb = val
1150 self.sys_excepthook.call_pdb = val
997 except:
1151 except:
998 warn('Failed to activate pdb for threaded exception handler')
1152 warn('Failed to activate pdb for threaded exception handler')
999
1153
1000 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1154 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1001 'Control auto-activation of pdb at exceptions')
1155 'Control auto-activation of pdb at exceptions')
1002
1156
1003 # These special functions get installed in the builtin namespace, to
1157 # These special functions get installed in the builtin namespace, to
1004 # provide programmatic (pure python) access to magics, aliases and system
1158 # provide programmatic (pure python) access to magics, aliases and system
1005 # calls. This is important for logging, user scripting, and more.
1159 # calls. This is important for logging, user scripting, and more.
1006
1160
1007 # We are basically exposing, via normal python functions, the three
1161 # We are basically exposing, via normal python functions, the three
1008 # mechanisms in which ipython offers special call modes (magics for
1162 # mechanisms in which ipython offers special call modes (magics for
1009 # internal control, aliases for direct system access via pre-selected
1163 # internal control, aliases for direct system access via pre-selected
1010 # names, and !cmd for calling arbitrary system commands).
1164 # names, and !cmd for calling arbitrary system commands).
1011
1165
1012 def ipmagic(self,arg_s):
1166 def ipmagic(self,arg_s):
1013 """Call a magic function by name.
1167 """Call a magic function by name.
1014
1168
1015 Input: a string containing the name of the magic function to call and any
1169 Input: a string containing the name of the magic function to call and any
1016 additional arguments to be passed to the magic.
1170 additional arguments to be passed to the magic.
1017
1171
1018 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1172 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1019 prompt:
1173 prompt:
1020
1174
1021 In[1]: %name -opt foo bar
1175 In[1]: %name -opt foo bar
1022
1176
1023 To call a magic without arguments, simply use ipmagic('name').
1177 To call a magic without arguments, simply use ipmagic('name').
1024
1178
1025 This provides a proper Python function to call IPython's magics in any
1179 This provides a proper Python function to call IPython's magics in any
1026 valid Python code you can type at the interpreter, including loops and
1180 valid Python code you can type at the interpreter, including loops and
1027 compound statements. It is added by IPython to the Python builtin
1181 compound statements. It is added by IPython to the Python builtin
1028 namespace upon initialization."""
1182 namespace upon initialization."""
1029
1183
1030 args = arg_s.split(' ',1)
1184 args = arg_s.split(' ',1)
1031 magic_name = args[0]
1185 magic_name = args[0]
1032 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1186 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1033
1187
1034 try:
1188 try:
1035 magic_args = args[1]
1189 magic_args = args[1]
1036 except IndexError:
1190 except IndexError:
1037 magic_args = ''
1191 magic_args = ''
1038 fn = getattr(self,'magic_'+magic_name,None)
1192 fn = getattr(self,'magic_'+magic_name,None)
1039 if fn is None:
1193 if fn is None:
1040 error("Magic function `%s` not found." % magic_name)
1194 error("Magic function `%s` not found." % magic_name)
1041 else:
1195 else:
1042 magic_args = self.var_expand(magic_args,1)
1196 magic_args = self.var_expand(magic_args,1)
1043 return fn(magic_args)
1197 return fn(magic_args)
1044
1198
1045 def define_alias(self, name, cmd):
1199 def define_alias(self, name, cmd):
1046 """ Define a new alias."""
1200 """ Define a new alias."""
1047
1201
1048 if callable(cmd):
1202 if callable(cmd):
1049 self.alias_table[name] = cmd
1203 self.alias_table[name] = cmd
1050 from IPython.core import shadowns
1204 from IPython.core import shadowns
1051 setattr(shadowns, name, cmd)
1205 setattr(shadowns, name, cmd)
1052 return
1206 return
1053
1207
1054 if isinstance(cmd, basestring):
1208 if isinstance(cmd, basestring):
1055 nargs = cmd.count('%s')
1209 nargs = cmd.count('%s')
1056 if nargs>0 and cmd.find('%l')>=0:
1210 if nargs>0 and cmd.find('%l')>=0:
1057 raise Exception('The %s and %l specifiers are mutually '
1211 raise Exception('The %s and %l specifiers are mutually '
1058 'exclusive in alias definitions.')
1212 'exclusive in alias definitions.')
1059
1213
1060 self.alias_table[name] = (nargs,cmd)
1214 self.alias_table[name] = (nargs,cmd)
1061 return
1215 return
1062
1216
1063 self.alias_table[name] = cmd
1217 self.alias_table[name] = cmd
1064
1218
1065 def ipalias(self,arg_s):
1219 def ipalias(self,arg_s):
1066 """Call an alias by name.
1220 """Call an alias by name.
1067
1221
1068 Input: a string containing the name of the alias to call and any
1222 Input: a string containing the name of the alias to call and any
1069 additional arguments to be passed to the magic.
1223 additional arguments to be passed to the magic.
1070
1224
1071 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1225 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1072 prompt:
1226 prompt:
1073
1227
1074 In[1]: name -opt foo bar
1228 In[1]: name -opt foo bar
1075
1229
1076 To call an alias without arguments, simply use ipalias('name').
1230 To call an alias without arguments, simply use ipalias('name').
1077
1231
1078 This provides a proper Python function to call IPython's aliases in any
1232 This provides a proper Python function to call IPython's aliases in any
1079 valid Python code you can type at the interpreter, including loops and
1233 valid Python code you can type at the interpreter, including loops and
1080 compound statements. It is added by IPython to the Python builtin
1234 compound statements. It is added by IPython to the Python builtin
1081 namespace upon initialization."""
1235 namespace upon initialization."""
1082
1236
1083 args = arg_s.split(' ',1)
1237 args = arg_s.split(' ',1)
1084 alias_name = args[0]
1238 alias_name = args[0]
1085 try:
1239 try:
1086 alias_args = args[1]
1240 alias_args = args[1]
1087 except IndexError:
1241 except IndexError:
1088 alias_args = ''
1242 alias_args = ''
1089 if alias_name in self.alias_table:
1243 if alias_name in self.alias_table:
1090 self.call_alias(alias_name,alias_args)
1244 self.call_alias(alias_name,alias_args)
1091 else:
1245 else:
1092 error("Alias `%s` not found." % alias_name)
1246 error("Alias `%s` not found." % alias_name)
1093
1247
1094 def system(self, cmd):
1248 def system(self, cmd):
1095 """Make a system call, using IPython."""
1249 """Make a system call, using IPython."""
1096 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1250 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1097
1251
1098 ipsystem = system
1252 ipsystem = system
1099
1253
1100 def getoutput(self, cmd):
1254 def getoutput(self, cmd):
1101 return getoutput(self.var_expand(cmd,depth=2),
1255 return getoutput(self.var_expand(cmd,depth=2),
1102 header=self.system_header,
1256 header=self.system_header,
1103 verbose=self.system_verbose)
1257 verbose=self.system_verbose)
1104
1258
1105 def getoutputerror(self, cmd):
1259 def getoutputerror(self, cmd):
1106 return getoutputerror(self.var_expand(cmd,depth=2),
1260 return getoutputerror(self.var_expand(cmd,depth=2),
1107 header=self.system_header,
1261 header=self.system_header,
1108 verbose=self.system_verbose)
1262 verbose=self.system_verbose)
1109
1263
1110 def complete(self,text):
1264 def complete(self,text):
1111 """Return a sorted list of all possible completions on text.
1265 """Return a sorted list of all possible completions on text.
1112
1266
1113 Inputs:
1267 Inputs:
1114
1268
1115 - text: a string of text to be completed on.
1269 - text: a string of text to be completed on.
1116
1270
1117 This is a wrapper around the completion mechanism, similar to what
1271 This is a wrapper around the completion mechanism, similar to what
1118 readline does at the command line when the TAB key is hit. By
1272 readline does at the command line when the TAB key is hit. By
1119 exposing it as a method, it can be used by other non-readline
1273 exposing it as a method, it can be used by other non-readline
1120 environments (such as GUIs) for text completion.
1274 environments (such as GUIs) for text completion.
1121
1275
1122 Simple usage example:
1276 Simple usage example:
1123
1277
1124 In [7]: x = 'hello'
1278 In [7]: x = 'hello'
1125
1279
1126 In [8]: x
1280 In [8]: x
1127 Out[8]: 'hello'
1281 Out[8]: 'hello'
1128
1282
1129 In [9]: print x
1283 In [9]: print x
1130 hello
1284 hello
1131
1285
1132 In [10]: _ip.IP.complete('x.l')
1286 In [10]: _ip.IP.complete('x.l')
1133 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1287 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1134 """
1288 """
1135
1289
1136 complete = self.Completer.complete
1290 complete = self.Completer.complete
1137 state = 0
1291 state = 0
1138 # use a dict so we get unique keys, since ipyhton's multiple
1292 # use a dict so we get unique keys, since ipyhton's multiple
1139 # completers can return duplicates. When we make 2.4 a requirement,
1293 # completers can return duplicates. When we make 2.4 a requirement,
1140 # start using sets instead, which are faster.
1294 # start using sets instead, which are faster.
1141 comps = {}
1295 comps = {}
1142 while True:
1296 while True:
1143 newcomp = complete(text,state,line_buffer=text)
1297 newcomp = complete(text,state,line_buffer=text)
1144 if newcomp is None:
1298 if newcomp is None:
1145 break
1299 break
1146 comps[newcomp] = 1
1300 comps[newcomp] = 1
1147 state += 1
1301 state += 1
1148 outcomps = comps.keys()
1302 outcomps = comps.keys()
1149 outcomps.sort()
1303 outcomps.sort()
1150 #print "T:",text,"OC:",outcomps # dbg
1304 #print "T:",text,"OC:",outcomps # dbg
1151 #print "vars:",self.user_ns.keys()
1305 #print "vars:",self.user_ns.keys()
1152 return outcomps
1306 return outcomps
1153
1307
1154 def set_completer_frame(self, frame=None):
1308 def set_completer_frame(self, frame=None):
1155 if frame:
1309 if frame:
1156 self.Completer.namespace = frame.f_locals
1310 self.Completer.namespace = frame.f_locals
1157 self.Completer.global_namespace = frame.f_globals
1311 self.Completer.global_namespace = frame.f_globals
1158 else:
1312 else:
1159 self.Completer.namespace = self.user_ns
1313 self.Completer.namespace = self.user_ns
1160 self.Completer.global_namespace = self.user_global_ns
1314 self.Completer.global_namespace = self.user_global_ns
1161
1315
1162 def init_auto_alias(self):
1316 def init_auto_alias(self):
1163 """Define some aliases automatically.
1317 """Define some aliases automatically.
1164
1318
1165 These are ALL parameter-less aliases"""
1319 These are ALL parameter-less aliases"""
1166
1320
1167 for alias,cmd in self.auto_alias:
1321 for alias,cmd in self.auto_alias:
1168 self.getapi().defalias(alias,cmd)
1322 self.getapi().defalias(alias,cmd)
1169
1323
1170
1324
1171 def alias_table_validate(self,verbose=0):
1325 def alias_table_validate(self,verbose=0):
1172 """Update information about the alias table.
1326 """Update information about the alias table.
1173
1327
1174 In particular, make sure no Python keywords/builtins are in it."""
1328 In particular, make sure no Python keywords/builtins are in it."""
1175
1329
1176 no_alias = self.no_alias
1330 no_alias = self.no_alias
1177 for k in self.alias_table.keys():
1331 for k in self.alias_table.keys():
1178 if k in no_alias:
1332 if k in no_alias:
1179 del self.alias_table[k]
1333 del self.alias_table[k]
1180 if verbose:
1334 if verbose:
1181 print ("Deleting alias <%s>, it's a Python "
1335 print ("Deleting alias <%s>, it's a Python "
1182 "keyword or builtin." % k)
1336 "keyword or builtin." % k)
1183
1337
1184 def set_autoindent(self,value=None):
1338 def set_autoindent(self,value=None):
1185 """Set the autoindent flag, checking for readline support.
1339 """Set the autoindent flag, checking for readline support.
1186
1340
1187 If called with no arguments, it acts as a toggle."""
1341 If called with no arguments, it acts as a toggle."""
1188
1342
1189 if not self.has_readline:
1343 if not self.has_readline:
1190 if os.name == 'posix':
1344 if os.name == 'posix':
1191 warn("The auto-indent feature requires the readline library")
1345 warn("The auto-indent feature requires the readline library")
1192 self.autoindent = 0
1346 self.autoindent = 0
1193 return
1347 return
1194 if value is None:
1348 if value is None:
1195 self.autoindent = not self.autoindent
1349 self.autoindent = not self.autoindent
1196 else:
1350 else:
1197 self.autoindent = value
1351 self.autoindent = value
1198
1352
1199 def atexit_operations(self):
1353 def atexit_operations(self):
1200 """This will be executed at the time of exit.
1354 """This will be executed at the time of exit.
1201
1355
1202 Saving of persistent data should be performed here. """
1356 Saving of persistent data should be performed here. """
1203
1357
1204 #print '*** IPython exit cleanup ***' # dbg
1358 #print '*** IPython exit cleanup ***' # dbg
1205 # input history
1359 # input history
1206 self.savehist()
1360 self.savehist()
1207
1361
1208 # Cleanup all tempfiles left around
1362 # Cleanup all tempfiles left around
1209 for tfile in self.tempfiles:
1363 for tfile in self.tempfiles:
1210 try:
1364 try:
1211 os.unlink(tfile)
1365 os.unlink(tfile)
1212 except OSError:
1366 except OSError:
1213 pass
1367 pass
1214
1368
1215 # Clear all user namespaces to release all references cleanly.
1369 # Clear all user namespaces to release all references cleanly.
1216 self.reset()
1370 self.reset()
1217
1371
1218 # Run user hooks
1372 # Run user hooks
1219 self.hooks.shutdown_hook()
1373 self.hooks.shutdown_hook()
1220
1374
1221 def reset(self):
1375 def reset(self):
1222 """Clear all internal namespaces.
1376 """Clear all internal namespaces.
1223
1377
1224 Note that this is much more aggressive than %reset, since it clears
1378 Note that this is much more aggressive than %reset, since it clears
1225 fully all namespaces, as well as all input/output lists.
1379 fully all namespaces, as well as all input/output lists.
1226 """
1380 """
1227 for ns in self.ns_refs_table:
1381 for ns in self.ns_refs_table:
1228 ns.clear()
1382 ns.clear()
1229
1383
1230 # Clear input and output histories
1384 # Clear input and output histories
1231 self.input_hist[:] = []
1385 self.input_hist[:] = []
1232 self.input_hist_raw[:] = []
1386 self.input_hist_raw[:] = []
1233 self.output_hist.clear()
1387 self.output_hist.clear()
1234 # Restore the user namespaces to minimal usability
1388 # Restore the user namespaces to minimal usability
1235 self.init_namespaces()
1389 self.init_namespaces()
1236
1390
1237 def savehist(self):
1391 def savehist(self):
1238 """Save input history to a file (via readline library)."""
1392 """Save input history to a file (via readline library)."""
1239
1393
1240 if not self.has_readline:
1394 if not self.has_readline:
1241 return
1395 return
1242
1396
1243 try:
1397 try:
1244 self.readline.write_history_file(self.histfile)
1398 self.readline.write_history_file(self.histfile)
1245 except:
1399 except:
1246 print 'Unable to save IPython command history to file: ' + \
1400 print 'Unable to save IPython command history to file: ' + \
1247 `self.histfile`
1401 `self.histfile`
1248
1402
1249 def reloadhist(self):
1403 def reloadhist(self):
1250 """Reload the input history from disk file."""
1404 """Reload the input history from disk file."""
1251
1405
1252 if self.has_readline:
1406 if self.has_readline:
1253 try:
1407 try:
1254 self.readline.clear_history()
1408 self.readline.clear_history()
1255 self.readline.read_history_file(self.shell.histfile)
1409 self.readline.read_history_file(self.shell.histfile)
1256 except AttributeError:
1410 except AttributeError:
1257 pass
1411 pass
1258
1412
1259
1413
1260 def history_saving_wrapper(self, func):
1414 def history_saving_wrapper(self, func):
1261 """ Wrap func for readline history saving
1415 """ Wrap func for readline history saving
1262
1416
1263 Convert func into callable that saves & restores
1417 Convert func into callable that saves & restores
1264 history around the call """
1418 history around the call """
1265
1419
1266 if not self.has_readline:
1420 if not self.has_readline:
1267 return func
1421 return func
1268
1422
1269 def wrapper():
1423 def wrapper():
1270 self.savehist()
1424 self.savehist()
1271 try:
1425 try:
1272 func()
1426 func()
1273 finally:
1427 finally:
1274 readline.read_history_file(self.histfile)
1428 readline.read_history_file(self.histfile)
1275 return wrapper
1429 return wrapper
1276
1430
1277 def pre_readline(self):
1431 def pre_readline(self):
1278 """readline hook to be used at the start of each line.
1432 """readline hook to be used at the start of each line.
1279
1433
1280 Currently it handles auto-indent only."""
1434 Currently it handles auto-indent only."""
1281
1435
1282 #debugx('self.indent_current_nsp','pre_readline:')
1436 #debugx('self.indent_current_nsp','pre_readline:')
1283
1437
1284 if self.rl_do_indent:
1438 if self.rl_do_indent:
1285 self.readline.insert_text(self.indent_current_str())
1439 self.readline.insert_text(self.indent_current_str())
1286 if self.rl_next_input is not None:
1440 if self.rl_next_input is not None:
1287 self.readline.insert_text(self.rl_next_input)
1441 self.readline.insert_text(self.rl_next_input)
1288 self.rl_next_input = None
1442 self.rl_next_input = None
1289
1443
1290 def init_readline(self):
1291 """Command history completion/saving/reloading."""
1292
1293
1294 import IPython.utils.rlineimpl as readline
1295
1296 if not readline.have_readline:
1297 self.has_readline = 0
1298 self.readline = None
1299 # no point in bugging windows users with this every time:
1300 warn('Readline services not available on this platform.')
1301 else:
1302 sys.modules['readline'] = readline
1303 import atexit
1304 from IPython.core.completer import IPCompleter
1305 self.Completer = IPCompleter(self,
1306 self.user_ns,
1307 self.user_global_ns,
1308 self.readline_omit__names,
1309 self.alias_table)
1310 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1311 self.strdispatchers['complete_command'] = sdisp
1312 self.Completer.custom_completers = sdisp
1313 # Platform-specific configuration
1314 if os.name == 'nt':
1315 self.readline_startup_hook = readline.set_pre_input_hook
1316 else:
1317 self.readline_startup_hook = readline.set_startup_hook
1318
1319 # Load user's initrc file (readline config)
1320 # Or if libedit is used, load editrc.
1321 inputrc_name = os.environ.get('INPUTRC')
1322 if inputrc_name is None:
1323 home_dir = get_home_dir()
1324 if home_dir is not None:
1325 inputrc_name = '.inputrc'
1326 if readline.uses_libedit:
1327 inputrc_name = '.editrc'
1328 inputrc_name = os.path.join(home_dir, inputrc_name)
1329 if os.path.isfile(inputrc_name):
1330 try:
1331 readline.read_init_file(inputrc_name)
1332 except:
1333 warn('Problems reading readline initialization file <%s>'
1334 % inputrc_name)
1335
1336 self.has_readline = 1
1337 self.readline = readline
1338 # save this in sys so embedded copies can restore it properly
1339 sys.ipcompleter = self.Completer.complete
1340 self.set_completer()
1341
1342 # Configure readline according to user's prefs
1343 # This is only done if GNU readline is being used. If libedit
1344 # is being used (as on Leopard) the readline config is
1345 # not run as the syntax for libedit is different.
1346 if not readline.uses_libedit:
1347 for rlcommand in self.readline_parse_and_bind:
1348 #print "loading rl:",rlcommand # dbg
1349 readline.parse_and_bind(rlcommand)
1350
1351 # Remove some chars from the delimiters list. If we encounter
1352 # unicode chars, discard them.
1353 delims = readline.get_completer_delims().encode("ascii", "ignore")
1354 delims = delims.translate(string._idmap,
1355 self.readline_remove_delims)
1356 readline.set_completer_delims(delims)
1357 # otherwise we end up with a monster history after a while:
1358 readline.set_history_length(1000)
1359 try:
1360 #print '*** Reading readline history' # dbg
1361 readline.read_history_file(self.histfile)
1362 except IOError:
1363 pass # It doesn't exist yet.
1364
1365 atexit.register(self.atexit_operations)
1366 del atexit
1367
1368 # Configure auto-indent for all platforms
1369 self.set_autoindent(self.autoindent)
1370
1371 def ask_yes_no(self,prompt,default=True):
1444 def ask_yes_no(self,prompt,default=True):
1372 if self.quiet:
1445 if self.quiet:
1373 return True
1446 return True
1374 return ask_yes_no(prompt,default)
1447 return ask_yes_no(prompt,default)
1375
1448
1376 def new_main_mod(self,ns=None):
1449 def new_main_mod(self,ns=None):
1377 """Return a new 'main' module object for user code execution.
1450 """Return a new 'main' module object for user code execution.
1378 """
1451 """
1379 main_mod = self._user_main_module
1452 main_mod = self._user_main_module
1380 init_fakemod_dict(main_mod,ns)
1453 init_fakemod_dict(main_mod,ns)
1381 return main_mod
1454 return main_mod
1382
1455
1383 def cache_main_mod(self,ns,fname):
1456 def cache_main_mod(self,ns,fname):
1384 """Cache a main module's namespace.
1457 """Cache a main module's namespace.
1385
1458
1386 When scripts are executed via %run, we must keep a reference to the
1459 When scripts are executed via %run, we must keep a reference to the
1387 namespace of their __main__ module (a FakeModule instance) around so
1460 namespace of their __main__ module (a FakeModule instance) around so
1388 that Python doesn't clear it, rendering objects defined therein
1461 that Python doesn't clear it, rendering objects defined therein
1389 useless.
1462 useless.
1390
1463
1391 This method keeps said reference in a private dict, keyed by the
1464 This method keeps said reference in a private dict, keyed by the
1392 absolute path of the module object (which corresponds to the script
1465 absolute path of the module object (which corresponds to the script
1393 path). This way, for multiple executions of the same script we only
1466 path). This way, for multiple executions of the same script we only
1394 keep one copy of the namespace (the last one), thus preventing memory
1467 keep one copy of the namespace (the last one), thus preventing memory
1395 leaks from old references while allowing the objects from the last
1468 leaks from old references while allowing the objects from the last
1396 execution to be accessible.
1469 execution to be accessible.
1397
1470
1398 Note: we can not allow the actual FakeModule instances to be deleted,
1471 Note: we can not allow the actual FakeModule instances to be deleted,
1399 because of how Python tears down modules (it hard-sets all their
1472 because of how Python tears down modules (it hard-sets all their
1400 references to None without regard for reference counts). This method
1473 references to None without regard for reference counts). This method
1401 must therefore make a *copy* of the given namespace, to allow the
1474 must therefore make a *copy* of the given namespace, to allow the
1402 original module's __dict__ to be cleared and reused.
1475 original module's __dict__ to be cleared and reused.
1403
1476
1404
1477
1405 Parameters
1478 Parameters
1406 ----------
1479 ----------
1407 ns : a namespace (a dict, typically)
1480 ns : a namespace (a dict, typically)
1408
1481
1409 fname : str
1482 fname : str
1410 Filename associated with the namespace.
1483 Filename associated with the namespace.
1411
1484
1412 Examples
1485 Examples
1413 --------
1486 --------
1414
1487
1415 In [10]: import IPython
1488 In [10]: import IPython
1416
1489
1417 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1490 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1418
1491
1419 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1492 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1420 Out[12]: True
1493 Out[12]: True
1421 """
1494 """
1422 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1495 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1423
1496
1424 def clear_main_mod_cache(self):
1497 def clear_main_mod_cache(self):
1425 """Clear the cache of main modules.
1498 """Clear the cache of main modules.
1426
1499
1427 Mainly for use by utilities like %reset.
1500 Mainly for use by utilities like %reset.
1428
1501
1429 Examples
1502 Examples
1430 --------
1503 --------
1431
1504
1432 In [15]: import IPython
1505 In [15]: import IPython
1433
1506
1434 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1507 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1435
1508
1436 In [17]: len(_ip.IP._main_ns_cache) > 0
1509 In [17]: len(_ip.IP._main_ns_cache) > 0
1437 Out[17]: True
1510 Out[17]: True
1438
1511
1439 In [18]: _ip.IP.clear_main_mod_cache()
1512 In [18]: _ip.IP.clear_main_mod_cache()
1440
1513
1441 In [19]: len(_ip.IP._main_ns_cache) == 0
1514 In [19]: len(_ip.IP._main_ns_cache) == 0
1442 Out[19]: True
1515 Out[19]: True
1443 """
1516 """
1444 self._main_ns_cache.clear()
1517 self._main_ns_cache.clear()
1445
1518
1446 def _should_recompile(self,e):
1519 def _should_recompile(self,e):
1447 """Utility routine for edit_syntax_error"""
1520 """Utility routine for edit_syntax_error"""
1448
1521
1449 if e.filename in ('<ipython console>','<input>','<string>',
1522 if e.filename in ('<ipython console>','<input>','<string>',
1450 '<console>','<BackgroundJob compilation>',
1523 '<console>','<BackgroundJob compilation>',
1451 None):
1524 None):
1452
1525
1453 return False
1526 return False
1454 try:
1527 try:
1455 if (self.autoedit_syntax and
1528 if (self.autoedit_syntax and
1456 not self.ask_yes_no('Return to editor to correct syntax error? '
1529 not self.ask_yes_no('Return to editor to correct syntax error? '
1457 '[Y/n] ','y')):
1530 '[Y/n] ','y')):
1458 return False
1531 return False
1459 except EOFError:
1532 except EOFError:
1460 return False
1533 return False
1461
1534
1462 def int0(x):
1535 def int0(x):
1463 try:
1536 try:
1464 return int(x)
1537 return int(x)
1465 except TypeError:
1538 except TypeError:
1466 return 0
1539 return 0
1467 # always pass integer line and offset values to editor hook
1540 # always pass integer line and offset values to editor hook
1468 try:
1541 try:
1469 self.hooks.fix_error_editor(e.filename,
1542 self.hooks.fix_error_editor(e.filename,
1470 int0(e.lineno),int0(e.offset),e.msg)
1543 int0(e.lineno),int0(e.offset),e.msg)
1471 except ipapi.TryNext:
1544 except ipapi.TryNext:
1472 warn('Could not open editor')
1545 warn('Could not open editor')
1473 return False
1546 return False
1474 return True
1547 return True
1475
1548
1476 def edit_syntax_error(self):
1549 def edit_syntax_error(self):
1477 """The bottom half of the syntax error handler called in the main loop.
1550 """The bottom half of the syntax error handler called in the main loop.
1478
1551
1479 Loop until syntax error is fixed or user cancels.
1552 Loop until syntax error is fixed or user cancels.
1480 """
1553 """
1481
1554
1482 while self.SyntaxTB.last_syntax_error:
1555 while self.SyntaxTB.last_syntax_error:
1483 # copy and clear last_syntax_error
1556 # copy and clear last_syntax_error
1484 err = self.SyntaxTB.clear_err_state()
1557 err = self.SyntaxTB.clear_err_state()
1485 if not self._should_recompile(err):
1558 if not self._should_recompile(err):
1486 return
1559 return
1487 try:
1560 try:
1488 # may set last_syntax_error again if a SyntaxError is raised
1561 # may set last_syntax_error again if a SyntaxError is raised
1489 self.safe_execfile(err.filename,self.user_ns)
1562 self.safe_execfile(err.filename,self.user_ns)
1490 except:
1563 except:
1491 self.showtraceback()
1564 self.showtraceback()
1492 else:
1565 else:
1493 try:
1566 try:
1494 f = file(err.filename)
1567 f = file(err.filename)
1495 try:
1568 try:
1496 sys.displayhook(f.read())
1569 sys.displayhook(f.read())
1497 finally:
1570 finally:
1498 f.close()
1571 f.close()
1499 except:
1572 except:
1500 self.showtraceback()
1573 self.showtraceback()
1501
1574
1502 def showsyntaxerror(self, filename=None):
1575 def showsyntaxerror(self, filename=None):
1503 """Display the syntax error that just occurred.
1576 """Display the syntax error that just occurred.
1504
1577
1505 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.
1506
1579
1507 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
1508 of what was there before (because Python's parser always uses
1581 of what was there before (because Python's parser always uses
1509 "<string>" when reading from a string).
1582 "<string>" when reading from a string).
1510 """
1583 """
1511 etype, value, last_traceback = sys.exc_info()
1584 etype, value, last_traceback = sys.exc_info()
1512
1585
1513 # See note about these variables in showtraceback() below
1586 # See note about these variables in showtraceback() below
1514 sys.last_type = etype
1587 sys.last_type = etype
1515 sys.last_value = value
1588 sys.last_value = value
1516 sys.last_traceback = last_traceback
1589 sys.last_traceback = last_traceback
1517
1590
1518 if filename and etype is SyntaxError:
1591 if filename and etype is SyntaxError:
1519 # Work hard to stuff the correct filename in the exception
1592 # Work hard to stuff the correct filename in the exception
1520 try:
1593 try:
1521 msg, (dummy_filename, lineno, offset, line) = value
1594 msg, (dummy_filename, lineno, offset, line) = value
1522 except:
1595 except:
1523 # Not the format we expect; leave it alone
1596 # Not the format we expect; leave it alone
1524 pass
1597 pass
1525 else:
1598 else:
1526 # Stuff in the right filename
1599 # Stuff in the right filename
1527 try:
1600 try:
1528 # Assume SyntaxError is a class exception
1601 # Assume SyntaxError is a class exception
1529 value = SyntaxError(msg, (filename, lineno, offset, line))
1602 value = SyntaxError(msg, (filename, lineno, offset, line))
1530 except:
1603 except:
1531 # If that failed, assume SyntaxError is a string
1604 # If that failed, assume SyntaxError is a string
1532 value = msg, (filename, lineno, offset, line)
1605 value = msg, (filename, lineno, offset, line)
1533 self.SyntaxTB(etype,value,[])
1606 self.SyntaxTB(etype,value,[])
1534
1607
1535 def debugger(self,force=False):
1608 def debugger(self,force=False):
1536 """Call the pydb/pdb debugger.
1609 """Call the pydb/pdb debugger.
1537
1610
1538 Keywords:
1611 Keywords:
1539
1612
1540 - force(False): by default, this routine checks the instance call_pdb
1613 - force(False): by default, this routine checks the instance call_pdb
1541 flag and does not actually invoke the debugger if the flag is false.
1614 flag and does not actually invoke the debugger if the flag is false.
1542 The 'force' option forces the debugger to activate even if the flag
1615 The 'force' option forces the debugger to activate even if the flag
1543 is false.
1616 is false.
1544 """
1617 """
1545
1618
1546 if not (force or self.call_pdb):
1619 if not (force or self.call_pdb):
1547 return
1620 return
1548
1621
1549 if not hasattr(sys,'last_traceback'):
1622 if not hasattr(sys,'last_traceback'):
1550 error('No traceback has been produced, nothing to debug.')
1623 error('No traceback has been produced, nothing to debug.')
1551 return
1624 return
1552
1625
1553 # use pydb if available
1626 # use pydb if available
1554 if debugger.has_pydb:
1627 if debugger.has_pydb:
1555 from pydb import pm
1628 from pydb import pm
1556 else:
1629 else:
1557 # fallback to our internal debugger
1630 # fallback to our internal debugger
1558 pm = lambda : self.InteractiveTB.debugger(force=True)
1631 pm = lambda : self.InteractiveTB.debugger(force=True)
1559 self.history_saving_wrapper(pm)()
1632 self.history_saving_wrapper(pm)()
1560
1633
1561 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1634 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1562 """Display the exception that just occurred.
1635 """Display the exception that just occurred.
1563
1636
1564 If nothing is known about the exception, this is the method which
1637 If nothing is known about the exception, this is the method which
1565 should be used throughout the code for presenting user tracebacks,
1638 should be used throughout the code for presenting user tracebacks,
1566 rather than directly invoking the InteractiveTB object.
1639 rather than directly invoking the InteractiveTB object.
1567
1640
1568 A specific showsyntaxerror() also exists, but this method can take
1641 A specific showsyntaxerror() also exists, but this method can take
1569 care of calling it if needed, so unless you are explicitly catching a
1642 care of calling it if needed, so unless you are explicitly catching a
1570 SyntaxError exception, don't try to analyze the stack manually and
1643 SyntaxError exception, don't try to analyze the stack manually and
1571 simply call this method."""
1644 simply call this method."""
1572
1645
1573
1646
1574 # Though this won't be called by syntax errors in the input line,
1647 # Though this won't be called by syntax errors in the input line,
1575 # there may be SyntaxError cases whith imported code.
1648 # there may be SyntaxError cases whith imported code.
1576
1649
1577 try:
1650 try:
1578 if exc_tuple is None:
1651 if exc_tuple is None:
1579 etype, value, tb = sys.exc_info()
1652 etype, value, tb = sys.exc_info()
1580 else:
1653 else:
1581 etype, value, tb = exc_tuple
1654 etype, value, tb = exc_tuple
1582
1655
1583 if etype is SyntaxError:
1656 if etype is SyntaxError:
1584 self.showsyntaxerror(filename)
1657 self.showsyntaxerror(filename)
1585 elif etype is ipapi.UsageError:
1658 elif etype is ipapi.UsageError:
1586 print "UsageError:", value
1659 print "UsageError:", value
1587 else:
1660 else:
1588 # WARNING: these variables are somewhat deprecated and not
1661 # WARNING: these variables are somewhat deprecated and not
1589 # necessarily safe to use in a threaded environment, but tools
1662 # necessarily safe to use in a threaded environment, but tools
1590 # like pdb depend on their existence, so let's set them. If we
1663 # like pdb depend on their existence, so let's set them. If we
1591 # find problems in the field, we'll need to revisit their use.
1664 # find problems in the field, we'll need to revisit their use.
1592 sys.last_type = etype
1665 sys.last_type = etype
1593 sys.last_value = value
1666 sys.last_value = value
1594 sys.last_traceback = tb
1667 sys.last_traceback = tb
1595
1668
1596 if etype in self.custom_exceptions:
1669 if etype in self.custom_exceptions:
1597 self.CustomTB(etype,value,tb)
1670 self.CustomTB(etype,value,tb)
1598 else:
1671 else:
1599 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1672 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1600 if self.InteractiveTB.call_pdb and self.has_readline:
1673 if self.InteractiveTB.call_pdb and self.has_readline:
1601 # pdb mucks up readline, fix it back
1674 # pdb mucks up readline, fix it back
1602 self.set_completer()
1675 self.set_completer()
1603 except KeyboardInterrupt:
1676 except KeyboardInterrupt:
1604 self.write("\nKeyboardInterrupt\n")
1677 self.write("\nKeyboardInterrupt\n")
1605
1678
1606 def mainloop(self, banner=None):
1679 def mainloop(self, banner=None):
1607 """Start the mainloop.
1680 """Start the mainloop.
1608
1681
1609 If an optional banner argument is given, it will override the
1682 If an optional banner argument is given, it will override the
1610 internally created default banner.
1683 internally created default banner.
1611 """
1684 """
1612 if self.c: # Emulate Python's -c option
1685 if self.c: # Emulate Python's -c option
1613 self.exec_init_cmd()
1686 self.exec_init_cmd()
1614
1687
1615 if self.display_banner:
1688 if self.display_banner:
1616 if banner is None:
1689 if banner is None:
1617 banner = self.banner
1690 banner = self.banner
1618
1691
1619 # if you run stuff with -c <cmd>, raw hist is not updated
1692 # if you run stuff with -c <cmd>, raw hist is not updated
1620 # ensure that it's in sync
1693 # ensure that it's in sync
1621 if len(self.input_hist) != len (self.input_hist_raw):
1694 if len(self.input_hist) != len (self.input_hist_raw):
1622 self.input_hist_raw = InputList(self.input_hist)
1695 self.input_hist_raw = InputList(self.input_hist)
1623
1696
1624 while 1:
1697 while 1:
1625 try:
1698 try:
1626 self.interact()
1699 self.interact()
1627 #self.interact_with_readline()
1700 #self.interact_with_readline()
1628 # XXX for testing of a readline-decoupled repl loop, call
1701 # XXX for testing of a readline-decoupled repl loop, call
1629 # interact_with_readline above
1702 # interact_with_readline above
1630 break
1703 break
1631 except KeyboardInterrupt:
1704 except KeyboardInterrupt:
1632 # this should not be necessary, but KeyboardInterrupt
1705 # this should not be necessary, but KeyboardInterrupt
1633 # handling seems rather unpredictable...
1706 # handling seems rather unpredictable...
1634 self.write("\nKeyboardInterrupt in interact()\n")
1707 self.write("\nKeyboardInterrupt in interact()\n")
1635
1708
1636 def exec_init_cmd(self):
1709 def exec_init_cmd(self):
1637 """Execute a command given at the command line.
1710 """Execute a command given at the command line.
1638
1711
1639 This emulates Python's -c option."""
1712 This emulates Python's -c option."""
1640
1713
1641 #sys.argv = ['-c']
1714 #sys.argv = ['-c']
1642 self.push(self.prefilter(self.c, False))
1715 self.push(self.prefilter(self.c, False))
1643 if not self.interactive:
1716 if not self.interactive:
1644 self.ask_exit()
1717 self.ask_exit()
1645
1718
1646 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1719 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1647 """Embeds IPython into a running python program.
1720 """Embeds IPython into a running python program.
1648
1721
1649 Input:
1722 Input:
1650
1723
1651 - header: An optional header message can be specified.
1724 - header: An optional header message can be specified.
1652
1725
1653 - local_ns, global_ns: working namespaces. If given as None, the
1726 - local_ns, global_ns: working namespaces. If given as None, the
1654 IPython-initialized one is updated with __main__.__dict__, so that
1727 IPython-initialized one is updated with __main__.__dict__, so that
1655 program variables become visible but user-specific configuration
1728 program variables become visible but user-specific configuration
1656 remains possible.
1729 remains possible.
1657
1730
1658 - stack_depth: specifies how many levels in the stack to go to
1731 - stack_depth: specifies how many levels in the stack to go to
1659 looking for namespaces (when local_ns and global_ns are None). This
1732 looking for namespaces (when local_ns and global_ns are None). This
1660 allows an intermediate caller to make sure that this function gets
1733 allows an intermediate caller to make sure that this function gets
1661 the namespace from the intended level in the stack. By default (0)
1734 the namespace from the intended level in the stack. By default (0)
1662 it will get its locals and globals from the immediate caller.
1735 it will get its locals and globals from the immediate caller.
1663
1736
1664 Warning: it's possible to use this in a program which is being run by
1737 Warning: it's possible to use this in a program which is being run by
1665 IPython itself (via %run), but some funny things will happen (a few
1738 IPython itself (via %run), but some funny things will happen (a few
1666 globals get overwritten). In the future this will be cleaned up, as
1739 globals get overwritten). In the future this will be cleaned up, as
1667 there is no fundamental reason why it can't work perfectly."""
1740 there is no fundamental reason why it can't work perfectly."""
1668
1741
1669 # Get locals and globals from caller
1742 # Get locals and globals from caller
1670 if local_ns is None or global_ns is None:
1743 if local_ns is None or global_ns is None:
1671 call_frame = sys._getframe(stack_depth).f_back
1744 call_frame = sys._getframe(stack_depth).f_back
1672
1745
1673 if local_ns is None:
1746 if local_ns is None:
1674 local_ns = call_frame.f_locals
1747 local_ns = call_frame.f_locals
1675 if global_ns is None:
1748 if global_ns is None:
1676 global_ns = call_frame.f_globals
1749 global_ns = call_frame.f_globals
1677
1750
1678 # Update namespaces and fire up interpreter
1751 # Update namespaces and fire up interpreter
1679
1752
1680 # The global one is easy, we can just throw it in
1753 # The global one is easy, we can just throw it in
1681 self.user_global_ns = global_ns
1754 self.user_global_ns = global_ns
1682
1755
1683 # but the user/local one is tricky: ipython needs it to store internal
1756 # but the user/local one is tricky: ipython needs it to store internal
1684 # data, but we also need the locals. We'll copy locals in the user
1757 # data, but we also need the locals. We'll copy locals in the user
1685 # one, but will track what got copied so we can delete them at exit.
1758 # one, but will track what got copied so we can delete them at exit.
1686 # This is so that a later embedded call doesn't see locals from a
1759 # This is so that a later embedded call doesn't see locals from a
1687 # previous call (which most likely existed in a separate scope).
1760 # previous call (which most likely existed in a separate scope).
1688 local_varnames = local_ns.keys()
1761 local_varnames = local_ns.keys()
1689 self.user_ns.update(local_ns)
1762 self.user_ns.update(local_ns)
1690 #self.user_ns['local_ns'] = local_ns # dbg
1763 #self.user_ns['local_ns'] = local_ns # dbg
1691
1764
1692 # Patch for global embedding to make sure that things don't overwrite
1765 # Patch for global embedding to make sure that things don't overwrite
1693 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1766 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1694 # FIXME. Test this a bit more carefully (the if.. is new)
1767 # FIXME. Test this a bit more carefully (the if.. is new)
1695 if local_ns is None and global_ns is None:
1768 if local_ns is None and global_ns is None:
1696 self.user_global_ns.update(__main__.__dict__)
1769 self.user_global_ns.update(__main__.__dict__)
1697
1770
1698 # make sure the tab-completer has the correct frame information, so it
1771 # make sure the tab-completer has the correct frame information, so it
1699 # actually completes using the frame's locals/globals
1772 # actually completes using the frame's locals/globals
1700 self.set_completer_frame()
1773 self.set_completer_frame()
1701
1774
1702 # before activating the interactive mode, we need to make sure that
1775 # before activating the interactive mode, we need to make sure that
1703 # all names in the builtin namespace needed by ipython point to
1776 # all names in the builtin namespace needed by ipython point to
1704 # ourselves, and not to other instances.
1777 # ourselves, and not to other instances.
1705 self.add_builtins()
1778 self.add_builtins()
1706
1779
1707 self.interact(header)
1780 self.interact(header)
1708
1781
1709 # now, purge out the user namespace from anything we might have added
1782 # now, purge out the user namespace from anything we might have added
1710 # from the caller's local namespace
1783 # from the caller's local namespace
1711 delvar = self.user_ns.pop
1784 delvar = self.user_ns.pop
1712 for var in local_varnames:
1785 for var in local_varnames:
1713 delvar(var,None)
1786 delvar(var,None)
1714 # and clean builtins we may have overridden
1787 # and clean builtins we may have overridden
1715 self.clean_builtins()
1788 self.clean_builtins()
1716
1789
1717 def interact_prompt(self):
1790 def interact_prompt(self):
1718 """ Print the prompt (in read-eval-print loop)
1791 """ Print the prompt (in read-eval-print loop)
1719
1792
1720 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1793 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1721 used in standard IPython flow.
1794 used in standard IPython flow.
1722 """
1795 """
1723 if self.more:
1796 if self.more:
1724 try:
1797 try:
1725 prompt = self.hooks.generate_prompt(True)
1798 prompt = self.hooks.generate_prompt(True)
1726 except:
1799 except:
1727 self.showtraceback()
1800 self.showtraceback()
1728 if self.autoindent:
1801 if self.autoindent:
1729 self.rl_do_indent = True
1802 self.rl_do_indent = True
1730
1803
1731 else:
1804 else:
1732 try:
1805 try:
1733 prompt = self.hooks.generate_prompt(False)
1806 prompt = self.hooks.generate_prompt(False)
1734 except:
1807 except:
1735 self.showtraceback()
1808 self.showtraceback()
1736 self.write(prompt)
1809 self.write(prompt)
1737
1810
1738 def interact_handle_input(self,line):
1811 def interact_handle_input(self,line):
1739 """ Handle the input line (in read-eval-print loop)
1812 """ Handle the input line (in read-eval-print loop)
1740
1813
1741 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1814 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1742 used in standard IPython flow.
1815 used in standard IPython flow.
1743 """
1816 """
1744 if line.lstrip() == line:
1817 if line.lstrip() == line:
1745 self.shadowhist.add(line.strip())
1818 self.shadowhist.add(line.strip())
1746 lineout = self.prefilter(line,self.more)
1819 lineout = self.prefilter(line,self.more)
1747
1820
1748 if line.strip():
1821 if line.strip():
1749 if self.more:
1822 if self.more:
1750 self.input_hist_raw[-1] += '%s\n' % line
1823 self.input_hist_raw[-1] += '%s\n' % line
1751 else:
1824 else:
1752 self.input_hist_raw.append('%s\n' % line)
1825 self.input_hist_raw.append('%s\n' % line)
1753
1826
1754
1827
1755 self.more = self.push(lineout)
1828 self.more = self.push(lineout)
1756 if (self.SyntaxTB.last_syntax_error and
1829 if (self.SyntaxTB.last_syntax_error and
1757 self.autoedit_syntax):
1830 self.autoedit_syntax):
1758 self.edit_syntax_error()
1831 self.edit_syntax_error()
1759
1832
1760 def interact_with_readline(self):
1833 def interact_with_readline(self):
1761 """ Demo of using interact_handle_input, interact_prompt
1834 """ Demo of using interact_handle_input, interact_prompt
1762
1835
1763 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1836 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1764 it should work like this.
1837 it should work like this.
1765 """
1838 """
1766 self.readline_startup_hook(self.pre_readline)
1839 self.readline_startup_hook(self.pre_readline)
1767 while not self.exit_now:
1840 while not self.exit_now:
1768 self.interact_prompt()
1841 self.interact_prompt()
1769 if self.more:
1842 if self.more:
1770 self.rl_do_indent = True
1843 self.rl_do_indent = True
1771 else:
1844 else:
1772 self.rl_do_indent = False
1845 self.rl_do_indent = False
1773 line = raw_input_original().decode(self.stdin_encoding)
1846 line = raw_input_original().decode(self.stdin_encoding)
1774 self.interact_handle_input(line)
1847 self.interact_handle_input(line)
1775
1848
1776 def interact(self, banner=None):
1849 def interact(self, banner=None):
1777 """Closely emulate the interactive Python console."""
1850 """Closely emulate the interactive Python console."""
1778
1851
1779 # batch run -> do not interact
1852 # batch run -> do not interact
1780 if self.exit_now:
1853 if self.exit_now:
1781 return
1854 return
1782
1855
1783 if self.display_banner:
1856 if self.display_banner:
1784 if banner is None:
1857 if banner is None:
1785 banner = self.banner
1858 banner = self.banner
1786 self.write(banner)
1859 self.write(banner)
1787
1860
1788 more = 0
1861 more = 0
1789
1862
1790 # Mark activity in the builtins
1863 # Mark activity in the builtins
1791 __builtin__.__dict__['__IPYTHON__active'] += 1
1864 __builtin__.__dict__['__IPYTHON__active'] += 1
1792
1865
1793 if self.has_readline:
1866 if self.has_readline:
1794 self.readline_startup_hook(self.pre_readline)
1867 self.readline_startup_hook(self.pre_readline)
1795 # exit_now is set by a call to %Exit or %Quit, through the
1868 # exit_now is set by a call to %Exit or %Quit, through the
1796 # ask_exit callback.
1869 # ask_exit callback.
1797
1870
1798 while not self.exit_now:
1871 while not self.exit_now:
1799 self.hooks.pre_prompt_hook()
1872 self.hooks.pre_prompt_hook()
1800 if more:
1873 if more:
1801 try:
1874 try:
1802 prompt = self.hooks.generate_prompt(True)
1875 prompt = self.hooks.generate_prompt(True)
1803 except:
1876 except:
1804 self.showtraceback()
1877 self.showtraceback()
1805 if self.autoindent:
1878 if self.autoindent:
1806 self.rl_do_indent = True
1879 self.rl_do_indent = True
1807
1880
1808 else:
1881 else:
1809 try:
1882 try:
1810 prompt = self.hooks.generate_prompt(False)
1883 prompt = self.hooks.generate_prompt(False)
1811 except:
1884 except:
1812 self.showtraceback()
1885 self.showtraceback()
1813 try:
1886 try:
1814 line = self.raw_input(prompt, more)
1887 line = self.raw_input(prompt, more)
1815 if self.exit_now:
1888 if self.exit_now:
1816 # quick exit on sys.std[in|out] close
1889 # quick exit on sys.std[in|out] close
1817 break
1890 break
1818 if self.autoindent:
1891 if self.autoindent:
1819 self.rl_do_indent = False
1892 self.rl_do_indent = False
1820
1893
1821 except KeyboardInterrupt:
1894 except KeyboardInterrupt:
1822 #double-guard against keyboardinterrupts during kbdint handling
1895 #double-guard against keyboardinterrupts during kbdint handling
1823 try:
1896 try:
1824 self.write('\nKeyboardInterrupt\n')
1897 self.write('\nKeyboardInterrupt\n')
1825 self.resetbuffer()
1898 self.resetbuffer()
1826 # keep cache in sync with the prompt counter:
1899 # keep cache in sync with the prompt counter:
1827 self.outputcache.prompt_count -= 1
1900 self.outputcache.prompt_count -= 1
1828
1901
1829 if self.autoindent:
1902 if self.autoindent:
1830 self.indent_current_nsp = 0
1903 self.indent_current_nsp = 0
1831 more = 0
1904 more = 0
1832 except KeyboardInterrupt:
1905 except KeyboardInterrupt:
1833 pass
1906 pass
1834 except EOFError:
1907 except EOFError:
1835 if self.autoindent:
1908 if self.autoindent:
1836 self.rl_do_indent = False
1909 self.rl_do_indent = False
1837 self.readline_startup_hook(None)
1910 self.readline_startup_hook(None)
1838 self.write('\n')
1911 self.write('\n')
1839 self.exit()
1912 self.exit()
1840 except bdb.BdbQuit:
1913 except bdb.BdbQuit:
1841 warn('The Python debugger has exited with a BdbQuit exception.\n'
1914 warn('The Python debugger has exited with a BdbQuit exception.\n'
1842 'Because of how pdb handles the stack, it is impossible\n'
1915 'Because of how pdb handles the stack, it is impossible\n'
1843 'for IPython to properly format this particular exception.\n'
1916 'for IPython to properly format this particular exception.\n'
1844 'IPython will resume normal operation.')
1917 'IPython will resume normal operation.')
1845 except:
1918 except:
1846 # exceptions here are VERY RARE, but they can be triggered
1919 # exceptions here are VERY RARE, but they can be triggered
1847 # asynchronously by signal handlers, for example.
1920 # asynchronously by signal handlers, for example.
1848 self.showtraceback()
1921 self.showtraceback()
1849 else:
1922 else:
1850 more = self.push(line)
1923 more = self.push(line)
1851 if (self.SyntaxTB.last_syntax_error and
1924 if (self.SyntaxTB.last_syntax_error and
1852 self.autoedit_syntax):
1925 self.autoedit_syntax):
1853 self.edit_syntax_error()
1926 self.edit_syntax_error()
1854
1927
1855 # We are off again...
1928 # We are off again...
1856 __builtin__.__dict__['__IPYTHON__active'] -= 1
1929 __builtin__.__dict__['__IPYTHON__active'] -= 1
1857
1930
1858 def excepthook(self, etype, value, tb):
1931 def excepthook(self, etype, value, tb):
1859 """One more defense for GUI apps that call sys.excepthook.
1932 """One more defense for GUI apps that call sys.excepthook.
1860
1933
1861 GUI frameworks like wxPython trap exceptions and call
1934 GUI frameworks like wxPython trap exceptions and call
1862 sys.excepthook themselves. I guess this is a feature that
1935 sys.excepthook themselves. I guess this is a feature that
1863 enables them to keep running after exceptions that would
1936 enables them to keep running after exceptions that would
1864 otherwise kill their mainloop. This is a bother for IPython
1937 otherwise kill their mainloop. This is a bother for IPython
1865 which excepts to catch all of the program exceptions with a try:
1938 which excepts to catch all of the program exceptions with a try:
1866 except: statement.
1939 except: statement.
1867
1940
1868 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1941 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1869 any app directly invokes sys.excepthook, it will look to the user like
1942 any app directly invokes sys.excepthook, it will look to the user like
1870 IPython crashed. In order to work around this, we can disable the
1943 IPython crashed. In order to work around this, we can disable the
1871 CrashHandler and replace it with this excepthook instead, which prints a
1944 CrashHandler and replace it with this excepthook instead, which prints a
1872 regular traceback using our InteractiveTB. In this fashion, apps which
1945 regular traceback using our InteractiveTB. In this fashion, apps which
1873 call sys.excepthook will generate a regular-looking exception from
1946 call sys.excepthook will generate a regular-looking exception from
1874 IPython, and the CrashHandler will only be triggered by real IPython
1947 IPython, and the CrashHandler will only be triggered by real IPython
1875 crashes.
1948 crashes.
1876
1949
1877 This hook should be used sparingly, only in places which are not likely
1950 This hook should be used sparingly, only in places which are not likely
1878 to be true IPython errors.
1951 to be true IPython errors.
1879 """
1952 """
1880 self.showtraceback((etype,value,tb),tb_offset=0)
1953 self.showtraceback((etype,value,tb),tb_offset=0)
1881
1954
1882 def expand_aliases(self,fn,rest):
1955 def expand_aliases(self,fn,rest):
1883 """ Expand multiple levels of aliases:
1956 """ Expand multiple levels of aliases:
1884
1957
1885 if:
1958 if:
1886
1959
1887 alias foo bar /tmp
1960 alias foo bar /tmp
1888 alias baz foo
1961 alias baz foo
1889
1962
1890 then:
1963 then:
1891
1964
1892 baz huhhahhei -> bar /tmp huhhahhei
1965 baz huhhahhei -> bar /tmp huhhahhei
1893
1966
1894 """
1967 """
1895 line = fn + " " + rest
1968 line = fn + " " + rest
1896
1969
1897 done = set()
1970 done = set()
1898 while 1:
1971 while 1:
1899 pre,fn,rest = prefilter.splitUserInput(line,
1972 pre,fn,rest = prefilter.splitUserInput(line,
1900 prefilter.shell_line_split)
1973 prefilter.shell_line_split)
1901 if fn in self.alias_table:
1974 if fn in self.alias_table:
1902 if fn in done:
1975 if fn in done:
1903 warn("Cyclic alias definition, repeated '%s'" % fn)
1976 warn("Cyclic alias definition, repeated '%s'" % fn)
1904 return ""
1977 return ""
1905 done.add(fn)
1978 done.add(fn)
1906
1979
1907 l2 = self.transform_alias(fn,rest)
1980 l2 = self.transform_alias(fn,rest)
1908 # dir -> dir
1981 # dir -> dir
1909 # print "alias",line, "->",l2 #dbg
1982 # print "alias",line, "->",l2 #dbg
1910 if l2 == line:
1983 if l2 == line:
1911 break
1984 break
1912 # ls -> ls -F should not recurse forever
1985 # ls -> ls -F should not recurse forever
1913 if l2.split(None,1)[0] == line.split(None,1)[0]:
1986 if l2.split(None,1)[0] == line.split(None,1)[0]:
1914 line = l2
1987 line = l2
1915 break
1988 break
1916
1989
1917 line=l2
1990 line=l2
1918
1991
1919
1992
1920 # print "al expand to",line #dbg
1993 # print "al expand to",line #dbg
1921 else:
1994 else:
1922 break
1995 break
1923
1996
1924 return line
1997 return line
1925
1998
1926 def transform_alias(self, alias,rest=''):
1999 def transform_alias(self, alias,rest=''):
1927 """ Transform alias to system command string.
2000 """ Transform alias to system command string.
1928 """
2001 """
1929 trg = self.alias_table[alias]
2002 trg = self.alias_table[alias]
1930
2003
1931 nargs,cmd = trg
2004 nargs,cmd = trg
1932 # print trg #dbg
2005 # print trg #dbg
1933 if ' ' in cmd and os.path.isfile(cmd):
2006 if ' ' in cmd and os.path.isfile(cmd):
1934 cmd = '"%s"' % cmd
2007 cmd = '"%s"' % cmd
1935
2008
1936 # Expand the %l special to be the user's input line
2009 # Expand the %l special to be the user's input line
1937 if cmd.find('%l') >= 0:
2010 if cmd.find('%l') >= 0:
1938 cmd = cmd.replace('%l',rest)
2011 cmd = cmd.replace('%l',rest)
1939 rest = ''
2012 rest = ''
1940 if nargs==0:
2013 if nargs==0:
1941 # Simple, argument-less aliases
2014 # Simple, argument-less aliases
1942 cmd = '%s %s' % (cmd,rest)
2015 cmd = '%s %s' % (cmd,rest)
1943 else:
2016 else:
1944 # Handle aliases with positional arguments
2017 # Handle aliases with positional arguments
1945 args = rest.split(None,nargs)
2018 args = rest.split(None,nargs)
1946 if len(args)< nargs:
2019 if len(args)< nargs:
1947 error('Alias <%s> requires %s arguments, %s given.' %
2020 error('Alias <%s> requires %s arguments, %s given.' %
1948 (alias,nargs,len(args)))
2021 (alias,nargs,len(args)))
1949 return None
2022 return None
1950 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2023 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1951 # Now call the macro, evaluating in the user's namespace
2024 # Now call the macro, evaluating in the user's namespace
1952 #print 'new command: <%r>' % cmd # dbg
2025 #print 'new command: <%r>' % cmd # dbg
1953 return cmd
2026 return cmd
1954
2027
1955 def call_alias(self,alias,rest=''):
2028 def call_alias(self,alias,rest=''):
1956 """Call an alias given its name and the rest of the line.
2029 """Call an alias given its name and the rest of the line.
1957
2030
1958 This is only used to provide backwards compatibility for users of
2031 This is only used to provide backwards compatibility for users of
1959 ipalias(), use of which is not recommended for anymore."""
2032 ipalias(), use of which is not recommended for anymore."""
1960
2033
1961 # Now call the macro, evaluating in the user's namespace
2034 # Now call the macro, evaluating in the user's namespace
1962 cmd = self.transform_alias(alias, rest)
2035 cmd = self.transform_alias(alias, rest)
1963 try:
2036 try:
1964 self.system(cmd)
2037 self.system(cmd)
1965 except:
2038 except:
1966 self.showtraceback()
2039 self.showtraceback()
1967
2040
1968 def indent_current_str(self):
2041 def indent_current_str(self):
1969 """return the current level of indentation as a string"""
2042 """return the current level of indentation as a string"""
1970 return self.indent_current_nsp * ' '
2043 return self.indent_current_nsp * ' '
1971
2044
1972 def autoindent_update(self,line):
2045 def autoindent_update(self,line):
1973 """Keep track of the indent level."""
2046 """Keep track of the indent level."""
1974
2047
1975 #debugx('line')
2048 #debugx('line')
1976 #debugx('self.indent_current_nsp')
2049 #debugx('self.indent_current_nsp')
1977 if self.autoindent:
2050 if self.autoindent:
1978 if line:
2051 if line:
1979 inisp = num_ini_spaces(line)
2052 inisp = num_ini_spaces(line)
1980 if inisp < self.indent_current_nsp:
2053 if inisp < self.indent_current_nsp:
1981 self.indent_current_nsp = inisp
2054 self.indent_current_nsp = inisp
1982
2055
1983 if line[-1] == ':':
2056 if line[-1] == ':':
1984 self.indent_current_nsp += 4
2057 self.indent_current_nsp += 4
1985 elif dedent_re.match(line):
2058 elif dedent_re.match(line):
1986 self.indent_current_nsp -= 4
2059 self.indent_current_nsp -= 4
1987 else:
2060 else:
1988 self.indent_current_nsp = 0
2061 self.indent_current_nsp = 0
1989
2062
1990 def runlines(self,lines):
2063 def runlines(self,lines):
1991 """Run a string of one or more lines of source.
2064 """Run a string of one or more lines of source.
1992
2065
1993 This method is capable of running a string containing multiple source
2066 This method is capable of running a string containing multiple source
1994 lines, as if they had been entered at the IPython prompt. Since it
2067 lines, as if they had been entered at the IPython prompt. Since it
1995 exposes IPython's processing machinery, the given strings can contain
2068 exposes IPython's processing machinery, the given strings can contain
1996 magic calls (%magic), special shell access (!cmd), etc."""
2069 magic calls (%magic), special shell access (!cmd), etc."""
1997
2070
1998 # We must start with a clean buffer, in case this is run from an
2071 # We must start with a clean buffer, in case this is run from an
1999 # interactive IPython session (via a magic, for example).
2072 # interactive IPython session (via a magic, for example).
2000 self.resetbuffer()
2073 self.resetbuffer()
2001 lines = lines.split('\n')
2074 lines = lines.split('\n')
2002 more = 0
2075 more = 0
2003
2076
2004 for line in lines:
2077 for line in lines:
2005 # skip blank lines so we don't mess up the prompt counter, but do
2078 # skip blank lines so we don't mess up the prompt counter, but do
2006 # NOT skip even a blank line if we are in a code block (more is
2079 # NOT skip even a blank line if we are in a code block (more is
2007 # true)
2080 # true)
2008
2081
2009 if line or more:
2082 if line or more:
2010 # push to raw history, so hist line numbers stay in sync
2083 # push to raw history, so hist line numbers stay in sync
2011 self.input_hist_raw.append("# " + line + "\n")
2084 self.input_hist_raw.append("# " + line + "\n")
2012 more = self.push(self.prefilter(line,more))
2085 more = self.push(self.prefilter(line,more))
2013 # IPython's runsource returns None if there was an error
2086 # IPython's runsource returns None if there was an error
2014 # compiling the code. This allows us to stop processing right
2087 # compiling the code. This allows us to stop processing right
2015 # away, so the user gets the error message at the right place.
2088 # away, so the user gets the error message at the right place.
2016 if more is None:
2089 if more is None:
2017 break
2090 break
2018 else:
2091 else:
2019 self.input_hist_raw.append("\n")
2092 self.input_hist_raw.append("\n")
2020 # final newline in case the input didn't have it, so that the code
2093 # final newline in case the input didn't have it, so that the code
2021 # actually does get executed
2094 # actually does get executed
2022 if more:
2095 if more:
2023 self.push('\n')
2096 self.push('\n')
2024
2097
2025 def runsource(self, source, filename='<input>', symbol='single'):
2098 def runsource(self, source, filename='<input>', symbol='single'):
2026 """Compile and run some source in the interpreter.
2099 """Compile and run some source in the interpreter.
2027
2100
2028 Arguments are as for compile_command().
2101 Arguments are as for compile_command().
2029
2102
2030 One several things can happen:
2103 One several things can happen:
2031
2104
2032 1) The input is incorrect; compile_command() raised an
2105 1) The input is incorrect; compile_command() raised an
2033 exception (SyntaxError or OverflowError). A syntax traceback
2106 exception (SyntaxError or OverflowError). A syntax traceback
2034 will be printed by calling the showsyntaxerror() method.
2107 will be printed by calling the showsyntaxerror() method.
2035
2108
2036 2) The input is incomplete, and more input is required;
2109 2) The input is incomplete, and more input is required;
2037 compile_command() returned None. Nothing happens.
2110 compile_command() returned None. Nothing happens.
2038
2111
2039 3) The input is complete; compile_command() returned a code
2112 3) The input is complete; compile_command() returned a code
2040 object. The code is executed by calling self.runcode() (which
2113 object. The code is executed by calling self.runcode() (which
2041 also handles run-time exceptions, except for SystemExit).
2114 also handles run-time exceptions, except for SystemExit).
2042
2115
2043 The return value is:
2116 The return value is:
2044
2117
2045 - True in case 2
2118 - True in case 2
2046
2119
2047 - False in the other cases, unless an exception is raised, where
2120 - False in the other cases, unless an exception is raised, where
2048 None is returned instead. This can be used by external callers to
2121 None is returned instead. This can be used by external callers to
2049 know whether to continue feeding input or not.
2122 know whether to continue feeding input or not.
2050
2123
2051 The return value can be used to decide whether to use sys.ps1 or
2124 The return value can be used to decide whether to use sys.ps1 or
2052 sys.ps2 to prompt the next line."""
2125 sys.ps2 to prompt the next line."""
2053
2126
2054 # if the source code has leading blanks, add 'if 1:\n' to it
2127 # if the source code has leading blanks, add 'if 1:\n' to it
2055 # this allows execution of indented pasted code. It is tempting
2128 # this allows execution of indented pasted code. It is tempting
2056 # to add '\n' at the end of source to run commands like ' a=1'
2129 # to add '\n' at the end of source to run commands like ' a=1'
2057 # directly, but this fails for more complicated scenarios
2130 # directly, but this fails for more complicated scenarios
2058 source=source.encode(self.stdin_encoding)
2131 source=source.encode(self.stdin_encoding)
2059 if source[:1] in [' ', '\t']:
2132 if source[:1] in [' ', '\t']:
2060 source = 'if 1:\n%s' % source
2133 source = 'if 1:\n%s' % source
2061
2134
2062 try:
2135 try:
2063 code = self.compile(source,filename,symbol)
2136 code = self.compile(source,filename,symbol)
2064 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2137 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2065 # Case 1
2138 # Case 1
2066 self.showsyntaxerror(filename)
2139 self.showsyntaxerror(filename)
2067 return None
2140 return None
2068
2141
2069 if code is None:
2142 if code is None:
2070 # Case 2
2143 # Case 2
2071 return True
2144 return True
2072
2145
2073 # Case 3
2146 # Case 3
2074 # We store the code object so that threaded shells and
2147 # We store the code object so that threaded shells and
2075 # custom exception handlers can access all this info if needed.
2148 # custom exception handlers can access all this info if needed.
2076 # The source corresponding to this can be obtained from the
2149 # The source corresponding to this can be obtained from the
2077 # buffer attribute as '\n'.join(self.buffer).
2150 # buffer attribute as '\n'.join(self.buffer).
2078 self.code_to_run = code
2151 self.code_to_run = code
2079 # now actually execute the code object
2152 # now actually execute the code object
2080 if self.runcode(code) == 0:
2153 if self.runcode(code) == 0:
2081 return False
2154 return False
2082 else:
2155 else:
2083 return None
2156 return None
2084
2157
2085 def runcode(self,code_obj):
2158 def runcode(self,code_obj):
2086 """Execute a code object.
2159 """Execute a code object.
2087
2160
2088 When an exception occurs, self.showtraceback() is called to display a
2161 When an exception occurs, self.showtraceback() is called to display a
2089 traceback.
2162 traceback.
2090
2163
2091 Return value: a flag indicating whether the code to be run completed
2164 Return value: a flag indicating whether the code to be run completed
2092 successfully:
2165 successfully:
2093
2166
2094 - 0: successful execution.
2167 - 0: successful execution.
2095 - 1: an error occurred.
2168 - 1: an error occurred.
2096 """
2169 """
2097
2170
2098 # Set our own excepthook in case the user code tries to call it
2171 # Set our own excepthook in case the user code tries to call it
2099 # directly, so that the IPython crash handler doesn't get triggered
2172 # directly, so that the IPython crash handler doesn't get triggered
2100 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2173 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2101
2174
2102 # we save the original sys.excepthook in the instance, in case config
2175 # we save the original sys.excepthook in the instance, in case config
2103 # code (such as magics) needs access to it.
2176 # code (such as magics) needs access to it.
2104 self.sys_excepthook = old_excepthook
2177 self.sys_excepthook = old_excepthook
2105 outflag = 1 # happens in more places, so it's easier as default
2178 outflag = 1 # happens in more places, so it's easier as default
2106 try:
2179 try:
2107 try:
2180 try:
2108 self.hooks.pre_runcode_hook()
2181 self.hooks.pre_runcode_hook()
2109 exec code_obj in self.user_global_ns, self.user_ns
2182 exec code_obj in self.user_global_ns, self.user_ns
2110 finally:
2183 finally:
2111 # Reset our crash handler in place
2184 # Reset our crash handler in place
2112 sys.excepthook = old_excepthook
2185 sys.excepthook = old_excepthook
2113 except SystemExit:
2186 except SystemExit:
2114 self.resetbuffer()
2187 self.resetbuffer()
2115 self.showtraceback()
2188 self.showtraceback()
2116 warn("Type %exit or %quit to exit IPython "
2189 warn("Type %exit or %quit to exit IPython "
2117 "(%Exit or %Quit do so unconditionally).",level=1)
2190 "(%Exit or %Quit do so unconditionally).",level=1)
2118 except self.custom_exceptions:
2191 except self.custom_exceptions:
2119 etype,value,tb = sys.exc_info()
2192 etype,value,tb = sys.exc_info()
2120 self.CustomTB(etype,value,tb)
2193 self.CustomTB(etype,value,tb)
2121 except:
2194 except:
2122 self.showtraceback()
2195 self.showtraceback()
2123 else:
2196 else:
2124 outflag = 0
2197 outflag = 0
2125 if softspace(sys.stdout, 0):
2198 if softspace(sys.stdout, 0):
2126 print
2199 print
2127 # Flush out code object which has been run (and source)
2200 # Flush out code object which has been run (and source)
2128 self.code_to_run = None
2201 self.code_to_run = None
2129 return outflag
2202 return outflag
2130
2203
2131 def push(self, line):
2204 def push(self, line):
2132 """Push a line to the interpreter.
2205 """Push a line to the interpreter.
2133
2206
2134 The line should not have a trailing newline; it may have
2207 The line should not have a trailing newline; it may have
2135 internal newlines. The line is appended to a buffer and the
2208 internal newlines. The line is appended to a buffer and the
2136 interpreter's runsource() method is called with the
2209 interpreter's runsource() method is called with the
2137 concatenated contents of the buffer as source. If this
2210 concatenated contents of the buffer as source. If this
2138 indicates that the command was executed or invalid, the buffer
2211 indicates that the command was executed or invalid, the buffer
2139 is reset; otherwise, the command is incomplete, and the buffer
2212 is reset; otherwise, the command is incomplete, and the buffer
2140 is left as it was after the line was appended. The return
2213 is left as it was after the line was appended. The return
2141 value is 1 if more input is required, 0 if the line was dealt
2214 value is 1 if more input is required, 0 if the line was dealt
2142 with in some way (this is the same as runsource()).
2215 with in some way (this is the same as runsource()).
2143 """
2216 """
2144
2217
2145 # autoindent management should be done here, and not in the
2218 # autoindent management should be done here, and not in the
2146 # interactive loop, since that one is only seen by keyboard input. We
2219 # interactive loop, since that one is only seen by keyboard input. We
2147 # need this done correctly even for code run via runlines (which uses
2220 # need this done correctly even for code run via runlines (which uses
2148 # push).
2221 # push).
2149
2222
2150 #print 'push line: <%s>' % line # dbg
2223 #print 'push line: <%s>' % line # dbg
2151 for subline in line.splitlines():
2224 for subline in line.splitlines():
2152 self.autoindent_update(subline)
2225 self.autoindent_update(subline)
2153 self.buffer.append(line)
2226 self.buffer.append(line)
2154 more = self.runsource('\n'.join(self.buffer), self.filename)
2227 more = self.runsource('\n'.join(self.buffer), self.filename)
2155 if not more:
2228 if not more:
2156 self.resetbuffer()
2229 self.resetbuffer()
2157 return more
2230 return more
2158
2231
2159 def split_user_input(self, line):
2232 def split_user_input(self, line):
2160 # This is really a hold-over to support ipapi and some extensions
2233 # This is really a hold-over to support ipapi and some extensions
2161 return prefilter.splitUserInput(line)
2234 return prefilter.splitUserInput(line)
2162
2235
2163 def resetbuffer(self):
2236 def resetbuffer(self):
2164 """Reset the input buffer."""
2237 """Reset the input buffer."""
2165 self.buffer[:] = []
2238 self.buffer[:] = []
2166
2239
2167 def raw_input(self,prompt='',continue_prompt=False):
2240 def raw_input(self,prompt='',continue_prompt=False):
2168 """Write a prompt and read a line.
2241 """Write a prompt and read a line.
2169
2242
2170 The returned line does not include the trailing newline.
2243 The returned line does not include the trailing newline.
2171 When the user enters the EOF key sequence, EOFError is raised.
2244 When the user enters the EOF key sequence, EOFError is raised.
2172
2245
2173 Optional inputs:
2246 Optional inputs:
2174
2247
2175 - prompt(''): a string to be printed to prompt the user.
2248 - prompt(''): a string to be printed to prompt the user.
2176
2249
2177 - continue_prompt(False): whether this line is the first one or a
2250 - continue_prompt(False): whether this line is the first one or a
2178 continuation in a sequence of inputs.
2251 continuation in a sequence of inputs.
2179 """
2252 """
2180
2253
2181 # Code run by the user may have modified the readline completer state.
2254 # Code run by the user may have modified the readline completer state.
2182 # We must ensure that our completer is back in place.
2255 # We must ensure that our completer is back in place.
2183 if self.has_readline:
2256 if self.has_readline:
2184 self.set_completer()
2257 self.set_completer()
2185
2258
2186 try:
2259 try:
2187 line = raw_input_original(prompt).decode(self.stdin_encoding)
2260 line = raw_input_original(prompt).decode(self.stdin_encoding)
2188 except ValueError:
2261 except ValueError:
2189 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2262 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2190 " or sys.stdout.close()!\nExiting IPython!")
2263 " or sys.stdout.close()!\nExiting IPython!")
2191 self.ask_exit()
2264 self.ask_exit()
2192 return ""
2265 return ""
2193
2266
2194 # Try to be reasonably smart about not re-indenting pasted input more
2267 # Try to be reasonably smart about not re-indenting pasted input more
2195 # than necessary. We do this by trimming out the auto-indent initial
2268 # than necessary. We do this by trimming out the auto-indent initial
2196 # spaces, if the user's actual input started itself with whitespace.
2269 # spaces, if the user's actual input started itself with whitespace.
2197 #debugx('self.buffer[-1]')
2270 #debugx('self.buffer[-1]')
2198
2271
2199 if self.autoindent:
2272 if self.autoindent:
2200 if num_ini_spaces(line) > self.indent_current_nsp:
2273 if num_ini_spaces(line) > self.indent_current_nsp:
2201 line = line[self.indent_current_nsp:]
2274 line = line[self.indent_current_nsp:]
2202 self.indent_current_nsp = 0
2275 self.indent_current_nsp = 0
2203
2276
2204 # store the unfiltered input before the user has any chance to modify
2277 # store the unfiltered input before the user has any chance to modify
2205 # it.
2278 # it.
2206 if line.strip():
2279 if line.strip():
2207 if continue_prompt:
2280 if continue_prompt:
2208 self.input_hist_raw[-1] += '%s\n' % line
2281 self.input_hist_raw[-1] += '%s\n' % line
2209 if self.has_readline: # and some config option is set?
2282 if self.has_readline: # and some config option is set?
2210 try:
2283 try:
2211 histlen = self.readline.get_current_history_length()
2284 histlen = self.readline.get_current_history_length()
2212 if histlen > 1:
2285 if histlen > 1:
2213 newhist = self.input_hist_raw[-1].rstrip()
2286 newhist = self.input_hist_raw[-1].rstrip()
2214 self.readline.remove_history_item(histlen-1)
2287 self.readline.remove_history_item(histlen-1)
2215 self.readline.replace_history_item(histlen-2,
2288 self.readline.replace_history_item(histlen-2,
2216 newhist.encode(self.stdin_encoding))
2289 newhist.encode(self.stdin_encoding))
2217 except AttributeError:
2290 except AttributeError:
2218 pass # re{move,place}_history_item are new in 2.4.
2291 pass # re{move,place}_history_item are new in 2.4.
2219 else:
2292 else:
2220 self.input_hist_raw.append('%s\n' % line)
2293 self.input_hist_raw.append('%s\n' % line)
2221 # only entries starting at first column go to shadow history
2294 # only entries starting at first column go to shadow history
2222 if line.lstrip() == line:
2295 if line.lstrip() == line:
2223 self.shadowhist.add(line.strip())
2296 self.shadowhist.add(line.strip())
2224 elif not continue_prompt:
2297 elif not continue_prompt:
2225 self.input_hist_raw.append('\n')
2298 self.input_hist_raw.append('\n')
2226 try:
2299 try:
2227 lineout = self.prefilter(line,continue_prompt)
2300 lineout = self.prefilter(line,continue_prompt)
2228 except:
2301 except:
2229 # blanket except, in case a user-defined prefilter crashes, so it
2302 # blanket except, in case a user-defined prefilter crashes, so it
2230 # can't take all of ipython with it.
2303 # can't take all of ipython with it.
2231 self.showtraceback()
2304 self.showtraceback()
2232 return ''
2305 return ''
2233 else:
2306 else:
2234 return lineout
2307 return lineout
2235
2308
2236 def _prefilter(self, line, continue_prompt):
2309 def _prefilter(self, line, continue_prompt):
2237 """Calls different preprocessors, depending on the form of line."""
2310 """Calls different preprocessors, depending on the form of line."""
2238
2311
2239 # All handlers *must* return a value, even if it's blank ('').
2312 # All handlers *must* return a value, even if it's blank ('').
2240
2313
2241 # Lines are NOT logged here. Handlers should process the line as
2314 # Lines are NOT logged here. Handlers should process the line as
2242 # needed, update the cache AND log it (so that the input cache array
2315 # needed, update the cache AND log it (so that the input cache array
2243 # stays synced).
2316 # stays synced).
2244
2317
2245 #.....................................................................
2318 #.....................................................................
2246 # Code begins
2319 # Code begins
2247
2320
2248 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2321 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2249
2322
2250 # save the line away in case we crash, so the post-mortem handler can
2323 # save the line away in case we crash, so the post-mortem handler can
2251 # record it
2324 # record it
2252 self._last_input_line = line
2325 self._last_input_line = line
2253
2326
2254 #print '***line: <%s>' % line # dbg
2327 #print '***line: <%s>' % line # dbg
2255
2328
2256 if not line:
2329 if not line:
2257 # Return immediately on purely empty lines, so that if the user
2330 # Return immediately on purely empty lines, so that if the user
2258 # previously typed some whitespace that started a continuation
2331 # previously typed some whitespace that started a continuation
2259 # prompt, he can break out of that loop with just an empty line.
2332 # prompt, he can break out of that loop with just an empty line.
2260 # This is how the default python prompt works.
2333 # This is how the default python prompt works.
2261
2334
2262 # Only return if the accumulated input buffer was just whitespace!
2335 # Only return if the accumulated input buffer was just whitespace!
2263 if ''.join(self.buffer).isspace():
2336 if ''.join(self.buffer).isspace():
2264 self.buffer[:] = []
2337 self.buffer[:] = []
2265 return ''
2338 return ''
2266
2339
2267 line_info = prefilter.LineInfo(line, continue_prompt)
2340 line_info = prefilter.LineInfo(line, continue_prompt)
2268
2341
2269 # the input history needs to track even empty lines
2342 # the input history needs to track even empty lines
2270 stripped = line.strip()
2343 stripped = line.strip()
2271
2344
2272 if not stripped:
2345 if not stripped:
2273 if not continue_prompt:
2346 if not continue_prompt:
2274 self.outputcache.prompt_count -= 1
2347 self.outputcache.prompt_count -= 1
2275 return self.handle_normal(line_info)
2348 return self.handle_normal(line_info)
2276
2349
2277 # print '***cont',continue_prompt # dbg
2350 # print '***cont',continue_prompt # dbg
2278 # special handlers are only allowed for single line statements
2351 # special handlers are only allowed for single line statements
2279 if continue_prompt and not self.multi_line_specials:
2352 if continue_prompt and not self.multi_line_specials:
2280 return self.handle_normal(line_info)
2353 return self.handle_normal(line_info)
2281
2354
2282
2355
2283 # See whether any pre-existing handler can take care of it
2356 # See whether any pre-existing handler can take care of it
2284 rewritten = self.hooks.input_prefilter(stripped)
2357 rewritten = self.hooks.input_prefilter(stripped)
2285 if rewritten != stripped: # ok, some prefilter did something
2358 if rewritten != stripped: # ok, some prefilter did something
2286 rewritten = line_info.pre + rewritten # add indentation
2359 rewritten = line_info.pre + rewritten # add indentation
2287 return self.handle_normal(prefilter.LineInfo(rewritten,
2360 return self.handle_normal(prefilter.LineInfo(rewritten,
2288 continue_prompt))
2361 continue_prompt))
2289
2362
2290 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2363 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2291
2364
2292 return prefilter.prefilter(line_info, self)
2365 return prefilter.prefilter(line_info, self)
2293
2366
2294
2367
2295 def _prefilter_dumb(self, line, continue_prompt):
2368 def _prefilter_dumb(self, line, continue_prompt):
2296 """simple prefilter function, for debugging"""
2369 """simple prefilter function, for debugging"""
2297 return self.handle_normal(line,continue_prompt)
2370 return self.handle_normal(line,continue_prompt)
2298
2371
2299
2372
2300 def multiline_prefilter(self, line, continue_prompt):
2373 def multiline_prefilter(self, line, continue_prompt):
2301 """ Run _prefilter for each line of input
2374 """ Run _prefilter for each line of input
2302
2375
2303 Covers cases where there are multiple lines in the user entry,
2376 Covers cases where there are multiple lines in the user entry,
2304 which is the case when the user goes back to a multiline history
2377 which is the case when the user goes back to a multiline history
2305 entry and presses enter.
2378 entry and presses enter.
2306
2379
2307 """
2380 """
2308 out = []
2381 out = []
2309 for l in line.rstrip('\n').split('\n'):
2382 for l in line.rstrip('\n').split('\n'):
2310 out.append(self._prefilter(l, continue_prompt))
2383 out.append(self._prefilter(l, continue_prompt))
2311 return '\n'.join(out)
2384 return '\n'.join(out)
2312
2385
2313 # Set the default prefilter() function (this can be user-overridden)
2386 # Set the default prefilter() function (this can be user-overridden)
2314 prefilter = multiline_prefilter
2387 prefilter = multiline_prefilter
2315
2388
2316 def handle_normal(self,line_info):
2389 def handle_normal(self,line_info):
2317 """Handle normal input lines. Use as a template for handlers."""
2390 """Handle normal input lines. Use as a template for handlers."""
2318
2391
2319 # With autoindent on, we need some way to exit the input loop, and I
2392 # With autoindent on, we need some way to exit the input loop, and I
2320 # don't want to force the user to have to backspace all the way to
2393 # don't want to force the user to have to backspace all the way to
2321 # clear the line. The rule will be in this case, that either two
2394 # clear the line. The rule will be in this case, that either two
2322 # lines of pure whitespace in a row, or a line of pure whitespace but
2395 # lines of pure whitespace in a row, or a line of pure whitespace but
2323 # of a size different to the indent level, will exit the input loop.
2396 # of a size different to the indent level, will exit the input loop.
2324 line = line_info.line
2397 line = line_info.line
2325 continue_prompt = line_info.continue_prompt
2398 continue_prompt = line_info.continue_prompt
2326
2399
2327 if (continue_prompt and self.autoindent and line.isspace() and
2400 if (continue_prompt and self.autoindent and line.isspace() and
2328 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2401 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2329 (self.buffer[-1]).isspace() )):
2402 (self.buffer[-1]).isspace() )):
2330 line = ''
2403 line = ''
2331
2404
2332 self.log(line,line,continue_prompt)
2405 self.log(line,line,continue_prompt)
2333 return line
2406 return line
2334
2407
2335 def handle_alias(self,line_info):
2408 def handle_alias(self,line_info):
2336 """Handle alias input lines. """
2409 """Handle alias input lines. """
2337 tgt = self.alias_table[line_info.iFun]
2410 tgt = self.alias_table[line_info.iFun]
2338 # print "=>",tgt #dbg
2411 # print "=>",tgt #dbg
2339 if callable(tgt):
2412 if callable(tgt):
2340 if '$' in line_info.line:
2413 if '$' in line_info.line:
2341 call_meth = '(_ip, _ip.itpl(%s))'
2414 call_meth = '(_ip, _ip.itpl(%s))'
2342 else:
2415 else:
2343 call_meth = '(_ip,%s)'
2416 call_meth = '(_ip,%s)'
2344 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2417 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2345 line_info.iFun,
2418 line_info.iFun,
2346 make_quoted_expr(line_info.line))
2419 make_quoted_expr(line_info.line))
2347 else:
2420 else:
2348 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2421 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2349
2422
2350 # pre is needed, because it carries the leading whitespace. Otherwise
2423 # pre is needed, because it carries the leading whitespace. Otherwise
2351 # aliases won't work in indented sections.
2424 # aliases won't work in indented sections.
2352 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2425 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2353 make_quoted_expr( transformed ))
2426 make_quoted_expr( transformed ))
2354
2427
2355 self.log(line_info.line,line_out,line_info.continue_prompt)
2428 self.log(line_info.line,line_out,line_info.continue_prompt)
2356 #print 'line out:',line_out # dbg
2429 #print 'line out:',line_out # dbg
2357 return line_out
2430 return line_out
2358
2431
2359 def handle_shell_escape(self, line_info):
2432 def handle_shell_escape(self, line_info):
2360 """Execute the line in a shell, empty return value"""
2433 """Execute the line in a shell, empty return value"""
2361 #print 'line in :', `line` # dbg
2434 #print 'line in :', `line` # dbg
2362 line = line_info.line
2435 line = line_info.line
2363 if line.lstrip().startswith('!!'):
2436 if line.lstrip().startswith('!!'):
2364 # rewrite LineInfo's line, iFun and theRest to properly hold the
2437 # rewrite LineInfo's line, iFun and theRest to properly hold the
2365 # call to %sx and the actual command to be executed, so
2438 # call to %sx and the actual command to be executed, so
2366 # handle_magic can work correctly. Note that this works even if
2439 # handle_magic can work correctly. Note that this works even if
2367 # the line is indented, so it handles multi_line_specials
2440 # the line is indented, so it handles multi_line_specials
2368 # properly.
2441 # properly.
2369 new_rest = line.lstrip()[2:]
2442 new_rest = line.lstrip()[2:]
2370 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2443 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2371 line_info.iFun = 'sx'
2444 line_info.iFun = 'sx'
2372 line_info.theRest = new_rest
2445 line_info.theRest = new_rest
2373 return self.handle_magic(line_info)
2446 return self.handle_magic(line_info)
2374 else:
2447 else:
2375 cmd = line.lstrip().lstrip('!')
2448 cmd = line.lstrip().lstrip('!')
2376 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2449 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2377 make_quoted_expr(cmd))
2450 make_quoted_expr(cmd))
2378 # update cache/log and return
2451 # update cache/log and return
2379 self.log(line,line_out,line_info.continue_prompt)
2452 self.log(line,line_out,line_info.continue_prompt)
2380 return line_out
2453 return line_out
2381
2454
2382 def handle_magic(self, line_info):
2455 def handle_magic(self, line_info):
2383 """Execute magic functions."""
2456 """Execute magic functions."""
2384 iFun = line_info.iFun
2457 iFun = line_info.iFun
2385 theRest = line_info.theRest
2458 theRest = line_info.theRest
2386 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2459 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2387 make_quoted_expr(iFun + " " + theRest))
2460 make_quoted_expr(iFun + " " + theRest))
2388 self.log(line_info.line,cmd,line_info.continue_prompt)
2461 self.log(line_info.line,cmd,line_info.continue_prompt)
2389 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2462 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2390 return cmd
2463 return cmd
2391
2464
2392 def handle_auto(self, line_info):
2465 def handle_auto(self, line_info):
2393 """Hande lines which can be auto-executed, quoting if requested."""
2466 """Hande lines which can be auto-executed, quoting if requested."""
2394
2467
2395 line = line_info.line
2468 line = line_info.line
2396 iFun = line_info.iFun
2469 iFun = line_info.iFun
2397 theRest = line_info.theRest
2470 theRest = line_info.theRest
2398 pre = line_info.pre
2471 pre = line_info.pre
2399 continue_prompt = line_info.continue_prompt
2472 continue_prompt = line_info.continue_prompt
2400 obj = line_info.ofind(self)['obj']
2473 obj = line_info.ofind(self)['obj']
2401
2474
2402 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2475 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2403
2476
2404 # This should only be active for single-line input!
2477 # This should only be active for single-line input!
2405 if continue_prompt:
2478 if continue_prompt:
2406 self.log(line,line,continue_prompt)
2479 self.log(line,line,continue_prompt)
2407 return line
2480 return line
2408
2481
2409 force_auto = isinstance(obj, ipapi.IPyAutocall)
2482 force_auto = isinstance(obj, ipapi.IPyAutocall)
2410 auto_rewrite = True
2483 auto_rewrite = True
2411
2484
2412 if pre == self.ESC_QUOTE:
2485 if pre == self.ESC_QUOTE:
2413 # Auto-quote splitting on whitespace
2486 # Auto-quote splitting on whitespace
2414 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2487 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2415 elif pre == self.ESC_QUOTE2:
2488 elif pre == self.ESC_QUOTE2:
2416 # Auto-quote whole string
2489 # Auto-quote whole string
2417 newcmd = '%s("%s")' % (iFun,theRest)
2490 newcmd = '%s("%s")' % (iFun,theRest)
2418 elif pre == self.ESC_PAREN:
2491 elif pre == self.ESC_PAREN:
2419 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2492 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2420 else:
2493 else:
2421 # Auto-paren.
2494 # Auto-paren.
2422 # We only apply it to argument-less calls if the autocall
2495 # We only apply it to argument-less calls if the autocall
2423 # parameter is set to 2. We only need to check that autocall is <
2496 # parameter is set to 2. We only need to check that autocall is <
2424 # 2, since this function isn't called unless it's at least 1.
2497 # 2, since this function isn't called unless it's at least 1.
2425 if not theRest and (self.autocall < 2) and not force_auto:
2498 if not theRest and (self.autocall < 2) and not force_auto:
2426 newcmd = '%s %s' % (iFun,theRest)
2499 newcmd = '%s %s' % (iFun,theRest)
2427 auto_rewrite = False
2500 auto_rewrite = False
2428 else:
2501 else:
2429 if not force_auto and theRest.startswith('['):
2502 if not force_auto and theRest.startswith('['):
2430 if hasattr(obj,'__getitem__'):
2503 if hasattr(obj,'__getitem__'):
2431 # Don't autocall in this case: item access for an object
2504 # Don't autocall in this case: item access for an object
2432 # which is BOTH callable and implements __getitem__.
2505 # which is BOTH callable and implements __getitem__.
2433 newcmd = '%s %s' % (iFun,theRest)
2506 newcmd = '%s %s' % (iFun,theRest)
2434 auto_rewrite = False
2507 auto_rewrite = False
2435 else:
2508 else:
2436 # if the object doesn't support [] access, go ahead and
2509 # if the object doesn't support [] access, go ahead and
2437 # autocall
2510 # autocall
2438 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2511 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2439 elif theRest.endswith(';'):
2512 elif theRest.endswith(';'):
2440 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2513 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2441 else:
2514 else:
2442 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2515 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2443
2516
2444 if auto_rewrite:
2517 if auto_rewrite:
2445 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2518 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2446
2519
2447 try:
2520 try:
2448 # plain ascii works better w/ pyreadline, on some machines, so
2521 # plain ascii works better w/ pyreadline, on some machines, so
2449 # we use it and only print uncolored rewrite if we have unicode
2522 # we use it and only print uncolored rewrite if we have unicode
2450 rw = str(rw)
2523 rw = str(rw)
2451 print >>Term.cout, rw
2524 print >>Term.cout, rw
2452 except UnicodeEncodeError:
2525 except UnicodeEncodeError:
2453 print "-------------->" + newcmd
2526 print "-------------->" + newcmd
2454
2527
2455 # log what is now valid Python, not the actual user input (without the
2528 # log what is now valid Python, not the actual user input (without the
2456 # final newline)
2529 # final newline)
2457 self.log(line,newcmd,continue_prompt)
2530 self.log(line,newcmd,continue_prompt)
2458 return newcmd
2531 return newcmd
2459
2532
2460 def handle_help(self, line_info):
2533 def handle_help(self, line_info):
2461 """Try to get some help for the object.
2534 """Try to get some help for the object.
2462
2535
2463 obj? or ?obj -> basic information.
2536 obj? or ?obj -> basic information.
2464 obj?? or ??obj -> more details.
2537 obj?? or ??obj -> more details.
2465 """
2538 """
2466
2539
2467 line = line_info.line
2540 line = line_info.line
2468 # We need to make sure that we don't process lines which would be
2541 # We need to make sure that we don't process lines which would be
2469 # otherwise valid python, such as "x=1 # what?"
2542 # otherwise valid python, such as "x=1 # what?"
2470 try:
2543 try:
2471 codeop.compile_command(line)
2544 codeop.compile_command(line)
2472 except SyntaxError:
2545 except SyntaxError:
2473 # We should only handle as help stuff which is NOT valid syntax
2546 # We should only handle as help stuff which is NOT valid syntax
2474 if line[0]==self.ESC_HELP:
2547 if line[0]==self.ESC_HELP:
2475 line = line[1:]
2548 line = line[1:]
2476 elif line[-1]==self.ESC_HELP:
2549 elif line[-1]==self.ESC_HELP:
2477 line = line[:-1]
2550 line = line[:-1]
2478 self.log(line,'#?'+line,line_info.continue_prompt)
2551 self.log(line,'#?'+line,line_info.continue_prompt)
2479 if line:
2552 if line:
2480 #print 'line:<%r>' % line # dbg
2553 #print 'line:<%r>' % line # dbg
2481 self.magic_pinfo(line)
2554 self.magic_pinfo(line)
2482 else:
2555 else:
2483 page(self.usage,screen_lines=self.screen_length)
2556 page(self.usage,screen_lines=self.usable_screen_length)
2484 return '' # Empty string is needed here!
2557 return '' # Empty string is needed here!
2485 except:
2558 except:
2486 # Pass any other exceptions through to the normal handler
2559 # Pass any other exceptions through to the normal handler
2487 return self.handle_normal(line_info)
2560 return self.handle_normal(line_info)
2488 else:
2561 else:
2489 # If the code compiles ok, we should handle it normally
2562 # If the code compiles ok, we should handle it normally
2490 return self.handle_normal(line_info)
2563 return self.handle_normal(line_info)
2491
2564
2492 def getapi(self):
2565 def getapi(self):
2493 """ Get an IPApi object for this shell instance
2566 """ Get an IPApi object for this shell instance
2494
2567
2495 Getting an IPApi object is always preferable to accessing the shell
2568 Getting an IPApi object is always preferable to accessing the shell
2496 directly, but this holds true especially for extensions.
2569 directly, but this holds true especially for extensions.
2497
2570
2498 It should always be possible to implement an extension with IPApi
2571 It should always be possible to implement an extension with IPApi
2499 alone. If not, contact maintainer to request an addition.
2572 alone. If not, contact maintainer to request an addition.
2500
2573
2501 """
2574 """
2502 return self.api
2575 return self.api
2503
2576
2504 def handle_emacs(self, line_info):
2577 def handle_emacs(self, line_info):
2505 """Handle input lines marked by python-mode."""
2578 """Handle input lines marked by python-mode."""
2506
2579
2507 # Currently, nothing is done. Later more functionality can be added
2580 # Currently, nothing is done. Later more functionality can be added
2508 # here if needed.
2581 # here if needed.
2509
2582
2510 # The input cache shouldn't be updated
2583 # The input cache shouldn't be updated
2511 return line_info.line
2584 return line_info.line
2512
2585
2513 def var_expand(self,cmd,depth=0):
2586 def var_expand(self,cmd,depth=0):
2514 """Expand python variables in a string.
2587 """Expand python variables in a string.
2515
2588
2516 The depth argument indicates how many frames above the caller should
2589 The depth argument indicates how many frames above the caller should
2517 be walked to look for the local namespace where to expand variables.
2590 be walked to look for the local namespace where to expand variables.
2518
2591
2519 The global namespace for expansion is always the user's interactive
2592 The global namespace for expansion is always the user's interactive
2520 namespace.
2593 namespace.
2521 """
2594 """
2522
2595
2523 return str(ItplNS(cmd,
2596 return str(ItplNS(cmd,
2524 self.user_ns, # globals
2597 self.user_ns, # globals
2525 # Skip our own frame in searching for locals:
2598 # Skip our own frame in searching for locals:
2526 sys._getframe(depth+1).f_locals # locals
2599 sys._getframe(depth+1).f_locals # locals
2527 ))
2600 ))
2528
2601
2529 def mktempfile(self,data=None):
2602 def mktempfile(self,data=None):
2530 """Make a new tempfile and return its filename.
2603 """Make a new tempfile and return its filename.
2531
2604
2532 This makes a call to tempfile.mktemp, but it registers the created
2605 This makes a call to tempfile.mktemp, but it registers the created
2533 filename internally so ipython cleans it up at exit time.
2606 filename internally so ipython cleans it up at exit time.
2534
2607
2535 Optional inputs:
2608 Optional inputs:
2536
2609
2537 - data(None): if data is given, it gets written out to the temp file
2610 - data(None): if data is given, it gets written out to the temp file
2538 immediately, and the file is closed again."""
2611 immediately, and the file is closed again."""
2539
2612
2540 filename = tempfile.mktemp('.py','ipython_edit_')
2613 filename = tempfile.mktemp('.py','ipython_edit_')
2541 self.tempfiles.append(filename)
2614 self.tempfiles.append(filename)
2542
2615
2543 if data:
2616 if data:
2544 tmp_file = open(filename,'w')
2617 tmp_file = open(filename,'w')
2545 tmp_file.write(data)
2618 tmp_file.write(data)
2546 tmp_file.close()
2619 tmp_file.close()
2547 return filename
2620 return filename
2548
2621
2549 def write(self,data):
2622 def write(self,data):
2550 """Write a string to the default output"""
2623 """Write a string to the default output"""
2551 Term.cout.write(data)
2624 Term.cout.write(data)
2552
2625
2553 def write_err(self,data):
2626 def write_err(self,data):
2554 """Write a string to the default error output"""
2627 """Write a string to the default error output"""
2555 Term.cerr.write(data)
2628 Term.cerr.write(data)
2556
2629
2557 def ask_exit(self):
2630 def ask_exit(self):
2558 """ Call for exiting. Can be overiden and used as a callback. """
2631 """ Call for exiting. Can be overiden and used as a callback. """
2559 self.exit_now = True
2632 self.exit_now = True
2560
2633
2561 def exit(self):
2634 def exit(self):
2562 """Handle interactive exit.
2635 """Handle interactive exit.
2563
2636
2564 This method calls the ask_exit callback."""
2637 This method calls the ask_exit callback."""
2565 print "IN self.exit", self.confirm_exit
2566 if self.confirm_exit:
2638 if self.confirm_exit:
2567 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2639 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2568 self.ask_exit()
2640 self.ask_exit()
2569 else:
2641 else:
2570 self.ask_exit()
2642 self.ask_exit()
2571
2643
2572 def safe_execfile(self,fname,*where,**kw):
2644 def safe_execfile(self,fname,*where,**kw):
2573 """A safe version of the builtin execfile().
2645 """A safe version of the builtin execfile().
2574
2646
2575 This version will never throw an exception, and knows how to handle
2647 This version will never throw an exception, and knows how to handle
2576 ipython logs as well.
2648 ipython logs as well.
2577
2649
2578 :Parameters:
2650 :Parameters:
2579 fname : string
2651 fname : string
2580 Name of the file to be executed.
2652 Name of the file to be executed.
2581
2653
2582 where : tuple
2654 where : tuple
2583 One or two namespaces, passed to execfile() as (globals,locals).
2655 One or two namespaces, passed to execfile() as (globals,locals).
2584 If only one is given, it is passed as both.
2656 If only one is given, it is passed as both.
2585
2657
2586 :Keywords:
2658 :Keywords:
2587 islog : boolean (False)
2659 islog : boolean (False)
2588
2660
2589 quiet : boolean (True)
2661 quiet : boolean (True)
2590
2662
2591 exit_ignore : boolean (False)
2663 exit_ignore : boolean (False)
2592 """
2664 """
2593
2665
2594 def syspath_cleanup():
2666 def syspath_cleanup():
2595 """Internal cleanup routine for sys.path."""
2667 """Internal cleanup routine for sys.path."""
2596 if add_dname:
2668 if add_dname:
2597 try:
2669 try:
2598 sys.path.remove(dname)
2670 sys.path.remove(dname)
2599 except ValueError:
2671 except ValueError:
2600 # For some reason the user has already removed it, ignore.
2672 # For some reason the user has already removed it, ignore.
2601 pass
2673 pass
2602
2674
2603 fname = os.path.expanduser(fname)
2675 fname = os.path.expanduser(fname)
2604
2676
2605 # Find things also in current directory. This is needed to mimic the
2677 # Find things also in current directory. This is needed to mimic the
2606 # behavior of running a script from the system command line, where
2678 # behavior of running a script from the system command line, where
2607 # Python inserts the script's directory into sys.path
2679 # Python inserts the script's directory into sys.path
2608 dname = os.path.dirname(os.path.abspath(fname))
2680 dname = os.path.dirname(os.path.abspath(fname))
2609 add_dname = False
2681 add_dname = False
2610 if dname not in sys.path:
2682 if dname not in sys.path:
2611 sys.path.insert(0,dname)
2683 sys.path.insert(0,dname)
2612 add_dname = True
2684 add_dname = True
2613
2685
2614 try:
2686 try:
2615 xfile = open(fname)
2687 xfile = open(fname)
2616 except:
2688 except:
2617 print >> Term.cerr, \
2689 print >> Term.cerr, \
2618 'Could not open file <%s> for safe execution.' % fname
2690 'Could not open file <%s> for safe execution.' % fname
2619 syspath_cleanup()
2691 syspath_cleanup()
2620 return None
2692 return None
2621
2693
2622 kw.setdefault('islog',0)
2694 kw.setdefault('islog',0)
2623 kw.setdefault('quiet',1)
2695 kw.setdefault('quiet',1)
2624 kw.setdefault('exit_ignore',0)
2696 kw.setdefault('exit_ignore',0)
2625
2697
2626 first = xfile.readline()
2698 first = xfile.readline()
2627 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2699 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2628 xfile.close()
2700 xfile.close()
2629 # line by line execution
2701 # line by line execution
2630 if first.startswith(loghead) or kw['islog']:
2702 if first.startswith(loghead) or kw['islog']:
2631 print 'Loading log file <%s> one line at a time...' % fname
2703 print 'Loading log file <%s> one line at a time...' % fname
2632 if kw['quiet']:
2704 if kw['quiet']:
2633 stdout_save = sys.stdout
2705 stdout_save = sys.stdout
2634 sys.stdout = StringIO.StringIO()
2706 sys.stdout = StringIO.StringIO()
2635 try:
2707 try:
2636 globs,locs = where[0:2]
2708 globs,locs = where[0:2]
2637 except:
2709 except:
2638 try:
2710 try:
2639 globs = locs = where[0]
2711 globs = locs = where[0]
2640 except:
2712 except:
2641 globs = locs = globals()
2713 globs = locs = globals()
2642 badblocks = []
2714 badblocks = []
2643
2715
2644 # we also need to identify indented blocks of code when replaying
2716 # we also need to identify indented blocks of code when replaying
2645 # logs and put them together before passing them to an exec
2717 # logs and put them together before passing them to an exec
2646 # statement. This takes a bit of regexp and look-ahead work in the
2718 # statement. This takes a bit of regexp and look-ahead work in the
2647 # file. It's easiest if we swallow the whole thing in memory
2719 # file. It's easiest if we swallow the whole thing in memory
2648 # first, and manually walk through the lines list moving the
2720 # first, and manually walk through the lines list moving the
2649 # counter ourselves.
2721 # counter ourselves.
2650 indent_re = re.compile('\s+\S')
2722 indent_re = re.compile('\s+\S')
2651 xfile = open(fname)
2723 xfile = open(fname)
2652 filelines = xfile.readlines()
2724 filelines = xfile.readlines()
2653 xfile.close()
2725 xfile.close()
2654 nlines = len(filelines)
2726 nlines = len(filelines)
2655 lnum = 0
2727 lnum = 0
2656 while lnum < nlines:
2728 while lnum < nlines:
2657 line = filelines[lnum]
2729 line = filelines[lnum]
2658 lnum += 1
2730 lnum += 1
2659 # don't re-insert logger status info into cache
2731 # don't re-insert logger status info into cache
2660 if line.startswith('#log#'):
2732 if line.startswith('#log#'):
2661 continue
2733 continue
2662 else:
2734 else:
2663 # build a block of code (maybe a single line) for execution
2735 # build a block of code (maybe a single line) for execution
2664 block = line
2736 block = line
2665 try:
2737 try:
2666 next = filelines[lnum] # lnum has already incremented
2738 next = filelines[lnum] # lnum has already incremented
2667 except:
2739 except:
2668 next = None
2740 next = None
2669 while next and indent_re.match(next):
2741 while next and indent_re.match(next):
2670 block += next
2742 block += next
2671 lnum += 1
2743 lnum += 1
2672 try:
2744 try:
2673 next = filelines[lnum]
2745 next = filelines[lnum]
2674 except:
2746 except:
2675 next = None
2747 next = None
2676 # now execute the block of one or more lines
2748 # now execute the block of one or more lines
2677 try:
2749 try:
2678 exec block in globs,locs
2750 exec block in globs,locs
2679 except SystemExit:
2751 except SystemExit:
2680 pass
2752 pass
2681 except:
2753 except:
2682 badblocks.append(block.rstrip())
2754 badblocks.append(block.rstrip())
2683 if kw['quiet']: # restore stdout
2755 if kw['quiet']: # restore stdout
2684 sys.stdout.close()
2756 sys.stdout.close()
2685 sys.stdout = stdout_save
2757 sys.stdout = stdout_save
2686 print 'Finished replaying log file <%s>' % fname
2758 print 'Finished replaying log file <%s>' % fname
2687 if badblocks:
2759 if badblocks:
2688 print >> sys.stderr, ('\nThe following lines/blocks in file '
2760 print >> sys.stderr, ('\nThe following lines/blocks in file '
2689 '<%s> reported errors:' % fname)
2761 '<%s> reported errors:' % fname)
2690
2762
2691 for badline in badblocks:
2763 for badline in badblocks:
2692 print >> sys.stderr, badline
2764 print >> sys.stderr, badline
2693 else: # regular file execution
2765 else: # regular file execution
2694 try:
2766 try:
2695 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2767 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2696 # Work around a bug in Python for Windows. The bug was
2768 # Work around a bug in Python for Windows. The bug was
2697 # fixed in in Python 2.5 r54159 and 54158, but that's still
2769 # fixed in in Python 2.5 r54159 and 54158, but that's still
2698 # SVN Python as of March/07. For details, see:
2770 # SVN Python as of March/07. For details, see:
2699 # http://projects.scipy.org/ipython/ipython/ticket/123
2771 # http://projects.scipy.org/ipython/ipython/ticket/123
2700 try:
2772 try:
2701 globs,locs = where[0:2]
2773 globs,locs = where[0:2]
2702 except:
2774 except:
2703 try:
2775 try:
2704 globs = locs = where[0]
2776 globs = locs = where[0]
2705 except:
2777 except:
2706 globs = locs = globals()
2778 globs = locs = globals()
2707 exec file(fname) in globs,locs
2779 exec file(fname) in globs,locs
2708 else:
2780 else:
2709 execfile(fname,*where)
2781 execfile(fname,*where)
2710 except SyntaxError:
2782 except SyntaxError:
2711 self.showsyntaxerror()
2783 self.showsyntaxerror()
2712 warn('Failure executing file: <%s>' % fname)
2784 warn('Failure executing file: <%s>' % fname)
2713 except SystemExit,status:
2785 except SystemExit,status:
2714 # Code that correctly sets the exit status flag to success (0)
2786 # Code that correctly sets the exit status flag to success (0)
2715 # shouldn't be bothered with a traceback. Note that a plain
2787 # shouldn't be bothered with a traceback. Note that a plain
2716 # sys.exit() does NOT set the message to 0 (it's empty) so that
2788 # sys.exit() does NOT set the message to 0 (it's empty) so that
2717 # will still get a traceback. Note that the structure of the
2789 # will still get a traceback. Note that the structure of the
2718 # SystemExit exception changed between Python 2.4 and 2.5, so
2790 # SystemExit exception changed between Python 2.4 and 2.5, so
2719 # the checks must be done in a version-dependent way.
2791 # the checks must be done in a version-dependent way.
2720 show = False
2792 show = False
2721
2793
2722 if sys.version_info[:2] > (2,5):
2794 if sys.version_info[:2] > (2,5):
2723 if status.message!=0 and not kw['exit_ignore']:
2795 if status.message!=0 and not kw['exit_ignore']:
2724 show = True
2796 show = True
2725 else:
2797 else:
2726 if status.code and not kw['exit_ignore']:
2798 if status.code and not kw['exit_ignore']:
2727 show = True
2799 show = True
2728 if show:
2800 if show:
2729 self.showtraceback()
2801 self.showtraceback()
2730 warn('Failure executing file: <%s>' % fname)
2802 warn('Failure executing file: <%s>' % fname)
2731 except:
2803 except:
2732 self.showtraceback()
2804 self.showtraceback()
2733 warn('Failure executing file: <%s>' % fname)
2805 warn('Failure executing file: <%s>' % fname)
2734
2806
2735 syspath_cleanup()
2807 syspath_cleanup()
2736
2808
2737 #************************* end of file <iplib.py> *****************************
2809 #************************* end of file <iplib.py> *****************************
@@ -1,3588 +1,3588 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: 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-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import re
24 import re
25 import tempfile
25 import tempfile
26 import time
26 import time
27 import cPickle as pickle
27 import cPickle as pickle
28 import textwrap
28 import textwrap
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pprint, pformat
31 from pprint import pprint, pformat
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 # Homebrewed
44 # Homebrewed
45 import IPython
45 import IPython
46 from IPython.utils import wildcard
46 from IPython.utils import wildcard
47 from IPython.core import debugger, oinspect
47 from IPython.core import debugger, oinspect
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.utils.PyColorize import Parser
50 from IPython.utils.PyColorize import Parser
51 from IPython.utils.ipstruct import Struct
51 from IPython.utils.ipstruct import Struct
52 from IPython.core.macro import Macro
52 from IPython.core.macro import Macro
53 from IPython.utils.genutils import *
53 from IPython.utils.genutils import *
54 from IPython.utils import platutils
54 from IPython.utils import platutils
55 import IPython.utils.generics
55 import IPython.utils.generics
56 from IPython.core import ipapi
56 from IPython.core import ipapi
57 from IPython.core.ipapi import UsageError
57 from IPython.core.ipapi import UsageError
58 from IPython.testing import decorators as testdec
58 from IPython.testing import decorators as testdec
59
59
60 #***************************************************************************
60 #***************************************************************************
61 # Utility functions
61 # Utility functions
62 def on_off(tag):
62 def on_off(tag):
63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
64 return ['OFF','ON'][tag]
64 return ['OFF','ON'][tag]
65
65
66 class Bunch: pass
66 class Bunch: pass
67
67
68 def compress_dhist(dh):
68 def compress_dhist(dh):
69 head, tail = dh[:-10], dh[-10:]
69 head, tail = dh[:-10], dh[-10:]
70
70
71 newhead = []
71 newhead = []
72 done = set()
72 done = set()
73 for h in head:
73 for h in head:
74 if h in done:
74 if h in done:
75 continue
75 continue
76 newhead.append(h)
76 newhead.append(h)
77 done.add(h)
77 done.add(h)
78
78
79 return newhead + tail
79 return newhead + tail
80
80
81
81
82 #***************************************************************************
82 #***************************************************************************
83 # Main class implementing Magic functionality
83 # Main class implementing Magic functionality
84 class Magic:
84 class Magic:
85 """Magic functions for InteractiveShell.
85 """Magic functions for InteractiveShell.
86
86
87 Shell functions which can be reached as %function_name. All magic
87 Shell functions which can be reached as %function_name. All magic
88 functions should accept a string, which they can parse for their own
88 functions should accept a string, which they can parse for their own
89 needs. This can make some functions easier to type, eg `%cd ../`
89 needs. This can make some functions easier to type, eg `%cd ../`
90 vs. `%cd("../")`
90 vs. `%cd("../")`
91
91
92 ALL definitions MUST begin with the prefix magic_. The user won't need it
92 ALL definitions MUST begin with the prefix magic_. The user won't need it
93 at the command line, but it is is needed in the definition. """
93 at the command line, but it is is needed in the definition. """
94
94
95 # class globals
95 # class globals
96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
97 'Automagic is ON, % prefix NOT needed for magic functions.']
97 'Automagic is ON, % prefix NOT needed for magic functions.']
98
98
99 #......................................................................
99 #......................................................................
100 # some utility functions
100 # some utility functions
101
101
102 def __init__(self,shell):
102 def __init__(self,shell):
103
103
104 self.options_table = {}
104 self.options_table = {}
105 if profile is None:
105 if profile is None:
106 self.magic_prun = self.profile_missing_notice
106 self.magic_prun = self.profile_missing_notice
107 self.shell = shell
107 self.shell = shell
108
108
109 # namespace for holding state we may need
109 # namespace for holding state we may need
110 self._magic_state = Bunch()
110 self._magic_state = Bunch()
111
111
112 def profile_missing_notice(self, *args, **kwargs):
112 def profile_missing_notice(self, *args, **kwargs):
113 error("""\
113 error("""\
114 The profile module could not be found. It has been removed from the standard
114 The profile module could not be found. It has been removed from the standard
115 python packages because of its non-free license. To use profiling, install the
115 python packages because of its non-free license. To use profiling, install the
116 python-profiler package from non-free.""")
116 python-profiler package from non-free.""")
117
117
118 def default_option(self,fn,optstr):
118 def default_option(self,fn,optstr):
119 """Make an entry in the options_table for fn, with value optstr"""
119 """Make an entry in the options_table for fn, with value optstr"""
120
120
121 if fn not in self.lsmagic():
121 if fn not in self.lsmagic():
122 error("%s is not a magic function" % fn)
122 error("%s is not a magic function" % fn)
123 self.options_table[fn] = optstr
123 self.options_table[fn] = optstr
124
124
125 def lsmagic(self):
125 def lsmagic(self):
126 """Return a list of currently available magic functions.
126 """Return a list of currently available magic functions.
127
127
128 Gives a list of the bare names after mangling (['ls','cd', ...], not
128 Gives a list of the bare names after mangling (['ls','cd', ...], not
129 ['magic_ls','magic_cd',...]"""
129 ['magic_ls','magic_cd',...]"""
130
130
131 # FIXME. This needs a cleanup, in the way the magics list is built.
131 # FIXME. This needs a cleanup, in the way the magics list is built.
132
132
133 # magics in class definition
133 # magics in class definition
134 class_magic = lambda fn: fn.startswith('magic_') and \
134 class_magic = lambda fn: fn.startswith('magic_') and \
135 callable(Magic.__dict__[fn])
135 callable(Magic.__dict__[fn])
136 # in instance namespace (run-time user additions)
136 # in instance namespace (run-time user additions)
137 inst_magic = lambda fn: fn.startswith('magic_') and \
137 inst_magic = lambda fn: fn.startswith('magic_') and \
138 callable(self.__dict__[fn])
138 callable(self.__dict__[fn])
139 # and bound magics by user (so they can access self):
139 # and bound magics by user (so they can access self):
140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
141 callable(self.__class__.__dict__[fn])
141 callable(self.__class__.__dict__[fn])
142 magics = filter(class_magic,Magic.__dict__.keys()) + \
142 magics = filter(class_magic,Magic.__dict__.keys()) + \
143 filter(inst_magic,self.__dict__.keys()) + \
143 filter(inst_magic,self.__dict__.keys()) + \
144 filter(inst_bound_magic,self.__class__.__dict__.keys())
144 filter(inst_bound_magic,self.__class__.__dict__.keys())
145 out = []
145 out = []
146 for fn in set(magics):
146 for fn in set(magics):
147 out.append(fn.replace('magic_','',1))
147 out.append(fn.replace('magic_','',1))
148 out.sort()
148 out.sort()
149 return out
149 return out
150
150
151 def extract_input_slices(self,slices,raw=False):
151 def extract_input_slices(self,slices,raw=False):
152 """Return as a string a set of input history slices.
152 """Return as a string a set of input history slices.
153
153
154 Inputs:
154 Inputs:
155
155
156 - slices: the set of slices is given as a list of strings (like
156 - slices: the set of slices is given as a list of strings (like
157 ['1','4:8','9'], since this function is for use by magic functions
157 ['1','4:8','9'], since this function is for use by magic functions
158 which get their arguments as strings.
158 which get their arguments as strings.
159
159
160 Optional inputs:
160 Optional inputs:
161
161
162 - raw(False): by default, the processed input is used. If this is
162 - raw(False): by default, the processed input is used. If this is
163 true, the raw input history is used instead.
163 true, the raw input history is used instead.
164
164
165 Note that slices can be called with two notations:
165 Note that slices can be called with two notations:
166
166
167 N:M -> standard python form, means including items N...(M-1).
167 N:M -> standard python form, means including items N...(M-1).
168
168
169 N-M -> include items N..M (closed endpoint)."""
169 N-M -> include items N..M (closed endpoint)."""
170
170
171 if raw:
171 if raw:
172 hist = self.shell.input_hist_raw
172 hist = self.shell.input_hist_raw
173 else:
173 else:
174 hist = self.shell.input_hist
174 hist = self.shell.input_hist
175
175
176 cmds = []
176 cmds = []
177 for chunk in slices:
177 for chunk in slices:
178 if ':' in chunk:
178 if ':' in chunk:
179 ini,fin = map(int,chunk.split(':'))
179 ini,fin = map(int,chunk.split(':'))
180 elif '-' in chunk:
180 elif '-' in chunk:
181 ini,fin = map(int,chunk.split('-'))
181 ini,fin = map(int,chunk.split('-'))
182 fin += 1
182 fin += 1
183 else:
183 else:
184 ini = int(chunk)
184 ini = int(chunk)
185 fin = ini+1
185 fin = ini+1
186 cmds.append(hist[ini:fin])
186 cmds.append(hist[ini:fin])
187 return cmds
187 return cmds
188
188
189 def _ofind(self, oname, namespaces=None):
189 def _ofind(self, oname, namespaces=None):
190 """Find an object in the available namespaces.
190 """Find an object in the available namespaces.
191
191
192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
193
193
194 Has special code to detect magic functions.
194 Has special code to detect magic functions.
195 """
195 """
196
196
197 oname = oname.strip()
197 oname = oname.strip()
198
198
199 alias_ns = None
199 alias_ns = None
200 if namespaces is None:
200 if namespaces is None:
201 # Namespaces to search in:
201 # Namespaces to search in:
202 # Put them in a list. The order is important so that we
202 # Put them in a list. The order is important so that we
203 # find things in the same order that Python finds them.
203 # find things in the same order that Python finds them.
204 namespaces = [ ('Interactive', self.shell.user_ns),
204 namespaces = [ ('Interactive', self.shell.user_ns),
205 ('IPython internal', self.shell.internal_ns),
205 ('IPython internal', self.shell.internal_ns),
206 ('Python builtin', __builtin__.__dict__),
206 ('Python builtin', __builtin__.__dict__),
207 ('Alias', self.shell.alias_table),
207 ('Alias', self.shell.alias_table),
208 ]
208 ]
209 alias_ns = self.shell.alias_table
209 alias_ns = self.shell.alias_table
210
210
211 # initialize results to 'null'
211 # initialize results to 'null'
212 found = 0; obj = None; ospace = None; ds = None;
212 found = 0; obj = None; ospace = None; ds = None;
213 ismagic = 0; isalias = 0; parent = None
213 ismagic = 0; isalias = 0; parent = None
214
214
215 # Look for the given name by splitting it in parts. If the head is
215 # Look for the given name by splitting it in parts. If the head is
216 # found, then we look for all the remaining parts as members, and only
216 # found, then we look for all the remaining parts as members, and only
217 # declare success if we can find them all.
217 # declare success if we can find them all.
218 oname_parts = oname.split('.')
218 oname_parts = oname.split('.')
219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
220 for nsname,ns in namespaces:
220 for nsname,ns in namespaces:
221 try:
221 try:
222 obj = ns[oname_head]
222 obj = ns[oname_head]
223 except KeyError:
223 except KeyError:
224 continue
224 continue
225 else:
225 else:
226 #print 'oname_rest:', oname_rest # dbg
226 #print 'oname_rest:', oname_rest # dbg
227 for part in oname_rest:
227 for part in oname_rest:
228 try:
228 try:
229 parent = obj
229 parent = obj
230 obj = getattr(obj,part)
230 obj = getattr(obj,part)
231 except:
231 except:
232 # Blanket except b/c some badly implemented objects
232 # Blanket except b/c some badly implemented objects
233 # allow __getattr__ to raise exceptions other than
233 # allow __getattr__ to raise exceptions other than
234 # AttributeError, which then crashes IPython.
234 # AttributeError, which then crashes IPython.
235 break
235 break
236 else:
236 else:
237 # If we finish the for loop (no break), we got all members
237 # If we finish the for loop (no break), we got all members
238 found = 1
238 found = 1
239 ospace = nsname
239 ospace = nsname
240 if ns == alias_ns:
240 if ns == alias_ns:
241 isalias = 1
241 isalias = 1
242 break # namespace loop
242 break # namespace loop
243
243
244 # Try to see if it's magic
244 # Try to see if it's magic
245 if not found:
245 if not found:
246 if oname.startswith(self.shell.ESC_MAGIC):
246 if oname.startswith(self.shell.ESC_MAGIC):
247 oname = oname[1:]
247 oname = oname[1:]
248 obj = getattr(self,'magic_'+oname,None)
248 obj = getattr(self,'magic_'+oname,None)
249 if obj is not None:
249 if obj is not None:
250 found = 1
250 found = 1
251 ospace = 'IPython internal'
251 ospace = 'IPython internal'
252 ismagic = 1
252 ismagic = 1
253
253
254 # Last try: special-case some literals like '', [], {}, etc:
254 # Last try: special-case some literals like '', [], {}, etc:
255 if not found and oname_head in ["''",'""','[]','{}','()']:
255 if not found and oname_head in ["''",'""','[]','{}','()']:
256 obj = eval(oname_head)
256 obj = eval(oname_head)
257 found = 1
257 found = 1
258 ospace = 'Interactive'
258 ospace = 'Interactive'
259
259
260 return {'found':found, 'obj':obj, 'namespace':ospace,
260 return {'found':found, 'obj':obj, 'namespace':ospace,
261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
262
262
263 def arg_err(self,func):
263 def arg_err(self,func):
264 """Print docstring if incorrect arguments were passed"""
264 """Print docstring if incorrect arguments were passed"""
265 print 'Error in arguments:'
265 print 'Error in arguments:'
266 print OInspect.getdoc(func)
266 print OInspect.getdoc(func)
267
267
268 def format_latex(self,strng):
268 def format_latex(self,strng):
269 """Format a string for latex inclusion."""
269 """Format a string for latex inclusion."""
270
270
271 # Characters that need to be escaped for latex:
271 # Characters that need to be escaped for latex:
272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
273 # Magic command names as headers:
273 # Magic command names as headers:
274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
275 re.MULTILINE)
275 re.MULTILINE)
276 # Magic commands
276 # Magic commands
277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
278 re.MULTILINE)
278 re.MULTILINE)
279 # Paragraph continue
279 # Paragraph continue
280 par_re = re.compile(r'\\$',re.MULTILINE)
280 par_re = re.compile(r'\\$',re.MULTILINE)
281
281
282 # The "\n" symbol
282 # The "\n" symbol
283 newline_re = re.compile(r'\\n')
283 newline_re = re.compile(r'\\n')
284
284
285 # Now build the string for output:
285 # Now build the string for output:
286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
288 strng)
288 strng)
289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
290 strng = par_re.sub(r'\\\\',strng)
290 strng = par_re.sub(r'\\\\',strng)
291 strng = escape_re.sub(r'\\\1',strng)
291 strng = escape_re.sub(r'\\\1',strng)
292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
293 return strng
293 return strng
294
294
295 def format_screen(self,strng):
295 def format_screen(self,strng):
296 """Format a string for screen printing.
296 """Format a string for screen printing.
297
297
298 This removes some latex-type format codes."""
298 This removes some latex-type format codes."""
299 # Paragraph continue
299 # Paragraph continue
300 par_re = re.compile(r'\\$',re.MULTILINE)
300 par_re = re.compile(r'\\$',re.MULTILINE)
301 strng = par_re.sub('',strng)
301 strng = par_re.sub('',strng)
302 return strng
302 return strng
303
303
304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
305 """Parse options passed to an argument string.
305 """Parse options passed to an argument string.
306
306
307 The interface is similar to that of getopt(), but it returns back a
307 The interface is similar to that of getopt(), but it returns back a
308 Struct with the options as keys and the stripped argument string still
308 Struct with the options as keys and the stripped argument string still
309 as a string.
309 as a string.
310
310
311 arg_str is quoted as a true sys.argv vector by using shlex.split.
311 arg_str is quoted as a true sys.argv vector by using shlex.split.
312 This allows us to easily expand variables, glob files, quote
312 This allows us to easily expand variables, glob files, quote
313 arguments, etc.
313 arguments, etc.
314
314
315 Options:
315 Options:
316 -mode: default 'string'. If given as 'list', the argument string is
316 -mode: default 'string'. If given as 'list', the argument string is
317 returned as a list (split on whitespace) instead of a string.
317 returned as a list (split on whitespace) instead of a string.
318
318
319 -list_all: put all option values in lists. Normally only options
319 -list_all: put all option values in lists. Normally only options
320 appearing more than once are put in a list.
320 appearing more than once are put in a list.
321
321
322 -posix (True): whether to split the input line in POSIX mode or not,
322 -posix (True): whether to split the input line in POSIX mode or not,
323 as per the conventions outlined in the shlex module from the
323 as per the conventions outlined in the shlex module from the
324 standard library."""
324 standard library."""
325
325
326 # inject default options at the beginning of the input line
326 # inject default options at the beginning of the input line
327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
329
329
330 mode = kw.get('mode','string')
330 mode = kw.get('mode','string')
331 if mode not in ['string','list']:
331 if mode not in ['string','list']:
332 raise ValueError,'incorrect mode given: %s' % mode
332 raise ValueError,'incorrect mode given: %s' % mode
333 # Get options
333 # Get options
334 list_all = kw.get('list_all',0)
334 list_all = kw.get('list_all',0)
335 posix = kw.get('posix',True)
335 posix = kw.get('posix',True)
336
336
337 # Check if we have more than one argument to warrant extra processing:
337 # Check if we have more than one argument to warrant extra processing:
338 odict = {} # Dictionary with options
338 odict = {} # Dictionary with options
339 args = arg_str.split()
339 args = arg_str.split()
340 if len(args) >= 1:
340 if len(args) >= 1:
341 # If the list of inputs only has 0 or 1 thing in it, there's no
341 # If the list of inputs only has 0 or 1 thing in it, there's no
342 # need to look for options
342 # need to look for options
343 argv = arg_split(arg_str,posix)
343 argv = arg_split(arg_str,posix)
344 # Do regular option processing
344 # Do regular option processing
345 try:
345 try:
346 opts,args = getopt(argv,opt_str,*long_opts)
346 opts,args = getopt(argv,opt_str,*long_opts)
347 except GetoptError,e:
347 except GetoptError,e:
348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
349 " ".join(long_opts)))
349 " ".join(long_opts)))
350 for o,a in opts:
350 for o,a in opts:
351 if o.startswith('--'):
351 if o.startswith('--'):
352 o = o[2:]
352 o = o[2:]
353 else:
353 else:
354 o = o[1:]
354 o = o[1:]
355 try:
355 try:
356 odict[o].append(a)
356 odict[o].append(a)
357 except AttributeError:
357 except AttributeError:
358 odict[o] = [odict[o],a]
358 odict[o] = [odict[o],a]
359 except KeyError:
359 except KeyError:
360 if list_all:
360 if list_all:
361 odict[o] = [a]
361 odict[o] = [a]
362 else:
362 else:
363 odict[o] = a
363 odict[o] = a
364
364
365 # Prepare opts,args for return
365 # Prepare opts,args for return
366 opts = Struct(odict)
366 opts = Struct(odict)
367 if mode == 'string':
367 if mode == 'string':
368 args = ' '.join(args)
368 args = ' '.join(args)
369
369
370 return opts,args
370 return opts,args
371
371
372 #......................................................................
372 #......................................................................
373 # And now the actual magic functions
373 # And now the actual magic functions
374
374
375 # Functions for IPython shell work (vars,funcs, config, etc)
375 # Functions for IPython shell work (vars,funcs, config, etc)
376 def magic_lsmagic(self, parameter_s = ''):
376 def magic_lsmagic(self, parameter_s = ''):
377 """List currently available magic functions."""
377 """List currently available magic functions."""
378 mesc = self.shell.ESC_MAGIC
378 mesc = self.shell.ESC_MAGIC
379 print 'Available magic functions:\n'+mesc+\
379 print 'Available magic functions:\n'+mesc+\
380 (' '+mesc).join(self.lsmagic())
380 (' '+mesc).join(self.lsmagic())
381 print '\n' + Magic.auto_status[self.shell.automagic]
381 print '\n' + Magic.auto_status[self.shell.automagic]
382 return None
382 return None
383
383
384 def magic_magic(self, parameter_s = ''):
384 def magic_magic(self, parameter_s = ''):
385 """Print information about the magic function system.
385 """Print information about the magic function system.
386
386
387 Supported formats: -latex, -brief, -rest
387 Supported formats: -latex, -brief, -rest
388 """
388 """
389
389
390 mode = ''
390 mode = ''
391 try:
391 try:
392 if parameter_s.split()[0] == '-latex':
392 if parameter_s.split()[0] == '-latex':
393 mode = 'latex'
393 mode = 'latex'
394 if parameter_s.split()[0] == '-brief':
394 if parameter_s.split()[0] == '-brief':
395 mode = 'brief'
395 mode = 'brief'
396 if parameter_s.split()[0] == '-rest':
396 if parameter_s.split()[0] == '-rest':
397 mode = 'rest'
397 mode = 'rest'
398 rest_docs = []
398 rest_docs = []
399 except:
399 except:
400 pass
400 pass
401
401
402 magic_docs = []
402 magic_docs = []
403 for fname in self.lsmagic():
403 for fname in self.lsmagic():
404 mname = 'magic_' + fname
404 mname = 'magic_' + fname
405 for space in (Magic,self,self.__class__):
405 for space in (Magic,self,self.__class__):
406 try:
406 try:
407 fn = space.__dict__[mname]
407 fn = space.__dict__[mname]
408 except KeyError:
408 except KeyError:
409 pass
409 pass
410 else:
410 else:
411 break
411 break
412 if mode == 'brief':
412 if mode == 'brief':
413 # only first line
413 # only first line
414 if fn.__doc__:
414 if fn.__doc__:
415 fndoc = fn.__doc__.split('\n',1)[0]
415 fndoc = fn.__doc__.split('\n',1)[0]
416 else:
416 else:
417 fndoc = 'No documentation'
417 fndoc = 'No documentation'
418 else:
418 else:
419 if fn.__doc__:
419 if fn.__doc__:
420 fndoc = fn.__doc__.rstrip()
420 fndoc = fn.__doc__.rstrip()
421 else:
421 else:
422 fndoc = 'No documentation'
422 fndoc = 'No documentation'
423
423
424
424
425 if mode == 'rest':
425 if mode == 'rest':
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
427 fname,fndoc))
427 fname,fndoc))
428
428
429 else:
429 else:
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
431 fname,fndoc))
431 fname,fndoc))
432
432
433 magic_docs = ''.join(magic_docs)
433 magic_docs = ''.join(magic_docs)
434
434
435 if mode == 'rest':
435 if mode == 'rest':
436 return "".join(rest_docs)
436 return "".join(rest_docs)
437
437
438 if mode == 'latex':
438 if mode == 'latex':
439 print self.format_latex(magic_docs)
439 print self.format_latex(magic_docs)
440 return
440 return
441 else:
441 else:
442 magic_docs = self.format_screen(magic_docs)
442 magic_docs = self.format_screen(magic_docs)
443 if mode == 'brief':
443 if mode == 'brief':
444 return magic_docs
444 return magic_docs
445
445
446 outmsg = """
446 outmsg = """
447 IPython's 'magic' functions
447 IPython's 'magic' functions
448 ===========================
448 ===========================
449
449
450 The magic function system provides a series of functions which allow you to
450 The magic function system provides a series of functions which allow you to
451 control the behavior of IPython itself, plus a lot of system-type
451 control the behavior of IPython itself, plus a lot of system-type
452 features. All these functions are prefixed with a % character, but parameters
452 features. All these functions are prefixed with a % character, but parameters
453 are given without parentheses or quotes.
453 are given without parentheses or quotes.
454
454
455 NOTE: If you have 'automagic' enabled (via the command line option or with the
455 NOTE: If you have 'automagic' enabled (via the command line option or with the
456 %automagic function), you don't need to type in the % explicitly. By default,
456 %automagic function), you don't need to type in the % explicitly. By default,
457 IPython ships with automagic on, so you should only rarely need the % escape.
457 IPython ships with automagic on, so you should only rarely need the % escape.
458
458
459 Example: typing '%cd mydir' (without the quotes) changes you working directory
459 Example: typing '%cd mydir' (without the quotes) changes you working directory
460 to 'mydir', if it exists.
460 to 'mydir', if it exists.
461
461
462 You can define your own magic functions to extend the system. See the supplied
462 You can define your own magic functions to extend the system. See the supplied
463 ipythonrc and example-magic.py files for details (in your ipython
463 ipythonrc and example-magic.py files for details (in your ipython
464 configuration directory, typically $HOME/.ipython/).
464 configuration directory, typically $HOME/.ipython/).
465
465
466 You can also define your own aliased names for magic functions. In your
466 You can also define your own aliased names for magic functions. In your
467 ipythonrc file, placing a line like:
467 ipythonrc file, placing a line like:
468
468
469 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
469 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
470
470
471 will define %pf as a new name for %profile.
471 will define %pf as a new name for %profile.
472
472
473 You can also call magics in code using the ipmagic() function, which IPython
473 You can also call magics in code using the ipmagic() function, which IPython
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
475
475
476 For a list of the available magic functions, use %lsmagic. For a description
476 For a list of the available magic functions, use %lsmagic. For a description
477 of any of them, type %magic_name?, e.g. '%cd?'.
477 of any of them, type %magic_name?, e.g. '%cd?'.
478
478
479 Currently the magic system has the following functions:\n"""
479 Currently the magic system has the following functions:\n"""
480
480
481 mesc = self.shell.ESC_MAGIC
481 mesc = self.shell.ESC_MAGIC
482 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
483 "\n\n%s%s\n\n%s" % (outmsg,
483 "\n\n%s%s\n\n%s" % (outmsg,
484 magic_docs,mesc,mesc,
484 magic_docs,mesc,mesc,
485 (' '+mesc).join(self.lsmagic()),
485 (' '+mesc).join(self.lsmagic()),
486 Magic.auto_status[self.shell.automagic] ) )
486 Magic.auto_status[self.shell.automagic] ) )
487
487
488 page(outmsg,screen_lines=self.shell.screen_length)
488 page(outmsg,screen_lines=self.shell.usable_screen_length)
489
489
490
490
491 def magic_autoindent(self, parameter_s = ''):
491 def magic_autoindent(self, parameter_s = ''):
492 """Toggle autoindent on/off (if available)."""
492 """Toggle autoindent on/off (if available)."""
493
493
494 self.shell.set_autoindent()
494 self.shell.set_autoindent()
495 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
495 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
496
496
497
497
498 def magic_automagic(self, parameter_s = ''):
498 def magic_automagic(self, parameter_s = ''):
499 """Make magic functions callable without having to type the initial %.
499 """Make magic functions callable without having to type the initial %.
500
500
501 Without argumentsl toggles on/off (when off, you must call it as
501 Without argumentsl toggles on/off (when off, you must call it as
502 %automagic, of course). With arguments it sets the value, and you can
502 %automagic, of course). With arguments it sets the value, and you can
503 use any of (case insensitive):
503 use any of (case insensitive):
504
504
505 - on,1,True: to activate
505 - on,1,True: to activate
506
506
507 - off,0,False: to deactivate.
507 - off,0,False: to deactivate.
508
508
509 Note that magic functions have lowest priority, so if there's a
509 Note that magic functions have lowest priority, so if there's a
510 variable whose name collides with that of a magic fn, automagic won't
510 variable whose name collides with that of a magic fn, automagic won't
511 work for that function (you get the variable instead). However, if you
511 work for that function (you get the variable instead). However, if you
512 delete the variable (del var), the previously shadowed magic function
512 delete the variable (del var), the previously shadowed magic function
513 becomes visible to automagic again."""
513 becomes visible to automagic again."""
514
514
515 arg = parameter_s.lower()
515 arg = parameter_s.lower()
516 if parameter_s in ('on','1','true'):
516 if parameter_s in ('on','1','true'):
517 self.shell.automagic = True
517 self.shell.automagic = True
518 elif parameter_s in ('off','0','false'):
518 elif parameter_s in ('off','0','false'):
519 self.shell.automagic = False
519 self.shell.automagic = False
520 else:
520 else:
521 self.shell.automagic = not self.shell.automagic
521 self.shell.automagic = not self.shell.automagic
522 print '\n' + Magic.auto_status[self.shell.automagic]
522 print '\n' + Magic.auto_status[self.shell.automagic]
523
523
524 @testdec.skip_doctest
524 @testdec.skip_doctest
525 def magic_autocall(self, parameter_s = ''):
525 def magic_autocall(self, parameter_s = ''):
526 """Make functions callable without having to type parentheses.
526 """Make functions callable without having to type parentheses.
527
527
528 Usage:
528 Usage:
529
529
530 %autocall [mode]
530 %autocall [mode]
531
531
532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
533 value is toggled on and off (remembering the previous state).
533 value is toggled on and off (remembering the previous state).
534
534
535 In more detail, these values mean:
535 In more detail, these values mean:
536
536
537 0 -> fully disabled
537 0 -> fully disabled
538
538
539 1 -> active, but do not apply if there are no arguments on the line.
539 1 -> active, but do not apply if there are no arguments on the line.
540
540
541 In this mode, you get:
541 In this mode, you get:
542
542
543 In [1]: callable
543 In [1]: callable
544 Out[1]: <built-in function callable>
544 Out[1]: <built-in function callable>
545
545
546 In [2]: callable 'hello'
546 In [2]: callable 'hello'
547 ------> callable('hello')
547 ------> callable('hello')
548 Out[2]: False
548 Out[2]: False
549
549
550 2 -> Active always. Even if no arguments are present, the callable
550 2 -> Active always. Even if no arguments are present, the callable
551 object is called:
551 object is called:
552
552
553 In [2]: float
553 In [2]: float
554 ------> float()
554 ------> float()
555 Out[2]: 0.0
555 Out[2]: 0.0
556
556
557 Note that even with autocall off, you can still use '/' at the start of
557 Note that even with autocall off, you can still use '/' at the start of
558 a line to treat the first argument on the command line as a function
558 a line to treat the first argument on the command line as a function
559 and add parentheses to it:
559 and add parentheses to it:
560
560
561 In [8]: /str 43
561 In [8]: /str 43
562 ------> str(43)
562 ------> str(43)
563 Out[8]: '43'
563 Out[8]: '43'
564
564
565 # all-random (note for auto-testing)
565 # all-random (note for auto-testing)
566 """
566 """
567
567
568 if parameter_s:
568 if parameter_s:
569 arg = int(parameter_s)
569 arg = int(parameter_s)
570 else:
570 else:
571 arg = 'toggle'
571 arg = 'toggle'
572
572
573 if not arg in (0,1,2,'toggle'):
573 if not arg in (0,1,2,'toggle'):
574 error('Valid modes: (0->Off, 1->Smart, 2->Full')
574 error('Valid modes: (0->Off, 1->Smart, 2->Full')
575 return
575 return
576
576
577 if arg in (0,1,2):
577 if arg in (0,1,2):
578 self.shell.autocall = arg
578 self.shell.autocall = arg
579 else: # toggle
579 else: # toggle
580 if self.shell.autocall:
580 if self.shell.autocall:
581 self._magic_state.autocall_save = self.shell.autocall
581 self._magic_state.autocall_save = self.shell.autocall
582 self.shell.autocall = 0
582 self.shell.autocall = 0
583 else:
583 else:
584 try:
584 try:
585 self.shell.autocall = self._magic_state.autocall_save
585 self.shell.autocall = self._magic_state.autocall_save
586 except AttributeError:
586 except AttributeError:
587 self.shell.autocall = self._magic_state.autocall_save = 1
587 self.shell.autocall = self._magic_state.autocall_save = 1
588
588
589 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
589 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
590
590
591 def magic_system_verbose(self, parameter_s = ''):
591 def magic_system_verbose(self, parameter_s = ''):
592 """Set verbose printing of system calls.
592 """Set verbose printing of system calls.
593
593
594 If called without an argument, act as a toggle"""
594 If called without an argument, act as a toggle"""
595
595
596 if parameter_s:
596 if parameter_s:
597 val = bool(eval(parameter_s))
597 val = bool(eval(parameter_s))
598 else:
598 else:
599 val = None
599 val = None
600
600
601 if self.shell.system_verbose:
601 if self.shell.system_verbose:
602 self.shell.system_verbose = False
602 self.shell.system_verbose = False
603 else:
603 else:
604 self.shell.system_verbose = True
604 self.shell.system_verbose = True
605 print "System verbose printing is:",\
605 print "System verbose printing is:",\
606 ['OFF','ON'][self.shell.system_verbose]
606 ['OFF','ON'][self.shell.system_verbose]
607
607
608
608
609 def magic_page(self, parameter_s=''):
609 def magic_page(self, parameter_s=''):
610 """Pretty print the object and display it through a pager.
610 """Pretty print the object and display it through a pager.
611
611
612 %page [options] OBJECT
612 %page [options] OBJECT
613
613
614 If no object is given, use _ (last output).
614 If no object is given, use _ (last output).
615
615
616 Options:
616 Options:
617
617
618 -r: page str(object), don't pretty-print it."""
618 -r: page str(object), don't pretty-print it."""
619
619
620 # After a function contributed by Olivier Aubert, slightly modified.
620 # After a function contributed by Olivier Aubert, slightly modified.
621
621
622 # Process options/args
622 # Process options/args
623 opts,args = self.parse_options(parameter_s,'r')
623 opts,args = self.parse_options(parameter_s,'r')
624 raw = 'r' in opts
624 raw = 'r' in opts
625
625
626 oname = args and args or '_'
626 oname = args and args or '_'
627 info = self._ofind(oname)
627 info = self._ofind(oname)
628 if info['found']:
628 if info['found']:
629 txt = (raw and str or pformat)( info['obj'] )
629 txt = (raw and str or pformat)( info['obj'] )
630 page(txt)
630 page(txt)
631 else:
631 else:
632 print 'Object `%s` not found' % oname
632 print 'Object `%s` not found' % oname
633
633
634 def magic_profile(self, parameter_s=''):
634 def magic_profile(self, parameter_s=''):
635 """Print your currently active IPyhton profile."""
635 """Print your currently active IPyhton profile."""
636 if self.shell.profile:
636 if self.shell.profile:
637 printpl('Current IPython profile: $self.shell.profile.')
637 printpl('Current IPython profile: $self.shell.profile.')
638 else:
638 else:
639 print 'No profile active.'
639 print 'No profile active.'
640
640
641 def magic_pinfo(self, parameter_s='', namespaces=None):
641 def magic_pinfo(self, parameter_s='', namespaces=None):
642 """Provide detailed information about an object.
642 """Provide detailed information about an object.
643
643
644 '%pinfo object' is just a synonym for object? or ?object."""
644 '%pinfo object' is just a synonym for object? or ?object."""
645
645
646 #print 'pinfo par: <%s>' % parameter_s # dbg
646 #print 'pinfo par: <%s>' % parameter_s # dbg
647
647
648
648
649 # detail_level: 0 -> obj? , 1 -> obj??
649 # detail_level: 0 -> obj? , 1 -> obj??
650 detail_level = 0
650 detail_level = 0
651 # We need to detect if we got called as 'pinfo pinfo foo', which can
651 # We need to detect if we got called as 'pinfo pinfo foo', which can
652 # happen if the user types 'pinfo foo?' at the cmd line.
652 # happen if the user types 'pinfo foo?' at the cmd line.
653 pinfo,qmark1,oname,qmark2 = \
653 pinfo,qmark1,oname,qmark2 = \
654 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
654 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
655 if pinfo or qmark1 or qmark2:
655 if pinfo or qmark1 or qmark2:
656 detail_level = 1
656 detail_level = 1
657 if "*" in oname:
657 if "*" in oname:
658 self.magic_psearch(oname)
658 self.magic_psearch(oname)
659 else:
659 else:
660 self._inspect('pinfo', oname, detail_level=detail_level,
660 self._inspect('pinfo', oname, detail_level=detail_level,
661 namespaces=namespaces)
661 namespaces=namespaces)
662
662
663 def magic_pdef(self, parameter_s='', namespaces=None):
663 def magic_pdef(self, parameter_s='', namespaces=None):
664 """Print the definition header for any callable object.
664 """Print the definition header for any callable object.
665
665
666 If the object is a class, print the constructor information."""
666 If the object is a class, print the constructor information."""
667 self._inspect('pdef',parameter_s, namespaces)
667 self._inspect('pdef',parameter_s, namespaces)
668
668
669 def magic_pdoc(self, parameter_s='', namespaces=None):
669 def magic_pdoc(self, parameter_s='', namespaces=None):
670 """Print the docstring for an object.
670 """Print the docstring for an object.
671
671
672 If the given object is a class, it will print both the class and the
672 If the given object is a class, it will print both the class and the
673 constructor docstrings."""
673 constructor docstrings."""
674 self._inspect('pdoc',parameter_s, namespaces)
674 self._inspect('pdoc',parameter_s, namespaces)
675
675
676 def magic_psource(self, parameter_s='', namespaces=None):
676 def magic_psource(self, parameter_s='', namespaces=None):
677 """Print (or run through pager) the source code for an object."""
677 """Print (or run through pager) the source code for an object."""
678 self._inspect('psource',parameter_s, namespaces)
678 self._inspect('psource',parameter_s, namespaces)
679
679
680 def magic_pfile(self, parameter_s=''):
680 def magic_pfile(self, parameter_s=''):
681 """Print (or run through pager) the file where an object is defined.
681 """Print (or run through pager) the file where an object is defined.
682
682
683 The file opens at the line where the object definition begins. IPython
683 The file opens at the line where the object definition begins. IPython
684 will honor the environment variable PAGER if set, and otherwise will
684 will honor the environment variable PAGER if set, and otherwise will
685 do its best to print the file in a convenient form.
685 do its best to print the file in a convenient form.
686
686
687 If the given argument is not an object currently defined, IPython will
687 If the given argument is not an object currently defined, IPython will
688 try to interpret it as a filename (automatically adding a .py extension
688 try to interpret it as a filename (automatically adding a .py extension
689 if needed). You can thus use %pfile as a syntax highlighting code
689 if needed). You can thus use %pfile as a syntax highlighting code
690 viewer."""
690 viewer."""
691
691
692 # first interpret argument as an object name
692 # first interpret argument as an object name
693 out = self._inspect('pfile',parameter_s)
693 out = self._inspect('pfile',parameter_s)
694 # if not, try the input as a filename
694 # if not, try the input as a filename
695 if out == 'not found':
695 if out == 'not found':
696 try:
696 try:
697 filename = get_py_filename(parameter_s)
697 filename = get_py_filename(parameter_s)
698 except IOError,msg:
698 except IOError,msg:
699 print msg
699 print msg
700 return
700 return
701 page(self.shell.inspector.format(file(filename).read()))
701 page(self.shell.inspector.format(file(filename).read()))
702
702
703 def _inspect(self,meth,oname,namespaces=None,**kw):
703 def _inspect(self,meth,oname,namespaces=None,**kw):
704 """Generic interface to the inspector system.
704 """Generic interface to the inspector system.
705
705
706 This function is meant to be called by pdef, pdoc & friends."""
706 This function is meant to be called by pdef, pdoc & friends."""
707
707
708 #oname = oname.strip()
708 #oname = oname.strip()
709 #print '1- oname: <%r>' % oname # dbg
709 #print '1- oname: <%r>' % oname # dbg
710 try:
710 try:
711 oname = oname.strip().encode('ascii')
711 oname = oname.strip().encode('ascii')
712 #print '2- oname: <%r>' % oname # dbg
712 #print '2- oname: <%r>' % oname # dbg
713 except UnicodeEncodeError:
713 except UnicodeEncodeError:
714 print 'Python identifiers can only contain ascii characters.'
714 print 'Python identifiers can only contain ascii characters.'
715 return 'not found'
715 return 'not found'
716
716
717 info = Struct(self._ofind(oname, namespaces))
717 info = Struct(self._ofind(oname, namespaces))
718
718
719 if info.found:
719 if info.found:
720 try:
720 try:
721 IPython.utils.generics.inspect_object(info.obj)
721 IPython.utils.generics.inspect_object(info.obj)
722 return
722 return
723 except ipapi.TryNext:
723 except ipapi.TryNext:
724 pass
724 pass
725 # Get the docstring of the class property if it exists.
725 # Get the docstring of the class property if it exists.
726 path = oname.split('.')
726 path = oname.split('.')
727 root = '.'.join(path[:-1])
727 root = '.'.join(path[:-1])
728 if info.parent is not None:
728 if info.parent is not None:
729 try:
729 try:
730 target = getattr(info.parent, '__class__')
730 target = getattr(info.parent, '__class__')
731 # The object belongs to a class instance.
731 # The object belongs to a class instance.
732 try:
732 try:
733 target = getattr(target, path[-1])
733 target = getattr(target, path[-1])
734 # The class defines the object.
734 # The class defines the object.
735 if isinstance(target, property):
735 if isinstance(target, property):
736 oname = root + '.__class__.' + path[-1]
736 oname = root + '.__class__.' + path[-1]
737 info = Struct(self._ofind(oname))
737 info = Struct(self._ofind(oname))
738 except AttributeError: pass
738 except AttributeError: pass
739 except AttributeError: pass
739 except AttributeError: pass
740
740
741 pmethod = getattr(self.shell.inspector,meth)
741 pmethod = getattr(self.shell.inspector,meth)
742 formatter = info.ismagic and self.format_screen or None
742 formatter = info.ismagic and self.format_screen or None
743 if meth == 'pdoc':
743 if meth == 'pdoc':
744 pmethod(info.obj,oname,formatter)
744 pmethod(info.obj,oname,formatter)
745 elif meth == 'pinfo':
745 elif meth == 'pinfo':
746 pmethod(info.obj,oname,formatter,info,**kw)
746 pmethod(info.obj,oname,formatter,info,**kw)
747 else:
747 else:
748 pmethod(info.obj,oname)
748 pmethod(info.obj,oname)
749 else:
749 else:
750 print 'Object `%s` not found.' % oname
750 print 'Object `%s` not found.' % oname
751 return 'not found' # so callers can take other action
751 return 'not found' # so callers can take other action
752
752
753 def magic_psearch(self, parameter_s=''):
753 def magic_psearch(self, parameter_s=''):
754 """Search for object in namespaces by wildcard.
754 """Search for object in namespaces by wildcard.
755
755
756 %psearch [options] PATTERN [OBJECT TYPE]
756 %psearch [options] PATTERN [OBJECT TYPE]
757
757
758 Note: ? can be used as a synonym for %psearch, at the beginning or at
758 Note: ? can be used as a synonym for %psearch, at the beginning or at
759 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
759 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
760 rest of the command line must be unchanged (options come first), so
760 rest of the command line must be unchanged (options come first), so
761 for example the following forms are equivalent
761 for example the following forms are equivalent
762
762
763 %psearch -i a* function
763 %psearch -i a* function
764 -i a* function?
764 -i a* function?
765 ?-i a* function
765 ?-i a* function
766
766
767 Arguments:
767 Arguments:
768
768
769 PATTERN
769 PATTERN
770
770
771 where PATTERN is a string containing * as a wildcard similar to its
771 where PATTERN is a string containing * as a wildcard similar to its
772 use in a shell. The pattern is matched in all namespaces on the
772 use in a shell. The pattern is matched in all namespaces on the
773 search path. By default objects starting with a single _ are not
773 search path. By default objects starting with a single _ are not
774 matched, many IPython generated objects have a single
774 matched, many IPython generated objects have a single
775 underscore. The default is case insensitive matching. Matching is
775 underscore. The default is case insensitive matching. Matching is
776 also done on the attributes of objects and not only on the objects
776 also done on the attributes of objects and not only on the objects
777 in a module.
777 in a module.
778
778
779 [OBJECT TYPE]
779 [OBJECT TYPE]
780
780
781 Is the name of a python type from the types module. The name is
781 Is the name of a python type from the types module. The name is
782 given in lowercase without the ending type, ex. StringType is
782 given in lowercase without the ending type, ex. StringType is
783 written string. By adding a type here only objects matching the
783 written string. By adding a type here only objects matching the
784 given type are matched. Using all here makes the pattern match all
784 given type are matched. Using all here makes the pattern match all
785 types (this is the default).
785 types (this is the default).
786
786
787 Options:
787 Options:
788
788
789 -a: makes the pattern match even objects whose names start with a
789 -a: makes the pattern match even objects whose names start with a
790 single underscore. These names are normally ommitted from the
790 single underscore. These names are normally ommitted from the
791 search.
791 search.
792
792
793 -i/-c: make the pattern case insensitive/sensitive. If neither of
793 -i/-c: make the pattern case insensitive/sensitive. If neither of
794 these options is given, the default is read from your ipythonrc
794 these options is given, the default is read from your ipythonrc
795 file. The option name which sets this value is
795 file. The option name which sets this value is
796 'wildcards_case_sensitive'. If this option is not specified in your
796 'wildcards_case_sensitive'. If this option is not specified in your
797 ipythonrc file, IPython's internal default is to do a case sensitive
797 ipythonrc file, IPython's internal default is to do a case sensitive
798 search.
798 search.
799
799
800 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
800 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
801 specifiy can be searched in any of the following namespaces:
801 specifiy can be searched in any of the following namespaces:
802 'builtin', 'user', 'user_global','internal', 'alias', where
802 'builtin', 'user', 'user_global','internal', 'alias', where
803 'builtin' and 'user' are the search defaults. Note that you should
803 'builtin' and 'user' are the search defaults. Note that you should
804 not use quotes when specifying namespaces.
804 not use quotes when specifying namespaces.
805
805
806 'Builtin' contains the python module builtin, 'user' contains all
806 'Builtin' contains the python module builtin, 'user' contains all
807 user data, 'alias' only contain the shell aliases and no python
807 user data, 'alias' only contain the shell aliases and no python
808 objects, 'internal' contains objects used by IPython. The
808 objects, 'internal' contains objects used by IPython. The
809 'user_global' namespace is only used by embedded IPython instances,
809 'user_global' namespace is only used by embedded IPython instances,
810 and it contains module-level globals. You can add namespaces to the
810 and it contains module-level globals. You can add namespaces to the
811 search with -s or exclude them with -e (these options can be given
811 search with -s or exclude them with -e (these options can be given
812 more than once).
812 more than once).
813
813
814 Examples:
814 Examples:
815
815
816 %psearch a* -> objects beginning with an a
816 %psearch a* -> objects beginning with an a
817 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
817 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
818 %psearch a* function -> all functions beginning with an a
818 %psearch a* function -> all functions beginning with an a
819 %psearch re.e* -> objects beginning with an e in module re
819 %psearch re.e* -> objects beginning with an e in module re
820 %psearch r*.e* -> objects that start with e in modules starting in r
820 %psearch r*.e* -> objects that start with e in modules starting in r
821 %psearch r*.* string -> all strings in modules beginning with r
821 %psearch r*.* string -> all strings in modules beginning with r
822
822
823 Case sensitve search:
823 Case sensitve search:
824
824
825 %psearch -c a* list all object beginning with lower case a
825 %psearch -c a* list all object beginning with lower case a
826
826
827 Show objects beginning with a single _:
827 Show objects beginning with a single _:
828
828
829 %psearch -a _* list objects beginning with a single underscore"""
829 %psearch -a _* list objects beginning with a single underscore"""
830 try:
830 try:
831 parameter_s = parameter_s.encode('ascii')
831 parameter_s = parameter_s.encode('ascii')
832 except UnicodeEncodeError:
832 except UnicodeEncodeError:
833 print 'Python identifiers can only contain ascii characters.'
833 print 'Python identifiers can only contain ascii characters.'
834 return
834 return
835
835
836 # default namespaces to be searched
836 # default namespaces to be searched
837 def_search = ['user','builtin']
837 def_search = ['user','builtin']
838
838
839 # Process options/args
839 # Process options/args
840 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
840 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
841 opt = opts.get
841 opt = opts.get
842 shell = self.shell
842 shell = self.shell
843 psearch = shell.inspector.psearch
843 psearch = shell.inspector.psearch
844
844
845 # select case options
845 # select case options
846 if opts.has_key('i'):
846 if opts.has_key('i'):
847 ignore_case = True
847 ignore_case = True
848 elif opts.has_key('c'):
848 elif opts.has_key('c'):
849 ignore_case = False
849 ignore_case = False
850 else:
850 else:
851 ignore_case = not shell.wildcards_case_sensitive
851 ignore_case = not shell.wildcards_case_sensitive
852
852
853 # Build list of namespaces to search from user options
853 # Build list of namespaces to search from user options
854 def_search.extend(opt('s',[]))
854 def_search.extend(opt('s',[]))
855 ns_exclude = ns_exclude=opt('e',[])
855 ns_exclude = ns_exclude=opt('e',[])
856 ns_search = [nm for nm in def_search if nm not in ns_exclude]
856 ns_search = [nm for nm in def_search if nm not in ns_exclude]
857
857
858 # Call the actual search
858 # Call the actual search
859 try:
859 try:
860 psearch(args,shell.ns_table,ns_search,
860 psearch(args,shell.ns_table,ns_search,
861 show_all=opt('a'),ignore_case=ignore_case)
861 show_all=opt('a'),ignore_case=ignore_case)
862 except:
862 except:
863 shell.showtraceback()
863 shell.showtraceback()
864
864
865 def magic_who_ls(self, parameter_s=''):
865 def magic_who_ls(self, parameter_s=''):
866 """Return a sorted list of all interactive variables.
866 """Return a sorted list of all interactive variables.
867
867
868 If arguments are given, only variables of types matching these
868 If arguments are given, only variables of types matching these
869 arguments are returned."""
869 arguments are returned."""
870
870
871 user_ns = self.shell.user_ns
871 user_ns = self.shell.user_ns
872 internal_ns = self.shell.internal_ns
872 internal_ns = self.shell.internal_ns
873 user_config_ns = self.shell.user_config_ns
873 user_config_ns = self.shell.user_config_ns
874 out = []
874 out = []
875 typelist = parameter_s.split()
875 typelist = parameter_s.split()
876
876
877 for i in user_ns:
877 for i in user_ns:
878 if not (i.startswith('_') or i.startswith('_i')) \
878 if not (i.startswith('_') or i.startswith('_i')) \
879 and not (i in internal_ns or i in user_config_ns):
879 and not (i in internal_ns or i in user_config_ns):
880 if typelist:
880 if typelist:
881 if type(user_ns[i]).__name__ in typelist:
881 if type(user_ns[i]).__name__ in typelist:
882 out.append(i)
882 out.append(i)
883 else:
883 else:
884 out.append(i)
884 out.append(i)
885 out.sort()
885 out.sort()
886 return out
886 return out
887
887
888 def magic_who(self, parameter_s=''):
888 def magic_who(self, parameter_s=''):
889 """Print all interactive variables, with some minimal formatting.
889 """Print all interactive variables, with some minimal formatting.
890
890
891 If any arguments are given, only variables whose type matches one of
891 If any arguments are given, only variables whose type matches one of
892 these are printed. For example:
892 these are printed. For example:
893
893
894 %who function str
894 %who function str
895
895
896 will only list functions and strings, excluding all other types of
896 will only list functions and strings, excluding all other types of
897 variables. To find the proper type names, simply use type(var) at a
897 variables. To find the proper type names, simply use type(var) at a
898 command line to see how python prints type names. For example:
898 command line to see how python prints type names. For example:
899
899
900 In [1]: type('hello')\\
900 In [1]: type('hello')\\
901 Out[1]: <type 'str'>
901 Out[1]: <type 'str'>
902
902
903 indicates that the type name for strings is 'str'.
903 indicates that the type name for strings is 'str'.
904
904
905 %who always excludes executed names loaded through your configuration
905 %who always excludes executed names loaded through your configuration
906 file and things which are internal to IPython.
906 file and things which are internal to IPython.
907
907
908 This is deliberate, as typically you may load many modules and the
908 This is deliberate, as typically you may load many modules and the
909 purpose of %who is to show you only what you've manually defined."""
909 purpose of %who is to show you only what you've manually defined."""
910
910
911 varlist = self.magic_who_ls(parameter_s)
911 varlist = self.magic_who_ls(parameter_s)
912 if not varlist:
912 if not varlist:
913 if parameter_s:
913 if parameter_s:
914 print 'No variables match your requested type.'
914 print 'No variables match your requested type.'
915 else:
915 else:
916 print 'Interactive namespace is empty.'
916 print 'Interactive namespace is empty.'
917 return
917 return
918
918
919 # if we have variables, move on...
919 # if we have variables, move on...
920 count = 0
920 count = 0
921 for i in varlist:
921 for i in varlist:
922 print i+'\t',
922 print i+'\t',
923 count += 1
923 count += 1
924 if count > 8:
924 if count > 8:
925 count = 0
925 count = 0
926 print
926 print
927 print
927 print
928
928
929 def magic_whos(self, parameter_s=''):
929 def magic_whos(self, parameter_s=''):
930 """Like %who, but gives some extra information about each variable.
930 """Like %who, but gives some extra information about each variable.
931
931
932 The same type filtering of %who can be applied here.
932 The same type filtering of %who can be applied here.
933
933
934 For all variables, the type is printed. Additionally it prints:
934 For all variables, the type is printed. Additionally it prints:
935
935
936 - For {},[],(): their length.
936 - For {},[],(): their length.
937
937
938 - For numpy and Numeric arrays, a summary with shape, number of
938 - For numpy and Numeric arrays, a summary with shape, number of
939 elements, typecode and size in memory.
939 elements, typecode and size in memory.
940
940
941 - Everything else: a string representation, snipping their middle if
941 - Everything else: a string representation, snipping their middle if
942 too long."""
942 too long."""
943
943
944 varnames = self.magic_who_ls(parameter_s)
944 varnames = self.magic_who_ls(parameter_s)
945 if not varnames:
945 if not varnames:
946 if parameter_s:
946 if parameter_s:
947 print 'No variables match your requested type.'
947 print 'No variables match your requested type.'
948 else:
948 else:
949 print 'Interactive namespace is empty.'
949 print 'Interactive namespace is empty.'
950 return
950 return
951
951
952 # if we have variables, move on...
952 # if we have variables, move on...
953
953
954 # for these types, show len() instead of data:
954 # for these types, show len() instead of data:
955 seq_types = [types.DictType,types.ListType,types.TupleType]
955 seq_types = [types.DictType,types.ListType,types.TupleType]
956
956
957 # for numpy/Numeric arrays, display summary info
957 # for numpy/Numeric arrays, display summary info
958 try:
958 try:
959 import numpy
959 import numpy
960 except ImportError:
960 except ImportError:
961 ndarray_type = None
961 ndarray_type = None
962 else:
962 else:
963 ndarray_type = numpy.ndarray.__name__
963 ndarray_type = numpy.ndarray.__name__
964 try:
964 try:
965 import Numeric
965 import Numeric
966 except ImportError:
966 except ImportError:
967 array_type = None
967 array_type = None
968 else:
968 else:
969 array_type = Numeric.ArrayType.__name__
969 array_type = Numeric.ArrayType.__name__
970
970
971 # Find all variable names and types so we can figure out column sizes
971 # Find all variable names and types so we can figure out column sizes
972 def get_vars(i):
972 def get_vars(i):
973 return self.shell.user_ns[i]
973 return self.shell.user_ns[i]
974
974
975 # some types are well known and can be shorter
975 # some types are well known and can be shorter
976 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
976 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
977 def type_name(v):
977 def type_name(v):
978 tn = type(v).__name__
978 tn = type(v).__name__
979 return abbrevs.get(tn,tn)
979 return abbrevs.get(tn,tn)
980
980
981 varlist = map(get_vars,varnames)
981 varlist = map(get_vars,varnames)
982
982
983 typelist = []
983 typelist = []
984 for vv in varlist:
984 for vv in varlist:
985 tt = type_name(vv)
985 tt = type_name(vv)
986
986
987 if tt=='instance':
987 if tt=='instance':
988 typelist.append( abbrevs.get(str(vv.__class__),
988 typelist.append( abbrevs.get(str(vv.__class__),
989 str(vv.__class__)))
989 str(vv.__class__)))
990 else:
990 else:
991 typelist.append(tt)
991 typelist.append(tt)
992
992
993 # column labels and # of spaces as separator
993 # column labels and # of spaces as separator
994 varlabel = 'Variable'
994 varlabel = 'Variable'
995 typelabel = 'Type'
995 typelabel = 'Type'
996 datalabel = 'Data/Info'
996 datalabel = 'Data/Info'
997 colsep = 3
997 colsep = 3
998 # variable format strings
998 # variable format strings
999 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
999 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1000 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1000 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1001 aformat = "%s: %s elems, type `%s`, %s bytes"
1001 aformat = "%s: %s elems, type `%s`, %s bytes"
1002 # find the size of the columns to format the output nicely
1002 # find the size of the columns to format the output nicely
1003 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1003 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1004 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1004 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1005 # table header
1005 # table header
1006 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1006 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1007 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1007 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1008 # and the table itself
1008 # and the table itself
1009 kb = 1024
1009 kb = 1024
1010 Mb = 1048576 # kb**2
1010 Mb = 1048576 # kb**2
1011 for vname,var,vtype in zip(varnames,varlist,typelist):
1011 for vname,var,vtype in zip(varnames,varlist,typelist):
1012 print itpl(vformat),
1012 print itpl(vformat),
1013 if vtype in seq_types:
1013 if vtype in seq_types:
1014 print len(var)
1014 print len(var)
1015 elif vtype in [array_type,ndarray_type]:
1015 elif vtype in [array_type,ndarray_type]:
1016 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1016 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1017 if vtype==ndarray_type:
1017 if vtype==ndarray_type:
1018 # numpy
1018 # numpy
1019 vsize = var.size
1019 vsize = var.size
1020 vbytes = vsize*var.itemsize
1020 vbytes = vsize*var.itemsize
1021 vdtype = var.dtype
1021 vdtype = var.dtype
1022 else:
1022 else:
1023 # Numeric
1023 # Numeric
1024 vsize = Numeric.size(var)
1024 vsize = Numeric.size(var)
1025 vbytes = vsize*var.itemsize()
1025 vbytes = vsize*var.itemsize()
1026 vdtype = var.typecode()
1026 vdtype = var.typecode()
1027
1027
1028 if vbytes < 100000:
1028 if vbytes < 100000:
1029 print aformat % (vshape,vsize,vdtype,vbytes)
1029 print aformat % (vshape,vsize,vdtype,vbytes)
1030 else:
1030 else:
1031 print aformat % (vshape,vsize,vdtype,vbytes),
1031 print aformat % (vshape,vsize,vdtype,vbytes),
1032 if vbytes < Mb:
1032 if vbytes < Mb:
1033 print '(%s kb)' % (vbytes/kb,)
1033 print '(%s kb)' % (vbytes/kb,)
1034 else:
1034 else:
1035 print '(%s Mb)' % (vbytes/Mb,)
1035 print '(%s Mb)' % (vbytes/Mb,)
1036 else:
1036 else:
1037 try:
1037 try:
1038 vstr = str(var)
1038 vstr = str(var)
1039 except UnicodeEncodeError:
1039 except UnicodeEncodeError:
1040 vstr = unicode(var).encode(sys.getdefaultencoding(),
1040 vstr = unicode(var).encode(sys.getdefaultencoding(),
1041 'backslashreplace')
1041 'backslashreplace')
1042 vstr = vstr.replace('\n','\\n')
1042 vstr = vstr.replace('\n','\\n')
1043 if len(vstr) < 50:
1043 if len(vstr) < 50:
1044 print vstr
1044 print vstr
1045 else:
1045 else:
1046 printpl(vfmt_short)
1046 printpl(vfmt_short)
1047
1047
1048 def magic_reset(self, parameter_s=''):
1048 def magic_reset(self, parameter_s=''):
1049 """Resets the namespace by removing all names defined by the user.
1049 """Resets the namespace by removing all names defined by the user.
1050
1050
1051 Input/Output history are left around in case you need them.
1051 Input/Output history are left around in case you need them.
1052
1052
1053 Parameters
1053 Parameters
1054 ----------
1054 ----------
1055 -y : force reset without asking for confirmation.
1055 -y : force reset without asking for confirmation.
1056
1056
1057 Examples
1057 Examples
1058 --------
1058 --------
1059 In [6]: a = 1
1059 In [6]: a = 1
1060
1060
1061 In [7]: a
1061 In [7]: a
1062 Out[7]: 1
1062 Out[7]: 1
1063
1063
1064 In [8]: 'a' in _ip.user_ns
1064 In [8]: 'a' in _ip.user_ns
1065 Out[8]: True
1065 Out[8]: True
1066
1066
1067 In [9]: %reset -f
1067 In [9]: %reset -f
1068
1068
1069 In [10]: 'a' in _ip.user_ns
1069 In [10]: 'a' in _ip.user_ns
1070 Out[10]: False
1070 Out[10]: False
1071 """
1071 """
1072
1072
1073 if parameter_s == '-f':
1073 if parameter_s == '-f':
1074 ans = True
1074 ans = True
1075 else:
1075 else:
1076 ans = self.shell.ask_yes_no(
1076 ans = self.shell.ask_yes_no(
1077 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1077 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1078 if not ans:
1078 if not ans:
1079 print 'Nothing done.'
1079 print 'Nothing done.'
1080 return
1080 return
1081 user_ns = self.shell.user_ns
1081 user_ns = self.shell.user_ns
1082 for i in self.magic_who_ls():
1082 for i in self.magic_who_ls():
1083 del(user_ns[i])
1083 del(user_ns[i])
1084
1084
1085 # Also flush the private list of module references kept for script
1085 # Also flush the private list of module references kept for script
1086 # execution protection
1086 # execution protection
1087 self.shell.clear_main_mod_cache()
1087 self.shell.clear_main_mod_cache()
1088
1088
1089 def magic_logstart(self,parameter_s=''):
1089 def magic_logstart(self,parameter_s=''):
1090 """Start logging anywhere in a session.
1090 """Start logging anywhere in a session.
1091
1091
1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1093
1093
1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1095 current directory, in 'rotate' mode (see below).
1095 current directory, in 'rotate' mode (see below).
1096
1096
1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1098 history up to that point and then continues logging.
1098 history up to that point and then continues logging.
1099
1099
1100 %logstart takes a second optional parameter: logging mode. This can be one
1100 %logstart takes a second optional parameter: logging mode. This can be one
1101 of (note that the modes are given unquoted):\\
1101 of (note that the modes are given unquoted):\\
1102 append: well, that says it.\\
1102 append: well, that says it.\\
1103 backup: rename (if exists) to name~ and start name.\\
1103 backup: rename (if exists) to name~ and start name.\\
1104 global: single logfile in your home dir, appended to.\\
1104 global: single logfile in your home dir, appended to.\\
1105 over : overwrite existing log.\\
1105 over : overwrite existing log.\\
1106 rotate: create rotating logs name.1~, name.2~, etc.
1106 rotate: create rotating logs name.1~, name.2~, etc.
1107
1107
1108 Options:
1108 Options:
1109
1109
1110 -o: log also IPython's output. In this mode, all commands which
1110 -o: log also IPython's output. In this mode, all commands which
1111 generate an Out[NN] prompt are recorded to the logfile, right after
1111 generate an Out[NN] prompt are recorded to the logfile, right after
1112 their corresponding input line. The output lines are always
1112 their corresponding input line. The output lines are always
1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1114 Python code.
1114 Python code.
1115
1115
1116 Since this marker is always the same, filtering only the output from
1116 Since this marker is always the same, filtering only the output from
1117 a log is very easy, using for example a simple awk call:
1117 a log is very easy, using for example a simple awk call:
1118
1118
1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1120
1120
1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1122 input, so that user lines are logged in their final form, converted
1122 input, so that user lines are logged in their final form, converted
1123 into valid Python. For example, %Exit is logged as
1123 into valid Python. For example, %Exit is logged as
1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1125 exactly as typed, with no transformations applied.
1125 exactly as typed, with no transformations applied.
1126
1126
1127 -t: put timestamps before each input line logged (these are put in
1127 -t: put timestamps before each input line logged (these are put in
1128 comments)."""
1128 comments)."""
1129
1129
1130 opts,par = self.parse_options(parameter_s,'ort')
1130 opts,par = self.parse_options(parameter_s,'ort')
1131 log_output = 'o' in opts
1131 log_output = 'o' in opts
1132 log_raw_input = 'r' in opts
1132 log_raw_input = 'r' in opts
1133 timestamp = 't' in opts
1133 timestamp = 't' in opts
1134
1134
1135 logger = self.shell.logger
1135 logger = self.shell.logger
1136
1136
1137 # if no args are given, the defaults set in the logger constructor by
1137 # if no args are given, the defaults set in the logger constructor by
1138 # ipytohn remain valid
1138 # ipytohn remain valid
1139 if par:
1139 if par:
1140 try:
1140 try:
1141 logfname,logmode = par.split()
1141 logfname,logmode = par.split()
1142 except:
1142 except:
1143 logfname = par
1143 logfname = par
1144 logmode = 'backup'
1144 logmode = 'backup'
1145 else:
1145 else:
1146 logfname = logger.logfname
1146 logfname = logger.logfname
1147 logmode = logger.logmode
1147 logmode = logger.logmode
1148 # put logfname into rc struct as if it had been called on the command
1148 # put logfname into rc struct as if it had been called on the command
1149 # line, so it ends up saved in the log header Save it in case we need
1149 # line, so it ends up saved in the log header Save it in case we need
1150 # to restore it...
1150 # to restore it...
1151 old_logfile = self.shell.logfile
1151 old_logfile = self.shell.logfile
1152 if logfname:
1152 if logfname:
1153 logfname = os.path.expanduser(logfname)
1153 logfname = os.path.expanduser(logfname)
1154 self.shell.logfile = logfname
1154 self.shell.logfile = logfname
1155 # TODO: we need to re-think how logs with args/opts are replayed
1155 # TODO: we need to re-think how logs with args/opts are replayed
1156 # and tracked.
1156 # and tracked.
1157 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1157 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1158 loghead = self.shell.loghead_tpl % ('','')
1158 loghead = self.shell.loghead_tpl % ('','')
1159 try:
1159 try:
1160 started = logger.logstart(logfname,loghead,logmode,
1160 started = logger.logstart(logfname,loghead,logmode,
1161 log_output,timestamp,log_raw_input)
1161 log_output,timestamp,log_raw_input)
1162 except:
1162 except:
1163 rc.opts.logfile = old_logfile
1163 rc.opts.logfile = old_logfile
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 else:
1165 else:
1166 # log input history up to this point, optionally interleaving
1166 # log input history up to this point, optionally interleaving
1167 # output if requested
1167 # output if requested
1168
1168
1169 if timestamp:
1169 if timestamp:
1170 # disable timestamping for the previous history, since we've
1170 # disable timestamping for the previous history, since we've
1171 # lost those already (no time machine here).
1171 # lost those already (no time machine here).
1172 logger.timestamp = False
1172 logger.timestamp = False
1173
1173
1174 if log_raw_input:
1174 if log_raw_input:
1175 input_hist = self.shell.input_hist_raw
1175 input_hist = self.shell.input_hist_raw
1176 else:
1176 else:
1177 input_hist = self.shell.input_hist
1177 input_hist = self.shell.input_hist
1178
1178
1179 if log_output:
1179 if log_output:
1180 log_write = logger.log_write
1180 log_write = logger.log_write
1181 output_hist = self.shell.output_hist
1181 output_hist = self.shell.output_hist
1182 for n in range(1,len(input_hist)-1):
1182 for n in range(1,len(input_hist)-1):
1183 log_write(input_hist[n].rstrip())
1183 log_write(input_hist[n].rstrip())
1184 if n in output_hist:
1184 if n in output_hist:
1185 log_write(repr(output_hist[n]),'output')
1185 log_write(repr(output_hist[n]),'output')
1186 else:
1186 else:
1187 logger.log_write(input_hist[1:])
1187 logger.log_write(input_hist[1:])
1188 if timestamp:
1188 if timestamp:
1189 # re-enable timestamping
1189 # re-enable timestamping
1190 logger.timestamp = True
1190 logger.timestamp = True
1191
1191
1192 print ('Activating auto-logging. '
1192 print ('Activating auto-logging. '
1193 'Current session state plus future input saved.')
1193 'Current session state plus future input saved.')
1194 logger.logstate()
1194 logger.logstate()
1195
1195
1196 def magic_logstop(self,parameter_s=''):
1196 def magic_logstop(self,parameter_s=''):
1197 """Fully stop logging and close log file.
1197 """Fully stop logging and close log file.
1198
1198
1199 In order to start logging again, a new %logstart call needs to be made,
1199 In order to start logging again, a new %logstart call needs to be made,
1200 possibly (though not necessarily) with a new filename, mode and other
1200 possibly (though not necessarily) with a new filename, mode and other
1201 options."""
1201 options."""
1202 self.logger.logstop()
1202 self.logger.logstop()
1203
1203
1204 def magic_logoff(self,parameter_s=''):
1204 def magic_logoff(self,parameter_s=''):
1205 """Temporarily stop logging.
1205 """Temporarily stop logging.
1206
1206
1207 You must have previously started logging."""
1207 You must have previously started logging."""
1208 self.shell.logger.switch_log(0)
1208 self.shell.logger.switch_log(0)
1209
1209
1210 def magic_logon(self,parameter_s=''):
1210 def magic_logon(self,parameter_s=''):
1211 """Restart logging.
1211 """Restart logging.
1212
1212
1213 This function is for restarting logging which you've temporarily
1213 This function is for restarting logging which you've temporarily
1214 stopped with %logoff. For starting logging for the first time, you
1214 stopped with %logoff. For starting logging for the first time, you
1215 must use the %logstart function, which allows you to specify an
1215 must use the %logstart function, which allows you to specify an
1216 optional log filename."""
1216 optional log filename."""
1217
1217
1218 self.shell.logger.switch_log(1)
1218 self.shell.logger.switch_log(1)
1219
1219
1220 def magic_logstate(self,parameter_s=''):
1220 def magic_logstate(self,parameter_s=''):
1221 """Print the status of the logging system."""
1221 """Print the status of the logging system."""
1222
1222
1223 self.shell.logger.logstate()
1223 self.shell.logger.logstate()
1224
1224
1225 def magic_pdb(self, parameter_s=''):
1225 def magic_pdb(self, parameter_s=''):
1226 """Control the automatic calling of the pdb interactive debugger.
1226 """Control the automatic calling of the pdb interactive debugger.
1227
1227
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 argument it works as a toggle.
1229 argument it works as a toggle.
1230
1230
1231 When an exception is triggered, IPython can optionally call the
1231 When an exception is triggered, IPython can optionally call the
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1233 this feature on and off.
1233 this feature on and off.
1234
1234
1235 The initial state of this feature is set in your ipythonrc
1235 The initial state of this feature is set in your ipythonrc
1236 configuration file (the variable is called 'pdb').
1236 configuration file (the variable is called 'pdb').
1237
1237
1238 If you want to just activate the debugger AFTER an exception has fired,
1238 If you want to just activate the debugger AFTER an exception has fired,
1239 without having to type '%pdb on' and rerunning your code, you can use
1239 without having to type '%pdb on' and rerunning your code, you can use
1240 the %debug magic."""
1240 the %debug magic."""
1241
1241
1242 par = parameter_s.strip().lower()
1242 par = parameter_s.strip().lower()
1243
1243
1244 if par:
1244 if par:
1245 try:
1245 try:
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 except KeyError:
1247 except KeyError:
1248 print ('Incorrect argument. Use on/1, off/0, '
1248 print ('Incorrect argument. Use on/1, off/0, '
1249 'or nothing for a toggle.')
1249 'or nothing for a toggle.')
1250 return
1250 return
1251 else:
1251 else:
1252 # toggle
1252 # toggle
1253 new_pdb = not self.shell.call_pdb
1253 new_pdb = not self.shell.call_pdb
1254
1254
1255 # set on the shell
1255 # set on the shell
1256 self.shell.call_pdb = new_pdb
1256 self.shell.call_pdb = new_pdb
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258
1258
1259 def magic_debug(self, parameter_s=''):
1259 def magic_debug(self, parameter_s=''):
1260 """Activate the interactive debugger in post-mortem mode.
1260 """Activate the interactive debugger in post-mortem mode.
1261
1261
1262 If an exception has just occurred, this lets you inspect its stack
1262 If an exception has just occurred, this lets you inspect its stack
1263 frames interactively. Note that this will always work only on the last
1263 frames interactively. Note that this will always work only on the last
1264 traceback that occurred, so you must call this quickly after an
1264 traceback that occurred, so you must call this quickly after an
1265 exception that you wish to inspect has fired, because if another one
1265 exception that you wish to inspect has fired, because if another one
1266 occurs, it clobbers the previous one.
1266 occurs, it clobbers the previous one.
1267
1267
1268 If you want IPython to automatically do this on every exception, see
1268 If you want IPython to automatically do this on every exception, see
1269 the %pdb magic for more details.
1269 the %pdb magic for more details.
1270 """
1270 """
1271
1271
1272 self.shell.debugger(force=True)
1272 self.shell.debugger(force=True)
1273
1273
1274 @testdec.skip_doctest
1274 @testdec.skip_doctest
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1276 opts=None,arg_lst=None,prog_ns=None):
1276 opts=None,arg_lst=None,prog_ns=None):
1277
1277
1278 """Run a statement through the python code profiler.
1278 """Run a statement through the python code profiler.
1279
1279
1280 Usage:
1280 Usage:
1281 %prun [options] statement
1281 %prun [options] statement
1282
1282
1283 The given statement (which doesn't require quote marks) is run via the
1283 The given statement (which doesn't require quote marks) is run via the
1284 python profiler in a manner similar to the profile.run() function.
1284 python profiler in a manner similar to the profile.run() function.
1285 Namespaces are internally managed to work correctly; profile.run
1285 Namespaces are internally managed to work correctly; profile.run
1286 cannot be used in IPython because it makes certain assumptions about
1286 cannot be used in IPython because it makes certain assumptions about
1287 namespaces which do not hold under IPython.
1287 namespaces which do not hold under IPython.
1288
1288
1289 Options:
1289 Options:
1290
1290
1291 -l <limit>: you can place restrictions on what or how much of the
1291 -l <limit>: you can place restrictions on what or how much of the
1292 profile gets printed. The limit value can be:
1292 profile gets printed. The limit value can be:
1293
1293
1294 * A string: only information for function names containing this string
1294 * A string: only information for function names containing this string
1295 is printed.
1295 is printed.
1296
1296
1297 * An integer: only these many lines are printed.
1297 * An integer: only these many lines are printed.
1298
1298
1299 * A float (between 0 and 1): this fraction of the report is printed
1299 * A float (between 0 and 1): this fraction of the report is printed
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1301
1301
1302 You can combine several limits with repeated use of the option. For
1302 You can combine several limits with repeated use of the option. For
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1304 information about class constructors.
1304 information about class constructors.
1305
1305
1306 -r: return the pstats.Stats object generated by the profiling. This
1306 -r: return the pstats.Stats object generated by the profiling. This
1307 object has all the information about the profile in it, and you can
1307 object has all the information about the profile in it, and you can
1308 later use it for further analysis or in other functions.
1308 later use it for further analysis or in other functions.
1309
1309
1310 -s <key>: sort profile by given key. You can provide more than one key
1310 -s <key>: sort profile by given key. You can provide more than one key
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1312 default sorting key is 'time'.
1312 default sorting key is 'time'.
1313
1313
1314 The following is copied verbatim from the profile documentation
1314 The following is copied verbatim from the profile documentation
1315 referenced below:
1315 referenced below:
1316
1316
1317 When more than one key is provided, additional keys are used as
1317 When more than one key is provided, additional keys are used as
1318 secondary criteria when the there is equality in all keys selected
1318 secondary criteria when the there is equality in all keys selected
1319 before them.
1319 before them.
1320
1320
1321 Abbreviations can be used for any key names, as long as the
1321 Abbreviations can be used for any key names, as long as the
1322 abbreviation is unambiguous. The following are the keys currently
1322 abbreviation is unambiguous. The following are the keys currently
1323 defined:
1323 defined:
1324
1324
1325 Valid Arg Meaning
1325 Valid Arg Meaning
1326 "calls" call count
1326 "calls" call count
1327 "cumulative" cumulative time
1327 "cumulative" cumulative time
1328 "file" file name
1328 "file" file name
1329 "module" file name
1329 "module" file name
1330 "pcalls" primitive call count
1330 "pcalls" primitive call count
1331 "line" line number
1331 "line" line number
1332 "name" function name
1332 "name" function name
1333 "nfl" name/file/line
1333 "nfl" name/file/line
1334 "stdname" standard name
1334 "stdname" standard name
1335 "time" internal time
1335 "time" internal time
1336
1336
1337 Note that all sorts on statistics are in descending order (placing
1337 Note that all sorts on statistics are in descending order (placing
1338 most time consuming items first), where as name, file, and line number
1338 most time consuming items first), where as name, file, and line number
1339 searches are in ascending order (i.e., alphabetical). The subtle
1339 searches are in ascending order (i.e., alphabetical). The subtle
1340 distinction between "nfl" and "stdname" is that the standard name is a
1340 distinction between "nfl" and "stdname" is that the standard name is a
1341 sort of the name as printed, which means that the embedded line
1341 sort of the name as printed, which means that the embedded line
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1343 would (if the file names were the same) appear in the string order
1343 would (if the file names were the same) appear in the string order
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1345 line numbers. In fact, sort_stats("nfl") is the same as
1345 line numbers. In fact, sort_stats("nfl") is the same as
1346 sort_stats("name", "file", "line").
1346 sort_stats("name", "file", "line").
1347
1347
1348 -T <filename>: save profile results as shown on screen to a text
1348 -T <filename>: save profile results as shown on screen to a text
1349 file. The profile is still shown on screen.
1349 file. The profile is still shown on screen.
1350
1350
1351 -D <filename>: save (via dump_stats) profile statistics to given
1351 -D <filename>: save (via dump_stats) profile statistics to given
1352 filename. This data is in a format understod by the pstats module, and
1352 filename. This data is in a format understod by the pstats module, and
1353 is generated by a call to the dump_stats() method of profile
1353 is generated by a call to the dump_stats() method of profile
1354 objects. The profile is still shown on screen.
1354 objects. The profile is still shown on screen.
1355
1355
1356 If you want to run complete programs under the profiler's control, use
1356 If you want to run complete programs under the profiler's control, use
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1358 contains profiler specific options as described here.
1358 contains profiler specific options as described here.
1359
1359
1360 You can read the complete documentation for the profile module with::
1360 You can read the complete documentation for the profile module with::
1361
1361
1362 In [1]: import profile; profile.help()
1362 In [1]: import profile; profile.help()
1363 """
1363 """
1364
1364
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1366 # protect user quote marks
1366 # protect user quote marks
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1368
1368
1369 if user_mode: # regular user call
1369 if user_mode: # regular user call
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1371 list_all=1)
1371 list_all=1)
1372 namespace = self.shell.user_ns
1372 namespace = self.shell.user_ns
1373 else: # called to run a program by %run -p
1373 else: # called to run a program by %run -p
1374 try:
1374 try:
1375 filename = get_py_filename(arg_lst[0])
1375 filename = get_py_filename(arg_lst[0])
1376 except IOError,msg:
1376 except IOError,msg:
1377 error(msg)
1377 error(msg)
1378 return
1378 return
1379
1379
1380 arg_str = 'execfile(filename,prog_ns)'
1380 arg_str = 'execfile(filename,prog_ns)'
1381 namespace = locals()
1381 namespace = locals()
1382
1382
1383 opts.merge(opts_def)
1383 opts.merge(opts_def)
1384
1384
1385 prof = profile.Profile()
1385 prof = profile.Profile()
1386 try:
1386 try:
1387 prof = prof.runctx(arg_str,namespace,namespace)
1387 prof = prof.runctx(arg_str,namespace,namespace)
1388 sys_exit = ''
1388 sys_exit = ''
1389 except SystemExit:
1389 except SystemExit:
1390 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390 sys_exit = """*** SystemExit exception caught in code being profiled."""
1391
1391
1392 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1393
1393
1394 lims = opts.l
1394 lims = opts.l
1395 if lims:
1395 if lims:
1396 lims = [] # rebuild lims with ints/floats/strings
1396 lims = [] # rebuild lims with ints/floats/strings
1397 for lim in opts.l:
1397 for lim in opts.l:
1398 try:
1398 try:
1399 lims.append(int(lim))
1399 lims.append(int(lim))
1400 except ValueError:
1400 except ValueError:
1401 try:
1401 try:
1402 lims.append(float(lim))
1402 lims.append(float(lim))
1403 except ValueError:
1403 except ValueError:
1404 lims.append(lim)
1404 lims.append(lim)
1405
1405
1406 # Trap output.
1406 # Trap output.
1407 stdout_trap = StringIO()
1407 stdout_trap = StringIO()
1408
1408
1409 if hasattr(stats,'stream'):
1409 if hasattr(stats,'stream'):
1410 # In newer versions of python, the stats object has a 'stream'
1410 # In newer versions of python, the stats object has a 'stream'
1411 # attribute to write into.
1411 # attribute to write into.
1412 stats.stream = stdout_trap
1412 stats.stream = stdout_trap
1413 stats.print_stats(*lims)
1413 stats.print_stats(*lims)
1414 else:
1414 else:
1415 # For older versions, we manually redirect stdout during printing
1415 # For older versions, we manually redirect stdout during printing
1416 sys_stdout = sys.stdout
1416 sys_stdout = sys.stdout
1417 try:
1417 try:
1418 sys.stdout = stdout_trap
1418 sys.stdout = stdout_trap
1419 stats.print_stats(*lims)
1419 stats.print_stats(*lims)
1420 finally:
1420 finally:
1421 sys.stdout = sys_stdout
1421 sys.stdout = sys_stdout
1422
1422
1423 output = stdout_trap.getvalue()
1423 output = stdout_trap.getvalue()
1424 output = output.rstrip()
1424 output = output.rstrip()
1425
1425
1426 page(output,screen_lines=self.shell.screen_length)
1426 page(output,screen_lines=self.shell.usable_screen_length)
1427 print sys_exit,
1427 print sys_exit,
1428
1428
1429 dump_file = opts.D[0]
1429 dump_file = opts.D[0]
1430 text_file = opts.T[0]
1430 text_file = opts.T[0]
1431 if dump_file:
1431 if dump_file:
1432 prof.dump_stats(dump_file)
1432 prof.dump_stats(dump_file)
1433 print '\n*** Profile stats marshalled to file',\
1433 print '\n*** Profile stats marshalled to file',\
1434 `dump_file`+'.',sys_exit
1434 `dump_file`+'.',sys_exit
1435 if text_file:
1435 if text_file:
1436 pfile = file(text_file,'w')
1436 pfile = file(text_file,'w')
1437 pfile.write(output)
1437 pfile.write(output)
1438 pfile.close()
1438 pfile.close()
1439 print '\n*** Profile printout saved to text file',\
1439 print '\n*** Profile printout saved to text file',\
1440 `text_file`+'.',sys_exit
1440 `text_file`+'.',sys_exit
1441
1441
1442 if opts.has_key('r'):
1442 if opts.has_key('r'):
1443 return stats
1443 return stats
1444 else:
1444 else:
1445 return None
1445 return None
1446
1446
1447 @testdec.skip_doctest
1447 @testdec.skip_doctest
1448 def magic_run(self, parameter_s ='',runner=None,
1448 def magic_run(self, parameter_s ='',runner=None,
1449 file_finder=get_py_filename):
1449 file_finder=get_py_filename):
1450 """Run the named file inside IPython as a program.
1450 """Run the named file inside IPython as a program.
1451
1451
1452 Usage:\\
1452 Usage:\\
1453 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1454
1454
1455 Parameters after the filename are passed as command-line arguments to
1455 Parameters after the filename are passed as command-line arguments to
1456 the program (put in sys.argv). Then, control returns to IPython's
1456 the program (put in sys.argv). Then, control returns to IPython's
1457 prompt.
1457 prompt.
1458
1458
1459 This is similar to running at a system prompt:\\
1459 This is similar to running at a system prompt:\\
1460 $ python file args\\
1460 $ python file args\\
1461 but with the advantage of giving you IPython's tracebacks, and of
1461 but with the advantage of giving you IPython's tracebacks, and of
1462 loading all variables into your interactive namespace for further use
1462 loading all variables into your interactive namespace for further use
1463 (unless -p is used, see below).
1463 (unless -p is used, see below).
1464
1464
1465 The file is executed in a namespace initially consisting only of
1465 The file is executed in a namespace initially consisting only of
1466 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 __name__=='__main__' and sys.argv constructed as indicated. It thus
1467 sees its environment as if it were being run as a stand-alone program
1467 sees its environment as if it were being run as a stand-alone program
1468 (except for sharing global objects such as previously imported
1468 (except for sharing global objects such as previously imported
1469 modules). But after execution, the IPython interactive namespace gets
1469 modules). But after execution, the IPython interactive namespace gets
1470 updated with all variables defined in the program (except for __name__
1470 updated with all variables defined in the program (except for __name__
1471 and sys.argv). This allows for very convenient loading of code for
1471 and sys.argv). This allows for very convenient loading of code for
1472 interactive work, while giving each program a 'clean sheet' to run in.
1472 interactive work, while giving each program a 'clean sheet' to run in.
1473
1473
1474 Options:
1474 Options:
1475
1475
1476 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 -n: __name__ is NOT set to '__main__', but to the running file's name
1477 without extension (as python does under import). This allows running
1477 without extension (as python does under import). This allows running
1478 scripts and reloading the definitions in them without calling code
1478 scripts and reloading the definitions in them without calling code
1479 protected by an ' if __name__ == "__main__" ' clause.
1479 protected by an ' if __name__ == "__main__" ' clause.
1480
1480
1481 -i: run the file in IPython's namespace instead of an empty one. This
1481 -i: run the file in IPython's namespace instead of an empty one. This
1482 is useful if you are experimenting with code written in a text editor
1482 is useful if you are experimenting with code written in a text editor
1483 which depends on variables defined interactively.
1483 which depends on variables defined interactively.
1484
1484
1485 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1486 being run. This is particularly useful if IPython is being used to
1486 being run. This is particularly useful if IPython is being used to
1487 run unittests, which always exit with a sys.exit() call. In such
1487 run unittests, which always exit with a sys.exit() call. In such
1488 cases you are interested in the output of the test results, not in
1488 cases you are interested in the output of the test results, not in
1489 seeing a traceback of the unittest module.
1489 seeing a traceback of the unittest module.
1490
1490
1491 -t: print timing information at the end of the run. IPython will give
1491 -t: print timing information at the end of the run. IPython will give
1492 you an estimated CPU time consumption for your script, which under
1492 you an estimated CPU time consumption for your script, which under
1493 Unix uses the resource module to avoid the wraparound problems of
1493 Unix uses the resource module to avoid the wraparound problems of
1494 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 time.clock(). Under Unix, an estimate of time spent on system tasks
1495 is also given (for Windows platforms this is reported as 0.0).
1495 is also given (for Windows platforms this is reported as 0.0).
1496
1496
1497 If -t is given, an additional -N<N> option can be given, where <N>
1497 If -t is given, an additional -N<N> option can be given, where <N>
1498 must be an integer indicating how many times you want the script to
1498 must be an integer indicating how many times you want the script to
1499 run. The final timing report will include total and per run results.
1499 run. The final timing report will include total and per run results.
1500
1500
1501 For example (testing the script uniq_stable.py):
1501 For example (testing the script uniq_stable.py):
1502
1502
1503 In [1]: run -t uniq_stable
1503 In [1]: run -t uniq_stable
1504
1504
1505 IPython CPU timings (estimated):\\
1505 IPython CPU timings (estimated):\\
1506 User : 0.19597 s.\\
1506 User : 0.19597 s.\\
1507 System: 0.0 s.\\
1507 System: 0.0 s.\\
1508
1508
1509 In [2]: run -t -N5 uniq_stable
1509 In [2]: run -t -N5 uniq_stable
1510
1510
1511 IPython CPU timings (estimated):\\
1511 IPython CPU timings (estimated):\\
1512 Total runs performed: 5\\
1512 Total runs performed: 5\\
1513 Times : Total Per run\\
1513 Times : Total Per run\\
1514 User : 0.910862 s, 0.1821724 s.\\
1514 User : 0.910862 s, 0.1821724 s.\\
1515 System: 0.0 s, 0.0 s.
1515 System: 0.0 s, 0.0 s.
1516
1516
1517 -d: run your program under the control of pdb, the Python debugger.
1517 -d: run your program under the control of pdb, the Python debugger.
1518 This allows you to execute your program step by step, watch variables,
1518 This allows you to execute your program step by step, watch variables,
1519 etc. Internally, what IPython does is similar to calling:
1519 etc. Internally, what IPython does is similar to calling:
1520
1520
1521 pdb.run('execfile("YOURFILENAME")')
1521 pdb.run('execfile("YOURFILENAME")')
1522
1522
1523 with a breakpoint set on line 1 of your file. You can change the line
1523 with a breakpoint set on line 1 of your file. You can change the line
1524 number for this automatic breakpoint to be <N> by using the -bN option
1524 number for this automatic breakpoint to be <N> by using the -bN option
1525 (where N must be an integer). For example:
1525 (where N must be an integer). For example:
1526
1526
1527 %run -d -b40 myscript
1527 %run -d -b40 myscript
1528
1528
1529 will set the first breakpoint at line 40 in myscript.py. Note that
1529 will set the first breakpoint at line 40 in myscript.py. Note that
1530 the first breakpoint must be set on a line which actually does
1530 the first breakpoint must be set on a line which actually does
1531 something (not a comment or docstring) for it to stop execution.
1531 something (not a comment or docstring) for it to stop execution.
1532
1532
1533 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1534 first enter 'c' (without qoutes) to start execution up to the first
1534 first enter 'c' (without qoutes) to start execution up to the first
1535 breakpoint.
1535 breakpoint.
1536
1536
1537 Entering 'help' gives information about the use of the debugger. You
1537 Entering 'help' gives information about the use of the debugger. You
1538 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 can easily see pdb's full documentation with "import pdb;pdb.help()"
1539 at a prompt.
1539 at a prompt.
1540
1540
1541 -p: run program under the control of the Python profiler module (which
1541 -p: run program under the control of the Python profiler module (which
1542 prints a detailed report of execution times, function calls, etc).
1542 prints a detailed report of execution times, function calls, etc).
1543
1543
1544 You can pass other options after -p which affect the behavior of the
1544 You can pass other options after -p which affect the behavior of the
1545 profiler itself. See the docs for %prun for details.
1545 profiler itself. See the docs for %prun for details.
1546
1546
1547 In this mode, the program's variables do NOT propagate back to the
1547 In this mode, the program's variables do NOT propagate back to the
1548 IPython interactive namespace (because they remain in the namespace
1548 IPython interactive namespace (because they remain in the namespace
1549 where the profiler executes them).
1549 where the profiler executes them).
1550
1550
1551 Internally this triggers a call to %prun, see its documentation for
1551 Internally this triggers a call to %prun, see its documentation for
1552 details on the options available specifically for profiling.
1552 details on the options available specifically for profiling.
1553
1553
1554 There is one special usage for which the text above doesn't apply:
1554 There is one special usage for which the text above doesn't apply:
1555 if the filename ends with .ipy, the file is run as ipython script,
1555 if the filename ends with .ipy, the file is run as ipython script,
1556 just as if the commands were written on IPython prompt.
1556 just as if the commands were written on IPython prompt.
1557 """
1557 """
1558
1558
1559 # get arguments and set sys.argv for program to be run.
1559 # get arguments and set sys.argv for program to be run.
1560 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1561 mode='list',list_all=1)
1561 mode='list',list_all=1)
1562
1562
1563 try:
1563 try:
1564 filename = file_finder(arg_lst[0])
1564 filename = file_finder(arg_lst[0])
1565 except IndexError:
1565 except IndexError:
1566 warn('you must provide at least a filename.')
1566 warn('you must provide at least a filename.')
1567 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1568 return
1568 return
1569 except IOError,msg:
1569 except IOError,msg:
1570 error(msg)
1570 error(msg)
1571 return
1571 return
1572
1572
1573 if filename.lower().endswith('.ipy'):
1573 if filename.lower().endswith('.ipy'):
1574 self.api.runlines(open(filename).read())
1574 self.api.runlines(open(filename).read())
1575 return
1575 return
1576
1576
1577 # Control the response to exit() calls made by the script being run
1577 # Control the response to exit() calls made by the script being run
1578 exit_ignore = opts.has_key('e')
1578 exit_ignore = opts.has_key('e')
1579
1579
1580 # Make sure that the running script gets a proper sys.argv as if it
1580 # Make sure that the running script gets a proper sys.argv as if it
1581 # were run from a system shell.
1581 # were run from a system shell.
1582 save_argv = sys.argv # save it for later restoring
1582 save_argv = sys.argv # save it for later restoring
1583 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1584
1584
1585 if opts.has_key('i'):
1585 if opts.has_key('i'):
1586 # Run in user's interactive namespace
1586 # Run in user's interactive namespace
1587 prog_ns = self.shell.user_ns
1587 prog_ns = self.shell.user_ns
1588 __name__save = self.shell.user_ns['__name__']
1588 __name__save = self.shell.user_ns['__name__']
1589 prog_ns['__name__'] = '__main__'
1589 prog_ns['__name__'] = '__main__'
1590 main_mod = self.shell.new_main_mod(prog_ns)
1590 main_mod = self.shell.new_main_mod(prog_ns)
1591 else:
1591 else:
1592 # Run in a fresh, empty namespace
1592 # Run in a fresh, empty namespace
1593 if opts.has_key('n'):
1593 if opts.has_key('n'):
1594 name = os.path.splitext(os.path.basename(filename))[0]
1594 name = os.path.splitext(os.path.basename(filename))[0]
1595 else:
1595 else:
1596 name = '__main__'
1596 name = '__main__'
1597
1597
1598 main_mod = self.shell.new_main_mod()
1598 main_mod = self.shell.new_main_mod()
1599 prog_ns = main_mod.__dict__
1599 prog_ns = main_mod.__dict__
1600 prog_ns['__name__'] = name
1600 prog_ns['__name__'] = name
1601
1601
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1603 # set the __file__ global in the script's namespace
1603 # set the __file__ global in the script's namespace
1604 prog_ns['__file__'] = filename
1604 prog_ns['__file__'] = filename
1605
1605
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1607 # that, if we overwrite __main__, we replace it at the end
1607 # that, if we overwrite __main__, we replace it at the end
1608 main_mod_name = prog_ns['__name__']
1608 main_mod_name = prog_ns['__name__']
1609
1609
1610 if main_mod_name == '__main__':
1610 if main_mod_name == '__main__':
1611 restore_main = sys.modules['__main__']
1611 restore_main = sys.modules['__main__']
1612 else:
1612 else:
1613 restore_main = False
1613 restore_main = False
1614
1614
1615 # This needs to be undone at the end to prevent holding references to
1615 # This needs to be undone at the end to prevent holding references to
1616 # every single object ever created.
1616 # every single object ever created.
1617 sys.modules[main_mod_name] = main_mod
1617 sys.modules[main_mod_name] = main_mod
1618
1618
1619 stats = None
1619 stats = None
1620 try:
1620 try:
1621 self.shell.savehist()
1621 self.shell.savehist()
1622
1622
1623 if opts.has_key('p'):
1623 if opts.has_key('p'):
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1625 else:
1625 else:
1626 if opts.has_key('d'):
1626 if opts.has_key('d'):
1627 deb = debugger.Pdb(self.shell.colors)
1627 deb = debugger.Pdb(self.shell.colors)
1628 # reset Breakpoint state, which is moronically kept
1628 # reset Breakpoint state, which is moronically kept
1629 # in a class
1629 # in a class
1630 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.next = 1
1631 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bplist = {}
1632 bdb.Breakpoint.bpbynumber = [None]
1632 bdb.Breakpoint.bpbynumber = [None]
1633 # Set an initial breakpoint to stop execution
1633 # Set an initial breakpoint to stop execution
1634 maxtries = 10
1634 maxtries = 10
1635 bp = int(opts.get('b',[1])[0])
1635 bp = int(opts.get('b',[1])[0])
1636 checkline = deb.checkline(filename,bp)
1636 checkline = deb.checkline(filename,bp)
1637 if not checkline:
1637 if not checkline:
1638 for bp in range(bp+1,bp+maxtries+1):
1638 for bp in range(bp+1,bp+maxtries+1):
1639 if deb.checkline(filename,bp):
1639 if deb.checkline(filename,bp):
1640 break
1640 break
1641 else:
1641 else:
1642 msg = ("\nI failed to find a valid line to set "
1642 msg = ("\nI failed to find a valid line to set "
1643 "a breakpoint\n"
1643 "a breakpoint\n"
1644 "after trying up to line: %s.\n"
1644 "after trying up to line: %s.\n"
1645 "Please set a valid breakpoint manually "
1645 "Please set a valid breakpoint manually "
1646 "with the -b option." % bp)
1646 "with the -b option." % bp)
1647 error(msg)
1647 error(msg)
1648 return
1648 return
1649 # if we find a good linenumber, set the breakpoint
1649 # if we find a good linenumber, set the breakpoint
1650 deb.do_break('%s:%s' % (filename,bp))
1650 deb.do_break('%s:%s' % (filename,bp))
1651 # Start file run
1651 # Start file run
1652 print "NOTE: Enter 'c' at the",
1652 print "NOTE: Enter 'c' at the",
1653 print "%s prompt to start your script." % deb.prompt
1653 print "%s prompt to start your script." % deb.prompt
1654 try:
1654 try:
1655 deb.run('execfile("%s")' % filename,prog_ns)
1655 deb.run('execfile("%s")' % filename,prog_ns)
1656
1656
1657 except:
1657 except:
1658 etype, value, tb = sys.exc_info()
1658 etype, value, tb = sys.exc_info()
1659 # Skip three frames in the traceback: the %run one,
1659 # Skip three frames in the traceback: the %run one,
1660 # one inside bdb.py, and the command-line typed by the
1660 # one inside bdb.py, and the command-line typed by the
1661 # user (run by exec in pdb itself).
1661 # user (run by exec in pdb itself).
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1663 else:
1663 else:
1664 if runner is None:
1664 if runner is None:
1665 runner = self.shell.safe_execfile
1665 runner = self.shell.safe_execfile
1666 if opts.has_key('t'):
1666 if opts.has_key('t'):
1667 # timed execution
1667 # timed execution
1668 try:
1668 try:
1669 nruns = int(opts['N'][0])
1669 nruns = int(opts['N'][0])
1670 if nruns < 1:
1670 if nruns < 1:
1671 error('Number of runs must be >=1')
1671 error('Number of runs must be >=1')
1672 return
1672 return
1673 except (KeyError):
1673 except (KeyError):
1674 nruns = 1
1674 nruns = 1
1675 if nruns == 1:
1675 if nruns == 1:
1676 t0 = clock2()
1676 t0 = clock2()
1677 runner(filename,prog_ns,prog_ns,
1677 runner(filename,prog_ns,prog_ns,
1678 exit_ignore=exit_ignore)
1678 exit_ignore=exit_ignore)
1679 t1 = clock2()
1679 t1 = clock2()
1680 t_usr = t1[0]-t0[0]
1680 t_usr = t1[0]-t0[0]
1681 t_sys = t1[1]-t0[1]
1681 t_sys = t1[1]-t0[1]
1682 print "\nIPython CPU timings (estimated):"
1682 print "\nIPython CPU timings (estimated):"
1683 print " User : %10s s." % t_usr
1683 print " User : %10s s." % t_usr
1684 print " System: %10s s." % t_sys
1684 print " System: %10s s." % t_sys
1685 else:
1685 else:
1686 runs = range(nruns)
1686 runs = range(nruns)
1687 t0 = clock2()
1687 t0 = clock2()
1688 for nr in runs:
1688 for nr in runs:
1689 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1690 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1691 t1 = clock2()
1691 t1 = clock2()
1692 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1693 t_sys = t1[1]-t0[1]
1693 t_sys = t1[1]-t0[1]
1694 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1695 print "Total runs performed:",nruns
1695 print "Total runs performed:",nruns
1696 print " Times : %10s %10s" % ('Total','Per run')
1696 print " Times : %10s %10s" % ('Total','Per run')
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1699
1699
1700 else:
1700 else:
1701 # regular execution
1701 # regular execution
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1703
1703
1704 if opts.has_key('i'):
1704 if opts.has_key('i'):
1705 self.shell.user_ns['__name__'] = __name__save
1705 self.shell.user_ns['__name__'] = __name__save
1706 else:
1706 else:
1707 # The shell MUST hold a reference to prog_ns so after %run
1707 # The shell MUST hold a reference to prog_ns so after %run
1708 # exits, the python deletion mechanism doesn't zero it out
1708 # exits, the python deletion mechanism doesn't zero it out
1709 # (leaving dangling references).
1709 # (leaving dangling references).
1710 self.shell.cache_main_mod(prog_ns,filename)
1710 self.shell.cache_main_mod(prog_ns,filename)
1711 # update IPython interactive namespace
1711 # update IPython interactive namespace
1712
1712
1713 # Some forms of read errors on the file may mean the
1713 # Some forms of read errors on the file may mean the
1714 # __name__ key was never set; using pop we don't have to
1714 # __name__ key was never set; using pop we don't have to
1715 # worry about a possible KeyError.
1715 # worry about a possible KeyError.
1716 prog_ns.pop('__name__', None)
1716 prog_ns.pop('__name__', None)
1717
1717
1718 self.shell.user_ns.update(prog_ns)
1718 self.shell.user_ns.update(prog_ns)
1719 finally:
1719 finally:
1720 # It's a bit of a mystery why, but __builtins__ can change from
1720 # It's a bit of a mystery why, but __builtins__ can change from
1721 # being a module to becoming a dict missing some key data after
1721 # being a module to becoming a dict missing some key data after
1722 # %run. As best I can see, this is NOT something IPython is doing
1722 # %run. As best I can see, this is NOT something IPython is doing
1723 # at all, and similar problems have been reported before:
1723 # at all, and similar problems have been reported before:
1724 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1725 # Since this seems to be done by the interpreter itself, the best
1725 # Since this seems to be done by the interpreter itself, the best
1726 # we can do is to at least restore __builtins__ for the user on
1726 # we can do is to at least restore __builtins__ for the user on
1727 # exit.
1727 # exit.
1728 self.shell.user_ns['__builtins__'] = __builtin__
1728 self.shell.user_ns['__builtins__'] = __builtin__
1729
1729
1730 # Ensure key global structures are restored
1730 # Ensure key global structures are restored
1731 sys.argv = save_argv
1731 sys.argv = save_argv
1732 if restore_main:
1732 if restore_main:
1733 sys.modules['__main__'] = restore_main
1733 sys.modules['__main__'] = restore_main
1734 else:
1734 else:
1735 # Remove from sys.modules the reference to main_mod we'd
1735 # Remove from sys.modules the reference to main_mod we'd
1736 # added. Otherwise it will trap references to objects
1736 # added. Otherwise it will trap references to objects
1737 # contained therein.
1737 # contained therein.
1738 del sys.modules[main_mod_name]
1738 del sys.modules[main_mod_name]
1739
1739
1740 self.shell.reloadhist()
1740 self.shell.reloadhist()
1741
1741
1742 return stats
1742 return stats
1743
1743
1744 def magic_runlog(self, parameter_s =''):
1744 def magic_runlog(self, parameter_s =''):
1745 """Run files as logs.
1745 """Run files as logs.
1746
1746
1747 Usage:\\
1747 Usage:\\
1748 %runlog file1 file2 ...
1748 %runlog file1 file2 ...
1749
1749
1750 Run the named files (treating them as log files) in sequence inside
1750 Run the named files (treating them as log files) in sequence inside
1751 the interpreter, and return to the prompt. This is much slower than
1751 the interpreter, and return to the prompt. This is much slower than
1752 %run because each line is executed in a try/except block, but it
1752 %run because each line is executed in a try/except block, but it
1753 allows running files with syntax errors in them.
1753 allows running files with syntax errors in them.
1754
1754
1755 Normally IPython will guess when a file is one of its own logfiles, so
1755 Normally IPython will guess when a file is one of its own logfiles, so
1756 you can typically use %run even for logs. This shorthand allows you to
1756 you can typically use %run even for logs. This shorthand allows you to
1757 force any file to be treated as a log file."""
1757 force any file to be treated as a log file."""
1758
1758
1759 for f in parameter_s.split():
1759 for f in parameter_s.split():
1760 self.shell.safe_execfile(f,self.shell.user_ns,
1760 self.shell.safe_execfile(f,self.shell.user_ns,
1761 self.shell.user_ns,islog=1)
1761 self.shell.user_ns,islog=1)
1762
1762
1763 @testdec.skip_doctest
1763 @testdec.skip_doctest
1764 def magic_timeit(self, parameter_s =''):
1764 def magic_timeit(self, parameter_s =''):
1765 """Time execution of a Python statement or expression
1765 """Time execution of a Python statement or expression
1766
1766
1767 Usage:\\
1767 Usage:\\
1768 %timeit [-n<N> -r<R> [-t|-c]] statement
1768 %timeit [-n<N> -r<R> [-t|-c]] statement
1769
1769
1770 Time execution of a Python statement or expression using the timeit
1770 Time execution of a Python statement or expression using the timeit
1771 module.
1771 module.
1772
1772
1773 Options:
1773 Options:
1774 -n<N>: execute the given statement <N> times in a loop. If this value
1774 -n<N>: execute the given statement <N> times in a loop. If this value
1775 is not given, a fitting value is chosen.
1775 is not given, a fitting value is chosen.
1776
1776
1777 -r<R>: repeat the loop iteration <R> times and take the best result.
1777 -r<R>: repeat the loop iteration <R> times and take the best result.
1778 Default: 3
1778 Default: 3
1779
1779
1780 -t: use time.time to measure the time, which is the default on Unix.
1780 -t: use time.time to measure the time, which is the default on Unix.
1781 This function measures wall time.
1781 This function measures wall time.
1782
1782
1783 -c: use time.clock to measure the time, which is the default on
1783 -c: use time.clock to measure the time, which is the default on
1784 Windows and measures wall time. On Unix, resource.getrusage is used
1784 Windows and measures wall time. On Unix, resource.getrusage is used
1785 instead and returns the CPU user time.
1785 instead and returns the CPU user time.
1786
1786
1787 -p<P>: use a precision of <P> digits to display the timing result.
1787 -p<P>: use a precision of <P> digits to display the timing result.
1788 Default: 3
1788 Default: 3
1789
1789
1790
1790
1791 Examples:
1791 Examples:
1792
1792
1793 In [1]: %timeit pass
1793 In [1]: %timeit pass
1794 10000000 loops, best of 3: 53.3 ns per loop
1794 10000000 loops, best of 3: 53.3 ns per loop
1795
1795
1796 In [2]: u = None
1796 In [2]: u = None
1797
1797
1798 In [3]: %timeit u is None
1798 In [3]: %timeit u is None
1799 10000000 loops, best of 3: 184 ns per loop
1799 10000000 loops, best of 3: 184 ns per loop
1800
1800
1801 In [4]: %timeit -r 4 u == None
1801 In [4]: %timeit -r 4 u == None
1802 1000000 loops, best of 4: 242 ns per loop
1802 1000000 loops, best of 4: 242 ns per loop
1803
1803
1804 In [5]: import time
1804 In [5]: import time
1805
1805
1806 In [6]: %timeit -n1 time.sleep(2)
1806 In [6]: %timeit -n1 time.sleep(2)
1807 1 loops, best of 3: 2 s per loop
1807 1 loops, best of 3: 2 s per loop
1808
1808
1809
1809
1810 The times reported by %timeit will be slightly higher than those
1810 The times reported by %timeit will be slightly higher than those
1811 reported by the timeit.py script when variables are accessed. This is
1811 reported by the timeit.py script when variables are accessed. This is
1812 due to the fact that %timeit executes the statement in the namespace
1812 due to the fact that %timeit executes the statement in the namespace
1813 of the shell, compared with timeit.py, which uses a single setup
1813 of the shell, compared with timeit.py, which uses a single setup
1814 statement to import function or create variables. Generally, the bias
1814 statement to import function or create variables. Generally, the bias
1815 does not matter as long as results from timeit.py are not mixed with
1815 does not matter as long as results from timeit.py are not mixed with
1816 those from %timeit."""
1816 those from %timeit."""
1817
1817
1818 import timeit
1818 import timeit
1819 import math
1819 import math
1820
1820
1821 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1821 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1822 # certain terminals. Until we figure out a robust way of
1822 # certain terminals. Until we figure out a robust way of
1823 # auto-detecting if the terminal can deal with it, use plain 'us' for
1823 # auto-detecting if the terminal can deal with it, use plain 'us' for
1824 # microseconds. I am really NOT happy about disabling the proper
1824 # microseconds. I am really NOT happy about disabling the proper
1825 # 'micro' prefix, but crashing is worse... If anyone knows what the
1825 # 'micro' prefix, but crashing is worse... If anyone knows what the
1826 # right solution for this is, I'm all ears...
1826 # right solution for this is, I'm all ears...
1827 #
1827 #
1828 # Note: using
1828 # Note: using
1829 #
1829 #
1830 # s = u'\xb5'
1830 # s = u'\xb5'
1831 # s.encode(sys.getdefaultencoding())
1831 # s.encode(sys.getdefaultencoding())
1832 #
1832 #
1833 # is not sufficient, as I've seen terminals where that fails but
1833 # is not sufficient, as I've seen terminals where that fails but
1834 # print s
1834 # print s
1835 #
1835 #
1836 # succeeds
1836 # succeeds
1837 #
1837 #
1838 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1838 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1839
1839
1840 #units = [u"s", u"ms",u'\xb5',"ns"]
1840 #units = [u"s", u"ms",u'\xb5',"ns"]
1841 units = [u"s", u"ms",u'us',"ns"]
1841 units = [u"s", u"ms",u'us',"ns"]
1842
1842
1843 scaling = [1, 1e3, 1e6, 1e9]
1843 scaling = [1, 1e3, 1e6, 1e9]
1844
1844
1845 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1845 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1846 posix=False)
1846 posix=False)
1847 if stmt == "":
1847 if stmt == "":
1848 return
1848 return
1849 timefunc = timeit.default_timer
1849 timefunc = timeit.default_timer
1850 number = int(getattr(opts, "n", 0))
1850 number = int(getattr(opts, "n", 0))
1851 repeat = int(getattr(opts, "r", timeit.default_repeat))
1851 repeat = int(getattr(opts, "r", timeit.default_repeat))
1852 precision = int(getattr(opts, "p", 3))
1852 precision = int(getattr(opts, "p", 3))
1853 if hasattr(opts, "t"):
1853 if hasattr(opts, "t"):
1854 timefunc = time.time
1854 timefunc = time.time
1855 if hasattr(opts, "c"):
1855 if hasattr(opts, "c"):
1856 timefunc = clock
1856 timefunc = clock
1857
1857
1858 timer = timeit.Timer(timer=timefunc)
1858 timer = timeit.Timer(timer=timefunc)
1859 # this code has tight coupling to the inner workings of timeit.Timer,
1859 # this code has tight coupling to the inner workings of timeit.Timer,
1860 # but is there a better way to achieve that the code stmt has access
1860 # but is there a better way to achieve that the code stmt has access
1861 # to the shell namespace?
1861 # to the shell namespace?
1862
1862
1863 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1863 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1864 'setup': "pass"}
1864 'setup': "pass"}
1865 # Track compilation time so it can be reported if too long
1865 # Track compilation time so it can be reported if too long
1866 # Minimum time above which compilation time will be reported
1866 # Minimum time above which compilation time will be reported
1867 tc_min = 0.1
1867 tc_min = 0.1
1868
1868
1869 t0 = clock()
1869 t0 = clock()
1870 code = compile(src, "<magic-timeit>", "exec")
1870 code = compile(src, "<magic-timeit>", "exec")
1871 tc = clock()-t0
1871 tc = clock()-t0
1872
1872
1873 ns = {}
1873 ns = {}
1874 exec code in self.shell.user_ns, ns
1874 exec code in self.shell.user_ns, ns
1875 timer.inner = ns["inner"]
1875 timer.inner = ns["inner"]
1876
1876
1877 if number == 0:
1877 if number == 0:
1878 # determine number so that 0.2 <= total time < 2.0
1878 # determine number so that 0.2 <= total time < 2.0
1879 number = 1
1879 number = 1
1880 for i in range(1, 10):
1880 for i in range(1, 10):
1881 if timer.timeit(number) >= 0.2:
1881 if timer.timeit(number) >= 0.2:
1882 break
1882 break
1883 number *= 10
1883 number *= 10
1884
1884
1885 best = min(timer.repeat(repeat, number)) / number
1885 best = min(timer.repeat(repeat, number)) / number
1886
1886
1887 if best > 0.0:
1887 if best > 0.0:
1888 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1888 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1889 else:
1889 else:
1890 order = 3
1890 order = 3
1891 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1891 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1892 precision,
1892 precision,
1893 best * scaling[order],
1893 best * scaling[order],
1894 units[order])
1894 units[order])
1895 if tc > tc_min:
1895 if tc > tc_min:
1896 print "Compiler time: %.2f s" % tc
1896 print "Compiler time: %.2f s" % tc
1897
1897
1898 @testdec.skip_doctest
1898 @testdec.skip_doctest
1899 def magic_time(self,parameter_s = ''):
1899 def magic_time(self,parameter_s = ''):
1900 """Time execution of a Python statement or expression.
1900 """Time execution of a Python statement or expression.
1901
1901
1902 The CPU and wall clock times are printed, and the value of the
1902 The CPU and wall clock times are printed, and the value of the
1903 expression (if any) is returned. Note that under Win32, system time
1903 expression (if any) is returned. Note that under Win32, system time
1904 is always reported as 0, since it can not be measured.
1904 is always reported as 0, since it can not be measured.
1905
1905
1906 This function provides very basic timing functionality. In Python
1906 This function provides very basic timing functionality. In Python
1907 2.3, the timeit module offers more control and sophistication, so this
1907 2.3, the timeit module offers more control and sophistication, so this
1908 could be rewritten to use it (patches welcome).
1908 could be rewritten to use it (patches welcome).
1909
1909
1910 Some examples:
1910 Some examples:
1911
1911
1912 In [1]: time 2**128
1912 In [1]: time 2**128
1913 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1913 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1914 Wall time: 0.00
1914 Wall time: 0.00
1915 Out[1]: 340282366920938463463374607431768211456L
1915 Out[1]: 340282366920938463463374607431768211456L
1916
1916
1917 In [2]: n = 1000000
1917 In [2]: n = 1000000
1918
1918
1919 In [3]: time sum(range(n))
1919 In [3]: time sum(range(n))
1920 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1920 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1921 Wall time: 1.37
1921 Wall time: 1.37
1922 Out[3]: 499999500000L
1922 Out[3]: 499999500000L
1923
1923
1924 In [4]: time print 'hello world'
1924 In [4]: time print 'hello world'
1925 hello world
1925 hello world
1926 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1926 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1927 Wall time: 0.00
1927 Wall time: 0.00
1928
1928
1929 Note that the time needed by Python to compile the given expression
1929 Note that the time needed by Python to compile the given expression
1930 will be reported if it is more than 0.1s. In this example, the
1930 will be reported if it is more than 0.1s. In this example, the
1931 actual exponentiation is done by Python at compilation time, so while
1931 actual exponentiation is done by Python at compilation time, so while
1932 the expression can take a noticeable amount of time to compute, that
1932 the expression can take a noticeable amount of time to compute, that
1933 time is purely due to the compilation:
1933 time is purely due to the compilation:
1934
1934
1935 In [5]: time 3**9999;
1935 In [5]: time 3**9999;
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1937 Wall time: 0.00 s
1937 Wall time: 0.00 s
1938
1938
1939 In [6]: time 3**999999;
1939 In [6]: time 3**999999;
1940 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1940 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1941 Wall time: 0.00 s
1941 Wall time: 0.00 s
1942 Compiler : 0.78 s
1942 Compiler : 0.78 s
1943 """
1943 """
1944
1944
1945 # fail immediately if the given expression can't be compiled
1945 # fail immediately if the given expression can't be compiled
1946
1946
1947 expr = self.shell.prefilter(parameter_s,False)
1947 expr = self.shell.prefilter(parameter_s,False)
1948
1948
1949 # Minimum time above which compilation time will be reported
1949 # Minimum time above which compilation time will be reported
1950 tc_min = 0.1
1950 tc_min = 0.1
1951
1951
1952 try:
1952 try:
1953 mode = 'eval'
1953 mode = 'eval'
1954 t0 = clock()
1954 t0 = clock()
1955 code = compile(expr,'<timed eval>',mode)
1955 code = compile(expr,'<timed eval>',mode)
1956 tc = clock()-t0
1956 tc = clock()-t0
1957 except SyntaxError:
1957 except SyntaxError:
1958 mode = 'exec'
1958 mode = 'exec'
1959 t0 = clock()
1959 t0 = clock()
1960 code = compile(expr,'<timed exec>',mode)
1960 code = compile(expr,'<timed exec>',mode)
1961 tc = clock()-t0
1961 tc = clock()-t0
1962 # skew measurement as little as possible
1962 # skew measurement as little as possible
1963 glob = self.shell.user_ns
1963 glob = self.shell.user_ns
1964 clk = clock2
1964 clk = clock2
1965 wtime = time.time
1965 wtime = time.time
1966 # time execution
1966 # time execution
1967 wall_st = wtime()
1967 wall_st = wtime()
1968 if mode=='eval':
1968 if mode=='eval':
1969 st = clk()
1969 st = clk()
1970 out = eval(code,glob)
1970 out = eval(code,glob)
1971 end = clk()
1971 end = clk()
1972 else:
1972 else:
1973 st = clk()
1973 st = clk()
1974 exec code in glob
1974 exec code in glob
1975 end = clk()
1975 end = clk()
1976 out = None
1976 out = None
1977 wall_end = wtime()
1977 wall_end = wtime()
1978 # Compute actual times and report
1978 # Compute actual times and report
1979 wall_time = wall_end-wall_st
1979 wall_time = wall_end-wall_st
1980 cpu_user = end[0]-st[0]
1980 cpu_user = end[0]-st[0]
1981 cpu_sys = end[1]-st[1]
1981 cpu_sys = end[1]-st[1]
1982 cpu_tot = cpu_user+cpu_sys
1982 cpu_tot = cpu_user+cpu_sys
1983 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1983 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1984 (cpu_user,cpu_sys,cpu_tot)
1984 (cpu_user,cpu_sys,cpu_tot)
1985 print "Wall time: %.2f s" % wall_time
1985 print "Wall time: %.2f s" % wall_time
1986 if tc > tc_min:
1986 if tc > tc_min:
1987 print "Compiler : %.2f s" % tc
1987 print "Compiler : %.2f s" % tc
1988 return out
1988 return out
1989
1989
1990 @testdec.skip_doctest
1990 @testdec.skip_doctest
1991 def magic_macro(self,parameter_s = ''):
1991 def magic_macro(self,parameter_s = ''):
1992 """Define a set of input lines as a macro for future re-execution.
1992 """Define a set of input lines as a macro for future re-execution.
1993
1993
1994 Usage:\\
1994 Usage:\\
1995 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1995 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1996
1996
1997 Options:
1997 Options:
1998
1998
1999 -r: use 'raw' input. By default, the 'processed' history is used,
1999 -r: use 'raw' input. By default, the 'processed' history is used,
2000 so that magics are loaded in their transformed version to valid
2000 so that magics are loaded in their transformed version to valid
2001 Python. If this option is given, the raw input as typed as the
2001 Python. If this option is given, the raw input as typed as the
2002 command line is used instead.
2002 command line is used instead.
2003
2003
2004 This will define a global variable called `name` which is a string
2004 This will define a global variable called `name` which is a string
2005 made of joining the slices and lines you specify (n1,n2,... numbers
2005 made of joining the slices and lines you specify (n1,n2,... numbers
2006 above) from your input history into a single string. This variable
2006 above) from your input history into a single string. This variable
2007 acts like an automatic function which re-executes those lines as if
2007 acts like an automatic function which re-executes those lines as if
2008 you had typed them. You just type 'name' at the prompt and the code
2008 you had typed them. You just type 'name' at the prompt and the code
2009 executes.
2009 executes.
2010
2010
2011 The notation for indicating number ranges is: n1-n2 means 'use line
2011 The notation for indicating number ranges is: n1-n2 means 'use line
2012 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2012 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2013 using the lines numbered 5,6 and 7.
2013 using the lines numbered 5,6 and 7.
2014
2014
2015 Note: as a 'hidden' feature, you can also use traditional python slice
2015 Note: as a 'hidden' feature, you can also use traditional python slice
2016 notation, where N:M means numbers N through M-1.
2016 notation, where N:M means numbers N through M-1.
2017
2017
2018 For example, if your history contains (%hist prints it):
2018 For example, if your history contains (%hist prints it):
2019
2019
2020 44: x=1
2020 44: x=1
2021 45: y=3
2021 45: y=3
2022 46: z=x+y
2022 46: z=x+y
2023 47: print x
2023 47: print x
2024 48: a=5
2024 48: a=5
2025 49: print 'x',x,'y',y
2025 49: print 'x',x,'y',y
2026
2026
2027 you can create a macro with lines 44 through 47 (included) and line 49
2027 you can create a macro with lines 44 through 47 (included) and line 49
2028 called my_macro with:
2028 called my_macro with:
2029
2029
2030 In [55]: %macro my_macro 44-47 49
2030 In [55]: %macro my_macro 44-47 49
2031
2031
2032 Now, typing `my_macro` (without quotes) will re-execute all this code
2032 Now, typing `my_macro` (without quotes) will re-execute all this code
2033 in one pass.
2033 in one pass.
2034
2034
2035 You don't need to give the line-numbers in order, and any given line
2035 You don't need to give the line-numbers in order, and any given line
2036 number can appear multiple times. You can assemble macros with any
2036 number can appear multiple times. You can assemble macros with any
2037 lines from your input history in any order.
2037 lines from your input history in any order.
2038
2038
2039 The macro is a simple object which holds its value in an attribute,
2039 The macro is a simple object which holds its value in an attribute,
2040 but IPython's display system checks for macros and executes them as
2040 but IPython's display system checks for macros and executes them as
2041 code instead of printing them when you type their name.
2041 code instead of printing them when you type their name.
2042
2042
2043 You can view a macro's contents by explicitly printing it with:
2043 You can view a macro's contents by explicitly printing it with:
2044
2044
2045 'print macro_name'.
2045 'print macro_name'.
2046
2046
2047 For one-off cases which DON'T contain magic function calls in them you
2047 For one-off cases which DON'T contain magic function calls in them you
2048 can obtain similar results by explicitly executing slices from your
2048 can obtain similar results by explicitly executing slices from your
2049 input history with:
2049 input history with:
2050
2050
2051 In [60]: exec In[44:48]+In[49]"""
2051 In [60]: exec In[44:48]+In[49]"""
2052
2052
2053 opts,args = self.parse_options(parameter_s,'r',mode='list')
2053 opts,args = self.parse_options(parameter_s,'r',mode='list')
2054 if not args:
2054 if not args:
2055 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2055 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2056 macs.sort()
2056 macs.sort()
2057 return macs
2057 return macs
2058 if len(args) == 1:
2058 if len(args) == 1:
2059 raise UsageError(
2059 raise UsageError(
2060 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2060 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2061 name,ranges = args[0], args[1:]
2061 name,ranges = args[0], args[1:]
2062
2062
2063 #print 'rng',ranges # dbg
2063 #print 'rng',ranges # dbg
2064 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2064 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2065 macro = Macro(lines)
2065 macro = Macro(lines)
2066 self.shell.user_ns.update({name:macro})
2066 self.shell.user_ns.update({name:macro})
2067 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2067 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2068 print 'Macro contents:'
2068 print 'Macro contents:'
2069 print macro,
2069 print macro,
2070
2070
2071 def magic_save(self,parameter_s = ''):
2071 def magic_save(self,parameter_s = ''):
2072 """Save a set of lines to a given filename.
2072 """Save a set of lines to a given filename.
2073
2073
2074 Usage:\\
2074 Usage:\\
2075 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2075 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2076
2076
2077 Options:
2077 Options:
2078
2078
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2080 so that magics are loaded in their transformed version to valid
2080 so that magics are loaded in their transformed version to valid
2081 Python. If this option is given, the raw input as typed as the
2081 Python. If this option is given, the raw input as typed as the
2082 command line is used instead.
2082 command line is used instead.
2083
2083
2084 This function uses the same syntax as %macro for line extraction, but
2084 This function uses the same syntax as %macro for line extraction, but
2085 instead of creating a macro it saves the resulting string to the
2085 instead of creating a macro it saves the resulting string to the
2086 filename you specify.
2086 filename you specify.
2087
2087
2088 It adds a '.py' extension to the file if you don't do so yourself, and
2088 It adds a '.py' extension to the file if you don't do so yourself, and
2089 it asks for confirmation before overwriting existing files."""
2089 it asks for confirmation before overwriting existing files."""
2090
2090
2091 opts,args = self.parse_options(parameter_s,'r',mode='list')
2091 opts,args = self.parse_options(parameter_s,'r',mode='list')
2092 fname,ranges = args[0], args[1:]
2092 fname,ranges = args[0], args[1:]
2093 if not fname.endswith('.py'):
2093 if not fname.endswith('.py'):
2094 fname += '.py'
2094 fname += '.py'
2095 if os.path.isfile(fname):
2095 if os.path.isfile(fname):
2096 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2096 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2097 if ans.lower() not in ['y','yes']:
2097 if ans.lower() not in ['y','yes']:
2098 print 'Operation cancelled.'
2098 print 'Operation cancelled.'
2099 return
2099 return
2100 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2100 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2101 f = file(fname,'w')
2101 f = file(fname,'w')
2102 f.write(cmds)
2102 f.write(cmds)
2103 f.close()
2103 f.close()
2104 print 'The following commands were written to file `%s`:' % fname
2104 print 'The following commands were written to file `%s`:' % fname
2105 print cmds
2105 print cmds
2106
2106
2107 def _edit_macro(self,mname,macro):
2107 def _edit_macro(self,mname,macro):
2108 """open an editor with the macro data in a file"""
2108 """open an editor with the macro data in a file"""
2109 filename = self.shell.mktempfile(macro.value)
2109 filename = self.shell.mktempfile(macro.value)
2110 self.shell.hooks.editor(filename)
2110 self.shell.hooks.editor(filename)
2111
2111
2112 # and make a new macro object, to replace the old one
2112 # and make a new macro object, to replace the old one
2113 mfile = open(filename)
2113 mfile = open(filename)
2114 mvalue = mfile.read()
2114 mvalue = mfile.read()
2115 mfile.close()
2115 mfile.close()
2116 self.shell.user_ns[mname] = Macro(mvalue)
2116 self.shell.user_ns[mname] = Macro(mvalue)
2117
2117
2118 def magic_ed(self,parameter_s=''):
2118 def magic_ed(self,parameter_s=''):
2119 """Alias to %edit."""
2119 """Alias to %edit."""
2120 return self.magic_edit(parameter_s)
2120 return self.magic_edit(parameter_s)
2121
2121
2122 @testdec.skip_doctest
2122 @testdec.skip_doctest
2123 def magic_edit(self,parameter_s='',last_call=['','']):
2123 def magic_edit(self,parameter_s='',last_call=['','']):
2124 """Bring up an editor and execute the resulting code.
2124 """Bring up an editor and execute the resulting code.
2125
2125
2126 Usage:
2126 Usage:
2127 %edit [options] [args]
2127 %edit [options] [args]
2128
2128
2129 %edit runs IPython's editor hook. The default version of this hook is
2129 %edit runs IPython's editor hook. The default version of this hook is
2130 set to call the __IPYTHON__.rc.editor command. This is read from your
2130 set to call the __IPYTHON__.rc.editor command. This is read from your
2131 environment variable $EDITOR. If this isn't found, it will default to
2131 environment variable $EDITOR. If this isn't found, it will default to
2132 vi under Linux/Unix and to notepad under Windows. See the end of this
2132 vi under Linux/Unix and to notepad under Windows. See the end of this
2133 docstring for how to change the editor hook.
2133 docstring for how to change the editor hook.
2134
2134
2135 You can also set the value of this editor via the command line option
2135 You can also set the value of this editor via the command line option
2136 '-editor' or in your ipythonrc file. This is useful if you wish to use
2136 '-editor' or in your ipythonrc file. This is useful if you wish to use
2137 specifically for IPython an editor different from your typical default
2137 specifically for IPython an editor different from your typical default
2138 (and for Windows users who typically don't set environment variables).
2138 (and for Windows users who typically don't set environment variables).
2139
2139
2140 This command allows you to conveniently edit multi-line code right in
2140 This command allows you to conveniently edit multi-line code right in
2141 your IPython session.
2141 your IPython session.
2142
2142
2143 If called without arguments, %edit opens up an empty editor with a
2143 If called without arguments, %edit opens up an empty editor with a
2144 temporary file and will execute the contents of this file when you
2144 temporary file and will execute the contents of this file when you
2145 close it (don't forget to save it!).
2145 close it (don't forget to save it!).
2146
2146
2147
2147
2148 Options:
2148 Options:
2149
2149
2150 -n <number>: open the editor at a specified line number. By default,
2150 -n <number>: open the editor at a specified line number. By default,
2151 the IPython editor hook uses the unix syntax 'editor +N filename', but
2151 the IPython editor hook uses the unix syntax 'editor +N filename', but
2152 you can configure this by providing your own modified hook if your
2152 you can configure this by providing your own modified hook if your
2153 favorite editor supports line-number specifications with a different
2153 favorite editor supports line-number specifications with a different
2154 syntax.
2154 syntax.
2155
2155
2156 -p: this will call the editor with the same data as the previous time
2156 -p: this will call the editor with the same data as the previous time
2157 it was used, regardless of how long ago (in your current session) it
2157 it was used, regardless of how long ago (in your current session) it
2158 was.
2158 was.
2159
2159
2160 -r: use 'raw' input. This option only applies to input taken from the
2160 -r: use 'raw' input. This option only applies to input taken from the
2161 user's history. By default, the 'processed' history is used, so that
2161 user's history. By default, the 'processed' history is used, so that
2162 magics are loaded in their transformed version to valid Python. If
2162 magics are loaded in their transformed version to valid Python. If
2163 this option is given, the raw input as typed as the command line is
2163 this option is given, the raw input as typed as the command line is
2164 used instead. When you exit the editor, it will be executed by
2164 used instead. When you exit the editor, it will be executed by
2165 IPython's own processor.
2165 IPython's own processor.
2166
2166
2167 -x: do not execute the edited code immediately upon exit. This is
2167 -x: do not execute the edited code immediately upon exit. This is
2168 mainly useful if you are editing programs which need to be called with
2168 mainly useful if you are editing programs which need to be called with
2169 command line arguments, which you can then do using %run.
2169 command line arguments, which you can then do using %run.
2170
2170
2171
2171
2172 Arguments:
2172 Arguments:
2173
2173
2174 If arguments are given, the following possibilites exist:
2174 If arguments are given, the following possibilites exist:
2175
2175
2176 - The arguments are numbers or pairs of colon-separated numbers (like
2176 - The arguments are numbers or pairs of colon-separated numbers (like
2177 1 4:8 9). These are interpreted as lines of previous input to be
2177 1 4:8 9). These are interpreted as lines of previous input to be
2178 loaded into the editor. The syntax is the same of the %macro command.
2178 loaded into the editor. The syntax is the same of the %macro command.
2179
2179
2180 - If the argument doesn't start with a number, it is evaluated as a
2180 - If the argument doesn't start with a number, it is evaluated as a
2181 variable and its contents loaded into the editor. You can thus edit
2181 variable and its contents loaded into the editor. You can thus edit
2182 any string which contains python code (including the result of
2182 any string which contains python code (including the result of
2183 previous edits).
2183 previous edits).
2184
2184
2185 - If the argument is the name of an object (other than a string),
2185 - If the argument is the name of an object (other than a string),
2186 IPython will try to locate the file where it was defined and open the
2186 IPython will try to locate the file where it was defined and open the
2187 editor at the point where it is defined. You can use `%edit function`
2187 editor at the point where it is defined. You can use `%edit function`
2188 to load an editor exactly at the point where 'function' is defined,
2188 to load an editor exactly at the point where 'function' is defined,
2189 edit it and have the file be executed automatically.
2189 edit it and have the file be executed automatically.
2190
2190
2191 If the object is a macro (see %macro for details), this opens up your
2191 If the object is a macro (see %macro for details), this opens up your
2192 specified editor with a temporary file containing the macro's data.
2192 specified editor with a temporary file containing the macro's data.
2193 Upon exit, the macro is reloaded with the contents of the file.
2193 Upon exit, the macro is reloaded with the contents of the file.
2194
2194
2195 Note: opening at an exact line is only supported under Unix, and some
2195 Note: opening at an exact line is only supported under Unix, and some
2196 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2196 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2197 '+NUMBER' parameter necessary for this feature. Good editors like
2197 '+NUMBER' parameter necessary for this feature. Good editors like
2198 (X)Emacs, vi, jed, pico and joe all do.
2198 (X)Emacs, vi, jed, pico and joe all do.
2199
2199
2200 - If the argument is not found as a variable, IPython will look for a
2200 - If the argument is not found as a variable, IPython will look for a
2201 file with that name (adding .py if necessary) and load it into the
2201 file with that name (adding .py if necessary) and load it into the
2202 editor. It will execute its contents with execfile() when you exit,
2202 editor. It will execute its contents with execfile() when you exit,
2203 loading any code in the file into your interactive namespace.
2203 loading any code in the file into your interactive namespace.
2204
2204
2205 After executing your code, %edit will return as output the code you
2205 After executing your code, %edit will return as output the code you
2206 typed in the editor (except when it was an existing file). This way
2206 typed in the editor (except when it was an existing file). This way
2207 you can reload the code in further invocations of %edit as a variable,
2207 you can reload the code in further invocations of %edit as a variable,
2208 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2208 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2209 the output.
2209 the output.
2210
2210
2211 Note that %edit is also available through the alias %ed.
2211 Note that %edit is also available through the alias %ed.
2212
2212
2213 This is an example of creating a simple function inside the editor and
2213 This is an example of creating a simple function inside the editor and
2214 then modifying it. First, start up the editor:
2214 then modifying it. First, start up the editor:
2215
2215
2216 In [1]: ed
2216 In [1]: ed
2217 Editing... done. Executing edited code...
2217 Editing... done. Executing edited code...
2218 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2218 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2219
2219
2220 We can then call the function foo():
2220 We can then call the function foo():
2221
2221
2222 In [2]: foo()
2222 In [2]: foo()
2223 foo() was defined in an editing session
2223 foo() was defined in an editing session
2224
2224
2225 Now we edit foo. IPython automatically loads the editor with the
2225 Now we edit foo. IPython automatically loads the editor with the
2226 (temporary) file where foo() was previously defined:
2226 (temporary) file where foo() was previously defined:
2227
2227
2228 In [3]: ed foo
2228 In [3]: ed foo
2229 Editing... done. Executing edited code...
2229 Editing... done. Executing edited code...
2230
2230
2231 And if we call foo() again we get the modified version:
2231 And if we call foo() again we get the modified version:
2232
2232
2233 In [4]: foo()
2233 In [4]: foo()
2234 foo() has now been changed!
2234 foo() has now been changed!
2235
2235
2236 Here is an example of how to edit a code snippet successive
2236 Here is an example of how to edit a code snippet successive
2237 times. First we call the editor:
2237 times. First we call the editor:
2238
2238
2239 In [5]: ed
2239 In [5]: ed
2240 Editing... done. Executing edited code...
2240 Editing... done. Executing edited code...
2241 hello
2241 hello
2242 Out[5]: "print 'hello'n"
2242 Out[5]: "print 'hello'n"
2243
2243
2244 Now we call it again with the previous output (stored in _):
2244 Now we call it again with the previous output (stored in _):
2245
2245
2246 In [6]: ed _
2246 In [6]: ed _
2247 Editing... done. Executing edited code...
2247 Editing... done. Executing edited code...
2248 hello world
2248 hello world
2249 Out[6]: "print 'hello world'n"
2249 Out[6]: "print 'hello world'n"
2250
2250
2251 Now we call it with the output #8 (stored in _8, also as Out[8]):
2251 Now we call it with the output #8 (stored in _8, also as Out[8]):
2252
2252
2253 In [7]: ed _8
2253 In [7]: ed _8
2254 Editing... done. Executing edited code...
2254 Editing... done. Executing edited code...
2255 hello again
2255 hello again
2256 Out[7]: "print 'hello again'n"
2256 Out[7]: "print 'hello again'n"
2257
2257
2258
2258
2259 Changing the default editor hook:
2259 Changing the default editor hook:
2260
2260
2261 If you wish to write your own editor hook, you can put it in a
2261 If you wish to write your own editor hook, you can put it in a
2262 configuration file which you load at startup time. The default hook
2262 configuration file which you load at startup time. The default hook
2263 is defined in the IPython.core.hooks module, and you can use that as a
2263 is defined in the IPython.core.hooks module, and you can use that as a
2264 starting example for further modifications. That file also has
2264 starting example for further modifications. That file also has
2265 general instructions on how to set a new hook for use once you've
2265 general instructions on how to set a new hook for use once you've
2266 defined it."""
2266 defined it."""
2267
2267
2268 # FIXME: This function has become a convoluted mess. It needs a
2268 # FIXME: This function has become a convoluted mess. It needs a
2269 # ground-up rewrite with clean, simple logic.
2269 # ground-up rewrite with clean, simple logic.
2270
2270
2271 def make_filename(arg):
2271 def make_filename(arg):
2272 "Make a filename from the given args"
2272 "Make a filename from the given args"
2273 try:
2273 try:
2274 filename = get_py_filename(arg)
2274 filename = get_py_filename(arg)
2275 except IOError:
2275 except IOError:
2276 if args.endswith('.py'):
2276 if args.endswith('.py'):
2277 filename = arg
2277 filename = arg
2278 else:
2278 else:
2279 filename = None
2279 filename = None
2280 return filename
2280 return filename
2281
2281
2282 # custom exceptions
2282 # custom exceptions
2283 class DataIsObject(Exception): pass
2283 class DataIsObject(Exception): pass
2284
2284
2285 opts,args = self.parse_options(parameter_s,'prxn:')
2285 opts,args = self.parse_options(parameter_s,'prxn:')
2286 # Set a few locals from the options for convenience:
2286 # Set a few locals from the options for convenience:
2287 opts_p = opts.has_key('p')
2287 opts_p = opts.has_key('p')
2288 opts_r = opts.has_key('r')
2288 opts_r = opts.has_key('r')
2289
2289
2290 # Default line number value
2290 # Default line number value
2291 lineno = opts.get('n',None)
2291 lineno = opts.get('n',None)
2292
2292
2293 if opts_p:
2293 if opts_p:
2294 args = '_%s' % last_call[0]
2294 args = '_%s' % last_call[0]
2295 if not self.shell.user_ns.has_key(args):
2295 if not self.shell.user_ns.has_key(args):
2296 args = last_call[1]
2296 args = last_call[1]
2297
2297
2298 # use last_call to remember the state of the previous call, but don't
2298 # use last_call to remember the state of the previous call, but don't
2299 # let it be clobbered by successive '-p' calls.
2299 # let it be clobbered by successive '-p' calls.
2300 try:
2300 try:
2301 last_call[0] = self.shell.outputcache.prompt_count
2301 last_call[0] = self.shell.outputcache.prompt_count
2302 if not opts_p:
2302 if not opts_p:
2303 last_call[1] = parameter_s
2303 last_call[1] = parameter_s
2304 except:
2304 except:
2305 pass
2305 pass
2306
2306
2307 # by default this is done with temp files, except when the given
2307 # by default this is done with temp files, except when the given
2308 # arg is a filename
2308 # arg is a filename
2309 use_temp = 1
2309 use_temp = 1
2310
2310
2311 if re.match(r'\d',args):
2311 if re.match(r'\d',args):
2312 # Mode where user specifies ranges of lines, like in %macro.
2312 # Mode where user specifies ranges of lines, like in %macro.
2313 # This means that you can't edit files whose names begin with
2313 # This means that you can't edit files whose names begin with
2314 # numbers this way. Tough.
2314 # numbers this way. Tough.
2315 ranges = args.split()
2315 ranges = args.split()
2316 data = ''.join(self.extract_input_slices(ranges,opts_r))
2316 data = ''.join(self.extract_input_slices(ranges,opts_r))
2317 elif args.endswith('.py'):
2317 elif args.endswith('.py'):
2318 filename = make_filename(args)
2318 filename = make_filename(args)
2319 data = ''
2319 data = ''
2320 use_temp = 0
2320 use_temp = 0
2321 elif args:
2321 elif args:
2322 try:
2322 try:
2323 # Load the parameter given as a variable. If not a string,
2323 # Load the parameter given as a variable. If not a string,
2324 # process it as an object instead (below)
2324 # process it as an object instead (below)
2325
2325
2326 #print '*** args',args,'type',type(args) # dbg
2326 #print '*** args',args,'type',type(args) # dbg
2327 data = eval(args,self.shell.user_ns)
2327 data = eval(args,self.shell.user_ns)
2328 if not type(data) in StringTypes:
2328 if not type(data) in StringTypes:
2329 raise DataIsObject
2329 raise DataIsObject
2330
2330
2331 except (NameError,SyntaxError):
2331 except (NameError,SyntaxError):
2332 # given argument is not a variable, try as a filename
2332 # given argument is not a variable, try as a filename
2333 filename = make_filename(args)
2333 filename = make_filename(args)
2334 if filename is None:
2334 if filename is None:
2335 warn("Argument given (%s) can't be found as a variable "
2335 warn("Argument given (%s) can't be found as a variable "
2336 "or as a filename." % args)
2336 "or as a filename." % args)
2337 return
2337 return
2338
2338
2339 data = ''
2339 data = ''
2340 use_temp = 0
2340 use_temp = 0
2341 except DataIsObject:
2341 except DataIsObject:
2342
2342
2343 # macros have a special edit function
2343 # macros have a special edit function
2344 if isinstance(data,Macro):
2344 if isinstance(data,Macro):
2345 self._edit_macro(args,data)
2345 self._edit_macro(args,data)
2346 return
2346 return
2347
2347
2348 # For objects, try to edit the file where they are defined
2348 # For objects, try to edit the file where they are defined
2349 try:
2349 try:
2350 filename = inspect.getabsfile(data)
2350 filename = inspect.getabsfile(data)
2351 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2351 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2352 # class created by %edit? Try to find source
2352 # class created by %edit? Try to find source
2353 # by looking for method definitions instead, the
2353 # by looking for method definitions instead, the
2354 # __module__ in those classes is FakeModule.
2354 # __module__ in those classes is FakeModule.
2355 attrs = [getattr(data, aname) for aname in dir(data)]
2355 attrs = [getattr(data, aname) for aname in dir(data)]
2356 for attr in attrs:
2356 for attr in attrs:
2357 if not inspect.ismethod(attr):
2357 if not inspect.ismethod(attr):
2358 continue
2358 continue
2359 filename = inspect.getabsfile(attr)
2359 filename = inspect.getabsfile(attr)
2360 if filename and 'fakemodule' not in filename.lower():
2360 if filename and 'fakemodule' not in filename.lower():
2361 # change the attribute to be the edit target instead
2361 # change the attribute to be the edit target instead
2362 data = attr
2362 data = attr
2363 break
2363 break
2364
2364
2365 datafile = 1
2365 datafile = 1
2366 except TypeError:
2366 except TypeError:
2367 filename = make_filename(args)
2367 filename = make_filename(args)
2368 datafile = 1
2368 datafile = 1
2369 warn('Could not find file where `%s` is defined.\n'
2369 warn('Could not find file where `%s` is defined.\n'
2370 'Opening a file named `%s`' % (args,filename))
2370 'Opening a file named `%s`' % (args,filename))
2371 # Now, make sure we can actually read the source (if it was in
2371 # Now, make sure we can actually read the source (if it was in
2372 # a temp file it's gone by now).
2372 # a temp file it's gone by now).
2373 if datafile:
2373 if datafile:
2374 try:
2374 try:
2375 if lineno is None:
2375 if lineno is None:
2376 lineno = inspect.getsourcelines(data)[1]
2376 lineno = inspect.getsourcelines(data)[1]
2377 except IOError:
2377 except IOError:
2378 filename = make_filename(args)
2378 filename = make_filename(args)
2379 if filename is None:
2379 if filename is None:
2380 warn('The file `%s` where `%s` was defined cannot '
2380 warn('The file `%s` where `%s` was defined cannot '
2381 'be read.' % (filename,data))
2381 'be read.' % (filename,data))
2382 return
2382 return
2383 use_temp = 0
2383 use_temp = 0
2384 else:
2384 else:
2385 data = ''
2385 data = ''
2386
2386
2387 if use_temp:
2387 if use_temp:
2388 filename = self.shell.mktempfile(data)
2388 filename = self.shell.mktempfile(data)
2389 print 'IPython will make a temporary file named:',filename
2389 print 'IPython will make a temporary file named:',filename
2390
2390
2391 # do actual editing here
2391 # do actual editing here
2392 print 'Editing...',
2392 print 'Editing...',
2393 sys.stdout.flush()
2393 sys.stdout.flush()
2394 try:
2394 try:
2395 self.shell.hooks.editor(filename,lineno)
2395 self.shell.hooks.editor(filename,lineno)
2396 except ipapi.TryNext:
2396 except ipapi.TryNext:
2397 warn('Could not open editor')
2397 warn('Could not open editor')
2398 return
2398 return
2399
2399
2400 # XXX TODO: should this be generalized for all string vars?
2400 # XXX TODO: should this be generalized for all string vars?
2401 # For now, this is special-cased to blocks created by cpaste
2401 # For now, this is special-cased to blocks created by cpaste
2402 if args.strip() == 'pasted_block':
2402 if args.strip() == 'pasted_block':
2403 self.shell.user_ns['pasted_block'] = file_read(filename)
2403 self.shell.user_ns['pasted_block'] = file_read(filename)
2404
2404
2405 if opts.has_key('x'): # -x prevents actual execution
2405 if opts.has_key('x'): # -x prevents actual execution
2406 print
2406 print
2407 else:
2407 else:
2408 print 'done. Executing edited code...'
2408 print 'done. Executing edited code...'
2409 if opts_r:
2409 if opts_r:
2410 self.shell.runlines(file_read(filename))
2410 self.shell.runlines(file_read(filename))
2411 else:
2411 else:
2412 self.shell.safe_execfile(filename,self.shell.user_ns,
2412 self.shell.safe_execfile(filename,self.shell.user_ns,
2413 self.shell.user_ns)
2413 self.shell.user_ns)
2414
2414
2415
2415
2416 if use_temp:
2416 if use_temp:
2417 try:
2417 try:
2418 return open(filename).read()
2418 return open(filename).read()
2419 except IOError,msg:
2419 except IOError,msg:
2420 if msg.filename == filename:
2420 if msg.filename == filename:
2421 warn('File not found. Did you forget to save?')
2421 warn('File not found. Did you forget to save?')
2422 return
2422 return
2423 else:
2423 else:
2424 self.shell.showtraceback()
2424 self.shell.showtraceback()
2425
2425
2426 def magic_xmode(self,parameter_s = ''):
2426 def magic_xmode(self,parameter_s = ''):
2427 """Switch modes for the exception handlers.
2427 """Switch modes for the exception handlers.
2428
2428
2429 Valid modes: Plain, Context and Verbose.
2429 Valid modes: Plain, Context and Verbose.
2430
2430
2431 If called without arguments, acts as a toggle."""
2431 If called without arguments, acts as a toggle."""
2432
2432
2433 def xmode_switch_err(name):
2433 def xmode_switch_err(name):
2434 warn('Error changing %s exception modes.\n%s' %
2434 warn('Error changing %s exception modes.\n%s' %
2435 (name,sys.exc_info()[1]))
2435 (name,sys.exc_info()[1]))
2436
2436
2437 shell = self.shell
2437 shell = self.shell
2438 new_mode = parameter_s.strip().capitalize()
2438 new_mode = parameter_s.strip().capitalize()
2439 try:
2439 try:
2440 shell.InteractiveTB.set_mode(mode=new_mode)
2440 shell.InteractiveTB.set_mode(mode=new_mode)
2441 print 'Exception reporting mode:',shell.InteractiveTB.mode
2441 print 'Exception reporting mode:',shell.InteractiveTB.mode
2442 except:
2442 except:
2443 xmode_switch_err('user')
2443 xmode_switch_err('user')
2444
2444
2445 # threaded shells use a special handler in sys.excepthook
2445 # threaded shells use a special handler in sys.excepthook
2446 if shell.isthreaded:
2446 if shell.isthreaded:
2447 try:
2447 try:
2448 shell.sys_excepthook.set_mode(mode=new_mode)
2448 shell.sys_excepthook.set_mode(mode=new_mode)
2449 except:
2449 except:
2450 xmode_switch_err('threaded')
2450 xmode_switch_err('threaded')
2451
2451
2452 def magic_colors(self,parameter_s = ''):
2452 def magic_colors(self,parameter_s = ''):
2453 """Switch color scheme for prompts, info system and exception handlers.
2453 """Switch color scheme for prompts, info system and exception handlers.
2454
2454
2455 Currently implemented schemes: NoColor, Linux, LightBG.
2455 Currently implemented schemes: NoColor, Linux, LightBG.
2456
2456
2457 Color scheme names are not case-sensitive."""
2457 Color scheme names are not case-sensitive."""
2458
2458
2459 def color_switch_err(name):
2459 def color_switch_err(name):
2460 warn('Error changing %s color schemes.\n%s' %
2460 warn('Error changing %s color schemes.\n%s' %
2461 (name,sys.exc_info()[1]))
2461 (name,sys.exc_info()[1]))
2462
2462
2463
2463
2464 new_scheme = parameter_s.strip()
2464 new_scheme = parameter_s.strip()
2465 if not new_scheme:
2465 if not new_scheme:
2466 raise UsageError(
2466 raise UsageError(
2467 "%colors: you must specify a color scheme. See '%colors?'")
2467 "%colors: you must specify a color scheme. See '%colors?'")
2468 return
2468 return
2469 # local shortcut
2469 # local shortcut
2470 shell = self.shell
2470 shell = self.shell
2471
2471
2472 import IPython.utils.rlineimpl as readline
2472 import IPython.utils.rlineimpl as readline
2473
2473
2474 if not readline.have_readline and sys.platform == "win32":
2474 if not readline.have_readline and sys.platform == "win32":
2475 msg = """\
2475 msg = """\
2476 Proper color support under MS Windows requires the pyreadline library.
2476 Proper color support under MS Windows requires the pyreadline library.
2477 You can find it at:
2477 You can find it at:
2478 http://ipython.scipy.org/moin/PyReadline/Intro
2478 http://ipython.scipy.org/moin/PyReadline/Intro
2479 Gary's readline needs the ctypes module, from:
2479 Gary's readline needs the ctypes module, from:
2480 http://starship.python.net/crew/theller/ctypes
2480 http://starship.python.net/crew/theller/ctypes
2481 (Note that ctypes is already part of Python versions 2.5 and newer).
2481 (Note that ctypes is already part of Python versions 2.5 and newer).
2482
2482
2483 Defaulting color scheme to 'NoColor'"""
2483 Defaulting color scheme to 'NoColor'"""
2484 new_scheme = 'NoColor'
2484 new_scheme = 'NoColor'
2485 warn(msg)
2485 warn(msg)
2486
2486
2487 # readline option is 0
2487 # readline option is 0
2488 if not shell.has_readline:
2488 if not shell.has_readline:
2489 new_scheme = 'NoColor'
2489 new_scheme = 'NoColor'
2490
2490
2491 # Set prompt colors
2491 # Set prompt colors
2492 try:
2492 try:
2493 shell.outputcache.set_colors(new_scheme)
2493 shell.outputcache.set_colors(new_scheme)
2494 except:
2494 except:
2495 color_switch_err('prompt')
2495 color_switch_err('prompt')
2496 else:
2496 else:
2497 shell.colors = \
2497 shell.colors = \
2498 shell.outputcache.color_table.active_scheme_name
2498 shell.outputcache.color_table.active_scheme_name
2499 # Set exception colors
2499 # Set exception colors
2500 try:
2500 try:
2501 shell.InteractiveTB.set_colors(scheme = new_scheme)
2501 shell.InteractiveTB.set_colors(scheme = new_scheme)
2502 shell.SyntaxTB.set_colors(scheme = new_scheme)
2502 shell.SyntaxTB.set_colors(scheme = new_scheme)
2503 except:
2503 except:
2504 color_switch_err('exception')
2504 color_switch_err('exception')
2505
2505
2506 # threaded shells use a verbose traceback in sys.excepthook
2506 # threaded shells use a verbose traceback in sys.excepthook
2507 if shell.isthreaded:
2507 if shell.isthreaded:
2508 try:
2508 try:
2509 shell.sys_excepthook.set_colors(scheme=new_scheme)
2509 shell.sys_excepthook.set_colors(scheme=new_scheme)
2510 except:
2510 except:
2511 color_switch_err('system exception handler')
2511 color_switch_err('system exception handler')
2512
2512
2513 # Set info (for 'object?') colors
2513 # Set info (for 'object?') colors
2514 if shell.color_info:
2514 if shell.color_info:
2515 try:
2515 try:
2516 shell.inspector.set_active_scheme(new_scheme)
2516 shell.inspector.set_active_scheme(new_scheme)
2517 except:
2517 except:
2518 color_switch_err('object inspector')
2518 color_switch_err('object inspector')
2519 else:
2519 else:
2520 shell.inspector.set_active_scheme('NoColor')
2520 shell.inspector.set_active_scheme('NoColor')
2521
2521
2522 def magic_color_info(self,parameter_s = ''):
2522 def magic_color_info(self,parameter_s = ''):
2523 """Toggle color_info.
2523 """Toggle color_info.
2524
2524
2525 The color_info configuration parameter controls whether colors are
2525 The color_info configuration parameter controls whether colors are
2526 used for displaying object details (by things like %psource, %pfile or
2526 used for displaying object details (by things like %psource, %pfile or
2527 the '?' system). This function toggles this value with each call.
2527 the '?' system). This function toggles this value with each call.
2528
2528
2529 Note that unless you have a fairly recent pager (less works better
2529 Note that unless you have a fairly recent pager (less works better
2530 than more) in your system, using colored object information displays
2530 than more) in your system, using colored object information displays
2531 will not work properly. Test it and see."""
2531 will not work properly. Test it and see."""
2532
2532
2533 self.shell.color_info = 1 - self.shell.color_info
2533 self.shell.color_info = not self.shell.color_info
2534 self.magic_colors(self.shell.colors)
2534 self.magic_colors(self.shell.colors)
2535 print 'Object introspection functions have now coloring:',
2535 print 'Object introspection functions have now coloring:',
2536 print ['OFF','ON'][self.shell.color_info]
2536 print ['OFF','ON'][int(self.shell.color_info)]
2537
2537
2538 def magic_Pprint(self, parameter_s=''):
2538 def magic_Pprint(self, parameter_s=''):
2539 """Toggle pretty printing on/off."""
2539 """Toggle pretty printing on/off."""
2540
2540
2541 self.shell.pprint = 1 - self.shell.pprint
2541 self.shell.pprint = 1 - self.shell.pprint
2542 print 'Pretty printing has been turned', \
2542 print 'Pretty printing has been turned', \
2543 ['OFF','ON'][self.shell.pprint]
2543 ['OFF','ON'][self.shell.pprint]
2544
2544
2545 def magic_exit(self, parameter_s=''):
2545 def magic_exit(self, parameter_s=''):
2546 """Exit IPython, confirming if configured to do so.
2546 """Exit IPython, confirming if configured to do so.
2547
2547
2548 You can configure whether IPython asks for confirmation upon exit by
2548 You can configure whether IPython asks for confirmation upon exit by
2549 setting the confirm_exit flag in the ipythonrc file."""
2549 setting the confirm_exit flag in the ipythonrc file."""
2550
2550
2551 self.shell.exit()
2551 self.shell.exit()
2552
2552
2553 def magic_quit(self, parameter_s=''):
2553 def magic_quit(self, parameter_s=''):
2554 """Exit IPython, confirming if configured to do so (like %exit)"""
2554 """Exit IPython, confirming if configured to do so (like %exit)"""
2555
2555
2556 self.shell.exit()
2556 self.shell.exit()
2557
2557
2558 def magic_Exit(self, parameter_s=''):
2558 def magic_Exit(self, parameter_s=''):
2559 """Exit IPython without confirmation."""
2559 """Exit IPython without confirmation."""
2560
2560
2561 self.shell.ask_exit()
2561 self.shell.ask_exit()
2562
2562
2563 #......................................................................
2563 #......................................................................
2564 # Functions to implement unix shell-type things
2564 # Functions to implement unix shell-type things
2565
2565
2566 @testdec.skip_doctest
2566 @testdec.skip_doctest
2567 def magic_alias(self, parameter_s = ''):
2567 def magic_alias(self, parameter_s = ''):
2568 """Define an alias for a system command.
2568 """Define an alias for a system command.
2569
2569
2570 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2570 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2571
2571
2572 Then, typing 'alias_name params' will execute the system command 'cmd
2572 Then, typing 'alias_name params' will execute the system command 'cmd
2573 params' (from your underlying operating system).
2573 params' (from your underlying operating system).
2574
2574
2575 Aliases have lower precedence than magic functions and Python normal
2575 Aliases have lower precedence than magic functions and Python normal
2576 variables, so if 'foo' is both a Python variable and an alias, the
2576 variables, so if 'foo' is both a Python variable and an alias, the
2577 alias can not be executed until 'del foo' removes the Python variable.
2577 alias can not be executed until 'del foo' removes the Python variable.
2578
2578
2579 You can use the %l specifier in an alias definition to represent the
2579 You can use the %l specifier in an alias definition to represent the
2580 whole line when the alias is called. For example:
2580 whole line when the alias is called. For example:
2581
2581
2582 In [2]: alias all echo "Input in brackets: <%l>"
2582 In [2]: alias all echo "Input in brackets: <%l>"
2583 In [3]: all hello world
2583 In [3]: all hello world
2584 Input in brackets: <hello world>
2584 Input in brackets: <hello world>
2585
2585
2586 You can also define aliases with parameters using %s specifiers (one
2586 You can also define aliases with parameters using %s specifiers (one
2587 per parameter):
2587 per parameter):
2588
2588
2589 In [1]: alias parts echo first %s second %s
2589 In [1]: alias parts echo first %s second %s
2590 In [2]: %parts A B
2590 In [2]: %parts A B
2591 first A second B
2591 first A second B
2592 In [3]: %parts A
2592 In [3]: %parts A
2593 Incorrect number of arguments: 2 expected.
2593 Incorrect number of arguments: 2 expected.
2594 parts is an alias to: 'echo first %s second %s'
2594 parts is an alias to: 'echo first %s second %s'
2595
2595
2596 Note that %l and %s are mutually exclusive. You can only use one or
2596 Note that %l and %s are mutually exclusive. You can only use one or
2597 the other in your aliases.
2597 the other in your aliases.
2598
2598
2599 Aliases expand Python variables just like system calls using ! or !!
2599 Aliases expand Python variables just like system calls using ! or !!
2600 do: all expressions prefixed with '$' get expanded. For details of
2600 do: all expressions prefixed with '$' get expanded. For details of
2601 the semantic rules, see PEP-215:
2601 the semantic rules, see PEP-215:
2602 http://www.python.org/peps/pep-0215.html. This is the library used by
2602 http://www.python.org/peps/pep-0215.html. This is the library used by
2603 IPython for variable expansion. If you want to access a true shell
2603 IPython for variable expansion. If you want to access a true shell
2604 variable, an extra $ is necessary to prevent its expansion by IPython:
2604 variable, an extra $ is necessary to prevent its expansion by IPython:
2605
2605
2606 In [6]: alias show echo
2606 In [6]: alias show echo
2607 In [7]: PATH='A Python string'
2607 In [7]: PATH='A Python string'
2608 In [8]: show $PATH
2608 In [8]: show $PATH
2609 A Python string
2609 A Python string
2610 In [9]: show $$PATH
2610 In [9]: show $$PATH
2611 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2611 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2612
2612
2613 You can use the alias facility to acess all of $PATH. See the %rehash
2613 You can use the alias facility to acess all of $PATH. See the %rehash
2614 and %rehashx functions, which automatically create aliases for the
2614 and %rehashx functions, which automatically create aliases for the
2615 contents of your $PATH.
2615 contents of your $PATH.
2616
2616
2617 If called with no parameters, %alias prints the current alias table."""
2617 If called with no parameters, %alias prints the current alias table."""
2618
2618
2619 par = parameter_s.strip()
2619 par = parameter_s.strip()
2620 if not par:
2620 if not par:
2621 stored = self.db.get('stored_aliases', {} )
2621 stored = self.db.get('stored_aliases', {} )
2622 atab = self.shell.alias_table
2622 atab = self.shell.alias_table
2623 aliases = atab.keys()
2623 aliases = atab.keys()
2624 aliases.sort()
2624 aliases.sort()
2625 res = []
2625 res = []
2626 showlast = []
2626 showlast = []
2627 for alias in aliases:
2627 for alias in aliases:
2628 special = False
2628 special = False
2629 try:
2629 try:
2630 tgt = atab[alias][1]
2630 tgt = atab[alias][1]
2631 except (TypeError, AttributeError):
2631 except (TypeError, AttributeError):
2632 # unsubscriptable? probably a callable
2632 # unsubscriptable? probably a callable
2633 tgt = atab[alias]
2633 tgt = atab[alias]
2634 special = True
2634 special = True
2635 # 'interesting' aliases
2635 # 'interesting' aliases
2636 if (alias in stored or
2636 if (alias in stored or
2637 special or
2637 special or
2638 alias.lower() != os.path.splitext(tgt)[0].lower() or
2638 alias.lower() != os.path.splitext(tgt)[0].lower() or
2639 ' ' in tgt):
2639 ' ' in tgt):
2640 showlast.append((alias, tgt))
2640 showlast.append((alias, tgt))
2641 else:
2641 else:
2642 res.append((alias, tgt ))
2642 res.append((alias, tgt ))
2643
2643
2644 # show most interesting aliases last
2644 # show most interesting aliases last
2645 res.extend(showlast)
2645 res.extend(showlast)
2646 print "Total number of aliases:",len(aliases)
2646 print "Total number of aliases:",len(aliases)
2647 return res
2647 return res
2648 try:
2648 try:
2649 alias,cmd = par.split(None,1)
2649 alias,cmd = par.split(None,1)
2650 except:
2650 except:
2651 print oinspect.getdoc(self.magic_alias)
2651 print oinspect.getdoc(self.magic_alias)
2652 else:
2652 else:
2653 nargs = cmd.count('%s')
2653 nargs = cmd.count('%s')
2654 if nargs>0 and cmd.find('%l')>=0:
2654 if nargs>0 and cmd.find('%l')>=0:
2655 error('The %s and %l specifiers are mutually exclusive '
2655 error('The %s and %l specifiers are mutually exclusive '
2656 'in alias definitions.')
2656 'in alias definitions.')
2657 else: # all looks OK
2657 else: # all looks OK
2658 self.shell.alias_table[alias] = (nargs,cmd)
2658 self.shell.alias_table[alias] = (nargs,cmd)
2659 self.shell.alias_table_validate(verbose=0)
2659 self.shell.alias_table_validate(verbose=0)
2660 # end magic_alias
2660 # end magic_alias
2661
2661
2662 def magic_unalias(self, parameter_s = ''):
2662 def magic_unalias(self, parameter_s = ''):
2663 """Remove an alias"""
2663 """Remove an alias"""
2664
2664
2665 aname = parameter_s.strip()
2665 aname = parameter_s.strip()
2666 if aname in self.shell.alias_table:
2666 if aname in self.shell.alias_table:
2667 del self.shell.alias_table[aname]
2667 del self.shell.alias_table[aname]
2668 stored = self.db.get('stored_aliases', {} )
2668 stored = self.db.get('stored_aliases', {} )
2669 if aname in stored:
2669 if aname in stored:
2670 print "Removing %stored alias",aname
2670 print "Removing %stored alias",aname
2671 del stored[aname]
2671 del stored[aname]
2672 self.db['stored_aliases'] = stored
2672 self.db['stored_aliases'] = stored
2673
2673
2674
2674
2675 def magic_rehashx(self, parameter_s = ''):
2675 def magic_rehashx(self, parameter_s = ''):
2676 """Update the alias table with all executable files in $PATH.
2676 """Update the alias table with all executable files in $PATH.
2677
2677
2678 This version explicitly checks that every entry in $PATH is a file
2678 This version explicitly checks that every entry in $PATH is a file
2679 with execute access (os.X_OK), so it is much slower than %rehash.
2679 with execute access (os.X_OK), so it is much slower than %rehash.
2680
2680
2681 Under Windows, it checks executability as a match agains a
2681 Under Windows, it checks executability as a match agains a
2682 '|'-separated string of extensions, stored in the IPython config
2682 '|'-separated string of extensions, stored in the IPython config
2683 variable win_exec_ext. This defaults to 'exe|com|bat'.
2683 variable win_exec_ext. This defaults to 'exe|com|bat'.
2684
2684
2685 This function also resets the root module cache of module completer,
2685 This function also resets the root module cache of module completer,
2686 used on slow filesystems.
2686 used on slow filesystems.
2687 """
2687 """
2688
2688
2689
2689
2690 ip = self.api
2690 ip = self.api
2691
2691
2692 # for the benefit of module completer in ipy_completers.py
2692 # for the benefit of module completer in ipy_completers.py
2693 del ip.db['rootmodules']
2693 del ip.db['rootmodules']
2694
2694
2695 path = [os.path.abspath(os.path.expanduser(p)) for p in
2695 path = [os.path.abspath(os.path.expanduser(p)) for p in
2696 os.environ.get('PATH','').split(os.pathsep)]
2696 os.environ.get('PATH','').split(os.pathsep)]
2697 path = filter(os.path.isdir,path)
2697 path = filter(os.path.isdir,path)
2698
2698
2699 alias_table = self.shell.alias_table
2699 alias_table = self.shell.alias_table
2700 syscmdlist = []
2700 syscmdlist = []
2701 if os.name == 'posix':
2701 if os.name == 'posix':
2702 isexec = lambda fname:os.path.isfile(fname) and \
2702 isexec = lambda fname:os.path.isfile(fname) and \
2703 os.access(fname,os.X_OK)
2703 os.access(fname,os.X_OK)
2704 else:
2704 else:
2705
2705
2706 try:
2706 try:
2707 winext = os.environ['pathext'].replace(';','|').replace('.','')
2707 winext = os.environ['pathext'].replace(';','|').replace('.','')
2708 except KeyError:
2708 except KeyError:
2709 winext = 'exe|com|bat|py'
2709 winext = 'exe|com|bat|py'
2710 if 'py' not in winext:
2710 if 'py' not in winext:
2711 winext += '|py'
2711 winext += '|py'
2712 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2712 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2713 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2713 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2714 savedir = os.getcwd()
2714 savedir = os.getcwd()
2715 try:
2715 try:
2716 # write the whole loop for posix/Windows so we don't have an if in
2716 # write the whole loop for posix/Windows so we don't have an if in
2717 # the innermost part
2717 # the innermost part
2718 if os.name == 'posix':
2718 if os.name == 'posix':
2719 for pdir in path:
2719 for pdir in path:
2720 os.chdir(pdir)
2720 os.chdir(pdir)
2721 for ff in os.listdir(pdir):
2721 for ff in os.listdir(pdir):
2722 if isexec(ff) and ff not in self.shell.no_alias:
2722 if isexec(ff) and ff not in self.shell.no_alias:
2723 # each entry in the alias table must be (N,name),
2723 # each entry in the alias table must be (N,name),
2724 # where N is the number of positional arguments of the
2724 # where N is the number of positional arguments of the
2725 # alias.
2725 # alias.
2726 # Dots will be removed from alias names, since ipython
2726 # Dots will be removed from alias names, since ipython
2727 # assumes names with dots to be python code
2727 # assumes names with dots to be python code
2728 alias_table[ff.replace('.','')] = (0,ff)
2728 alias_table[ff.replace('.','')] = (0,ff)
2729 syscmdlist.append(ff)
2729 syscmdlist.append(ff)
2730 else:
2730 else:
2731 for pdir in path:
2731 for pdir in path:
2732 os.chdir(pdir)
2732 os.chdir(pdir)
2733 for ff in os.listdir(pdir):
2733 for ff in os.listdir(pdir):
2734 base, ext = os.path.splitext(ff)
2734 base, ext = os.path.splitext(ff)
2735 if isexec(ff) and base.lower() not in self.shell.no_alias:
2735 if isexec(ff) and base.lower() not in self.shell.no_alias:
2736 if ext.lower() == '.exe':
2736 if ext.lower() == '.exe':
2737 ff = base
2737 ff = base
2738 alias_table[base.lower().replace('.','')] = (0,ff)
2738 alias_table[base.lower().replace('.','')] = (0,ff)
2739 syscmdlist.append(ff)
2739 syscmdlist.append(ff)
2740 # Make sure the alias table doesn't contain keywords or builtins
2740 # Make sure the alias table doesn't contain keywords or builtins
2741 self.shell.alias_table_validate()
2741 self.shell.alias_table_validate()
2742 # Call again init_auto_alias() so we get 'rm -i' and other
2742 # Call again init_auto_alias() so we get 'rm -i' and other
2743 # modified aliases since %rehashx will probably clobber them
2743 # modified aliases since %rehashx will probably clobber them
2744
2744
2745 # no, we don't want them. if %rehashx clobbers them, good,
2745 # no, we don't want them. if %rehashx clobbers them, good,
2746 # we'll probably get better versions
2746 # we'll probably get better versions
2747 # self.shell.init_auto_alias()
2747 # self.shell.init_auto_alias()
2748 db = ip.db
2748 db = ip.db
2749 db['syscmdlist'] = syscmdlist
2749 db['syscmdlist'] = syscmdlist
2750 finally:
2750 finally:
2751 os.chdir(savedir)
2751 os.chdir(savedir)
2752
2752
2753 def magic_pwd(self, parameter_s = ''):
2753 def magic_pwd(self, parameter_s = ''):
2754 """Return the current working directory path."""
2754 """Return the current working directory path."""
2755 return os.getcwd()
2755 return os.getcwd()
2756
2756
2757 def magic_cd(self, parameter_s=''):
2757 def magic_cd(self, parameter_s=''):
2758 """Change the current working directory.
2758 """Change the current working directory.
2759
2759
2760 This command automatically maintains an internal list of directories
2760 This command automatically maintains an internal list of directories
2761 you visit during your IPython session, in the variable _dh. The
2761 you visit during your IPython session, in the variable _dh. The
2762 command %dhist shows this history nicely formatted. You can also
2762 command %dhist shows this history nicely formatted. You can also
2763 do 'cd -<tab>' to see directory history conveniently.
2763 do 'cd -<tab>' to see directory history conveniently.
2764
2764
2765 Usage:
2765 Usage:
2766
2766
2767 cd 'dir': changes to directory 'dir'.
2767 cd 'dir': changes to directory 'dir'.
2768
2768
2769 cd -: changes to the last visited directory.
2769 cd -: changes to the last visited directory.
2770
2770
2771 cd -<n>: changes to the n-th directory in the directory history.
2771 cd -<n>: changes to the n-th directory in the directory history.
2772
2772
2773 cd --foo: change to directory that matches 'foo' in history
2773 cd --foo: change to directory that matches 'foo' in history
2774
2774
2775 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2775 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2776 (note: cd <bookmark_name> is enough if there is no
2776 (note: cd <bookmark_name> is enough if there is no
2777 directory <bookmark_name>, but a bookmark with the name exists.)
2777 directory <bookmark_name>, but a bookmark with the name exists.)
2778 'cd -b <tab>' allows you to tab-complete bookmark names.
2778 'cd -b <tab>' allows you to tab-complete bookmark names.
2779
2779
2780 Options:
2780 Options:
2781
2781
2782 -q: quiet. Do not print the working directory after the cd command is
2782 -q: quiet. Do not print the working directory after the cd command is
2783 executed. By default IPython's cd command does print this directory,
2783 executed. By default IPython's cd command does print this directory,
2784 since the default prompts do not display path information.
2784 since the default prompts do not display path information.
2785
2785
2786 Note that !cd doesn't work for this purpose because the shell where
2786 Note that !cd doesn't work for this purpose because the shell where
2787 !command runs is immediately discarded after executing 'command'."""
2787 !command runs is immediately discarded after executing 'command'."""
2788
2788
2789 parameter_s = parameter_s.strip()
2789 parameter_s = parameter_s.strip()
2790 #bkms = self.shell.persist.get("bookmarks",{})
2790 #bkms = self.shell.persist.get("bookmarks",{})
2791
2791
2792 oldcwd = os.getcwd()
2792 oldcwd = os.getcwd()
2793 numcd = re.match(r'(-)(\d+)$',parameter_s)
2793 numcd = re.match(r'(-)(\d+)$',parameter_s)
2794 # jump in directory history by number
2794 # jump in directory history by number
2795 if numcd:
2795 if numcd:
2796 nn = int(numcd.group(2))
2796 nn = int(numcd.group(2))
2797 try:
2797 try:
2798 ps = self.shell.user_ns['_dh'][nn]
2798 ps = self.shell.user_ns['_dh'][nn]
2799 except IndexError:
2799 except IndexError:
2800 print 'The requested directory does not exist in history.'
2800 print 'The requested directory does not exist in history.'
2801 return
2801 return
2802 else:
2802 else:
2803 opts = {}
2803 opts = {}
2804 elif parameter_s.startswith('--'):
2804 elif parameter_s.startswith('--'):
2805 ps = None
2805 ps = None
2806 fallback = None
2806 fallback = None
2807 pat = parameter_s[2:]
2807 pat = parameter_s[2:]
2808 dh = self.shell.user_ns['_dh']
2808 dh = self.shell.user_ns['_dh']
2809 # first search only by basename (last component)
2809 # first search only by basename (last component)
2810 for ent in reversed(dh):
2810 for ent in reversed(dh):
2811 if pat in os.path.basename(ent) and os.path.isdir(ent):
2811 if pat in os.path.basename(ent) and os.path.isdir(ent):
2812 ps = ent
2812 ps = ent
2813 break
2813 break
2814
2814
2815 if fallback is None and pat in ent and os.path.isdir(ent):
2815 if fallback is None and pat in ent and os.path.isdir(ent):
2816 fallback = ent
2816 fallback = ent
2817
2817
2818 # if we have no last part match, pick the first full path match
2818 # if we have no last part match, pick the first full path match
2819 if ps is None:
2819 if ps is None:
2820 ps = fallback
2820 ps = fallback
2821
2821
2822 if ps is None:
2822 if ps is None:
2823 print "No matching entry in directory history"
2823 print "No matching entry in directory history"
2824 return
2824 return
2825 else:
2825 else:
2826 opts = {}
2826 opts = {}
2827
2827
2828
2828
2829 else:
2829 else:
2830 #turn all non-space-escaping backslashes to slashes,
2830 #turn all non-space-escaping backslashes to slashes,
2831 # for c:\windows\directory\names\
2831 # for c:\windows\directory\names\
2832 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2832 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2833 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2833 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2834 # jump to previous
2834 # jump to previous
2835 if ps == '-':
2835 if ps == '-':
2836 try:
2836 try:
2837 ps = self.shell.user_ns['_dh'][-2]
2837 ps = self.shell.user_ns['_dh'][-2]
2838 except IndexError:
2838 except IndexError:
2839 raise UsageError('%cd -: No previous directory to change to.')
2839 raise UsageError('%cd -: No previous directory to change to.')
2840 # jump to bookmark if needed
2840 # jump to bookmark if needed
2841 else:
2841 else:
2842 if not os.path.isdir(ps) or opts.has_key('b'):
2842 if not os.path.isdir(ps) or opts.has_key('b'):
2843 bkms = self.db.get('bookmarks', {})
2843 bkms = self.db.get('bookmarks', {})
2844
2844
2845 if bkms.has_key(ps):
2845 if bkms.has_key(ps):
2846 target = bkms[ps]
2846 target = bkms[ps]
2847 print '(bookmark:%s) -> %s' % (ps,target)
2847 print '(bookmark:%s) -> %s' % (ps,target)
2848 ps = target
2848 ps = target
2849 else:
2849 else:
2850 if opts.has_key('b'):
2850 if opts.has_key('b'):
2851 raise UsageError("Bookmark '%s' not found. "
2851 raise UsageError("Bookmark '%s' not found. "
2852 "Use '%%bookmark -l' to see your bookmarks." % ps)
2852 "Use '%%bookmark -l' to see your bookmarks." % ps)
2853
2853
2854 # at this point ps should point to the target dir
2854 # at this point ps should point to the target dir
2855 if ps:
2855 if ps:
2856 try:
2856 try:
2857 os.chdir(os.path.expanduser(ps))
2857 os.chdir(os.path.expanduser(ps))
2858 if self.shell.term_title:
2858 if self.shell.term_title:
2859 #print 'set term title:',self.shell.term_title # dbg
2859 #print 'set term title:',self.shell.term_title # dbg
2860 platutils.set_term_title('IPy ' + abbrev_cwd())
2860 platutils.set_term_title('IPy ' + abbrev_cwd())
2861 except OSError:
2861 except OSError:
2862 print sys.exc_info()[1]
2862 print sys.exc_info()[1]
2863 else:
2863 else:
2864 cwd = os.getcwd()
2864 cwd = os.getcwd()
2865 dhist = self.shell.user_ns['_dh']
2865 dhist = self.shell.user_ns['_dh']
2866 if oldcwd != cwd:
2866 if oldcwd != cwd:
2867 dhist.append(cwd)
2867 dhist.append(cwd)
2868 self.db['dhist'] = compress_dhist(dhist)[-100:]
2868 self.db['dhist'] = compress_dhist(dhist)[-100:]
2869
2869
2870 else:
2870 else:
2871 os.chdir(self.shell.home_dir)
2871 os.chdir(self.shell.home_dir)
2872 if self.shell.term_title:
2872 if self.shell.term_title:
2873 platutils.set_term_title("IPy ~")
2873 platutils.set_term_title("IPy ~")
2874 cwd = os.getcwd()
2874 cwd = os.getcwd()
2875 dhist = self.shell.user_ns['_dh']
2875 dhist = self.shell.user_ns['_dh']
2876
2876
2877 if oldcwd != cwd:
2877 if oldcwd != cwd:
2878 dhist.append(cwd)
2878 dhist.append(cwd)
2879 self.db['dhist'] = compress_dhist(dhist)[-100:]
2879 self.db['dhist'] = compress_dhist(dhist)[-100:]
2880 if not 'q' in opts and self.shell.user_ns['_dh']:
2880 if not 'q' in opts and self.shell.user_ns['_dh']:
2881 print self.shell.user_ns['_dh'][-1]
2881 print self.shell.user_ns['_dh'][-1]
2882
2882
2883
2883
2884 def magic_env(self, parameter_s=''):
2884 def magic_env(self, parameter_s=''):
2885 """List environment variables."""
2885 """List environment variables."""
2886
2886
2887 return os.environ.data
2887 return os.environ.data
2888
2888
2889 def magic_pushd(self, parameter_s=''):
2889 def magic_pushd(self, parameter_s=''):
2890 """Place the current dir on stack and change directory.
2890 """Place the current dir on stack and change directory.
2891
2891
2892 Usage:\\
2892 Usage:\\
2893 %pushd ['dirname']
2893 %pushd ['dirname']
2894 """
2894 """
2895
2895
2896 dir_s = self.shell.dir_stack
2896 dir_s = self.shell.dir_stack
2897 tgt = os.path.expanduser(parameter_s)
2897 tgt = os.path.expanduser(parameter_s)
2898 cwd = os.getcwd().replace(self.home_dir,'~')
2898 cwd = os.getcwd().replace(self.home_dir,'~')
2899 if tgt:
2899 if tgt:
2900 self.magic_cd(parameter_s)
2900 self.magic_cd(parameter_s)
2901 dir_s.insert(0,cwd)
2901 dir_s.insert(0,cwd)
2902 return self.magic_dirs()
2902 return self.magic_dirs()
2903
2903
2904 def magic_popd(self, parameter_s=''):
2904 def magic_popd(self, parameter_s=''):
2905 """Change to directory popped off the top of the stack.
2905 """Change to directory popped off the top of the stack.
2906 """
2906 """
2907 if not self.shell.dir_stack:
2907 if not self.shell.dir_stack:
2908 raise UsageError("%popd on empty stack")
2908 raise UsageError("%popd on empty stack")
2909 top = self.shell.dir_stack.pop(0)
2909 top = self.shell.dir_stack.pop(0)
2910 self.magic_cd(top)
2910 self.magic_cd(top)
2911 print "popd ->",top
2911 print "popd ->",top
2912
2912
2913 def magic_dirs(self, parameter_s=''):
2913 def magic_dirs(self, parameter_s=''):
2914 """Return the current directory stack."""
2914 """Return the current directory stack."""
2915
2915
2916 return self.shell.dir_stack
2916 return self.shell.dir_stack
2917
2917
2918 def magic_dhist(self, parameter_s=''):
2918 def magic_dhist(self, parameter_s=''):
2919 """Print your history of visited directories.
2919 """Print your history of visited directories.
2920
2920
2921 %dhist -> print full history\\
2921 %dhist -> print full history\\
2922 %dhist n -> print last n entries only\\
2922 %dhist n -> print last n entries only\\
2923 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2923 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2924
2924
2925 This history is automatically maintained by the %cd command, and
2925 This history is automatically maintained by the %cd command, and
2926 always available as the global list variable _dh. You can use %cd -<n>
2926 always available as the global list variable _dh. You can use %cd -<n>
2927 to go to directory number <n>.
2927 to go to directory number <n>.
2928
2928
2929 Note that most of time, you should view directory history by entering
2929 Note that most of time, you should view directory history by entering
2930 cd -<TAB>.
2930 cd -<TAB>.
2931
2931
2932 """
2932 """
2933
2933
2934 dh = self.shell.user_ns['_dh']
2934 dh = self.shell.user_ns['_dh']
2935 if parameter_s:
2935 if parameter_s:
2936 try:
2936 try:
2937 args = map(int,parameter_s.split())
2937 args = map(int,parameter_s.split())
2938 except:
2938 except:
2939 self.arg_err(Magic.magic_dhist)
2939 self.arg_err(Magic.magic_dhist)
2940 return
2940 return
2941 if len(args) == 1:
2941 if len(args) == 1:
2942 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2942 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2943 elif len(args) == 2:
2943 elif len(args) == 2:
2944 ini,fin = args
2944 ini,fin = args
2945 else:
2945 else:
2946 self.arg_err(Magic.magic_dhist)
2946 self.arg_err(Magic.magic_dhist)
2947 return
2947 return
2948 else:
2948 else:
2949 ini,fin = 0,len(dh)
2949 ini,fin = 0,len(dh)
2950 nlprint(dh,
2950 nlprint(dh,
2951 header = 'Directory history (kept in _dh)',
2951 header = 'Directory history (kept in _dh)',
2952 start=ini,stop=fin)
2952 start=ini,stop=fin)
2953
2953
2954 @testdec.skip_doctest
2954 @testdec.skip_doctest
2955 def magic_sc(self, parameter_s=''):
2955 def magic_sc(self, parameter_s=''):
2956 """Shell capture - execute a shell command and capture its output.
2956 """Shell capture - execute a shell command and capture its output.
2957
2957
2958 DEPRECATED. Suboptimal, retained for backwards compatibility.
2958 DEPRECATED. Suboptimal, retained for backwards compatibility.
2959
2959
2960 You should use the form 'var = !command' instead. Example:
2960 You should use the form 'var = !command' instead. Example:
2961
2961
2962 "%sc -l myfiles = ls ~" should now be written as
2962 "%sc -l myfiles = ls ~" should now be written as
2963
2963
2964 "myfiles = !ls ~"
2964 "myfiles = !ls ~"
2965
2965
2966 myfiles.s, myfiles.l and myfiles.n still apply as documented
2966 myfiles.s, myfiles.l and myfiles.n still apply as documented
2967 below.
2967 below.
2968
2968
2969 --
2969 --
2970 %sc [options] varname=command
2970 %sc [options] varname=command
2971
2971
2972 IPython will run the given command using commands.getoutput(), and
2972 IPython will run the given command using commands.getoutput(), and
2973 will then update the user's interactive namespace with a variable
2973 will then update the user's interactive namespace with a variable
2974 called varname, containing the value of the call. Your command can
2974 called varname, containing the value of the call. Your command can
2975 contain shell wildcards, pipes, etc.
2975 contain shell wildcards, pipes, etc.
2976
2976
2977 The '=' sign in the syntax is mandatory, and the variable name you
2977 The '=' sign in the syntax is mandatory, and the variable name you
2978 supply must follow Python's standard conventions for valid names.
2978 supply must follow Python's standard conventions for valid names.
2979
2979
2980 (A special format without variable name exists for internal use)
2980 (A special format without variable name exists for internal use)
2981
2981
2982 Options:
2982 Options:
2983
2983
2984 -l: list output. Split the output on newlines into a list before
2984 -l: list output. Split the output on newlines into a list before
2985 assigning it to the given variable. By default the output is stored
2985 assigning it to the given variable. By default the output is stored
2986 as a single string.
2986 as a single string.
2987
2987
2988 -v: verbose. Print the contents of the variable.
2988 -v: verbose. Print the contents of the variable.
2989
2989
2990 In most cases you should not need to split as a list, because the
2990 In most cases you should not need to split as a list, because the
2991 returned value is a special type of string which can automatically
2991 returned value is a special type of string which can automatically
2992 provide its contents either as a list (split on newlines) or as a
2992 provide its contents either as a list (split on newlines) or as a
2993 space-separated string. These are convenient, respectively, either
2993 space-separated string. These are convenient, respectively, either
2994 for sequential processing or to be passed to a shell command.
2994 for sequential processing or to be passed to a shell command.
2995
2995
2996 For example:
2996 For example:
2997
2997
2998 # all-random
2998 # all-random
2999
2999
3000 # Capture into variable a
3000 # Capture into variable a
3001 In [1]: sc a=ls *py
3001 In [1]: sc a=ls *py
3002
3002
3003 # a is a string with embedded newlines
3003 # a is a string with embedded newlines
3004 In [2]: a
3004 In [2]: a
3005 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3005 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3006
3006
3007 # which can be seen as a list:
3007 # which can be seen as a list:
3008 In [3]: a.l
3008 In [3]: a.l
3009 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3009 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3010
3010
3011 # or as a whitespace-separated string:
3011 # or as a whitespace-separated string:
3012 In [4]: a.s
3012 In [4]: a.s
3013 Out[4]: 'setup.py win32_manual_post_install.py'
3013 Out[4]: 'setup.py win32_manual_post_install.py'
3014
3014
3015 # a.s is useful to pass as a single command line:
3015 # a.s is useful to pass as a single command line:
3016 In [5]: !wc -l $a.s
3016 In [5]: !wc -l $a.s
3017 146 setup.py
3017 146 setup.py
3018 130 win32_manual_post_install.py
3018 130 win32_manual_post_install.py
3019 276 total
3019 276 total
3020
3020
3021 # while the list form is useful to loop over:
3021 # while the list form is useful to loop over:
3022 In [6]: for f in a.l:
3022 In [6]: for f in a.l:
3023 ...: !wc -l $f
3023 ...: !wc -l $f
3024 ...:
3024 ...:
3025 146 setup.py
3025 146 setup.py
3026 130 win32_manual_post_install.py
3026 130 win32_manual_post_install.py
3027
3027
3028 Similiarly, the lists returned by the -l option are also special, in
3028 Similiarly, the lists returned by the -l option are also special, in
3029 the sense that you can equally invoke the .s attribute on them to
3029 the sense that you can equally invoke the .s attribute on them to
3030 automatically get a whitespace-separated string from their contents:
3030 automatically get a whitespace-separated string from their contents:
3031
3031
3032 In [7]: sc -l b=ls *py
3032 In [7]: sc -l b=ls *py
3033
3033
3034 In [8]: b
3034 In [8]: b
3035 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3035 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3036
3036
3037 In [9]: b.s
3037 In [9]: b.s
3038 Out[9]: 'setup.py win32_manual_post_install.py'
3038 Out[9]: 'setup.py win32_manual_post_install.py'
3039
3039
3040 In summary, both the lists and strings used for ouptut capture have
3040 In summary, both the lists and strings used for ouptut capture have
3041 the following special attributes:
3041 the following special attributes:
3042
3042
3043 .l (or .list) : value as list.
3043 .l (or .list) : value as list.
3044 .n (or .nlstr): value as newline-separated string.
3044 .n (or .nlstr): value as newline-separated string.
3045 .s (or .spstr): value as space-separated string.
3045 .s (or .spstr): value as space-separated string.
3046 """
3046 """
3047
3047
3048 opts,args = self.parse_options(parameter_s,'lv')
3048 opts,args = self.parse_options(parameter_s,'lv')
3049 # Try to get a variable name and command to run
3049 # Try to get a variable name and command to run
3050 try:
3050 try:
3051 # the variable name must be obtained from the parse_options
3051 # the variable name must be obtained from the parse_options
3052 # output, which uses shlex.split to strip options out.
3052 # output, which uses shlex.split to strip options out.
3053 var,_ = args.split('=',1)
3053 var,_ = args.split('=',1)
3054 var = var.strip()
3054 var = var.strip()
3055 # But the the command has to be extracted from the original input
3055 # But the the command has to be extracted from the original input
3056 # parameter_s, not on what parse_options returns, to avoid the
3056 # parameter_s, not on what parse_options returns, to avoid the
3057 # quote stripping which shlex.split performs on it.
3057 # quote stripping which shlex.split performs on it.
3058 _,cmd = parameter_s.split('=',1)
3058 _,cmd = parameter_s.split('=',1)
3059 except ValueError:
3059 except ValueError:
3060 var,cmd = '',''
3060 var,cmd = '',''
3061 # If all looks ok, proceed
3061 # If all looks ok, proceed
3062 out,err = self.shell.getoutputerror(cmd)
3062 out,err = self.shell.getoutputerror(cmd)
3063 if err:
3063 if err:
3064 print >> Term.cerr,err
3064 print >> Term.cerr,err
3065 if opts.has_key('l'):
3065 if opts.has_key('l'):
3066 out = SList(out.split('\n'))
3066 out = SList(out.split('\n'))
3067 else:
3067 else:
3068 out = LSString(out)
3068 out = LSString(out)
3069 if opts.has_key('v'):
3069 if opts.has_key('v'):
3070 print '%s ==\n%s' % (var,pformat(out))
3070 print '%s ==\n%s' % (var,pformat(out))
3071 if var:
3071 if var:
3072 self.shell.user_ns.update({var:out})
3072 self.shell.user_ns.update({var:out})
3073 else:
3073 else:
3074 return out
3074 return out
3075
3075
3076 def magic_sx(self, parameter_s=''):
3076 def magic_sx(self, parameter_s=''):
3077 """Shell execute - run a shell command and capture its output.
3077 """Shell execute - run a shell command and capture its output.
3078
3078
3079 %sx command
3079 %sx command
3080
3080
3081 IPython will run the given command using commands.getoutput(), and
3081 IPython will run the given command using commands.getoutput(), and
3082 return the result formatted as a list (split on '\\n'). Since the
3082 return the result formatted as a list (split on '\\n'). Since the
3083 output is _returned_, it will be stored in ipython's regular output
3083 output is _returned_, it will be stored in ipython's regular output
3084 cache Out[N] and in the '_N' automatic variables.
3084 cache Out[N] and in the '_N' automatic variables.
3085
3085
3086 Notes:
3086 Notes:
3087
3087
3088 1) If an input line begins with '!!', then %sx is automatically
3088 1) If an input line begins with '!!', then %sx is automatically
3089 invoked. That is, while:
3089 invoked. That is, while:
3090 !ls
3090 !ls
3091 causes ipython to simply issue system('ls'), typing
3091 causes ipython to simply issue system('ls'), typing
3092 !!ls
3092 !!ls
3093 is a shorthand equivalent to:
3093 is a shorthand equivalent to:
3094 %sx ls
3094 %sx ls
3095
3095
3096 2) %sx differs from %sc in that %sx automatically splits into a list,
3096 2) %sx differs from %sc in that %sx automatically splits into a list,
3097 like '%sc -l'. The reason for this is to make it as easy as possible
3097 like '%sc -l'. The reason for this is to make it as easy as possible
3098 to process line-oriented shell output via further python commands.
3098 to process line-oriented shell output via further python commands.
3099 %sc is meant to provide much finer control, but requires more
3099 %sc is meant to provide much finer control, but requires more
3100 typing.
3100 typing.
3101
3101
3102 3) Just like %sc -l, this is a list with special attributes:
3102 3) Just like %sc -l, this is a list with special attributes:
3103
3103
3104 .l (or .list) : value as list.
3104 .l (or .list) : value as list.
3105 .n (or .nlstr): value as newline-separated string.
3105 .n (or .nlstr): value as newline-separated string.
3106 .s (or .spstr): value as whitespace-separated string.
3106 .s (or .spstr): value as whitespace-separated string.
3107
3107
3108 This is very useful when trying to use such lists as arguments to
3108 This is very useful when trying to use such lists as arguments to
3109 system commands."""
3109 system commands."""
3110
3110
3111 if parameter_s:
3111 if parameter_s:
3112 out,err = self.shell.getoutputerror(parameter_s)
3112 out,err = self.shell.getoutputerror(parameter_s)
3113 if err:
3113 if err:
3114 print >> Term.cerr,err
3114 print >> Term.cerr,err
3115 return SList(out.split('\n'))
3115 return SList(out.split('\n'))
3116
3116
3117 def magic_bg(self, parameter_s=''):
3117 def magic_bg(self, parameter_s=''):
3118 """Run a job in the background, in a separate thread.
3118 """Run a job in the background, in a separate thread.
3119
3119
3120 For example,
3120 For example,
3121
3121
3122 %bg myfunc(x,y,z=1)
3122 %bg myfunc(x,y,z=1)
3123
3123
3124 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3124 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3125 execution starts, a message will be printed indicating the job
3125 execution starts, a message will be printed indicating the job
3126 number. If your job number is 5, you can use
3126 number. If your job number is 5, you can use
3127
3127
3128 myvar = jobs.result(5) or myvar = jobs[5].result
3128 myvar = jobs.result(5) or myvar = jobs[5].result
3129
3129
3130 to assign this result to variable 'myvar'.
3130 to assign this result to variable 'myvar'.
3131
3131
3132 IPython has a job manager, accessible via the 'jobs' object. You can
3132 IPython has a job manager, accessible via the 'jobs' object. You can
3133 type jobs? to get more information about it, and use jobs.<TAB> to see
3133 type jobs? to get more information about it, and use jobs.<TAB> to see
3134 its attributes. All attributes not starting with an underscore are
3134 its attributes. All attributes not starting with an underscore are
3135 meant for public use.
3135 meant for public use.
3136
3136
3137 In particular, look at the jobs.new() method, which is used to create
3137 In particular, look at the jobs.new() method, which is used to create
3138 new jobs. This magic %bg function is just a convenience wrapper
3138 new jobs. This magic %bg function is just a convenience wrapper
3139 around jobs.new(), for expression-based jobs. If you want to create a
3139 around jobs.new(), for expression-based jobs. If you want to create a
3140 new job with an explicit function object and arguments, you must call
3140 new job with an explicit function object and arguments, you must call
3141 jobs.new() directly.
3141 jobs.new() directly.
3142
3142
3143 The jobs.new docstring also describes in detail several important
3143 The jobs.new docstring also describes in detail several important
3144 caveats associated with a thread-based model for background job
3144 caveats associated with a thread-based model for background job
3145 execution. Type jobs.new? for details.
3145 execution. Type jobs.new? for details.
3146
3146
3147 You can check the status of all jobs with jobs.status().
3147 You can check the status of all jobs with jobs.status().
3148
3148
3149 The jobs variable is set by IPython into the Python builtin namespace.
3149 The jobs variable is set by IPython into the Python builtin namespace.
3150 If you ever declare a variable named 'jobs', you will shadow this
3150 If you ever declare a variable named 'jobs', you will shadow this
3151 name. You can either delete your global jobs variable to regain
3151 name. You can either delete your global jobs variable to regain
3152 access to the job manager, or make a new name and assign it manually
3152 access to the job manager, or make a new name and assign it manually
3153 to the manager (stored in IPython's namespace). For example, to
3153 to the manager (stored in IPython's namespace). For example, to
3154 assign the job manager to the Jobs name, use:
3154 assign the job manager to the Jobs name, use:
3155
3155
3156 Jobs = __builtins__.jobs"""
3156 Jobs = __builtins__.jobs"""
3157
3157
3158 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3158 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3159
3159
3160 def magic_r(self, parameter_s=''):
3160 def magic_r(self, parameter_s=''):
3161 """Repeat previous input.
3161 """Repeat previous input.
3162
3162
3163 Note: Consider using the more powerfull %rep instead!
3163 Note: Consider using the more powerfull %rep instead!
3164
3164
3165 If given an argument, repeats the previous command which starts with
3165 If given an argument, repeats the previous command which starts with
3166 the same string, otherwise it just repeats the previous input.
3166 the same string, otherwise it just repeats the previous input.
3167
3167
3168 Shell escaped commands (with ! as first character) are not recognized
3168 Shell escaped commands (with ! as first character) are not recognized
3169 by this system, only pure python code and magic commands.
3169 by this system, only pure python code and magic commands.
3170 """
3170 """
3171
3171
3172 start = parameter_s.strip()
3172 start = parameter_s.strip()
3173 esc_magic = self.shell.ESC_MAGIC
3173 esc_magic = self.shell.ESC_MAGIC
3174 # Identify magic commands even if automagic is on (which means
3174 # Identify magic commands even if automagic is on (which means
3175 # the in-memory version is different from that typed by the user).
3175 # the in-memory version is different from that typed by the user).
3176 if self.shell.automagic:
3176 if self.shell.automagic:
3177 start_magic = esc_magic+start
3177 start_magic = esc_magic+start
3178 else:
3178 else:
3179 start_magic = start
3179 start_magic = start
3180 # Look through the input history in reverse
3180 # Look through the input history in reverse
3181 for n in range(len(self.shell.input_hist)-2,0,-1):
3181 for n in range(len(self.shell.input_hist)-2,0,-1):
3182 input = self.shell.input_hist[n]
3182 input = self.shell.input_hist[n]
3183 # skip plain 'r' lines so we don't recurse to infinity
3183 # skip plain 'r' lines so we don't recurse to infinity
3184 if input != '_ip.magic("r")\n' and \
3184 if input != '_ip.magic("r")\n' and \
3185 (input.startswith(start) or input.startswith(start_magic)):
3185 (input.startswith(start) or input.startswith(start_magic)):
3186 #print 'match',`input` # dbg
3186 #print 'match',`input` # dbg
3187 print 'Executing:',input,
3187 print 'Executing:',input,
3188 self.shell.runlines(input)
3188 self.shell.runlines(input)
3189 return
3189 return
3190 print 'No previous input matching `%s` found.' % start
3190 print 'No previous input matching `%s` found.' % start
3191
3191
3192
3192
3193 def magic_bookmark(self, parameter_s=''):
3193 def magic_bookmark(self, parameter_s=''):
3194 """Manage IPython's bookmark system.
3194 """Manage IPython's bookmark system.
3195
3195
3196 %bookmark <name> - set bookmark to current dir
3196 %bookmark <name> - set bookmark to current dir
3197 %bookmark <name> <dir> - set bookmark to <dir>
3197 %bookmark <name> <dir> - set bookmark to <dir>
3198 %bookmark -l - list all bookmarks
3198 %bookmark -l - list all bookmarks
3199 %bookmark -d <name> - remove bookmark
3199 %bookmark -d <name> - remove bookmark
3200 %bookmark -r - remove all bookmarks
3200 %bookmark -r - remove all bookmarks
3201
3201
3202 You can later on access a bookmarked folder with:
3202 You can later on access a bookmarked folder with:
3203 %cd -b <name>
3203 %cd -b <name>
3204 or simply '%cd <name>' if there is no directory called <name> AND
3204 or simply '%cd <name>' if there is no directory called <name> AND
3205 there is such a bookmark defined.
3205 there is such a bookmark defined.
3206
3206
3207 Your bookmarks persist through IPython sessions, but they are
3207 Your bookmarks persist through IPython sessions, but they are
3208 associated with each profile."""
3208 associated with each profile."""
3209
3209
3210 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3210 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3211 if len(args) > 2:
3211 if len(args) > 2:
3212 raise UsageError("%bookmark: too many arguments")
3212 raise UsageError("%bookmark: too many arguments")
3213
3213
3214 bkms = self.db.get('bookmarks',{})
3214 bkms = self.db.get('bookmarks',{})
3215
3215
3216 if opts.has_key('d'):
3216 if opts.has_key('d'):
3217 try:
3217 try:
3218 todel = args[0]
3218 todel = args[0]
3219 except IndexError:
3219 except IndexError:
3220 raise UsageError(
3220 raise UsageError(
3221 "%bookmark -d: must provide a bookmark to delete")
3221 "%bookmark -d: must provide a bookmark to delete")
3222 else:
3222 else:
3223 try:
3223 try:
3224 del bkms[todel]
3224 del bkms[todel]
3225 except KeyError:
3225 except KeyError:
3226 raise UsageError(
3226 raise UsageError(
3227 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3227 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3228
3228
3229 elif opts.has_key('r'):
3229 elif opts.has_key('r'):
3230 bkms = {}
3230 bkms = {}
3231 elif opts.has_key('l'):
3231 elif opts.has_key('l'):
3232 bks = bkms.keys()
3232 bks = bkms.keys()
3233 bks.sort()
3233 bks.sort()
3234 if bks:
3234 if bks:
3235 size = max(map(len,bks))
3235 size = max(map(len,bks))
3236 else:
3236 else:
3237 size = 0
3237 size = 0
3238 fmt = '%-'+str(size)+'s -> %s'
3238 fmt = '%-'+str(size)+'s -> %s'
3239 print 'Current bookmarks:'
3239 print 'Current bookmarks:'
3240 for bk in bks:
3240 for bk in bks:
3241 print fmt % (bk,bkms[bk])
3241 print fmt % (bk,bkms[bk])
3242 else:
3242 else:
3243 if not args:
3243 if not args:
3244 raise UsageError("%bookmark: You must specify the bookmark name")
3244 raise UsageError("%bookmark: You must specify the bookmark name")
3245 elif len(args)==1:
3245 elif len(args)==1:
3246 bkms[args[0]] = os.getcwd()
3246 bkms[args[0]] = os.getcwd()
3247 elif len(args)==2:
3247 elif len(args)==2:
3248 bkms[args[0]] = args[1]
3248 bkms[args[0]] = args[1]
3249 self.db['bookmarks'] = bkms
3249 self.db['bookmarks'] = bkms
3250
3250
3251 def magic_pycat(self, parameter_s=''):
3251 def magic_pycat(self, parameter_s=''):
3252 """Show a syntax-highlighted file through a pager.
3252 """Show a syntax-highlighted file through a pager.
3253
3253
3254 This magic is similar to the cat utility, but it will assume the file
3254 This magic is similar to the cat utility, but it will assume the file
3255 to be Python source and will show it with syntax highlighting. """
3255 to be Python source and will show it with syntax highlighting. """
3256
3256
3257 try:
3257 try:
3258 filename = get_py_filename(parameter_s)
3258 filename = get_py_filename(parameter_s)
3259 cont = file_read(filename)
3259 cont = file_read(filename)
3260 except IOError:
3260 except IOError:
3261 try:
3261 try:
3262 cont = eval(parameter_s,self.user_ns)
3262 cont = eval(parameter_s,self.user_ns)
3263 except NameError:
3263 except NameError:
3264 cont = None
3264 cont = None
3265 if cont is None:
3265 if cont is None:
3266 print "Error: no such file or variable"
3266 print "Error: no such file or variable"
3267 return
3267 return
3268
3268
3269 page(self.shell.pycolorize(cont),
3269 page(self.shell.pycolorize(cont),
3270 screen_lines=self.shell.screen_length)
3270 screen_lines=self.shell.usable_screen_length)
3271
3271
3272 def _rerun_pasted(self):
3272 def _rerun_pasted(self):
3273 """ Rerun a previously pasted command.
3273 """ Rerun a previously pasted command.
3274 """
3274 """
3275 b = self.user_ns.get('pasted_block', None)
3275 b = self.user_ns.get('pasted_block', None)
3276 if b is None:
3276 if b is None:
3277 raise UsageError('No previous pasted block available')
3277 raise UsageError('No previous pasted block available')
3278 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3278 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3279 exec b in self.user_ns
3279 exec b in self.user_ns
3280
3280
3281 def _get_pasted_lines(self, sentinel):
3281 def _get_pasted_lines(self, sentinel):
3282 """ Yield pasted lines until the user enters the given sentinel value.
3282 """ Yield pasted lines until the user enters the given sentinel value.
3283 """
3283 """
3284 from IPython.core import iplib
3284 from IPython.core import iplib
3285 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3285 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3286 while True:
3286 while True:
3287 l = iplib.raw_input_original(':')
3287 l = iplib.raw_input_original(':')
3288 if l == sentinel:
3288 if l == sentinel:
3289 return
3289 return
3290 else:
3290 else:
3291 yield l
3291 yield l
3292
3292
3293 def _strip_pasted_lines_for_code(self, raw_lines):
3293 def _strip_pasted_lines_for_code(self, raw_lines):
3294 """ Strip non-code parts of a sequence of lines to return a block of
3294 """ Strip non-code parts of a sequence of lines to return a block of
3295 code.
3295 code.
3296 """
3296 """
3297 # Regular expressions that declare text we strip from the input:
3297 # Regular expressions that declare text we strip from the input:
3298 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3298 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3299 r'^\s*(\s?>)+', # Python input prompt
3299 r'^\s*(\s?>)+', # Python input prompt
3300 r'^\s*\.{3,}', # Continuation prompts
3300 r'^\s*\.{3,}', # Continuation prompts
3301 r'^\++',
3301 r'^\++',
3302 ]
3302 ]
3303
3303
3304 strip_from_start = map(re.compile,strip_re)
3304 strip_from_start = map(re.compile,strip_re)
3305
3305
3306 lines = []
3306 lines = []
3307 for l in raw_lines:
3307 for l in raw_lines:
3308 for pat in strip_from_start:
3308 for pat in strip_from_start:
3309 l = pat.sub('',l)
3309 l = pat.sub('',l)
3310 lines.append(l)
3310 lines.append(l)
3311
3311
3312 block = "\n".join(lines) + '\n'
3312 block = "\n".join(lines) + '\n'
3313 #print "block:\n",block
3313 #print "block:\n",block
3314 return block
3314 return block
3315
3315
3316 def _execute_block(self, block, par):
3316 def _execute_block(self, block, par):
3317 """ Execute a block, or store it in a variable, per the user's request.
3317 """ Execute a block, or store it in a variable, per the user's request.
3318 """
3318 """
3319 if not par:
3319 if not par:
3320 b = textwrap.dedent(block)
3320 b = textwrap.dedent(block)
3321 self.user_ns['pasted_block'] = b
3321 self.user_ns['pasted_block'] = b
3322 exec b in self.user_ns
3322 exec b in self.user_ns
3323 else:
3323 else:
3324 self.user_ns[par] = SList(block.splitlines())
3324 self.user_ns[par] = SList(block.splitlines())
3325 print "Block assigned to '%s'" % par
3325 print "Block assigned to '%s'" % par
3326
3326
3327 def magic_cpaste(self, parameter_s=''):
3327 def magic_cpaste(self, parameter_s=''):
3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3329
3329
3330 You must terminate the block with '--' (two minus-signs) alone on the
3330 You must terminate the block with '--' (two minus-signs) alone on the
3331 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3331 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3332 is the new sentinel for this operation)
3332 is the new sentinel for this operation)
3333
3333
3334 The block is dedented prior to execution to enable execution of method
3334 The block is dedented prior to execution to enable execution of method
3335 definitions. '>' and '+' characters at the beginning of a line are
3335 definitions. '>' and '+' characters at the beginning of a line are
3336 ignored, to allow pasting directly from e-mails, diff files and
3336 ignored, to allow pasting directly from e-mails, diff files and
3337 doctests (the '...' continuation prompt is also stripped). The
3337 doctests (the '...' continuation prompt is also stripped). The
3338 executed block is also assigned to variable named 'pasted_block' for
3338 executed block is also assigned to variable named 'pasted_block' for
3339 later editing with '%edit pasted_block'.
3339 later editing with '%edit pasted_block'.
3340
3340
3341 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3341 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3342 This assigns the pasted block to variable 'foo' as string, without
3342 This assigns the pasted block to variable 'foo' as string, without
3343 dedenting or executing it (preceding >>> and + is still stripped)
3343 dedenting or executing it (preceding >>> and + is still stripped)
3344
3344
3345 '%cpaste -r' re-executes the block previously entered by cpaste.
3345 '%cpaste -r' re-executes the block previously entered by cpaste.
3346
3346
3347 Do not be alarmed by garbled output on Windows (it's a readline bug).
3347 Do not be alarmed by garbled output on Windows (it's a readline bug).
3348 Just press enter and type -- (and press enter again) and the block
3348 Just press enter and type -- (and press enter again) and the block
3349 will be what was just pasted.
3349 will be what was just pasted.
3350
3350
3351 IPython statements (magics, shell escapes) are not supported (yet).
3351 IPython statements (magics, shell escapes) are not supported (yet).
3352
3352
3353 See also
3353 See also
3354 --------
3354 --------
3355 paste: automatically pull code from clipboard.
3355 paste: automatically pull code from clipboard.
3356 """
3356 """
3357
3357
3358 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3358 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3359 par = args.strip()
3359 par = args.strip()
3360 if opts.has_key('r'):
3360 if opts.has_key('r'):
3361 self._rerun_pasted()
3361 self._rerun_pasted()
3362 return
3362 return
3363
3363
3364 sentinel = opts.get('s','--')
3364 sentinel = opts.get('s','--')
3365
3365
3366 block = self._strip_pasted_lines_for_code(
3366 block = self._strip_pasted_lines_for_code(
3367 self._get_pasted_lines(sentinel))
3367 self._get_pasted_lines(sentinel))
3368
3368
3369 self._execute_block(block, par)
3369 self._execute_block(block, par)
3370
3370
3371 def magic_paste(self, parameter_s=''):
3371 def magic_paste(self, parameter_s=''):
3372 """Allows you to paste & execute a pre-formatted code block from clipboard.
3372 """Allows you to paste & execute a pre-formatted code block from clipboard.
3373
3373
3374 The text is pulled directly from the clipboard without user
3374 The text is pulled directly from the clipboard without user
3375 intervention and printed back on the screen before execution (unless
3375 intervention and printed back on the screen before execution (unless
3376 the -q flag is given to force quiet mode).
3376 the -q flag is given to force quiet mode).
3377
3377
3378 The block is dedented prior to execution to enable execution of method
3378 The block is dedented prior to execution to enable execution of method
3379 definitions. '>' and '+' characters at the beginning of a line are
3379 definitions. '>' and '+' characters at the beginning of a line are
3380 ignored, to allow pasting directly from e-mails, diff files and
3380 ignored, to allow pasting directly from e-mails, diff files and
3381 doctests (the '...' continuation prompt is also stripped). The
3381 doctests (the '...' continuation prompt is also stripped). The
3382 executed block is also assigned to variable named 'pasted_block' for
3382 executed block is also assigned to variable named 'pasted_block' for
3383 later editing with '%edit pasted_block'.
3383 later editing with '%edit pasted_block'.
3384
3384
3385 You can also pass a variable name as an argument, e.g. '%paste foo'.
3385 You can also pass a variable name as an argument, e.g. '%paste foo'.
3386 This assigns the pasted block to variable 'foo' as string, without
3386 This assigns the pasted block to variable 'foo' as string, without
3387 dedenting or executing it (preceding >>> and + is still stripped)
3387 dedenting or executing it (preceding >>> and + is still stripped)
3388
3388
3389 Options
3389 Options
3390 -------
3390 -------
3391
3391
3392 -r: re-executes the block previously entered by cpaste.
3392 -r: re-executes the block previously entered by cpaste.
3393
3393
3394 -q: quiet mode: do not echo the pasted text back to the terminal.
3394 -q: quiet mode: do not echo the pasted text back to the terminal.
3395
3395
3396 IPython statements (magics, shell escapes) are not supported (yet).
3396 IPython statements (magics, shell escapes) are not supported (yet).
3397
3397
3398 See also
3398 See also
3399 --------
3399 --------
3400 cpaste: manually paste code into terminal until you mark its end.
3400 cpaste: manually paste code into terminal until you mark its end.
3401 """
3401 """
3402 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3402 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3403 par = args.strip()
3403 par = args.strip()
3404 if opts.has_key('r'):
3404 if opts.has_key('r'):
3405 self._rerun_pasted()
3405 self._rerun_pasted()
3406 return
3406 return
3407
3407
3408 text = self.shell.hooks.clipboard_get()
3408 text = self.shell.hooks.clipboard_get()
3409 block = self._strip_pasted_lines_for_code(text.splitlines())
3409 block = self._strip_pasted_lines_for_code(text.splitlines())
3410
3410
3411 # By default, echo back to terminal unless quiet mode is requested
3411 # By default, echo back to terminal unless quiet mode is requested
3412 if not opts.has_key('q'):
3412 if not opts.has_key('q'):
3413 write = self.shell.write
3413 write = self.shell.write
3414 write(block)
3414 write(block)
3415 if not block.endswith('\n'):
3415 if not block.endswith('\n'):
3416 write('\n')
3416 write('\n')
3417 write("## -- End pasted text --\n")
3417 write("## -- End pasted text --\n")
3418
3418
3419 self._execute_block(block, par)
3419 self._execute_block(block, par)
3420
3420
3421 def magic_quickref(self,arg):
3421 def magic_quickref(self,arg):
3422 """ Show a quick reference sheet """
3422 """ Show a quick reference sheet """
3423 import IPython.core.usage
3423 import IPython.core.usage
3424 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3424 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3425
3425
3426 page(qr)
3426 page(qr)
3427
3427
3428 def magic_upgrade(self,arg):
3428 def magic_upgrade(self,arg):
3429 """ Upgrade your IPython installation
3429 """ Upgrade your IPython installation
3430
3430
3431 This will copy the config files that don't yet exist in your
3431 This will copy the config files that don't yet exist in your
3432 ipython dir from the system config dir. Use this after upgrading
3432 ipython dir from the system config dir. Use this after upgrading
3433 IPython if you don't wish to delete your .ipython dir.
3433 IPython if you don't wish to delete your .ipython dir.
3434
3434
3435 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3435 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3436 new users)
3436 new users)
3437
3437
3438 """
3438 """
3439 ip = self.getapi()
3439 ip = self.getapi()
3440 ipinstallation = path(IPython.__file__).dirname()
3440 ipinstallation = path(IPython.__file__).dirname()
3441 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3441 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3442 src_config = ipinstallation / 'config' / 'userconfig'
3442 src_config = ipinstallation / 'config' / 'userconfig'
3443 userdir = path(ip.options.IPYTHONDIR)
3443 userdir = path(ip.options.IPYTHONDIR)
3444 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3444 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3445 print ">",cmd
3445 print ">",cmd
3446 shell(cmd)
3446 shell(cmd)
3447 if arg == '-nolegacy':
3447 if arg == '-nolegacy':
3448 legacy = userdir.files('ipythonrc*')
3448 legacy = userdir.files('ipythonrc*')
3449 print "Nuking legacy files:",legacy
3449 print "Nuking legacy files:",legacy
3450
3450
3451 [p.remove() for p in legacy]
3451 [p.remove() for p in legacy]
3452 suffix = (sys.platform == 'win32' and '.ini' or '')
3452 suffix = (sys.platform == 'win32' and '.ini' or '')
3453 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3453 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3454
3454
3455
3455
3456 def magic_doctest_mode(self,parameter_s=''):
3456 def magic_doctest_mode(self,parameter_s=''):
3457 """Toggle doctest mode on and off.
3457 """Toggle doctest mode on and off.
3458
3458
3459 This mode allows you to toggle the prompt behavior between normal
3459 This mode allows you to toggle the prompt behavior between normal
3460 IPython prompts and ones that are as similar to the default IPython
3460 IPython prompts and ones that are as similar to the default IPython
3461 interpreter as possible.
3461 interpreter as possible.
3462
3462
3463 It also supports the pasting of code snippets that have leading '>>>'
3463 It also supports the pasting of code snippets that have leading '>>>'
3464 and '...' prompts in them. This means that you can paste doctests from
3464 and '...' prompts in them. This means that you can paste doctests from
3465 files or docstrings (even if they have leading whitespace), and the
3465 files or docstrings (even if they have leading whitespace), and the
3466 code will execute correctly. You can then use '%history -tn' to see
3466 code will execute correctly. You can then use '%history -tn' to see
3467 the translated history without line numbers; this will give you the
3467 the translated history without line numbers; this will give you the
3468 input after removal of all the leading prompts and whitespace, which
3468 input after removal of all the leading prompts and whitespace, which
3469 can be pasted back into an editor.
3469 can be pasted back into an editor.
3470
3470
3471 With these features, you can switch into this mode easily whenever you
3471 With these features, you can switch into this mode easily whenever you
3472 need to do testing and changes to doctests, without having to leave
3472 need to do testing and changes to doctests, without having to leave
3473 your existing IPython session.
3473 your existing IPython session.
3474 """
3474 """
3475
3475
3476 # XXX - Fix this to have cleaner activate/deactivate calls.
3476 # XXX - Fix this to have cleaner activate/deactivate calls.
3477 from IPython.extensions import InterpreterPasteInput as ipaste
3477 from IPython.extensions import InterpreterPasteInput as ipaste
3478 from IPython.utils.ipstruct import Struct
3478 from IPython.utils.ipstruct import Struct
3479
3479
3480 # Shorthands
3480 # Shorthands
3481 shell = self.shell
3481 shell = self.shell
3482 oc = shell.outputcache
3482 oc = shell.outputcache
3483 meta = shell.meta
3483 meta = shell.meta
3484 # dstore is a data store kept in the instance metadata bag to track any
3484 # dstore is a data store kept in the instance metadata bag to track any
3485 # changes we make, so we can undo them later.
3485 # changes we make, so we can undo them later.
3486 dstore = meta.setdefault('doctest_mode',Struct())
3486 dstore = meta.setdefault('doctest_mode',Struct())
3487 save_dstore = dstore.setdefault
3487 save_dstore = dstore.setdefault
3488
3488
3489 # save a few values we'll need to recover later
3489 # save a few values we'll need to recover later
3490 mode = save_dstore('mode',False)
3490 mode = save_dstore('mode',False)
3491 save_dstore('rc_pprint',shell.pprint)
3491 save_dstore('rc_pprint',shell.pprint)
3492 save_dstore('xmode',shell.InteractiveTB.mode)
3492 save_dstore('xmode',shell.InteractiveTB.mode)
3493 save_dstore('rc_separate_out',shell.separate_out)
3493 save_dstore('rc_separate_out',shell.separate_out)
3494 save_dstore('rc_separate_out2',shell.separate_out2)
3494 save_dstore('rc_separate_out2',shell.separate_out2)
3495 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3495 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3496 save_dstore('rc_separate_in',shell.separate_in)
3496 save_dstore('rc_separate_in',shell.separate_in)
3497
3497
3498 if mode == False:
3498 if mode == False:
3499 # turn on
3499 # turn on
3500 ipaste.activate_prefilter()
3500 ipaste.activate_prefilter()
3501
3501
3502 oc.prompt1.p_template = '>>> '
3502 oc.prompt1.p_template = '>>> '
3503 oc.prompt2.p_template = '... '
3503 oc.prompt2.p_template = '... '
3504 oc.prompt_out.p_template = ''
3504 oc.prompt_out.p_template = ''
3505
3505
3506 # Prompt separators like plain python
3506 # Prompt separators like plain python
3507 oc.input_sep = oc.prompt1.sep = ''
3507 oc.input_sep = oc.prompt1.sep = ''
3508 oc.output_sep = ''
3508 oc.output_sep = ''
3509 oc.output_sep2 = ''
3509 oc.output_sep2 = ''
3510
3510
3511 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3511 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3512 oc.prompt_out.pad_left = False
3512 oc.prompt_out.pad_left = False
3513
3513
3514 shell.pprint = False
3514 shell.pprint = False
3515
3515
3516 shell.magic_xmode('Plain')
3516 shell.magic_xmode('Plain')
3517
3517
3518 else:
3518 else:
3519 # turn off
3519 # turn off
3520 ipaste.deactivate_prefilter()
3520 ipaste.deactivate_prefilter()
3521
3521
3522 oc.prompt1.p_template = shell.prompt_in1
3522 oc.prompt1.p_template = shell.prompt_in1
3523 oc.prompt2.p_template = shell.prompt_in2
3523 oc.prompt2.p_template = shell.prompt_in2
3524 oc.prompt_out.p_template = shell.prompt_out
3524 oc.prompt_out.p_template = shell.prompt_out
3525
3525
3526 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3526 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3527
3527
3528 oc.output_sep = dstore.rc_separate_out
3528 oc.output_sep = dstore.rc_separate_out
3529 oc.output_sep2 = dstore.rc_separate_out2
3529 oc.output_sep2 = dstore.rc_separate_out2
3530
3530
3531 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3531 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3532 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3532 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3533
3533
3534 rc.pprint = dstore.rc_pprint
3534 rc.pprint = dstore.rc_pprint
3535
3535
3536 shell.magic_xmode(dstore.xmode)
3536 shell.magic_xmode(dstore.xmode)
3537
3537
3538 # Store new mode and inform
3538 # Store new mode and inform
3539 dstore.mode = bool(1-int(mode))
3539 dstore.mode = bool(1-int(mode))
3540 print 'Doctest mode is:',
3540 print 'Doctest mode is:',
3541 print ['OFF','ON'][dstore.mode]
3541 print ['OFF','ON'][dstore.mode]
3542
3542
3543 def magic_gui(self, parameter_s=''):
3543 def magic_gui(self, parameter_s=''):
3544 """Enable or disable IPython GUI event loop integration.
3544 """Enable or disable IPython GUI event loop integration.
3545
3545
3546 %gui [-a] [GUINAME]
3546 %gui [-a] [GUINAME]
3547
3547
3548 This magic replaces IPython's threaded shells that were activated
3548 This magic replaces IPython's threaded shells that were activated
3549 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3549 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3550 can now be enabled, disabled and swtiched at runtime and keyboard
3550 can now be enabled, disabled and swtiched at runtime and keyboard
3551 interrupts should work without any problems. The following toolkits
3551 interrupts should work without any problems. The following toolkits
3552 are supports: wxPython, PyQt4, PyGTK, and Tk::
3552 are supports: wxPython, PyQt4, PyGTK, and Tk::
3553
3553
3554 %gui wx # enable wxPython event loop integration
3554 %gui wx # enable wxPython event loop integration
3555 %gui qt4 # enable PyQt4 event loop integration
3555 %gui qt4 # enable PyQt4 event loop integration
3556 %gui gtk # enable PyGTK event loop integration
3556 %gui gtk # enable PyGTK event loop integration
3557 %gui tk # enable Tk event loop integration
3557 %gui tk # enable Tk event loop integration
3558 %gui # disable all event loop integration
3558 %gui # disable all event loop integration
3559
3559
3560 WARNING: after any of these has been called you can simply create
3560 WARNING: after any of these has been called you can simply create
3561 an application object, but DO NOT start the event loop yourself, as
3561 an application object, but DO NOT start the event loop yourself, as
3562 we have already handled that.
3562 we have already handled that.
3563
3563
3564 If you want us to create an appropriate application object add the
3564 If you want us to create an appropriate application object add the
3565 "-a" flag to your command::
3565 "-a" flag to your command::
3566
3566
3567 %gui -a wx
3567 %gui -a wx
3568
3568
3569 This is highly recommended for most users.
3569 This is highly recommended for most users.
3570 """
3570 """
3571 from IPython.lib import inputhook
3571 from IPython.lib import inputhook
3572 if "-a" in parameter_s:
3572 if "-a" in parameter_s:
3573 app = True
3573 app = True
3574 else:
3574 else:
3575 app = False
3575 app = False
3576 if not parameter_s:
3576 if not parameter_s:
3577 inputhook.clear_inputhook()
3577 inputhook.clear_inputhook()
3578 elif 'wx' in parameter_s:
3578 elif 'wx' in parameter_s:
3579 return inputhook.enable_wx(app)
3579 return inputhook.enable_wx(app)
3580 elif 'qt4' in parameter_s:
3580 elif 'qt4' in parameter_s:
3581 return inputhook.enable_qt4(app)
3581 return inputhook.enable_qt4(app)
3582 elif 'gtk' in parameter_s:
3582 elif 'gtk' in parameter_s:
3583 return inputhook.enable_gtk(app)
3583 return inputhook.enable_gtk(app)
3584 elif 'tk' in parameter_s:
3584 elif 'tk' in parameter_s:
3585 return inputhook.enable_tk(app)
3585 return inputhook.enable_tk(app)
3586
3586
3587
3587
3588 # end Magic
3588 # end Magic
@@ -1,586 +1,588 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 import sys
9 import sys
10 from IPython.core import release
10 from IPython.core import release
11
11
12 __doc__ = """
12 __doc__ = """
13 IPython -- An enhanced Interactive Python
13 IPython -- An enhanced Interactive Python
14 =========================================
14 =========================================
15
15
16 A Python shell with automatic history (input and output), dynamic object
16 A Python shell with automatic history (input and output), dynamic object
17 introspection, easier configuration, command completion, access to the system
17 introspection, easier configuration, command completion, access to the system
18 shell and more.
18 shell and more.
19
19
20 IPython can also be embedded in running programs. See EMBEDDING below.
20 IPython can also be embedded in running programs. See EMBEDDING below.
21
21
22
22
23 USAGE
23 USAGE
24 ipython [options] files
24 ipython [options] files
25
25
26 If invoked with no options, it executes all the files listed in
26 If invoked with no options, it executes all the files listed in
27 sequence and drops you into the interpreter while still acknowledging
27 sequence and drops you into the interpreter while still acknowledging
28 any options you may have set in your ipythonrc file. This behavior is
28 any options you may have set in your ipythonrc file. This behavior is
29 different from standard Python, which when called as python -i will
29 different from standard Python, which when called as python -i will
30 only execute one file and will ignore your configuration setup.
30 only execute one file and will ignore your configuration setup.
31
31
32 Please note that some of the configuration options are not available at
32 Please note that some of the configuration options are not available at
33 the command line, simply because they are not practical here. Look into
33 the command line, simply because they are not practical here. Look into
34 your ipythonrc configuration file for details on those. This file
34 your ipythonrc configuration file for details on those. This file
35 typically installed in the $HOME/.ipython directory.
35 typically installed in the $HOME/.ipython directory.
36
36
37 For Windows users, $HOME resolves to C:\\Documents and
37 For Windows users, $HOME resolves to C:\\Documents and
38 Settings\\YourUserName in most instances, and _ipython is used instead
38 Settings\\YourUserName in most instances, and _ipython is used instead
39 of .ipython, since some Win32 programs have problems with dotted names
39 of .ipython, since some Win32 programs have problems with dotted names
40 in directories.
40 in directories.
41
41
42 In the rest of this text, we will refer to this directory as
42 In the rest of this text, we will refer to this directory as
43 IPYTHONDIR.
43 IPYTHONDIR.
44
44
45 REGULAR OPTIONS
45 REGULAR OPTIONS
46 After the above threading options have been given, regular options can
46 After the above threading options have been given, regular options can
47 follow in any order. All options can be abbreviated to their shortest
47 follow in any order. All options can be abbreviated to their shortest
48 non-ambiguous form and are case-sensitive. One or two dashes can be
48 non-ambiguous form and are case-sensitive. One or two dashes can be
49 used. Some options have an alternate short form, indicated after a |.
49 used. Some options have an alternate short form, indicated after a |.
50
50
51 Most options can also be set from your ipythonrc configuration file.
51 Most options can also be set from your ipythonrc configuration file.
52 See the provided examples for assistance. Options given on the comman-
52 See the provided examples for assistance. Options given on the comman-
53 dline override the values set in the ipythonrc file.
53 dline override the values set in the ipythonrc file.
54
54
55 All options with a [no] prepended can be specified in negated form
55 All options with a [no] prepended can be specified in negated form
56 (using -nooption instead of -option) to turn the feature off.
56 (using -nooption instead of -option) to turn the feature off.
57
57
58 -h, --help
58 -h, --help
59 Show summary of options.
59 Show summary of options.
60
60
61 -autocall <val>
61 -autocall <val>
62 Make IPython automatically call any callable object even if you
62 Make IPython automatically call any callable object even if you
63 didn't type explicit parentheses. For example, 'str 43' becomes
63 didn't type explicit parentheses. For example, 'str 43' becomes
64 'str(43)' automatically. The value can be '0' to disable the
64 'str(43)' automatically. The value can be '0' to disable the
65 feature, '1' for 'smart' autocall, where it is not applied if
65 feature, '1' for 'smart' autocall, where it is not applied if
66 there are no more arguments on the line, and '2' for 'full'
66 there are no more arguments on the line, and '2' for 'full'
67 autocall, where all callable objects are automatically called
67 autocall, where all callable objects are automatically called
68 (even if no arguments are present). The default is '1'.
68 (even if no arguments are present). The default is '1'.
69
69
70 -[no]autoindent
70 -[no]autoindent
71 Turn automatic indentation on/off.
71 Turn automatic indentation on/off.
72
72
73 -[no]automagic
73 -[no]automagic
74 Make magic commands automatic (without needing their first char-
74 Make magic commands automatic (without needing their first char-
75 acter to be %). Type %magic at the IPython prompt for more
75 acter to be %). Type %magic at the IPython prompt for more
76 information.
76 information.
77
77
78 -[no]autoedit_syntax
78 -[no]autoedit_syntax
79 When a syntax error occurs after editing a file, automatically
79 When a syntax error occurs after editing a file, automatically
80 open the file to the trouble causing line for convenient fixing.
80 open the file to the trouble causing line for convenient fixing.
81
81
82 -[no]banner
82 -[no]banner
83 Print the intial information banner (default on).
83 Print the intial information banner (default on).
84
84
85 -c <command>
85 -c <command>
86 Execute the given command string, and set sys.argv to ['c'].
86 Execute the given command string, and set sys.argv to ['c'].
87 This is similar to the -c option in the normal Python inter-
87 This is similar to the -c option in the normal Python inter-
88 preter.
88 preter.
89
89
90 -cache_size|cs <n>
90 -cache_size|cs <n>
91 Size of the output cache (maximum number of entries to hold in
91 Size of the output cache (maximum number of entries to hold in
92 memory). The default is 1000, you can change it permanently in
92 memory). The default is 1000, you can change it permanently in
93 your config file. Setting it to 0 completely disables the
93 your config file. Setting it to 0 completely disables the
94 caching system, and the minimum value accepted is 20 (if you
94 caching system, and the minimum value accepted is 20 (if you
95 provide a value less than 20, it is reset to 0 and a warning is
95 provide a value less than 20, it is reset to 0 and a warning is
96 issued). This limit is defined because otherwise you'll spend
96 issued). This limit is defined because otherwise you'll spend
97 more time re-flushing a too small cache than working.
97 more time re-flushing a too small cache than working.
98
98
99 -classic|cl
99 -classic|cl
100 Gives IPython a similar feel to the classic Python prompt.
100 Gives IPython a similar feel to the classic Python prompt.
101
101
102 -colors <scheme>
102 -colors <scheme>
103 Color scheme for prompts and exception reporting. Currently
103 Color scheme for prompts and exception reporting. Currently
104 implemented: NoColor, Linux, and LightBG.
104 implemented: NoColor, Linux, and LightBG.
105
105
106 -[no]color_info
106 -[no]color_info
107 IPython can display information about objects via a set of func-
107 IPython can display information about objects via a set of func-
108 tions, and optionally can use colors for this, syntax highlight-
108 tions, and optionally can use colors for this, syntax highlight-
109 ing source code and various other elements. However, because
109 ing source code and various other elements. However, because
110 this information is passed through a pager (like 'less') and
110 this information is passed through a pager (like 'less') and
111 many pagers get confused with color codes, this option is off by
111 many pagers get confused with color codes, this option is off by
112 default. You can test it and turn it on permanently in your
112 default. You can test it and turn it on permanently in your
113 ipythonrc file if it works for you. As a reference, the 'less'
113 ipythonrc file if it works for you. As a reference, the 'less'
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
115 7.2 doesn't.
115 7.2 doesn't.
116
116
117 Test it and turn it on permanently if it works with your system.
117 Test it and turn it on permanently if it works with your system.
118 The magic function @color_info allows you to toggle this inter-
118 The magic function @color_info allows you to toggle this inter-
119 actively for testing.
119 actively for testing.
120
120
121 -[no]confirm_exit
121 -[no]confirm_exit
122 Set to confirm when you try to exit IPython with an EOF (Con-
122 Set to confirm when you try to exit IPython with an EOF (Con-
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
124 magic functions @Exit or @Quit you can force a direct exit,
124 magic functions @Exit or @Quit you can force a direct exit,
125 bypassing any confirmation.
125 bypassing any confirmation.
126
126
127 -[no]debug
127 -[no]debug
128 Show information about the loading process. Very useful to pin
128 Show information about the loading process. Very useful to pin
129 down problems with your configuration files or to get details
129 down problems with your configuration files or to get details
130 about session restores.
130 about session restores.
131
131
132 -[no]deep_reload
132 -[no]deep_reload
133 IPython can use the deep_reload module which reloads changes in
133 IPython can use the deep_reload module which reloads changes in
134 modules recursively (it replaces the reload() function, so you
134 modules recursively (it replaces the reload() function, so you
135 don't need to change anything to use it). deep_reload() forces a
135 don't need to change anything to use it). deep_reload() forces a
136 full reload of modules whose code may have changed, which the
136 full reload of modules whose code may have changed, which the
137 default reload() function does not.
137 default reload() function does not.
138
138
139 When deep_reload is off, IPython will use the normal reload(),
139 When deep_reload is off, IPython will use the normal reload(),
140 but deep_reload will still be available as dreload(). This fea-
140 but deep_reload will still be available as dreload(). This fea-
141 ture is off by default [which means that you have both normal
141 ture is off by default [which means that you have both normal
142 reload() and dreload()].
142 reload() and dreload()].
143
143
144 -editor <name>
144 -editor <name>
145 Which editor to use with the @edit command. By default, IPython
145 Which editor to use with the @edit command. By default, IPython
146 will honor your EDITOR environment variable (if not set, vi is
146 will honor your EDITOR environment variable (if not set, vi is
147 the Unix default and notepad the Windows one). Since this editor
147 the Unix default and notepad the Windows one). Since this editor
148 is invoked on the fly by IPython and is meant for editing small
148 is invoked on the fly by IPython and is meant for editing small
149 code snippets, you may want to use a small, lightweight editor
149 code snippets, you may want to use a small, lightweight editor
150 here (in case your default EDITOR is something like Emacs).
150 here (in case your default EDITOR is something like Emacs).
151
151
152 -ipythondir <name>
152 -ipythondir <name>
153 The name of your IPython configuration directory IPYTHONDIR.
153 The name of your IPython configuration directory IPYTHONDIR.
154 This can also be specified through the environment variable
154 This can also be specified through the environment variable
155 IPYTHONDIR.
155 IPYTHONDIR.
156
156
157 -log|l Generate a log file of all input. The file is named
157 -log|l Generate a log file of all input. The file is named
158 ipython_log.py in your current directory (which prevents logs
158 ipython_log.py in your current directory (which prevents logs
159 from multiple IPython sessions from trampling each other). You
159 from multiple IPython sessions from trampling each other). You
160 can use this to later restore a session by loading your logfile
160 can use this to later restore a session by loading your logfile
161 as a file to be executed with option -logplay (see below).
161 as a file to be executed with option -logplay (see below).
162
162
163 -logfile|lf
163 -logfile|lf
164 Specify the name of your logfile.
164 Specify the name of your logfile.
165
165
166 -logplay|lp
166 -logplay|lp
167 Replay a previous log. For restoring a session as close as pos-
167 Replay a previous log. For restoring a session as close as pos-
168 sible to the state you left it in, use this option (don't just
168 sible to the state you left it in, use this option (don't just
169 run the logfile). With -logplay, IPython will try to reconstruct
169 run the logfile). With -logplay, IPython will try to reconstruct
170 the previous working environment in full, not just execute the
170 the previous working environment in full, not just execute the
171 commands in the logfile.
171 commands in the logfile.
172 When a session is restored, logging is automatically turned on
172 When a session is restored, logging is automatically turned on
173 again with the name of the logfile it was invoked with (it is
173 again with the name of the logfile it was invoked with (it is
174 read from the log header). So once you've turned logging on for
174 read from the log header). So once you've turned logging on for
175 a session, you can quit IPython and reload it as many times as
175 a session, you can quit IPython and reload it as many times as
176 you want and it will continue to log its history and restore
176 you want and it will continue to log its history and restore
177 from the beginning every time.
177 from the beginning every time.
178
178
179 Caveats: there are limitations in this option. The history vari-
179 Caveats: there are limitations in this option. The history vari-
180 ables _i*,_* and _dh don't get restored properly. In the future
180 ables _i*,_* and _dh don't get restored properly. In the future
181 we will try to implement full session saving by writing and
181 we will try to implement full session saving by writing and
182 retrieving a failed because of inherent limitations of Python's
182 retrieving a failed because of inherent limitations of Python's
183 Pickle module, so this may have to wait.
183 Pickle module, so this may have to wait.
184
184
185 -[no]messages
185 -[no]messages
186 Print messages which IPython collects about its startup process
186 Print messages which IPython collects about its startup process
187 (default on).
187 (default on).
188
188
189 -[no]pdb
189 -[no]pdb
190 Automatically call the pdb debugger after every uncaught excep-
190 Automatically call the pdb debugger after every uncaught excep-
191 tion. If you are used to debugging using pdb, this puts you
191 tion. If you are used to debugging using pdb, this puts you
192 automatically inside of it after any call (either in IPython or
192 automatically inside of it after any call (either in IPython or
193 in code called by it) which triggers an exception which goes
193 in code called by it) which triggers an exception which goes
194 uncaught.
194 uncaught.
195
195
196 -[no]pprint
196 -[no]pprint
197 IPython can optionally use the pprint (pretty printer) module
197 IPython can optionally use the pprint (pretty printer) module
198 for displaying results. pprint tends to give a nicer display of
198 for displaying results. pprint tends to give a nicer display of
199 nested data structures. If you like it, you can turn it on per-
199 nested data structures. If you like it, you can turn it on per-
200 manently in your config file (default off).
200 manently in your config file (default off).
201
201
202 -profile|p <name>
202 -profile|p <name>
203 Assume that your config file is ipythonrc-<name> (looks in cur-
203 Assume that your config file is ipythonrc-<name> (looks in cur-
204 rent dir first, then in IPYTHONDIR). This is a quick way to keep
204 rent dir first, then in IPYTHONDIR). This is a quick way to keep
205 and load multiple config files for different tasks, especially
205 and load multiple config files for different tasks, especially
206 if you use the include option of config files. You can keep a
206 if you use the include option of config files. You can keep a
207 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
207 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
208 which include this one and load extra things for particular
208 which include this one and load extra things for particular
209 tasks. For example:
209 tasks. For example:
210
210
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
213 related modules.
213 related modules.
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
215 plotting modules.
215 plotting modules.
216
216
217 Since it is possible to create an endless loop by having circu-
217 Since it is possible to create an endless loop by having circu-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
219 sive inclusions.
219 sive inclusions.
220
220
221 -prompt_in1|pi1 <string>
221 -prompt_in1|pi1 <string>
222 Specify the string used for input prompts. Note that if you are
222 Specify the string used for input prompts. Note that if you are
223 using numbered prompts, the number is represented with a '\#' in
223 using numbered prompts, the number is represented with a '\#' in
224 the string. Don't forget to quote strings with spaces embedded
224 the string. Don't forget to quote strings with spaces embedded
225 in them. Default: 'In [\#]: '.
225 in them. Default: 'In [\#]: '.
226
226
227 Most bash-like escapes can be used to customize IPython's
227 Most bash-like escapes can be used to customize IPython's
228 prompts, as well as a few additional ones which are IPython-spe-
228 prompts, as well as a few additional ones which are IPython-spe-
229 cific. All valid prompt escapes are described in detail in the
229 cific. All valid prompt escapes are described in detail in the
230 Customization section of the IPython HTML/PDF manual.
230 Customization section of the IPython HTML/PDF manual.
231
231
232 -prompt_in2|pi2 <string>
232 -prompt_in2|pi2 <string>
233 Similar to the previous option, but used for the continuation
233 Similar to the previous option, but used for the continuation
234 prompts. The special sequence '\D' is similar to '\#', but with
234 prompts. The special sequence '\D' is similar to '\#', but with
235 all digits replaced dots (so you can have your continuation
235 all digits replaced dots (so you can have your continuation
236 prompt aligned with your input prompt). Default: ' .\D.: '
236 prompt aligned with your input prompt). Default: ' .\D.: '
237 (note three spaces at the start for alignment with 'In [\#]').
237 (note three spaces at the start for alignment with 'In [\#]').
238
238
239 -prompt_out|po <string>
239 -prompt_out|po <string>
240 String used for output prompts, also uses numbers like
240 String used for output prompts, also uses numbers like
241 prompt_in1. Default: 'Out[\#]:'.
241 prompt_in1. Default: 'Out[\#]:'.
242
242
243 -quick Start in bare bones mode (no config file loaded).
243 -quick Start in bare bones mode (no config file loaded).
244
244
245 -rcfile <name>
245 -rcfile <name>
246 Name of your IPython resource configuration file. normally
246 Name of your IPython resource configuration file. normally
247 IPython loads ipythonrc (from current directory) or
247 IPython loads ipythonrc (from current directory) or
248 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
248 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
249 IPython starts with a bare bones configuration (no modules
249 IPython starts with a bare bones configuration (no modules
250 loaded at all).
250 loaded at all).
251
251
252 -[no]readline
252 -[no]readline
253 Use the readline library, which is needed to support name com-
253 Use the readline library, which is needed to support name com-
254 pletion and command history, among other things. It is enabled
254 pletion and command history, among other things. It is enabled
255 by default, but may cause problems for users of X/Emacs in
255 by default, but may cause problems for users of X/Emacs in
256 Python comint or shell buffers.
256 Python comint or shell buffers.
257
257
258 Note that emacs 'eterm' buffers (opened with M-x term) support
258 Note that emacs 'eterm' buffers (opened with M-x term) support
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
260 shell and C-c !) buffers do not.
260 shell and C-c !) buffers do not.
261
261
262 -screen_length|sl <n>
262 -screen_length|sl <n>
263 Number of lines of your screen. This is used to control print-
263 Number of lines of your screen. This is used to control print-
264 ing of very long strings. Strings longer than this number of
264 ing of very long strings. Strings longer than this number of
265 lines will be sent through a pager instead of directly printed.
265 lines will be sent through a pager instead of directly printed.
266
266
267 The default value for this is 0, which means IPython will auto-
267 The default value for this is 0, which means IPython will auto-
268 detect your screen size every time it needs to print certain
268 detect your screen size every time it needs to print certain
269 potentially long strings (this doesn't change the behavior of
269 potentially long strings (this doesn't change the behavior of
270 the 'print' keyword, it's only triggered internally). If for
270 the 'print' keyword, it's only triggered internally). If for
271 some reason this isn't working well (it needs curses support),
271 some reason this isn't working well (it needs curses support),
272 specify it yourself. Otherwise don't change the default.
272 specify it yourself. Otherwise don't change the default.
273
273
274 -separate_in|si <string>
274 -separate_in|si <string>
275 Separator before input prompts. Default '0.
275 Separator before input prompts. Default '0.
276
276
277 -separate_out|so <string>
277 -separate_out|so <string>
278 Separator before output prompts. Default: 0 (nothing).
278 Separator before output prompts. Default: 0 (nothing).
279
279
280 -separate_out2|so2 <string>
280 -separate_out2|so2 <string>
281 Separator after output prompts. Default: 0 (nothing).
281 Separator after output prompts. Default: 0 (nothing).
282
282
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
284 Simply removes all input/output separators.
284 Simply removes all input/output separators.
285
285
286 -upgrade
286 -upgrade
287 Allows you to upgrade your IPYTHONDIR configuration when you
287 Allows you to upgrade your IPYTHONDIR configuration when you
288 install a new version of IPython. Since new versions may
288 install a new version of IPython. Since new versions may
289 include new command lines options or example files, this copies
289 include new command lines options or example files, this copies
290 updated ipythonrc-type files. However, it backs up (with a .old
290 updated ipythonrc-type files. However, it backs up (with a .old
291 extension) all files which it overwrites so that you can merge
291 extension) all files which it overwrites so that you can merge
292 back any custimizations you might have in your personal files.
292 back any custimizations you might have in your personal files.
293
293
294 -Version
294 -Version
295 Print version information and exit.
295 Print version information and exit.
296
296
297 -wxversion <string>
297 -wxversion <string>
298 Select a specific version of wxPython (used in conjunction with
298 Select a specific version of wxPython (used in conjunction with
299 -wthread). Requires the wxversion module, part of recent
299 -wthread). Requires the wxversion module, part of recent
300 wxPython distributions.
300 wxPython distributions.
301
301
302 -xmode <modename>
302 -xmode <modename>
303 Mode for exception reporting. The valid modes are Plain, Con-
303 Mode for exception reporting. The valid modes are Plain, Con-
304 text, and Verbose.
304 text, and Verbose.
305
305
306 - Plain: similar to python's normal traceback printing.
306 - Plain: similar to python's normal traceback printing.
307
307
308 - Context: prints 5 lines of context source code around each
308 - Context: prints 5 lines of context source code around each
309 line in the traceback.
309 line in the traceback.
310
310
311 - Verbose: similar to Context, but additionally prints the vari-
311 - Verbose: similar to Context, but additionally prints the vari-
312 ables currently visible where the exception happened (shortening
312 ables currently visible where the exception happened (shortening
313 their strings if too long). This can potentially be very slow,
313 their strings if too long). This can potentially be very slow,
314 if you happen to have a huge data structure whose string repre-
314 if you happen to have a huge data structure whose string repre-
315 sentation is complex to compute. Your computer may appear to
315 sentation is complex to compute. Your computer may appear to
316 freeze for a while with cpu usage at 100%. If this occurs, you
316 freeze for a while with cpu usage at 100%. If this occurs, you
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
318 once).
318 once).
319
319
320
320
321 EMBEDDING
321 EMBEDDING
322 It is possible to start an IPython instance inside your own Python pro-
322 It is possible to start an IPython instance inside your own Python pro-
323 grams. In the documentation example files there are some illustrations
323 grams. In the documentation example files there are some illustrations
324 on how to do this.
324 on how to do this.
325
325
326 This feature allows you to evalutate dynamically the state of your
326 This feature allows you to evalutate dynamically the state of your
327 code, operate with your variables, analyze them, etc. Note however
327 code, operate with your variables, analyze them, etc. Note however
328 that any changes you make to values while in the shell do NOT propagate
328 that any changes you make to values while in the shell do NOT propagate
329 back to the running code, so it is safe to modify your values because
329 back to the running code, so it is safe to modify your values because
330 you won't break your code in bizarre ways by doing so.
330 you won't break your code in bizarre ways by doing so.
331 """
331 """
332
332
333 cmd_line_usage = __doc__
333 cmd_line_usage = __doc__
334
334
335 #---------------------------------------------------------------------------
335 #---------------------------------------------------------------------------
336 interactive_usage = """
336 interactive_usage = """
337 IPython -- An enhanced Interactive Python
337 IPython -- An enhanced Interactive Python
338 =========================================
338 =========================================
339
339
340 IPython offers a combination of convenient shell features, special commands
340 IPython offers a combination of convenient shell features, special commands
341 and a history mechanism for both input (command history) and output (results
341 and a history mechanism for both input (command history) and output (results
342 caching, similar to Mathematica). It is intended to be a fully compatible
342 caching, similar to Mathematica). It is intended to be a fully compatible
343 replacement for the standard Python interpreter, while offering vastly
343 replacement for the standard Python interpreter, while offering vastly
344 improved functionality and flexibility.
344 improved functionality and flexibility.
345
345
346 At your system command line, type 'ipython -help' to see the command line
346 At your system command line, type 'ipython -help' to see the command line
347 options available. This document only describes interactive features.
347 options available. This document only describes interactive features.
348
348
349 Warning: IPython relies on the existence of a global variable called __IP which
349 Warning: IPython relies on the existence of a global variable called __IP which
350 controls the shell itself. If you redefine __IP to anything, bizarre behavior
350 controls the shell itself. If you redefine __IP to anything, bizarre behavior
351 will quickly occur.
351 will quickly occur.
352
352
353 MAIN FEATURES
353 MAIN FEATURES
354
354
355 * Access to the standard Python help. As of Python 2.1, a help system is
355 * Access to the standard Python help. As of Python 2.1, a help system is
356 available with access to object docstrings and the Python manuals. Simply
356 available with access to object docstrings and the Python manuals. Simply
357 type 'help' (no quotes) to access it.
357 type 'help' (no quotes) to access it.
358
358
359 * Magic commands: type %magic for information on the magic subsystem.
359 * Magic commands: type %magic for information on the magic subsystem.
360
360
361 * System command aliases, via the %alias command or the ipythonrc config file.
361 * System command aliases, via the %alias command or the ipythonrc config file.
362
362
363 * Dynamic object information:
363 * Dynamic object information:
364
364
365 Typing ?word or word? prints detailed information about an object. If
365 Typing ?word or word? prints detailed information about an object. If
366 certain strings in the object are too long (docstrings, code, etc.) they get
366 certain strings in the object are too long (docstrings, code, etc.) they get
367 snipped in the center for brevity.
367 snipped in the center for brevity.
368
368
369 Typing ??word or word?? gives access to the full information without
369 Typing ??word or word?? gives access to the full information without
370 snipping long strings. Long strings are sent to the screen through the less
370 snipping long strings. Long strings are sent to the screen through the less
371 pager if longer than the screen, printed otherwise.
371 pager if longer than the screen, printed otherwise.
372
372
373 The ?/?? system gives access to the full source code for any object (if
373 The ?/?? system gives access to the full source code for any object (if
374 available), shows function prototypes and other useful information.
374 available), shows function prototypes and other useful information.
375
375
376 If you just want to see an object's docstring, type '%pdoc object' (without
376 If you just want to see an object's docstring, type '%pdoc object' (without
377 quotes, and without % if you have automagic on).
377 quotes, and without % if you have automagic on).
378
378
379 Both %pdoc and ?/?? give you access to documentation even on things which are
379 Both %pdoc and ?/?? give you access to documentation even on things which are
380 not explicitely defined. Try for example typing {}.get? or after import os,
380 not explicitely defined. Try for example typing {}.get? or after import os,
381 type os.path.abspath??. The magic functions %pdef, %source and %file operate
381 type os.path.abspath??. The magic functions %pdef, %source and %file operate
382 similarly.
382 similarly.
383
383
384 * Completion in the local namespace, by typing TAB at the prompt.
384 * Completion in the local namespace, by typing TAB at the prompt.
385
385
386 At any time, hitting tab will complete any available python commands or
386 At any time, hitting tab will complete any available python commands or
387 variable names, and show you a list of the possible completions if there's
387 variable names, and show you a list of the possible completions if there's
388 no unambiguous one. It will also complete filenames in the current directory.
388 no unambiguous one. It will also complete filenames in the current directory.
389
389
390 This feature requires the readline and rlcomplete modules, so it won't work
390 This feature requires the readline and rlcomplete modules, so it won't work
391 if your Python lacks readline support (such as under Windows).
391 if your Python lacks readline support (such as under Windows).
392
392
393 * Search previous command history in two ways (also requires readline):
393 * Search previous command history in two ways (also requires readline):
394
394
395 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
395 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
396 search through only the history items that match what you've typed so
396 search through only the history items that match what you've typed so
397 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
397 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
398 normal arrow keys.
398 normal arrow keys.
399
399
400 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
400 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
401 your history for lines that match what you've typed so far, completing as
401 your history for lines that match what you've typed so far, completing as
402 much as it can.
402 much as it can.
403
403
404 * Persistent command history across sessions (readline required).
404 * Persistent command history across sessions (readline required).
405
405
406 * Logging of input with the ability to save and restore a working session.
406 * Logging of input with the ability to save and restore a working session.
407
407
408 * System escape with !. Typing !ls will run 'ls' in the current directory.
408 * System escape with !. Typing !ls will run 'ls' in the current directory.
409
409
410 * The reload command does a 'deep' reload of a module: changes made to the
410 * The reload command does a 'deep' reload of a module: changes made to the
411 module since you imported will actually be available without having to exit.
411 module since you imported will actually be available without having to exit.
412
412
413 * Verbose and colored exception traceback printouts. See the magic xmode and
413 * Verbose and colored exception traceback printouts. See the magic xmode and
414 xcolor functions for details (just type %magic).
414 xcolor functions for details (just type %magic).
415
415
416 * Input caching system:
416 * Input caching system:
417
417
418 IPython offers numbered prompts (In/Out) with input and output caching. All
418 IPython offers numbered prompts (In/Out) with input and output caching. All
419 input is saved and can be retrieved as variables (besides the usual arrow
419 input is saved and can be retrieved as variables (besides the usual arrow
420 key recall).
420 key recall).
421
421
422 The following GLOBAL variables always exist (so don't overwrite them!):
422 The following GLOBAL variables always exist (so don't overwrite them!):
423 _i: stores previous input.
423 _i: stores previous input.
424 _ii: next previous.
424 _ii: next previous.
425 _iii: next-next previous.
425 _iii: next-next previous.
426 _ih : a list of all input _ih[n] is the input from line n.
426 _ih : a list of all input _ih[n] is the input from line n.
427
427
428 Additionally, global variables named _i<n> are dynamically created (<n>
428 Additionally, global variables named _i<n> are dynamically created (<n>
429 being the prompt counter), such that _i<n> == _ih[<n>]
429 being the prompt counter), such that _i<n> == _ih[<n>]
430
430
431 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
431 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
432
432
433 You can create macros which contain multiple input lines from this history,
433 You can create macros which contain multiple input lines from this history,
434 for later re-execution, with the %macro function.
434 for later re-execution, with the %macro function.
435
435
436 The history function %hist allows you to see any part of your input history
436 The history function %hist allows you to see any part of your input history
437 by printing a range of the _i variables. Note that inputs which contain
437 by printing a range of the _i variables. Note that inputs which contain
438 magic functions (%) appear in the history with a prepended comment. This is
438 magic functions (%) appear in the history with a prepended comment. This is
439 because they aren't really valid Python code, so you can't exec them.
439 because they aren't really valid Python code, so you can't exec them.
440
440
441 * Output caching system:
441 * Output caching system:
442
442
443 For output that is returned from actions, a system similar to the input
443 For output that is returned from actions, a system similar to the input
444 cache exists but using _ instead of _i. Only actions that produce a result
444 cache exists but using _ instead of _i. Only actions that produce a result
445 (NOT assignments, for example) are cached. If you are familiar with
445 (NOT assignments, for example) are cached. If you are familiar with
446 Mathematica, IPython's _ variables behave exactly like Mathematica's %
446 Mathematica, IPython's _ variables behave exactly like Mathematica's %
447 variables.
447 variables.
448
448
449 The following GLOBAL variables always exist (so don't overwrite them!):
449 The following GLOBAL variables always exist (so don't overwrite them!):
450 _ (one underscore): previous output.
450 _ (one underscore): previous output.
451 __ (two underscores): next previous.
451 __ (two underscores): next previous.
452 ___ (three underscores): next-next previous.
452 ___ (three underscores): next-next previous.
453
453
454 Global variables named _<n> are dynamically created (<n> being the prompt
454 Global variables named _<n> are dynamically created (<n> being the prompt
455 counter), such that the result of output <n> is always available as _<n>.
455 counter), such that the result of output <n> is always available as _<n>.
456
456
457 Finally, a global dictionary named _oh exists with entries for all lines
457 Finally, a global dictionary named _oh exists with entries for all lines
458 which generated output.
458 which generated output.
459
459
460 * Directory history:
460 * Directory history:
461
461
462 Your history of visited directories is kept in the global list _dh, and the
462 Your history of visited directories is kept in the global list _dh, and the
463 magic %cd command can be used to go to any entry in that list.
463 magic %cd command can be used to go to any entry in that list.
464
464
465 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
465 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
466
466
467 1. Auto-parentheses
467 1. Auto-parentheses
468 Callable objects (i.e. functions, methods, etc) can be invoked like
468 Callable objects (i.e. functions, methods, etc) can be invoked like
469 this (notice the commas between the arguments):
469 this (notice the commas between the arguments):
470 >>> callable_ob arg1, arg2, arg3
470 >>> callable_ob arg1, arg2, arg3
471 and the input will be translated to this:
471 and the input will be translated to this:
472 --> callable_ob(arg1, arg2, arg3)
472 --> callable_ob(arg1, arg2, arg3)
473 You can force auto-parentheses by using '/' as the first character
473 You can force auto-parentheses by using '/' as the first character
474 of a line. For example:
474 of a line. For example:
475 >>> /globals # becomes 'globals()'
475 >>> /globals # becomes 'globals()'
476 Note that the '/' MUST be the first character on the line! This
476 Note that the '/' MUST be the first character on the line! This
477 won't work:
477 won't work:
478 >>> print /globals # syntax error
478 >>> print /globals # syntax error
479
479
480 In most cases the automatic algorithm should work, so you should
480 In most cases the automatic algorithm should work, so you should
481 rarely need to explicitly invoke /. One notable exception is if you
481 rarely need to explicitly invoke /. One notable exception is if you
482 are trying to call a function with a list of tuples as arguments (the
482 are trying to call a function with a list of tuples as arguments (the
483 parenthesis will confuse IPython):
483 parenthesis will confuse IPython):
484 In [1]: zip (1,2,3),(4,5,6) # won't work
484 In [1]: zip (1,2,3),(4,5,6) # won't work
485 but this will work:
485 but this will work:
486 In [2]: /zip (1,2,3),(4,5,6)
486 In [2]: /zip (1,2,3),(4,5,6)
487 ------> zip ((1,2,3),(4,5,6))
487 ------> zip ((1,2,3),(4,5,6))
488 Out[2]= [(1, 4), (2, 5), (3, 6)]
488 Out[2]= [(1, 4), (2, 5), (3, 6)]
489
489
490 IPython tells you that it has altered your command line by
490 IPython tells you that it has altered your command line by
491 displaying the new command line preceded by -->. e.g.:
491 displaying the new command line preceded by -->. e.g.:
492 In [18]: callable list
492 In [18]: callable list
493 -------> callable (list)
493 -------> callable (list)
494
494
495 2. Auto-Quoting
495 2. Auto-Quoting
496 You can force auto-quoting of a function's arguments by using ',' as
496 You can force auto-quoting of a function's arguments by using ',' as
497 the first character of a line. For example:
497 the first character of a line. For example:
498 >>> ,my_function /home/me # becomes my_function("/home/me")
498 >>> ,my_function /home/me # becomes my_function("/home/me")
499
499
500 If you use ';' instead, the whole argument is quoted as a single
500 If you use ';' instead, the whole argument is quoted as a single
501 string (while ',' splits on whitespace):
501 string (while ',' splits on whitespace):
502 >>> ,my_function a b c # becomes my_function("a","b","c")
502 >>> ,my_function a b c # becomes my_function("a","b","c")
503 >>> ;my_function a b c # becomes my_function("a b c")
503 >>> ;my_function a b c # becomes my_function("a b c")
504
504
505 Note that the ',' MUST be the first character on the line! This
505 Note that the ',' MUST be the first character on the line! This
506 won't work:
506 won't work:
507 >>> x = ,my_function /home/me # syntax error
507 >>> x = ,my_function /home/me # syntax error
508 """
508 """
509
509
510 interactive_usage_min = """\
510 interactive_usage_min = """\
511 An enhanced console for Python.
511 An enhanced console for Python.
512 Some of its features are:
512 Some of its features are:
513 - Readline support if the readline library is present.
513 - Readline support if the readline library is present.
514 - Tab completion in the local namespace.
514 - Tab completion in the local namespace.
515 - Logging of input, see command-line options.
515 - Logging of input, see command-line options.
516 - System shell escape via ! , eg !ls.
516 - System shell escape via ! , eg !ls.
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
518 - Keeps track of locally defined variables via %who, %whos.
518 - Keeps track of locally defined variables via %who, %whos.
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
520 """
520 """
521
521
522 quick_reference = r"""
522 quick_reference = r"""
523 IPython -- An enhanced Interactive Python - Quick Reference Card
523 IPython -- An enhanced Interactive Python - Quick Reference Card
524 ================================================================
524 ================================================================
525
525
526 obj?, obj?? : Get help, or more help for object (also works as
526 obj?, obj?? : Get help, or more help for object (also works as
527 ?obj, ??obj).
527 ?obj, ??obj).
528 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
528 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
529 %magic : Information about IPython's 'magic' % functions.
529 %magic : Information about IPython's 'magic' % functions.
530
530
531 Magic functions are prefixed by %, and typically take their arguments without
531 Magic functions are prefixed by %, and typically take their arguments without
532 parentheses, quotes or even commas for convenience.
532 parentheses, quotes or even commas for convenience.
533
533
534 Example magic function calls:
534 Example magic function calls:
535
535
536 %alias d ls -F : 'd' is now an alias for 'ls -F'
536 %alias d ls -F : 'd' is now an alias for 'ls -F'
537 alias d ls -F : Works if 'alias' not a python name
537 alias d ls -F : Works if 'alias' not a python name
538 alist = %alias : Get list of aliases to 'alist'
538 alist = %alias : Get list of aliases to 'alist'
539 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
539 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
540 %cd?? : See help AND source for magic %cd
540 %cd?? : See help AND source for magic %cd
541
541
542 System commands:
542 System commands:
543
543
544 !cp a.txt b/ : System command escape, calls os.system()
544 !cp a.txt b/ : System command escape, calls os.system()
545 cp a.txt b/ : after %rehashx, most system commands work without !
545 cp a.txt b/ : after %rehashx, most system commands work without !
546 cp ${f}.txt $bar : Variable expansion in magics and system commands
546 cp ${f}.txt $bar : Variable expansion in magics and system commands
547 files = !ls /usr : Capture sytem command output
547 files = !ls /usr : Capture sytem command output
548 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
548 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
549
549
550 History:
550 History:
551
551
552 _i, _ii, _iii : Previous, next previous, next next previous input
552 _i, _ii, _iii : Previous, next previous, next next previous input
553 _i4, _ih[2:5] : Input history line 4, lines 2-4
553 _i4, _ih[2:5] : Input history line 4, lines 2-4
554 exec _i81 : Execute input history line #81 again
554 exec _i81 : Execute input history line #81 again
555 %rep 81 : Edit input history line #81
555 %rep 81 : Edit input history line #81
556 _, __, ___ : previous, next previous, next next previous output
556 _, __, ___ : previous, next previous, next next previous output
557 _dh : Directory history
557 _dh : Directory history
558 _oh : Output history
558 _oh : Output history
559 %hist : Command history. '%hist -g foo' search history for 'foo'
559 %hist : Command history. '%hist -g foo' search history for 'foo'
560
560
561 Autocall:
561 Autocall:
562
562
563 f 1,2 : f(1,2)
563 f 1,2 : f(1,2)
564 /f 1,2 : f(1,2) (forced autoparen)
564 /f 1,2 : f(1,2) (forced autoparen)
565 ,f 1 2 : f("1","2")
565 ,f 1 2 : f("1","2")
566 ;f 1 2 : f("1 2")
566 ;f 1 2 : f("1 2")
567
567
568 Remember: TAB completion works in many contexts, not just file names
568 Remember: TAB completion works in many contexts, not just file names
569 or python names.
569 or python names.
570
570
571 The following magic functions are currently available:
571 The following magic functions are currently available:
572
572
573 """
573 """
574
574
575 quick_guide = """\
575 quick_guide = """\
576 ? -> Introduction and overview of IPython's features.
576 ? -> Introduction and overview of IPython's features.
577 %quickref -> Quick reference.
577 %quickref -> Quick reference.
578 help -> Python's own help system.
578 help -> Python's own help system.
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
580
580
581 banner_parts = [
581 default_banner_parts = [
582 'Python %s' % (sys.version.split('\n')[0],),
582 'Python %s' % (sys.version.split('\n')[0],),
583 'Type "copyright", "credits" or "license" for more information.\n',
583 'Type "copyright", "credits" or "license" for more information.\n',
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 quick_guide
585 quick_guide
586 ]
586 ]
587
588 default_banner = '\n'.join(default_banner_parts)
@@ -1,861 +1,899 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight Traits like module.
4 A lightweight Traits like module.
5
5
6 This is designed to provide a lightweight, simple, pure Python version of
6 This is designed to provide a lightweight, simple, pure Python version of
7 many of the capabilities of enthought.traits. This includes:
7 many of the capabilities of enthought.traits. This includes:
8
8
9 * Validation
9 * Validation
10 * Type specification with defaults
10 * Type specification with defaults
11 * Static and dynamic notification
11 * Static and dynamic notification
12 * Basic predefined types
12 * Basic predefined types
13 * An API that is similar to enthought.traits
13 * An API that is similar to enthought.traits
14
14
15 We don't support:
15 We don't support:
16
16
17 * Delegation
17 * Delegation
18 * Automatic GUI generation
18 * Automatic GUI generation
19 * A full set of trait types. Most importantly, we don't provide container
19 * A full set of trait types. Most importantly, we don't provide container
20 traitlets (list, dict, tuple) that can trigger notifications if their
20 traitlets (list, dict, tuple) that can trigger notifications if their
21 contents change.
21 contents change.
22 * API compatibility with enthought.traits
22 * API compatibility with enthought.traits
23
23
24 There are also some important difference in our design:
24 There are also some important difference in our design:
25
25
26 * enthought.traits does not validate default values. We do.
26 * enthought.traits does not validate default values. We do.
27
27
28 We choose to create this module because we need these capabilities, but
28 We choose to create this module because we need these capabilities, but
29 we need them to be pure Python so they work in all Python implementations,
29 we need them to be pure Python so they work in all Python implementations,
30 including Jython and IronPython.
30 including Jython and IronPython.
31
31
32 Authors:
32 Authors:
33
33
34 * Brian Granger
34 * Brian Granger
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
36 and is licensed under the BSD license. Also, many of the ideas also come
36 and is licensed under the BSD license. Also, many of the ideas also come
37 from enthought.traits even though our implementation is very different.
37 from enthought.traits even though our implementation is very different.
38 """
38 """
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Copyright (C) 2008-2009 The IPython Development Team
41 # Copyright (C) 2008-2009 The IPython Development Team
42 #
42 #
43 # Distributed under the terms of the BSD License. The full license is in
43 # Distributed under the terms of the BSD License. The full license is in
44 # the file COPYING, distributed as part of this software.
44 # the file COPYING, distributed as part of this software.
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Imports
48 # Imports
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51
51
52 import inspect
52 import inspect
53 import sys
53 import sys
54 import types
54 import types
55 from types import InstanceType, ClassType, FunctionType
55 from types import InstanceType, ClassType, FunctionType
56
56
57 ClassTypes = (ClassType, type)
57 ClassTypes = (ClassType, type)
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Basic classes
60 # Basic classes
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62
62
63
63
64 class NoDefaultSpecified ( object ): pass
64 class NoDefaultSpecified ( object ): pass
65 NoDefaultSpecified = NoDefaultSpecified()
65 NoDefaultSpecified = NoDefaultSpecified()
66
66
67
67
68 class Undefined ( object ): pass
68 class Undefined ( object ): pass
69 Undefined = Undefined()
69 Undefined = Undefined()
70
70
71
71
72 class TraitletError(Exception):
72 class TraitletError(Exception):
73 pass
73 pass
74
74
75
75
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77 # Utilities
77 # Utilities
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79
79
80
80
81 def class_of ( object ):
81 def class_of ( object ):
82 """ Returns a string containing the class name of an object with the
82 """ Returns a string containing the class name of an object with the
83 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
83 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
84 'a PlotValue').
84 'a PlotValue').
85 """
85 """
86 if isinstance( object, basestring ):
86 if isinstance( object, basestring ):
87 return add_article( object )
87 return add_article( object )
88
88
89 return add_article( object.__class__.__name__ )
89 return add_article( object.__class__.__name__ )
90
90
91
91
92 def add_article ( name ):
92 def add_article ( name ):
93 """ Returns a string containing the correct indefinite article ('a' or 'an')
93 """ Returns a string containing the correct indefinite article ('a' or 'an')
94 prefixed to the specified string.
94 prefixed to the specified string.
95 """
95 """
96 if name[:1].lower() in 'aeiou':
96 if name[:1].lower() in 'aeiou':
97 return 'an ' + name
97 return 'an ' + name
98
98
99 return 'a ' + name
99 return 'a ' + name
100
100
101
101
102 def repr_type(obj):
102 def repr_type(obj):
103 """ Return a string representation of a value and its type for readable
103 """ Return a string representation of a value and its type for readable
104 error messages.
104 error messages.
105 """
105 """
106 the_type = type(obj)
106 the_type = type(obj)
107 if the_type is InstanceType:
107 if the_type is InstanceType:
108 # Old-style class.
108 # Old-style class.
109 the_type = obj.__class__
109 the_type = obj.__class__
110 msg = '%r %r' % (obj, the_type)
110 msg = '%r %r' % (obj, the_type)
111 return msg
111 return msg
112
112
113
113
114 def parse_notifier_name(name):
114 def parse_notifier_name(name):
115 """Convert the name argument to a list of names.
115 """Convert the name argument to a list of names.
116
116
117 Examples
117 Examples
118 --------
118 --------
119
119
120 >>> parse_notifier_name('a')
120 >>> parse_notifier_name('a')
121 ['a']
121 ['a']
122 >>> parse_notifier_name(['a','b'])
122 >>> parse_notifier_name(['a','b'])
123 ['a', 'b']
123 ['a', 'b']
124 >>> parse_notifier_name(None)
124 >>> parse_notifier_name(None)
125 ['anytraitlet']
125 ['anytraitlet']
126 """
126 """
127 if isinstance(name, str):
127 if isinstance(name, str):
128 return [name]
128 return [name]
129 elif name is None:
129 elif name is None:
130 return ['anytraitlet']
130 return ['anytraitlet']
131 elif isinstance(name, (list, tuple)):
131 elif isinstance(name, (list, tuple)):
132 for n in name:
132 for n in name:
133 assert isinstance(n, str), "names must be strings"
133 assert isinstance(n, str), "names must be strings"
134 return name
134 return name
135
135
136
136
137 class _SimpleTest:
137 class _SimpleTest:
138 def __init__ ( self, value ): self.value = value
138 def __init__ ( self, value ): self.value = value
139 def __call__ ( self, test ):
139 def __call__ ( self, test ):
140 print test, self.value
140 print test, self.value
141 return test == self.value
141 return test == self.value
142 def __repr__(self):
142 def __repr__(self):
143 return "<SimpleTest(%r)" % self.value
143 return "<SimpleTest(%r)" % self.value
144 def __str__(self):
144 def __str__(self):
145 return self.__repr__()
145 return self.__repr__()
146
146
147
147
148 #-----------------------------------------------------------------------------
148 #-----------------------------------------------------------------------------
149 # Base TraitletType for all traitlets
149 # Base TraitletType for all traitlets
150 #-----------------------------------------------------------------------------
150 #-----------------------------------------------------------------------------
151
151
152
152
153 class TraitletType(object):
153 class TraitletType(object):
154 """A base class for all traitlet descriptors.
154 """A base class for all traitlet descriptors.
155
155
156 Notes
156 Notes
157 -----
157 -----
158 Our implementation of traitlets is based on Python's descriptor
158 Our implementation of traitlets is based on Python's descriptor
159 prototol. This class is the base class for all such descriptors. The
159 prototol. This class is the base class for all such descriptors. The
160 only magic we use is a custom metaclass for the main :class:`HasTraitlets`
160 only magic we use is a custom metaclass for the main :class:`HasTraitlets`
161 class that does the following:
161 class that does the following:
162
162
163 1. Sets the :attr:`name` attribute of every :class:`TraitletType`
163 1. Sets the :attr:`name` attribute of every :class:`TraitletType`
164 instance in the class dict to the name of the attribute.
164 instance in the class dict to the name of the attribute.
165 2. Sets the :attr:`this_class` attribute of every :class:`TraitletType`
165 2. Sets the :attr:`this_class` attribute of every :class:`TraitletType`
166 instance in the class dict to the *class* that declared the traitlet.
166 instance in the class dict to the *class* that declared the traitlet.
167 This is used by the :class:`This` traitlet to allow subclasses to
167 This is used by the :class:`This` traitlet to allow subclasses to
168 accept superclasses for :class:`This` values.
168 accept superclasses for :class:`This` values.
169 """
169 """
170
170
171
171
172 metadata = {}
172 metadata = {}
173 default_value = Undefined
173 default_value = Undefined
174 info_text = 'any value'
174 info_text = 'any value'
175
175
176 def __init__(self, default_value=NoDefaultSpecified, **metadata):
176 def __init__(self, default_value=NoDefaultSpecified, **metadata):
177 """Create a TraitletType.
177 """Create a TraitletType.
178 """
178 """
179 if default_value is not NoDefaultSpecified:
179 if default_value is not NoDefaultSpecified:
180 self.default_value = default_value
180 self.default_value = default_value
181
181
182 if len(metadata) > 0:
182 if len(metadata) > 0:
183 if len(self.metadata) > 0:
183 if len(self.metadata) > 0:
184 self._metadata = self.metadata.copy()
184 self._metadata = self.metadata.copy()
185 self._metadata.update(metadata)
185 self._metadata.update(metadata)
186 else:
186 else:
187 self._metadata = metadata
187 self._metadata = metadata
188 else:
188 else:
189 self._metadata = self.metadata
189 self._metadata = self.metadata
190
190
191 self.init()
191 self.init()
192
192
193 def init(self):
193 def init(self):
194 pass
194 pass
195
195
196 def get_default_value(self):
196 def get_default_value(self):
197 """Create a new instance of the default value."""
197 """Create a new instance of the default value."""
198 dv = self.default_value
198 dv = self.default_value
199 return dv
199 return dv
200
200
201 def set_default_value(self, obj):
201 def set_default_value(self, obj):
202 dv = self.get_default_value()
202 dv = self.get_default_value()
203 newdv = self._validate(obj, dv)
203 newdv = self._validate(obj, dv)
204 obj._traitlet_values[self.name] = newdv
204 obj._traitlet_values[self.name] = newdv
205
205
206
206
207 def __get__(self, obj, cls=None):
207 def __get__(self, obj, cls=None):
208 """Get the value of the traitlet by self.name for the instance.
208 """Get the value of the traitlet by self.name for the instance.
209
209
210 Default values are instantiated when :meth:`HasTraitlets.__new__`
210 Default values are instantiated when :meth:`HasTraitlets.__new__`
211 is called. Thus by the time this method gets called either the
211 is called. Thus by the time this method gets called either the
212 default value or a user defined value (they called :meth:`__set__`)
212 default value or a user defined value (they called :meth:`__set__`)
213 is in the :class:`HasTraitlets` instance.
213 is in the :class:`HasTraitlets` instance.
214 """
214 """
215 if obj is None:
215 if obj is None:
216 return self
216 return self
217 else:
217 else:
218 try:
218 try:
219 value = obj._traitlet_values[self.name]
219 value = obj._traitlet_values[self.name]
220 except:
220 except:
221 # HasTraitlets should call set_default_value to populate
221 # HasTraitlets should call set_default_value to populate
222 # this. So this should never be reached.
222 # this. So this should never be reached.
223 raise TraitletError('Unexpected error in TraitletType: '
223 raise TraitletError('Unexpected error in TraitletType: '
224 'default value not set properly')
224 'default value not set properly')
225 else:
225 else:
226 return value
226 return value
227
227
228 def __set__(self, obj, value):
228 def __set__(self, obj, value):
229 new_value = self._validate(obj, value)
229 new_value = self._validate(obj, value)
230 old_value = self.__get__(obj)
230 old_value = self.__get__(obj)
231 if old_value != new_value:
231 if old_value != new_value:
232 obj._traitlet_values[self.name] = new_value
232 obj._traitlet_values[self.name] = new_value
233 obj._notify_traitlet(self.name, old_value, new_value)
233 obj._notify_traitlet(self.name, old_value, new_value)
234
234
235 def _validate(self, obj, value):
235 def _validate(self, obj, value):
236 if hasattr(self, 'validate'):
236 if hasattr(self, 'validate'):
237 return self.validate(obj, value)
237 return self.validate(obj, value)
238 elif hasattr(self, 'is_valid_for'):
238 elif hasattr(self, 'is_valid_for'):
239 valid = self.is_valid_for(value)
239 valid = self.is_valid_for(value)
240 if valid:
240 if valid:
241 return value
241 return value
242 else:
242 else:
243 raise TraitletError('invalid value for type: %r' % value)
243 raise TraitletError('invalid value for type: %r' % value)
244 elif hasattr(self, 'value_for'):
244 elif hasattr(self, 'value_for'):
245 return self.value_for(value)
245 return self.value_for(value)
246 else:
246 else:
247 return value
247 return value
248
248
249 def info(self):
249 def info(self):
250 return self.info_text
250 return self.info_text
251
251
252 def error(self, obj, value):
252 def error(self, obj, value):
253 if obj is not None:
253 if obj is not None:
254 e = "The '%s' traitlet of %s instance must be %s, but a value of %s was specified." \
254 e = "The '%s' traitlet of %s instance must be %s, but a value of %s was specified." \
255 % (self.name, class_of(obj),
255 % (self.name, class_of(obj),
256 self.info(), repr_type(value))
256 self.info(), repr_type(value))
257 else:
257 else:
258 e = "The '%s' traitlet must be %s, but a value of %r was specified." \
258 e = "The '%s' traitlet must be %s, but a value of %r was specified." \
259 % (self.name, self.info(), repr_type(value))
259 % (self.name, self.info(), repr_type(value))
260 raise TraitletError(e)
260 raise TraitletError(e)
261
261
262 def get_metadata(self, key):
262 def get_metadata(self, key):
263 return getattr(self, '_metadata', {}).get(key, None)
263 return getattr(self, '_metadata', {}).get(key, None)
264
264
265 def set_metadata(self, key, value):
265 def set_metadata(self, key, value):
266 getattr(self, '_metadata', {})[key] = value
266 getattr(self, '_metadata', {})[key] = value
267
267
268
268
269 #-----------------------------------------------------------------------------
269 #-----------------------------------------------------------------------------
270 # The HasTraitlets implementation
270 # The HasTraitlets implementation
271 #-----------------------------------------------------------------------------
271 #-----------------------------------------------------------------------------
272
272
273
273
274 class MetaHasTraitlets(type):
274 class MetaHasTraitlets(type):
275 """A metaclass for HasTraitlets.
275 """A metaclass for HasTraitlets.
276
276
277 This metaclass makes sure that any TraitletType class attributes are
277 This metaclass makes sure that any TraitletType class attributes are
278 instantiated and sets their name attribute.
278 instantiated and sets their name attribute.
279 """
279 """
280
280
281 def __new__(mcls, name, bases, classdict):
281 def __new__(mcls, name, bases, classdict):
282 """Create the HasTraitlets class.
282 """Create the HasTraitlets class.
283
283
284 This instantiates all TraitletTypes in the class dict and sets their
284 This instantiates all TraitletTypes in the class dict and sets their
285 :attr:`name` attribute.
285 :attr:`name` attribute.
286 """
286 """
287 # print "========================="
287 # print "========================="
288 # print "MetaHasTraitlets.__new__"
288 # print "MetaHasTraitlets.__new__"
289 # print "mcls, ", mcls
289 # print "mcls, ", mcls
290 # print "name, ", name
290 # print "name, ", name
291 # print "bases, ", bases
291 # print "bases, ", bases
292 # print "classdict, ", classdict
292 # print "classdict, ", classdict
293 for k,v in classdict.iteritems():
293 for k,v in classdict.iteritems():
294 if isinstance(v, TraitletType):
294 if isinstance(v, TraitletType):
295 v.name = k
295 v.name = k
296 elif inspect.isclass(v):
296 elif inspect.isclass(v):
297 if issubclass(v, TraitletType):
297 if issubclass(v, TraitletType):
298 vinst = v()
298 vinst = v()
299 vinst.name = k
299 vinst.name = k
300 classdict[k] = vinst
300 classdict[k] = vinst
301 return super(MetaHasTraitlets, mcls).__new__(mcls, name, bases, classdict)
301 return super(MetaHasTraitlets, mcls).__new__(mcls, name, bases, classdict)
302
302
303 def __init__(cls, name, bases, classdict):
303 def __init__(cls, name, bases, classdict):
304 """Finish initializing the HasTraitlets class.
304 """Finish initializing the HasTraitlets class.
305
305
306 This sets the :attr:`this_class` attribute of each TraitletType in the
306 This sets the :attr:`this_class` attribute of each TraitletType in the
307 class dict to the newly created class ``cls``.
307 class dict to the newly created class ``cls``.
308 """
308 """
309 # print "========================="
309 # print "========================="
310 # print "MetaHasTraitlets.__init__"
310 # print "MetaHasTraitlets.__init__"
311 # print "cls, ", cls
311 # print "cls, ", cls
312 # print "name, ", name
312 # print "name, ", name
313 # print "bases, ", bases
313 # print "bases, ", bases
314 # print "classdict, ", classdict
314 # print "classdict, ", classdict
315 for k, v in classdict.iteritems():
315 for k, v in classdict.iteritems():
316 if isinstance(v, TraitletType):
316 if isinstance(v, TraitletType):
317 v.this_class = cls
317 v.this_class = cls
318 super(MetaHasTraitlets, cls).__init__(name, bases, classdict)
318 super(MetaHasTraitlets, cls).__init__(name, bases, classdict)
319
319
320 class HasTraitlets(object):
320 class HasTraitlets(object):
321
321
322 __metaclass__ = MetaHasTraitlets
322 __metaclass__ = MetaHasTraitlets
323
323
324 def __new__(cls, *args, **kw):
324 def __new__(cls, *args, **kw):
325 inst = super(HasTraitlets, cls).__new__(cls, *args, **kw)
325 inst = super(HasTraitlets, cls).__new__(cls, *args, **kw)
326 inst._traitlet_values = {}
326 inst._traitlet_values = {}
327 inst._traitlet_notifiers = {}
327 inst._traitlet_notifiers = {}
328 # Here we tell all the TraitletType instances to set their default
328 # Here we tell all the TraitletType instances to set their default
329 # values on the instance.
329 # values on the instance.
330 for key in dir(cls):
330 for key in dir(cls):
331 value = getattr(cls, key)
331 value = getattr(cls, key)
332 if isinstance(value, TraitletType):
332 if isinstance(value, TraitletType):
333 value.set_default_value(inst)
333 value.set_default_value(inst)
334 return inst
334 return inst
335
335
336 # def __init__(self):
336 # def __init__(self):
337 # self._traitlet_values = {}
337 # self._traitlet_values = {}
338 # self._traitlet_notifiers = {}
338 # self._traitlet_notifiers = {}
339
339
340 def _notify_traitlet(self, name, old_value, new_value):
340 def _notify_traitlet(self, name, old_value, new_value):
341
341
342 # First dynamic ones
342 # First dynamic ones
343 callables = self._traitlet_notifiers.get(name,[])
343 callables = self._traitlet_notifiers.get(name,[])
344 more_callables = self._traitlet_notifiers.get('anytraitlet',[])
344 more_callables = self._traitlet_notifiers.get('anytraitlet',[])
345 callables.extend(more_callables)
345 callables.extend(more_callables)
346
346
347 # Now static ones
347 # Now static ones
348 try:
348 try:
349 cb = getattr(self, '_%s_changed' % name)
349 cb = getattr(self, '_%s_changed' % name)
350 except:
350 except:
351 pass
351 pass
352 else:
352 else:
353 callables.append(cb)
353 callables.append(cb)
354
354
355 # Call them all now
355 # Call them all now
356 for c in callables:
356 for c in callables:
357 # Traits catches and logs errors here. I allow them to raise
357 # Traits catches and logs errors here. I allow them to raise
358 if callable(c):
358 if callable(c):
359 argspec = inspect.getargspec(c)
359 argspec = inspect.getargspec(c)
360 nargs = len(argspec[0])
360 nargs = len(argspec[0])
361 # Bound methods have an additional 'self' argument
361 # Bound methods have an additional 'self' argument
362 # I don't know how to treat unbound methods, but they
362 # I don't know how to treat unbound methods, but they
363 # can't really be used for callbacks.
363 # can't really be used for callbacks.
364 if isinstance(c, types.MethodType):
364 if isinstance(c, types.MethodType):
365 offset = -1
365 offset = -1
366 else:
366 else:
367 offset = 0
367 offset = 0
368 if nargs + offset == 0:
368 if nargs + offset == 0:
369 c()
369 c()
370 elif nargs + offset == 1:
370 elif nargs + offset == 1:
371 c(name)
371 c(name)
372 elif nargs + offset == 2:
372 elif nargs + offset == 2:
373 c(name, new_value)
373 c(name, new_value)
374 elif nargs + offset == 3:
374 elif nargs + offset == 3:
375 c(name, old_value, new_value)
375 c(name, old_value, new_value)
376 else:
376 else:
377 raise TraitletError('a traitlet changed callback '
377 raise TraitletError('a traitlet changed callback '
378 'must have 0-3 arguments.')
378 'must have 0-3 arguments.')
379 else:
379 else:
380 raise TraitletError('a traitlet changed callback '
380 raise TraitletError('a traitlet changed callback '
381 'must be callable.')
381 'must be callable.')
382
382
383
383
384 def _add_notifiers(self, handler, name):
384 def _add_notifiers(self, handler, name):
385 if not self._traitlet_notifiers.has_key(name):
385 if not self._traitlet_notifiers.has_key(name):
386 nlist = []
386 nlist = []
387 self._traitlet_notifiers[name] = nlist
387 self._traitlet_notifiers[name] = nlist
388 else:
388 else:
389 nlist = self._traitlet_notifiers[name]
389 nlist = self._traitlet_notifiers[name]
390 if handler not in nlist:
390 if handler not in nlist:
391 nlist.append(handler)
391 nlist.append(handler)
392
392
393 def _remove_notifiers(self, handler, name):
393 def _remove_notifiers(self, handler, name):
394 if self._traitlet_notifiers.has_key(name):
394 if self._traitlet_notifiers.has_key(name):
395 nlist = self._traitlet_notifiers[name]
395 nlist = self._traitlet_notifiers[name]
396 try:
396 try:
397 index = nlist.index(handler)
397 index = nlist.index(handler)
398 except ValueError:
398 except ValueError:
399 pass
399 pass
400 else:
400 else:
401 del nlist[index]
401 del nlist[index]
402
402
403 def on_traitlet_change(self, handler, name=None, remove=False):
403 def on_traitlet_change(self, handler, name=None, remove=False):
404 """Setup a handler to be called when a traitlet changes.
404 """Setup a handler to be called when a traitlet changes.
405
405
406 This is used to setup dynamic notifications of traitlet changes.
406 This is used to setup dynamic notifications of traitlet changes.
407
407
408 Static handlers can be created by creating methods on a HasTraitlets
408 Static handlers can be created by creating methods on a HasTraitlets
409 subclass with the naming convention '_[traitletname]_changed'. Thus,
409 subclass with the naming convention '_[traitletname]_changed'. Thus,
410 to create static handler for the traitlet 'a', create the method
410 to create static handler for the traitlet 'a', create the method
411 _a_changed(self, name, old, new) (fewer arguments can be used, see
411 _a_changed(self, name, old, new) (fewer arguments can be used, see
412 below).
412 below).
413
413
414 Parameters
414 Parameters
415 ----------
415 ----------
416 handler : callable
416 handler : callable
417 A callable that is called when a traitlet changes. Its
417 A callable that is called when a traitlet changes. Its
418 signature can be handler(), handler(name), handler(name, new)
418 signature can be handler(), handler(name), handler(name, new)
419 or handler(name, old, new).
419 or handler(name, old, new).
420 name : list, str, None
420 name : list, str, None
421 If None, the handler will apply to all traitlets. If a list
421 If None, the handler will apply to all traitlets. If a list
422 of str, handler will apply to all names in the list. If a
422 of str, handler will apply to all names in the list. If a
423 str, the handler will apply just to that name.
423 str, the handler will apply just to that name.
424 remove : bool
424 remove : bool
425 If False (the default), then install the handler. If True
425 If False (the default), then install the handler. If True
426 then unintall it.
426 then unintall it.
427 """
427 """
428 if remove:
428 if remove:
429 names = parse_notifier_name(name)
429 names = parse_notifier_name(name)
430 for n in names:
430 for n in names:
431 self._remove_notifiers(handler, n)
431 self._remove_notifiers(handler, n)
432 else:
432 else:
433 names = parse_notifier_name(name)
433 names = parse_notifier_name(name)
434 for n in names:
434 for n in names:
435 self._add_notifiers(handler, n)
435 self._add_notifiers(handler, n)
436
436
437 def traitlet_names(self, **metadata):
437 def traitlet_names(self, **metadata):
438 """Get a list of all the names of this classes traitlets."""
438 """Get a list of all the names of this classes traitlets."""
439 return self.traitlets(**metadata).keys()
439 return self.traitlets(**metadata).keys()
440
440
441 def traitlets(self, *args, **metadata):
441 def traitlets(self, *args, **metadata):
442 """Get a list of all the traitlets of this class.
442 """Get a list of all the traitlets of this class.
443
443
444 The TraitletTypes returned don't know anything about the values
444 The TraitletTypes returned don't know anything about the values
445 that the various HasTraitlet's instances are holding.
445 that the various HasTraitlet's instances are holding.
446 """
446 """
447 traitlets = dict([memb for memb in inspect.getmembers(self.__class__) if \
447 traitlets = dict([memb for memb in inspect.getmembers(self.__class__) if \
448 isinstance(memb[1], TraitletType)])
448 isinstance(memb[1], TraitletType)])
449 if len(metadata) == 0 and len(args) == 0:
449 if len(metadata) == 0 and len(args) == 0:
450 return traitlets
450 return traitlets
451
451
452 for meta_name in args:
452 for meta_name in args:
453 metadata[meta_name] = lambda _: True
453 metadata[meta_name] = lambda _: True
454
454
455 for meta_name, meta_eval in metadata.items():
455 for meta_name, meta_eval in metadata.items():
456 if type(meta_eval) is not FunctionType:
456 if type(meta_eval) is not FunctionType:
457 metadata[meta_name] = _SimpleTest(meta_eval)
457 metadata[meta_name] = _SimpleTest(meta_eval)
458
458
459 result = {}
459 result = {}
460 for name, traitlet in traitlets.items():
460 for name, traitlet in traitlets.items():
461 for meta_name, meta_eval in metadata.items():
461 for meta_name, meta_eval in metadata.items():
462 if not meta_eval(traitlet.get_metadata(meta_name)):
462 if not meta_eval(traitlet.get_metadata(meta_name)):
463 break
463 break
464 else:
464 else:
465 result[name] = traitlet
465 result[name] = traitlet
466
466
467 return result
467 return result
468
468
469 def traitlet_metadata(self, traitletname, key):
469 def traitlet_metadata(self, traitletname, key):
470 """Get metadata values for traitlet by key."""
470 """Get metadata values for traitlet by key."""
471 try:
471 try:
472 traitlet = getattr(self.__class__, traitletname)
472 traitlet = getattr(self.__class__, traitletname)
473 except AttributeError:
473 except AttributeError:
474 raise TraitletError("Class %s does not have a traitlet named %s" %
474 raise TraitletError("Class %s does not have a traitlet named %s" %
475 (self.__class__.__name__, traitletname))
475 (self.__class__.__name__, traitletname))
476 else:
476 else:
477 return traitlet.get_metadata(key)
477 return traitlet.get_metadata(key)
478
478
479 #-----------------------------------------------------------------------------
479 #-----------------------------------------------------------------------------
480 # Actual TraitletTypes implementations/subclasses
480 # Actual TraitletTypes implementations/subclasses
481 #-----------------------------------------------------------------------------
481 #-----------------------------------------------------------------------------
482
482
483 #-----------------------------------------------------------------------------
483 #-----------------------------------------------------------------------------
484 # TraitletTypes subclasses for handling classes and instances of classes
484 # TraitletTypes subclasses for handling classes and instances of classes
485 #-----------------------------------------------------------------------------
485 #-----------------------------------------------------------------------------
486
486
487
487
488 class ClassBasedTraitletType(TraitletType):
488 class ClassBasedTraitletType(TraitletType):
489 """A traitlet with error reporting for Type, Instance and This."""
489 """A traitlet with error reporting for Type, Instance and This."""
490
490
491 def error(self, obj, value):
491 def error(self, obj, value):
492 kind = type(value)
492 kind = type(value)
493 if kind is InstanceType:
493 if kind is InstanceType:
494 msg = 'class %s' % value.__class__.__name__
494 msg = 'class %s' % value.__class__.__name__
495 else:
495 else:
496 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
496 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
497
497
498 super(ClassBasedTraitletType, self).error(obj, msg)
498 super(ClassBasedTraitletType, self).error(obj, msg)
499
499
500
500
501 class Type(ClassBasedTraitletType):
501 class Type(ClassBasedTraitletType):
502 """A traitlet whose value must be a subclass of a specified class."""
502 """A traitlet whose value must be a subclass of a specified class."""
503
503
504 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
504 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
505 """Construct a Type traitlet
505 """Construct a Type traitlet
506
506
507 A Type traitlet specifies that its values must be subclasses of
507 A Type traitlet specifies that its values must be subclasses of
508 a particular class.
508 a particular class.
509
509
510 Parameters
510 Parameters
511 ----------
511 ----------
512 default_value : class
512 default_value : class
513 The default value must be a subclass of klass.
513 The default value must be a subclass of klass.
514 klass : class, str, None
514 klass : class, str, None
515 Values of this traitlet must be a subclass of klass. The klass
515 Values of this traitlet must be a subclass of klass. The klass
516 may be specified in a string like: 'foo.bar.MyClass'.
516 may be specified in a string like: 'foo.bar.MyClass'.
517 allow_none : boolean
517 allow_none : boolean
518 Indicates whether None is allowed as an assignable value. Even if
518 Indicates whether None is allowed as an assignable value. Even if
519 ``False``, the default value may be ``None``.
519 ``False``, the default value may be ``None``.
520 """
520 """
521 if default_value is None:
521 if default_value is None:
522 if klass is None:
522 if klass is None:
523 klass = object
523 klass = object
524 elif klass is None:
524 elif klass is None:
525 klass = default_value
525 klass = default_value
526
526
527 if not inspect.isclass(klass):
527 if not inspect.isclass(klass):
528 raise TraitletError("A Type traitlet must specify a class.")
528 raise TraitletError("A Type traitlet must specify a class.")
529
529
530 self.klass = klass
530 self.klass = klass
531 self._allow_none = allow_none
531 self._allow_none = allow_none
532
532
533 super(Type, self).__init__(default_value, **metadata)
533 super(Type, self).__init__(default_value, **metadata)
534
534
535 def validate(self, obj, value):
535 def validate(self, obj, value):
536 """Validates that the value is a valid object instance."""
536 """Validates that the value is a valid object instance."""
537 try:
537 try:
538 if issubclass(value, self.klass):
538 if issubclass(value, self.klass):
539 return value
539 return value
540 except:
540 except:
541 if (value is None) and (self._allow_none):
541 if (value is None) and (self._allow_none):
542 return value
542 return value
543
543
544 self.error(obj, value)
544 self.error(obj, value)
545
545
546 def info(self):
546 def info(self):
547 """ Returns a description of the trait."""
547 """ Returns a description of the trait."""
548 klass = self.klass.__name__
548 klass = self.klass.__name__
549 result = 'a subclass of ' + klass
549 result = 'a subclass of ' + klass
550 if self._allow_none:
550 if self._allow_none:
551 return result + ' or None'
551 return result + ' or None'
552 return result
552 return result
553
553
554
554
555 class DefaultValueGenerator(object):
555 class DefaultValueGenerator(object):
556 """A class for generating new default value instances."""
556 """A class for generating new default value instances."""
557
557
558 def __init__(self, klass, *args, **kw):
558 def __init__(self, klass, *args, **kw):
559 self.klass = klass
559 self.klass = klass
560 self.args = args
560 self.args = args
561 self.kw = kw
561 self.kw = kw
562
562
563 def generate(self):
563 def generate(self):
564 return self.klass(*self.args, **self.kw)
564 return self.klass(*self.args, **self.kw)
565
565
566
566
567 class Instance(ClassBasedTraitletType):
567 class Instance(ClassBasedTraitletType):
568 """A trait whose value must be an instance of a specified class.
568 """A trait whose value must be an instance of a specified class.
569
569
570 The value can also be an instance of a subclass of the specified class.
570 The value can also be an instance of a subclass of the specified class.
571 """
571 """
572
572
573 def __init__(self, klass=None, args=None, kw=None,
573 def __init__(self, klass=None, args=None, kw=None,
574 allow_none=True, **metadata ):
574 allow_none=True, **metadata ):
575 """Construct an Instance traitlet.
575 """Construct an Instance traitlet.
576
576
577 This traitlet allows values that are instances of a particular
577 This traitlet allows values that are instances of a particular
578 class or its sublclasses. Our implementation is quite different
578 class or its sublclasses. Our implementation is quite different
579 from that of enthough.traits as we don't allow instances to be used
579 from that of enthough.traits as we don't allow instances to be used
580 for klass and we handle the ``args`` and ``kw`` arguments differently.
580 for klass and we handle the ``args`` and ``kw`` arguments differently.
581
581
582 Parameters
582 Parameters
583 ----------
583 ----------
584 klass : class
584 klass : class
585 The class that forms the basis for the traitlet. Instances
585 The class that forms the basis for the traitlet. Instances
586 and strings are not allowed.
586 and strings are not allowed.
587 args : tuple
587 args : tuple
588 Positional arguments for generating the default value.
588 Positional arguments for generating the default value.
589 kw : dict
589 kw : dict
590 Keyword arguments for generating the default value.
590 Keyword arguments for generating the default value.
591 allow_none : bool
591 allow_none : bool
592 Indicates whether None is allowed as a value.
592 Indicates whether None is allowed as a value.
593
593
594 Default Value
594 Default Value
595 -------------
595 -------------
596 If both ``args`` and ``kw`` are None, then the default value is None.
596 If both ``args`` and ``kw`` are None, then the default value is None.
597 If ``args`` is a tuple and ``kw`` is a dict, then the default is
597 If ``args`` is a tuple and ``kw`` is a dict, then the default is
598 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
598 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
599 not (but not both), None is replace by ``()`` or ``{}``.
599 not (but not both), None is replace by ``()`` or ``{}``.
600 """
600 """
601
601
602 self._allow_none = allow_none
602 self._allow_none = allow_none
603
603
604 if (klass is None) or (not inspect.isclass(klass)):
604 if (klass is None) or (not inspect.isclass(klass)):
605 raise TraitletError('The klass argument must be a class'
605 raise TraitletError('The klass argument must be a class'
606 ' you gave: %r' % klass)
606 ' you gave: %r' % klass)
607 self.klass = klass
607 self.klass = klass
608
608
609 # self.klass is a class, so handle default_value
609 # self.klass is a class, so handle default_value
610 if args is None and kw is None:
610 if args is None and kw is None:
611 default_value = None
611 default_value = None
612 else:
612 else:
613 if args is None:
613 if args is None:
614 # kw is not None
614 # kw is not None
615 args = ()
615 args = ()
616 elif kw is None:
616 elif kw is None:
617 # args is not None
617 # args is not None
618 kw = {}
618 kw = {}
619
619
620 if not isinstance(kw, dict):
620 if not isinstance(kw, dict):
621 raise TraitletError("The 'kw' argument must be a dict or None.")
621 raise TraitletError("The 'kw' argument must be a dict or None.")
622 if not isinstance(args, tuple):
622 if not isinstance(args, tuple):
623 raise TraitletError("The 'args' argument must be a tuple or None.")
623 raise TraitletError("The 'args' argument must be a tuple or None.")
624
624
625 default_value = DefaultValueGenerator(self.klass, *args, **kw)
625 default_value = DefaultValueGenerator(self.klass, *args, **kw)
626
626
627 super(Instance, self).__init__(default_value, **metadata)
627 super(Instance, self).__init__(default_value, **metadata)
628
628
629 def validate(self, obj, value):
629 def validate(self, obj, value):
630 if value is None:
630 if value is None:
631 if self._allow_none:
631 if self._allow_none:
632 return value
632 return value
633 self.error(obj, value)
633 self.error(obj, value)
634
634
635 if isinstance(value, self.klass):
635 if isinstance(value, self.klass):
636 return value
636 return value
637 else:
637 else:
638 self.error(obj, value)
638 self.error(obj, value)
639
639
640 def info(self):
640 def info(self):
641 klass = self.klass.__name__
641 klass = self.klass.__name__
642 result = class_of(klass)
642 result = class_of(klass)
643 if self._allow_none:
643 if self._allow_none:
644 return result + ' or None'
644 return result + ' or None'
645
645
646 return result
646 return result
647
647
648 def get_default_value(self):
648 def get_default_value(self):
649 """Instantiate a default value instance.
649 """Instantiate a default value instance.
650
650
651 This is called when the containing HasTraitlets classes'
651 This is called when the containing HasTraitlets classes'
652 :meth:`__new__` method is called to ensure that a unique instance
652 :meth:`__new__` method is called to ensure that a unique instance
653 is created for each HasTraitlets instance.
653 is created for each HasTraitlets instance.
654 """
654 """
655 dv = self.default_value
655 dv = self.default_value
656 if isinstance(dv, DefaultValueGenerator):
656 if isinstance(dv, DefaultValueGenerator):
657 return dv.generate()
657 return dv.generate()
658 else:
658 else:
659 return dv
659 return dv
660
660
661
661
662 class This(ClassBasedTraitletType):
662 class This(ClassBasedTraitletType):
663 """A traitlet for instances of the class containing this trait.
663 """A traitlet for instances of the class containing this trait.
664
664
665 Because how how and when class bodies are executed, the ``This``
665 Because how how and when class bodies are executed, the ``This``
666 traitlet can only have a default value of None. This, and because we
666 traitlet can only have a default value of None. This, and because we
667 always validate default values, ``allow_none`` is *always* true.
667 always validate default values, ``allow_none`` is *always* true.
668 """
668 """
669
669
670 info_text = 'an instance of the same type as the receiver or None'
670 info_text = 'an instance of the same type as the receiver or None'
671
671
672 def __init__(self, **metadata):
672 def __init__(self, **metadata):
673 super(This, self).__init__(None, **metadata)
673 super(This, self).__init__(None, **metadata)
674
674
675 def validate(self, obj, value):
675 def validate(self, obj, value):
676 # What if value is a superclass of obj.__class__? This is
676 # What if value is a superclass of obj.__class__? This is
677 # complicated if it was the superclass that defined the This
677 # complicated if it was the superclass that defined the This
678 # traitlet.
678 # traitlet.
679 if isinstance(value, self.this_class) or (value is None):
679 if isinstance(value, self.this_class) or (value is None):
680 return value
680 return value
681 else:
681 else:
682 self.error(obj, value)
682 self.error(obj, value)
683
683
684
684
685 #-----------------------------------------------------------------------------
685 #-----------------------------------------------------------------------------
686 # Basic TraitletTypes implementations/subclasses
686 # Basic TraitletTypes implementations/subclasses
687 #-----------------------------------------------------------------------------
687 #-----------------------------------------------------------------------------
688
688
689
689
690 class Any(TraitletType):
690 class Any(TraitletType):
691 default_value = None
691 default_value = None
692 info_text = 'any value'
692 info_text = 'any value'
693
693
694
694
695 class Int(TraitletType):
695 class Int(TraitletType):
696 """A integer traitlet."""
696 """A integer traitlet."""
697
697
698 evaluate = int
698 evaluate = int
699 default_value = 0
699 default_value = 0
700 info_text = 'an integer'
700 info_text = 'an integer'
701
701
702 def validate(self, obj, value):
702 def validate(self, obj, value):
703 if isinstance(value, int):
703 if isinstance(value, int):
704 return value
704 return value
705 self.error(obj, value)
705 self.error(obj, value)
706
706
707 class CInt(Int):
707 class CInt(Int):
708 """A casting version of the int traitlet."""
708 """A casting version of the int traitlet."""
709
709
710 def validate(self, obj, value):
710 def validate(self, obj, value):
711 try:
711 try:
712 return int(value)
712 return int(value)
713 except:
713 except:
714 self.error(obj, value)
714 self.error(obj, value)
715
715
716
716
717 class Long(TraitletType):
717 class Long(TraitletType):
718 """A long integer traitlet."""
718 """A long integer traitlet."""
719
719
720 evaluate = long
720 evaluate = long
721 default_value = 0L
721 default_value = 0L
722 info_text = 'a long'
722 info_text = 'a long'
723
723
724 def validate(self, obj, value):
724 def validate(self, obj, value):
725 if isinstance(value, long):
725 if isinstance(value, long):
726 return value
726 return value
727 if isinstance(value, int):
727 if isinstance(value, int):
728 return long(value)
728 return long(value)
729 self.error(obj, value)
729 self.error(obj, value)
730
730
731
731
732 class CLong(Long):
732 class CLong(Long):
733 """A casting version of the long integer traitlet."""
733 """A casting version of the long integer traitlet."""
734
734
735 def validate(self, obj, value):
735 def validate(self, obj, value):
736 try:
736 try:
737 return long(value)
737 return long(value)
738 except:
738 except:
739 self.error(obj, value)
739 self.error(obj, value)
740
740
741
741
742 class Float(TraitletType):
742 class Float(TraitletType):
743 """A float traitlet."""
743 """A float traitlet."""
744
744
745 evaluate = float
745 evaluate = float
746 default_value = 0.0
746 default_value = 0.0
747 info_text = 'a float'
747 info_text = 'a float'
748
748
749 def validate(self, obj, value):
749 def validate(self, obj, value):
750 if isinstance(value, float):
750 if isinstance(value, float):
751 return value
751 return value
752 if isinstance(value, int):
752 if isinstance(value, int):
753 return float(value)
753 return float(value)
754 self.error(obj, value)
754 self.error(obj, value)
755
755
756
756
757 class CFloat(Float):
757 class CFloat(Float):
758 """A casting version of the float traitlet."""
758 """A casting version of the float traitlet."""
759
759
760 def validate(self, obj, value):
760 def validate(self, obj, value):
761 try:
761 try:
762 return float(value)
762 return float(value)
763 except:
763 except:
764 self.error(obj, value)
764 self.error(obj, value)
765
765
766 class Complex(TraitletType):
766 class Complex(TraitletType):
767 """A traitlet for complex numbers."""
767 """A traitlet for complex numbers."""
768
768
769 evaluate = complex
769 evaluate = complex
770 default_value = 0.0 + 0.0j
770 default_value = 0.0 + 0.0j
771 info_text = 'a complex number'
771 info_text = 'a complex number'
772
772
773 def validate(self, obj, value):
773 def validate(self, obj, value):
774 if isinstance(value, complex):
774 if isinstance(value, complex):
775 return value
775 return value
776 if isinstance(value, (float, int)):
776 if isinstance(value, (float, int)):
777 return complex(value)
777 return complex(value)
778 self.error(obj, value)
778 self.error(obj, value)
779
779
780
780
781 class CComplex(Complex):
781 class CComplex(Complex):
782 """A casting version of the complex number traitlet."""
782 """A casting version of the complex number traitlet."""
783
783
784 def validate (self, obj, value):
784 def validate (self, obj, value):
785 try:
785 try:
786 return complex(value)
786 return complex(value)
787 except:
787 except:
788 self.error(obj, value)
788 self.error(obj, value)
789
789
790
790
791 class Str(TraitletType):
791 class Str(TraitletType):
792 """A traitlet for strings."""
792 """A traitlet for strings."""
793
793
794 evaluate = lambda x: x
794 evaluate = lambda x: x
795 default_value = ''
795 default_value = ''
796 info_text = 'a string'
796 info_text = 'a string'
797
797
798 def validate(self, obj, value):
798 def validate(self, obj, value):
799 if isinstance(value, str):
799 if isinstance(value, str):
800 return value
800 return value
801 self.error(obj, value)
801 self.error(obj, value)
802
802
803
803
804 class CStr(Str):
804 class CStr(Str):
805 """A casting version of the string traitlet."""
805 """A casting version of the string traitlet."""
806
806
807 def validate(self, obj, value):
807 def validate(self, obj, value):
808 try:
808 try:
809 return str(value)
809 return str(value)
810 except:
810 except:
811 try:
811 try:
812 return unicode(value)
812 return unicode(value)
813 except:
813 except:
814 self.error(obj, value)
814 self.error(obj, value)
815
815
816
816
817 class Unicode(TraitletType):
817 class Unicode(TraitletType):
818 """A traitlet for unicode strings."""
818 """A traitlet for unicode strings."""
819
819
820 evaluate = unicode
820 evaluate = unicode
821 default_value = u''
821 default_value = u''
822 info_text = 'a unicode string'
822 info_text = 'a unicode string'
823
823
824 def validate(self, obj, value):
824 def validate(self, obj, value):
825 if isinstance(value, unicode):
825 if isinstance(value, unicode):
826 return value
826 return value
827 if isinstance(value, str):
827 if isinstance(value, str):
828 return unicode(value)
828 return unicode(value)
829 self.error(obj, value)
829 self.error(obj, value)
830
830
831
831
832 class CUnicode(Unicode):
832 class CUnicode(Unicode):
833 """A casting version of the unicode traitlet."""
833 """A casting version of the unicode traitlet."""
834
834
835 def validate(self, obj, value):
835 def validate(self, obj, value):
836 try:
836 try:
837 return unicode(value)
837 return unicode(value)
838 except:
838 except:
839 self.error(obj, value)
839 self.error(obj, value)
840
840
841
841
842 class Bool(TraitletType):
842 class Bool(TraitletType):
843 """A boolean (True, False) traitlet."""
843 """A boolean (True, False) traitlet."""
844 evaluate = bool
844 evaluate = bool
845 default_value = False
845 default_value = False
846 info_text = 'a boolean'
846 info_text = 'a boolean'
847
847
848 def validate(self, obj, value):
848 def validate(self, obj, value):
849 if isinstance(value, bool):
849 if isinstance(value, bool):
850 return value
850 return value
851 self.error(obj, value)
851 self.error(obj, value)
852
852
853
853
854 class CBool(Bool):
854 class CBool(Bool):
855 """A casting version of the boolean traitlet."""
855 """A casting version of the boolean traitlet."""
856
856
857 def validate(self, obj, value):
857 def validate(self, obj, value):
858 try:
858 try:
859 return bool(value)
859 return bool(value)
860 except:
860 except:
861 self.error(obj, value) No newline at end of file
861 self.error(obj, value)
862
863 class Enum(TraitletType):
864
865 def __init__(self, values, default_value=None, allow_none=True, **metadata):
866 self.values = values
867 self._allow_none = allow_none
868 super(Enum, self).__init__(default_value, **metadata)
869
870 def validate(self, obj, value):
871 if value is None:
872 if self._allow_none:
873 return value
874
875 if value in self.values:
876 return value
877 self.error(obj, value)
878
879 def info(self):
880 """ Returns a description of the trait."""
881 result = 'any of ' + repr(self.values)
882 if self._allow_none:
883 return result + ' or None'
884 return result
885
886 class CaselessStrEnum(Enum):
887
888 def validate(self, obj, value):
889 if value is None:
890 if self._allow_none:
891 return value
892
893 if not isinstance(value, str):
894 self.error(obj, value)
895
896 for v in self.values:
897 if v.lower() == value.lower():
898 return v
899 self.error(obj, value) No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now