Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,200 +1,203 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """A factory for creating configuration objects. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import os |
|
18 | 18 | import sys |
|
19 | 19 | |
|
20 | 20 | from IPython.external import argparse |
|
21 | 21 | from IPython.utils.ipstruct import Struct |
|
22 | 22 | from IPython.utils.genutils import filefind |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Code |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | |
|
29 | 29 | class ConfigLoaderError(Exception): |
|
30 | 30 | pass |
|
31 | 31 | |
|
32 | 32 | |
|
33 | 33 | class ConfigLoader(object): |
|
34 | 34 | """A object for loading configurations from just about anywhere. |
|
35 | 35 | |
|
36 | 36 | The resulting configuration is packaged as a :class:`Struct`. |
|
37 | 37 | |
|
38 | 38 | Notes |
|
39 | 39 | ----- |
|
40 | 40 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
41 | 41 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
42 | 42 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
43 | 43 | not implement complex logic for finding config files. It does not handle |
|
44 | 44 | default values or merge multiple configs. These things need to be |
|
45 | 45 | handled elsewhere. |
|
46 | 46 | """ |
|
47 | 47 | |
|
48 | 48 | def __init__(self): |
|
49 | 49 | """A base class for config loaders. |
|
50 | 50 | |
|
51 | 51 | Examples |
|
52 | 52 | -------- |
|
53 | 53 | |
|
54 | 54 | >>> cl = ConfigLoader() |
|
55 | 55 | >>> config = cl.load_config() |
|
56 | 56 | >>> config |
|
57 | 57 | {} |
|
58 | 58 | """ |
|
59 | 59 | self.clear() |
|
60 | 60 | |
|
61 | 61 | def clear(self): |
|
62 | 62 | self.config = Struct() |
|
63 | 63 | |
|
64 | 64 | def load_config(self): |
|
65 | 65 | """Load a config from somewhere, return a Struct. |
|
66 | 66 | |
|
67 | 67 | Usually, this will cause self.config to be set and then returned. |
|
68 | 68 | """ |
|
69 | 69 | return self.config |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class FileConfigLoader(ConfigLoader): |
|
73 | 73 | """A base class for file based configurations. |
|
74 | 74 | |
|
75 | 75 | As we add more file based config loaders, the common logic should go |
|
76 | 76 | here. |
|
77 | 77 | """ |
|
78 | 78 | pass |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | class PyFileConfigLoader(FileConfigLoader): |
|
82 | 82 | """A config loader for pure python files. |
|
83 | 83 | |
|
84 | 84 | This calls execfile on a plain python file and looks for attributes |
|
85 | 85 | that are all caps. These attribute are added to the config Struct. |
|
86 | 86 | """ |
|
87 | 87 | |
|
88 | 88 | def __init__(self, filename, path=None): |
|
89 | 89 | """Build a config loader for a filename and path. |
|
90 | 90 | |
|
91 | 91 | Parameters |
|
92 | 92 | ---------- |
|
93 | 93 | filename : str |
|
94 | 94 | The file name of the config file. |
|
95 | 95 | path : str, list, tuple |
|
96 | 96 | The path to search for the config file on, or a sequence of |
|
97 | 97 | paths to try in order. |
|
98 | 98 | """ |
|
99 | 99 | super(PyFileConfigLoader, self).__init__() |
|
100 | 100 | self.filename = filename |
|
101 | 101 | self.path = path |
|
102 | 102 | self.full_filename = '' |
|
103 | 103 | self.data = None |
|
104 | 104 | |
|
105 | 105 | def load_config(self): |
|
106 | 106 | """Load the config from a file and return it as a Struct.""" |
|
107 | 107 | self._find_file() |
|
108 | 108 | self._read_file_as_dict() |
|
109 | 109 | self._convert_to_struct() |
|
110 | 110 | return self.config |
|
111 | 111 | |
|
112 | 112 | def _find_file(self): |
|
113 | 113 | """Try to find the file by searching the paths.""" |
|
114 | 114 | self.full_filename = filefind(self.filename, self.path) |
|
115 | 115 | |
|
116 | 116 | def _read_file_as_dict(self): |
|
117 | 117 | self.data = {} |
|
118 | 118 | execfile(self.full_filename, self.data) |
|
119 | 119 | |
|
120 | 120 | def _convert_to_struct(self): |
|
121 | 121 | if self.data is None: |
|
122 | 122 | ConfigLoaderError('self.data does not exist') |
|
123 | 123 | for k, v in self.data.iteritems(): |
|
124 | 124 | if k == k.upper(): |
|
125 | 125 | self.config[k] = v |
|
126 | 126 | |
|
127 | 127 | |
|
128 | 128 | class CommandLineConfigLoader(ConfigLoader): |
|
129 | 129 | """A config loader for command line arguments. |
|
130 | 130 | |
|
131 | 131 | As we add more command line based loaders, the common logic should go |
|
132 | 132 | here. |
|
133 | 133 | """ |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | class NoDefault(object): pass |
|
137 | 137 | NoDefault = NoDefault() |
|
138 | 138 | |
|
139 | 139 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
140 | 140 | |
|
141 | 141 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] |
|
142 | 142 | arguments = () |
|
143 | 143 | |
|
144 | 144 | def __init__(self, *args, **kw): |
|
145 | 145 | """Create a config loader for use with argparse. |
|
146 | 146 | |
|
147 | 147 | The args and kwargs arguments here are passed onto the constructor |
|
148 | 148 | of :class:`argparse.ArgumentParser`. |
|
149 | 149 | """ |
|
150 | 150 | super(CommandLineConfigLoader, self).__init__() |
|
151 | 151 | self.args = args |
|
152 | 152 | self.kw = kw |
|
153 | 153 | |
|
154 | 154 | def load_config(self, args=None): |
|
155 | 155 | """Parse command line arguments and return as a Struct.""" |
|
156 | 156 | self._create_parser() |
|
157 | 157 | self._parse_args(args) |
|
158 | 158 | self._convert_to_struct() |
|
159 | 159 | return self.config |
|
160 | 160 | |
|
161 | 161 | def _create_parser(self): |
|
162 | 162 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) |
|
163 | 163 | self._add_arguments() |
|
164 | 164 | self._add_other_arguments() |
|
165 | 165 | |
|
166 | 166 | def _add_other_arguments(self): |
|
167 | 167 | pass |
|
168 | 168 | |
|
169 | 169 | def _add_arguments(self): |
|
170 | 170 | for argument in self.arguments: |
|
171 | 171 | if not argument[1].has_key('default'): |
|
172 | 172 | argument[1]['default'] = NoDefault |
|
173 | 173 | self.parser.add_argument(*argument[0],**argument[1]) |
|
174 | 174 | |
|
175 | 175 | def _parse_args(self, args=None): |
|
176 | 176 | """self.parser->self.parsed_data""" |
|
177 | 177 | if args is None: |
|
178 | 178 | self.parsed_data = self.parser.parse_args() |
|
179 | 179 | else: |
|
180 | 180 | self.parsed_data = self.parser.parse_args(args) |
|
181 | 181 | |
|
182 | 182 | def _convert_to_struct(self): |
|
183 | 183 | """self.parsed_data->self.config""" |
|
184 | 184 | self.config = Struct() |
|
185 | 185 | for k, v in vars(self.parsed_data).items(): |
|
186 | 186 | if v is not NoDefault: |
|
187 | 187 | setattr(self.config, k, v) |
|
188 | 188 | |
|
189 | 189 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): |
|
190 | 190 | |
|
191 | 191 | def _add_other_arguments(self): |
|
192 |
self.parser.add_argument(' |
|
|
193 |
help=' |
|
|
192 | self.parser.add_argument('-ipythondir',dest='IPYTHONDIR',type=str, | |
|
193 | help='Set to override default location of IPYTHONDIR.', | |
|
194 | 194 | default=NoDefault) |
|
195 |
self.parser.add_argument('-p',' |
|
|
196 |
help=' |
|
|
197 |
default=No |
|
|
198 |
self.parser.add_argument(' |
|
|
199 |
help=' |
|
|
195 | self.parser.add_argument('-p','-profile',dest='PROFILE',type=str, | |
|
196 | help='The string name of the ipython profile to be used.', | |
|
197 | default=NoDefault) | |
|
198 | self.parser.add_argument('-debug',dest="DEBUG",action='store_true', | |
|
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 | 203 | default=NoDefault) |
@@ -1,233 +1,241 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | An application for IPython |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez |
|
10 | 10 | |
|
11 | 11 | Notes |
|
12 | 12 | ----- |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | import os |
|
27 | 27 | import sys |
|
28 | 28 | import traceback |
|
29 | 29 | |
|
30 | 30 | from copy import deepcopy |
|
31 | 31 | from IPython.utils.ipstruct import Struct |
|
32 | 32 | from IPython.utils.genutils import get_ipython_dir, filefind |
|
33 | 33 | from IPython.config.loader import ( |
|
34 | 34 | IPythonArgParseConfigLoader, |
|
35 | 35 | PyFileConfigLoader |
|
36 | 36 | ) |
|
37 | 37 | |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | # Classes and functions |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | |
|
42 | 42 | |
|
43 | 43 | class ApplicationError(Exception): |
|
44 | 44 | pass |
|
45 | 45 | |
|
46 | 46 | |
|
47 | 47 | class Application(object): |
|
48 | 48 | """Load a config, construct an app and run it. |
|
49 | 49 | """ |
|
50 | 50 | |
|
51 | 51 | config_file_name = 'ipython_config.py' |
|
52 | 52 | name = 'ipython' |
|
53 | 53 | debug = False |
|
54 | 54 | |
|
55 | 55 | def __init__(self): |
|
56 | 56 | pass |
|
57 | 57 | |
|
58 | 58 | def start(self): |
|
59 | 59 | """Start the application.""" |
|
60 | 60 | self.attempt(self.create_default_config) |
|
61 | 61 | self.attempt(self.pre_load_command_line_config) |
|
62 |
self.attempt(self.load_command_line_config, action=' |
|
|
62 | self.attempt(self.load_command_line_config, action='abort') | |
|
63 | 63 | self.attempt(self.post_load_command_line_config) |
|
64 | 64 | self.attempt(self.find_ipythondir) |
|
65 | 65 | self.attempt(self.find_config_file_name) |
|
66 | 66 | self.attempt(self.find_config_file_paths) |
|
67 | 67 | self.attempt(self.pre_load_file_config) |
|
68 | 68 | self.attempt(self.load_file_config) |
|
69 | 69 | self.attempt(self.post_load_file_config) |
|
70 | 70 | self.attempt(self.merge_configs) |
|
71 | 71 | self.attempt(self.pre_construct) |
|
72 | 72 | self.attempt(self.construct) |
|
73 | 73 | self.attempt(self.post_construct) |
|
74 | 74 | self.attempt(self.start_app) |
|
75 | 75 | |
|
76 | 76 | #------------------------------------------------------------------------- |
|
77 | 77 | # Various stages of Application creation |
|
78 | 78 | #------------------------------------------------------------------------- |
|
79 | 79 | |
|
80 | 80 | def create_default_config(self): |
|
81 | 81 | """Create defaults that can't be set elsewhere.""" |
|
82 | 82 | self.default_config = Struct() |
|
83 | 83 | self.default_config.IPYTHONDIR = get_ipython_dir() |
|
84 | 84 | |
|
85 | 85 | def create_command_line_config(self): |
|
86 | 86 | """Create and return a command line config loader.""" |
|
87 | 87 | return IPythonArgParseConfigLoader(description=self.name) |
|
88 | 88 | |
|
89 | 89 | def pre_load_command_line_config(self): |
|
90 | 90 | """Do actions just before loading the command line config.""" |
|
91 | 91 | pass |
|
92 | 92 | |
|
93 | 93 | def load_command_line_config(self): |
|
94 | 94 | """Load the command line config. |
|
95 | 95 | |
|
96 | 96 | This method also sets ``self.debug``. |
|
97 | 97 | """ |
|
98 | 98 | |
|
99 | 99 | loader = self.create_command_line_config() |
|
100 | 100 | self.command_line_config = loader.load_config() |
|
101 | 101 | try: |
|
102 | 102 | self.debug = self.command_line_config.DEBUG |
|
103 | 103 | except AttributeError: |
|
104 | 104 | pass # use class default |
|
105 | 105 | self.log("Default config loaded:", self.default_config) |
|
106 | 106 | self.log("Command line config loaded:", self.command_line_config) |
|
107 | 107 | |
|
108 | 108 | def post_load_command_line_config(self): |
|
109 | 109 | """Do actions just after loading the command line config.""" |
|
110 | 110 | pass |
|
111 | 111 | |
|
112 | 112 | def find_ipythondir(self): |
|
113 | 113 | """Set the IPython directory. |
|
114 | 114 | |
|
115 | 115 | This sets ``self.ipythondir``, but the actual value that is passed |
|
116 | 116 | to the application is kept in either ``self.default_config`` or |
|
117 | 117 | ``self.command_line_config``. This also added ``self.ipythondir`` to |
|
118 | 118 | ``sys.path`` so config files there can be references by other config |
|
119 | 119 | files. |
|
120 | 120 | """ |
|
121 | 121 | |
|
122 | 122 | try: |
|
123 | 123 | self.ipythondir = self.command_line_config.IPYTHONDIR |
|
124 | 124 | except AttributeError: |
|
125 | 125 | self.ipythondir = self.default_config.IPYTHONDIR |
|
126 | 126 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
127 | 127 | if not os.path.isdir(self.ipythondir): |
|
128 | 128 | os.makedirs(self.ipythondir, mode = 0777) |
|
129 | 129 | self.log("IPYTHONDIR set to: %s" % self.ipythondir) |
|
130 | 130 | |
|
131 | 131 | def find_config_file_name(self): |
|
132 | 132 | """Find the config file name for this application. |
|
133 | 133 | |
|
134 | 134 | If a profile has been set at the command line, this will resolve |
|
135 | 135 | it. The search paths for the config file are set in |
|
136 | 136 | :meth:`find_config_file_paths` and then passed to the config file |
|
137 | 137 | loader where they are resolved to an absolute path. |
|
138 | 138 | """ |
|
139 | 139 | |
|
140 | if self.command_line_config.PROFILE_NAME is not None: | |
|
141 |
self. |
|
|
140 | try: | |
|
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 | 147 | name_parts = self.config_file_name.split('.') |
|
143 | 148 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
144 | 149 | self.config_file_name = ''.join(name_parts) |
|
150 | except AttributeError: | |
|
151 | pass | |
|
145 | 152 | |
|
146 | 153 | def find_config_file_paths(self): |
|
147 | 154 | """Set the search paths for resolving the config file.""" |
|
148 | 155 | self.config_file_paths = (os.getcwd(), self.ipythondir) |
|
149 | 156 | |
|
150 | 157 | def pre_load_file_config(self): |
|
151 | 158 | """Do actions before the config file is loaded.""" |
|
152 | 159 | pass |
|
153 | 160 | |
|
154 | 161 | def load_file_config(self): |
|
155 | 162 | """Load the config file. |
|
156 | 163 | |
|
157 | 164 | This tries to load the config file from disk. If successful, the |
|
158 | 165 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
159 | 166 | location. If not successful, an empty config is used. |
|
160 | 167 | """ |
|
161 | 168 | loader = PyFileConfigLoader(self.config_file_name, |
|
162 | 169 | self.config_file_paths) |
|
163 | 170 | try: |
|
164 | 171 | self.file_config = loader.load_config() |
|
165 | 172 | self.file_config.CONFIG_FILE = loader.full_filename |
|
166 | 173 | except IOError: |
|
167 | 174 | self.log("Config file not found, skipping: %s" % \ |
|
168 | 175 | self.config_file_name) |
|
169 | 176 | self.file_config = Struct() |
|
170 | 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 | 181 | def post_load_file_config(self): |
|
174 | 182 | """Do actions after the config file is loaded.""" |
|
175 | 183 | pass |
|
176 | 184 | |
|
177 | 185 | def merge_configs(self): |
|
178 | 186 | """Merge the default, command line and file config objects.""" |
|
179 | 187 | config = Struct() |
|
180 | 188 | config.update(self.default_config) |
|
181 | config.update(self.command_line_config) | |
|
182 | 189 | config.update(self.file_config) |
|
190 | config.update(self.command_line_config) | |
|
183 | 191 | self.master_config = config |
|
184 | 192 | self.log("Master config created:", self.master_config) |
|
185 | 193 | |
|
186 | 194 | def pre_construct(self): |
|
187 | 195 | """Do actions after the config has been built, but before construct.""" |
|
188 | 196 | pass |
|
189 | 197 | |
|
190 | 198 | def construct(self): |
|
191 | 199 | """Construct the main components that make up this app.""" |
|
192 | 200 | self.log("Constructing components for application...") |
|
193 | 201 | |
|
194 | 202 | def post_construct(self): |
|
195 | 203 | """Do actions after construct, but before starting the app.""" |
|
196 | 204 | pass |
|
197 | 205 | |
|
198 | 206 | def start_app(self): |
|
199 | 207 | """Actually start the app.""" |
|
200 | 208 | self.log("Starting application...") |
|
201 | 209 | |
|
202 | 210 | #------------------------------------------------------------------------- |
|
203 | 211 | # Utility methods |
|
204 | 212 | #------------------------------------------------------------------------- |
|
205 | 213 | |
|
206 | 214 | def abort(self): |
|
207 | 215 | """Abort the starting of the application.""" |
|
208 | 216 | print "Aborting application: ", self.name |
|
209 | 217 | sys.exit(1) |
|
210 | 218 | |
|
211 | 219 | def exit(self): |
|
212 | 220 | print "Exiting application: ", self.name |
|
213 | 221 | sys.exit(1) |
|
214 | 222 | |
|
215 | 223 | def attempt(self, func, action='abort'): |
|
216 | 224 | try: |
|
217 | 225 | func() |
|
218 | 226 | except: |
|
219 | 227 | if action == 'abort': |
|
220 | 228 | self.print_traceback() |
|
221 | 229 | self.abort() |
|
222 | 230 | elif action == 'exit': |
|
223 | 231 | self.exit() |
|
224 | 232 | |
|
225 | 233 | def print_traceback(self): |
|
226 | 234 | print "Error in appliction startup: ", self.name |
|
227 | 235 | |
|
228 | 236 | traceback.print_exc() |
|
229 | 237 | |
|
230 | 238 | def log(self, *args): |
|
231 | 239 | if self.debug: |
|
232 | 240 | for arg in args: |
|
233 | 241 | print "[%s] %s" % (self.name, arg) No newline at end of file |
@@ -1,65 +1,316 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The main IPython application object |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez |
|
10 | 10 | |
|
11 | 11 | Notes |
|
12 | 12 | ----- |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | import os | |
|
27 | import sys | |
|
28 | import warnings | |
|
29 | ||
|
26 | 30 | from IPython.core.application import Application |
|
27 | 31 | from IPython.core import release |
|
28 | 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 | 43 | ipython_desc = """ |
|
32 | 44 | A Python shell with automatic history (input and output), dynamic object |
|
33 | 45 | introspection, easier configuration, command completion, access to the system |
|
34 | 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 | 223 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): |
|
38 | arguments = ( | |
|
39 | () | |
|
40 | ) | |
|
224 | ||
|
225 | arguments = cl_args | |
|
226 | ||
|
41 | 227 | |
|
42 | 228 | class IPythonApp(Application): |
|
43 | 229 | name = 'ipython' |
|
44 | 230 | config_file_name = 'ipython_config.py' |
|
45 | 231 | |
|
46 | 232 | def create_command_line_config(self): |
|
47 | 233 | """Create and return a command line config loader.""" |
|
48 | 234 | return IPythonAppCLConfigLoader( |
|
49 | 235 | description=ipython_desc, |
|
50 | 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 | 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 | 304 | self.shell = InteractiveShell( |
|
54 | 305 | name='__IP', |
|
55 | 306 | parent=None, |
|
56 | 307 | config=self.master_config |
|
57 | 308 | ) |
|
58 | 309 | |
|
59 | 310 | def start_app(self): |
|
60 | 311 | self.shell.mainloop() |
|
61 | 312 | |
|
62 | 313 | |
|
63 | 314 | if __name__ == '__main__': |
|
64 | 315 | app = IPythonApp() |
|
65 | 316 | app.start() No newline at end of file |
@@ -1,2737 +1,2809 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Main IPython Component |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
8 | 8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
9 | 9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | import __main__ |
|
20 | 20 | import __builtin__ |
|
21 | 21 | import StringIO |
|
22 | 22 | import bdb |
|
23 | 23 | import codeop |
|
24 | 24 | import exceptions |
|
25 | 25 | import glob |
|
26 | 26 | import keyword |
|
27 | 27 | import new |
|
28 | 28 | import os |
|
29 | 29 | import re |
|
30 | 30 | import shutil |
|
31 | 31 | import string |
|
32 | 32 | import sys |
|
33 | 33 | import tempfile |
|
34 | 34 | |
|
35 | 35 | from IPython.core import ultratb |
|
36 | 36 | from IPython.core import debugger, oinspect |
|
37 | 37 | from IPython.core import ipapi |
|
38 | 38 | from IPython.core import shadowns |
|
39 | 39 | from IPython.core import history as ipcorehist |
|
40 | 40 | from IPython.core import prefilter |
|
41 | 41 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
42 | 42 | from IPython.core.logger import Logger |
|
43 | 43 | from IPython.core.magic import Magic |
|
44 | 44 | from IPython.core.prompts import CachedOutput |
|
45 | 45 | from IPython.core.component import Component |
|
46 | 46 | from IPython.core.oldusersetup import user_setup |
|
47 |
from IPython.core.usage import interactive_usage, banner |
|
|
47 | from IPython.core.usage import interactive_usage, default_banner | |
|
48 | 48 | |
|
49 | 49 | from IPython.extensions import pickleshare |
|
50 | 50 | from IPython.external.Itpl import ItplNS |
|
51 | 51 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
52 | 52 | from IPython.utils.ipstruct import Struct |
|
53 | 53 | from IPython.utils import PyColorize |
|
54 | 54 | from IPython.utils.genutils import * |
|
55 | 55 | from IPython.utils.strdispatch import StrDispatch |
|
56 | 56 | |
|
57 | 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 | 62 | # Globals |
|
63 | 63 | #----------------------------------------------------------------------------- |
|
64 | 64 | |
|
65 | 65 | |
|
66 | 66 | # store the builtin raw_input globally, and use this always, in case user code |
|
67 | 67 | # overwrites it (like wx.py.PyShell does) |
|
68 | 68 | raw_input_original = raw_input |
|
69 | 69 | |
|
70 | 70 | # compiled regexps for autoindent management |
|
71 | 71 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
72 | 72 | |
|
73 | 73 | |
|
74 | 74 | #----------------------------------------------------------------------------- |
|
75 | 75 | # Utilities |
|
76 | 76 | #----------------------------------------------------------------------------- |
|
77 | 77 | |
|
78 | 78 | |
|
79 | 79 | ini_spaces_re = re.compile(r'^(\s+)') |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | def num_ini_spaces(strng): |
|
83 | 83 | """Return the number of initial spaces in a string""" |
|
84 | 84 | |
|
85 | 85 | ini_spaces = ini_spaces_re.match(strng) |
|
86 | 86 | if ini_spaces: |
|
87 | 87 | return ini_spaces.end() |
|
88 | 88 | else: |
|
89 | 89 | return 0 |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | def softspace(file, newvalue): |
|
93 | 93 | """Copied from code.py, to remove the dependency""" |
|
94 | 94 | |
|
95 | 95 | oldvalue = 0 |
|
96 | 96 | try: |
|
97 | 97 | oldvalue = file.softspace |
|
98 | 98 | except AttributeError: |
|
99 | 99 | pass |
|
100 | 100 | try: |
|
101 | 101 | file.softspace = newvalue |
|
102 | 102 | except (AttributeError, TypeError): |
|
103 | 103 | # "attribute-less object" or "read-only attributes" |
|
104 | 104 | pass |
|
105 | 105 | return oldvalue |
|
106 | 106 | |
|
107 | 107 | |
|
108 | 108 | class SpaceInInput(exceptions.Exception): pass |
|
109 | 109 | |
|
110 | 110 | class Bunch: pass |
|
111 | 111 | |
|
112 | 112 | class Undefined: pass |
|
113 | 113 | |
|
114 | 114 | class Quitter(object): |
|
115 | 115 | """Simple class to handle exit, similar to Python 2.5's. |
|
116 | 116 | |
|
117 | 117 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
118 | 118 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
119 | 119 | |
|
120 | 120 | def __init__(self,shell,name): |
|
121 | 121 | self.shell = shell |
|
122 | 122 | self.name = name |
|
123 | 123 | |
|
124 | 124 | def __repr__(self): |
|
125 | 125 | return 'Type %s() to exit.' % self.name |
|
126 | 126 | __str__ = __repr__ |
|
127 | 127 | |
|
128 | 128 | def __call__(self): |
|
129 | 129 | self.shell.exit() |
|
130 | 130 | |
|
131 | 131 | class InputList(list): |
|
132 | 132 | """Class to store user input. |
|
133 | 133 | |
|
134 | 134 | It's basically a list, but slices return a string instead of a list, thus |
|
135 | 135 | allowing things like (assuming 'In' is an instance): |
|
136 | 136 | |
|
137 | 137 | exec In[4:7] |
|
138 | 138 | |
|
139 | 139 | or |
|
140 | 140 | |
|
141 | 141 | exec In[5:9] + In[14] + In[21:25]""" |
|
142 | 142 | |
|
143 | 143 | def __getslice__(self,i,j): |
|
144 | 144 | return ''.join(list.__getslice__(self,i,j)) |
|
145 | 145 | |
|
146 | 146 | class SyntaxTB(ultratb.ListTB): |
|
147 | 147 | """Extension which holds some state: the last exception value""" |
|
148 | 148 | |
|
149 | 149 | def __init__(self,color_scheme = 'NoColor'): |
|
150 | 150 | ultratb.ListTB.__init__(self,color_scheme) |
|
151 | 151 | self.last_syntax_error = None |
|
152 | 152 | |
|
153 | 153 | def __call__(self, etype, value, elist): |
|
154 | 154 | self.last_syntax_error = value |
|
155 | 155 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
156 | 156 | |
|
157 | 157 | def clear_err_state(self): |
|
158 | 158 | """Return the current error state and clear it""" |
|
159 | 159 | e = self.last_syntax_error |
|
160 | 160 | self.last_syntax_error = None |
|
161 | 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 | 174 | # Main IPython class |
|
166 | 175 | #----------------------------------------------------------------------------- |
|
167 | 176 | |
|
168 | 177 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
169 | 178 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
170 | 179 | # attributes and methods, but too much user code out there relies on the |
|
171 | 180 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
172 | 181 | # |
|
173 | 182 | # But at least now, all the pieces have been separated and we could, in |
|
174 | 183 | # principle, stop using the mixin. This will ease the transition to the |
|
175 | 184 | # chainsaw branch. |
|
176 | 185 | |
|
177 | 186 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
178 | 187 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
179 | 188 | # class, to prevent clashes. |
|
180 | 189 | |
|
181 | 190 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
182 | 191 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
183 | 192 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
184 | 193 | # 'self.value'] |
|
185 | 194 | |
|
186 | 195 | class InteractiveShell(Component, Magic): |
|
187 | 196 | """An enhanced console for Python.""" |
|
188 | 197 | |
|
189 | 198 | alias = [] |
|
190 | autocall = Bool(True) | |
|
191 | autoedit_syntax = Bool(False) | |
|
192 | autoindent = Bool(False) | |
|
193 | automagic = Bool(True) | |
|
199 | autocall = Enum((0,1,2), config_key='AUTOCALL') | |
|
200 | autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX') | |
|
201 | autoindent = CBool(True, config_key='AUTOINDENT') | |
|
202 | automagic = CBool(True, config_key='AUTOMAGIC') | |
|
194 | 203 | autoexec = [] |
|
195 | display_banner = Bool(True) | |
|
204 | display_banner = CBool(True, config_key='DISPLAY_BANNER') | |
|
196 | 205 | banner = Str('') |
|
197 | c = Str('') | |
|
198 | cache_size = Int(1000) | |
|
199 | classic = Bool(False) | |
|
200 | color_info = Int(0) | |
|
201 | colors = Str('LightBG') | |
|
202 | confirm_exit = Bool(True) | |
|
203 | debug = Bool(False) | |
|
204 | deep_reload = Bool(False) | |
|
205 | embedded = Bool(False) | |
|
206 | editor = Str('0') | |
|
206 | banner1 = Str(default_banner, config_key='BANNER1') | |
|
207 | banner2 = Str('', config_key='BANNER2') | |
|
208 | c = Str('', config_key='C') | |
|
209 | cache_size = Int(1000, config_key='CACHE_SIZE') | |
|
210 | classic = CBool(False, config_key='CLASSIC') | |
|
211 | color_info = CBool(True, config_key='COLOR_INFO') | |
|
212 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
|
213 | default_value='LightBG', config_key='COLORS') | |
|
214 | confirm_exit = CBool(True, config_key='CONFIRM_EXIT') | |
|
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 | 219 | filename = Str("<ipython console>") |
|
208 | help = Bool(False) | |
|
209 | interactive = Bool(False) | |
|
210 | logstart = Bool(False, config_key='LOGSTART') | |
|
211 | logfile = Str('') | |
|
212 | logplay = Str('') | |
|
213 |
m |
|
|
214 | multi_line_specials = Bool(True) | |
|
215 | nosep = Bool(False) | |
|
220 | help = CBool(False) | |
|
221 | interactive = CBool(False) | |
|
222 | logstart = CBool(False, config_key='LOGSTART') | |
|
223 | logfile = Str('', config_key='LOGFILE') | |
|
224 | logplay = Str('', config_key='LOGPLAY') | |
|
225 | multi_line_specials = CBool(True) | |
|
216 | 226 | object_info_string_level = Int(0) |
|
217 | 227 | pager = Str('less') |
|
218 | pdb = Bool(False) | |
|
219 | pprint = Bool(True) | |
|
220 | profile = Str('') | |
|
221 | prompt_in1 = Str('In [\\#]: ') | |
|
222 | prompt_in2 = Str(' .\\D.: ') | |
|
223 | prompt_out = Str('Out[\\#]: ') | |
|
224 | prompts_pad_left = Bool(True) | |
|
225 | pydb = Bool(False) | |
|
226 |
qui |
|
|
227 | quiet = Bool(False) | |
|
228 | ||
|
229 |
readline_ |
|
|
230 | readline_merge_completions = Bool(True) | |
|
228 | pdb = CBool(False, config_key='PDB') | |
|
229 | pprint = CBool(True, config_key='PPRINT') | |
|
230 | profile = Str('', config_key='PROFILE') | |
|
231 | prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1') | |
|
232 | prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2') | |
|
233 | prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1') | |
|
234 | prompts_pad_left = CBool(True) | |
|
235 | pydb = CBool(False) | |
|
236 | quiet = CBool(False) | |
|
237 | ||
|
238 | readline_use = CBool(True, config_key='READLINE_USE') | |
|
239 | readline_merge_completions = CBool(True) | |
|
231 | 240 | readline_omit__names = Int(0) |
|
232 | 241 | readline_remove_delims = '-/~' |
|
233 | 242 | readline_parse_and_bind = [ |
|
234 | 243 | 'tab: complete', |
|
235 | 244 | '"\C-l": possible-completions', |
|
236 | 245 | 'set show-all-if-ambiguous on', |
|
237 | 246 | '"\C-o": tab-insert', |
|
238 | 247 | '"\M-i": " "', |
|
239 | 248 | '"\M-o": "\d\d\d\d"', |
|
240 | 249 | '"\M-I": "\d\d\d\d"', |
|
241 | 250 | '"\C-r": reverse-search-history', |
|
242 | 251 | '"\C-s": forward-search-history', |
|
243 | 252 | '"\C-p": history-search-backward', |
|
244 | 253 | '"\C-n": history-search-forward', |
|
245 | 254 | '"\e[A": history-search-backward', |
|
246 | 255 | '"\e[B": history-search-forward', |
|
247 | 256 | '"\C-k": kill-line', |
|
248 | 257 | '"\C-u": unix-line-discard', |
|
249 | 258 | ] |
|
250 | 259 | |
|
251 | screen_length = Int(0) | |
|
252 | separate_in = Str('\n') | |
|
253 | separate_out = Str('') | |
|
254 | separate_out2 = Str('') | |
|
260 | screen_length = Int(0, config_key='SCREEN_LENGTH') | |
|
261 | separate_in = Str('\n', config_key='SEPARATE_IN') | |
|
262 | separate_out = Str('', config_key='SEPARATE_OUT') | |
|
263 | separate_out2 = Str('', config_key='SEPARATE_OUT2') | |
|
255 | 264 | system_header = Str('IPython system call: ') |
|
256 | system_verbose = Bool(False) | |
|
257 | term_title = Bool(True) | |
|
258 | wildcards_case_sensitive = Bool(True) | |
|
259 | xmode = Str('Context') | |
|
260 | magic_docstrings = Bool(False) | |
|
265 | system_verbose = CBool(False) | |
|
266 | term_title = CBool(True) | |
|
267 | wildcards_case_sensitive = CBool(True) | |
|
268 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
|
269 | default_value='Context', config_key='XMODE') | |
|
270 | magic_docstrings = CBool(False) | |
|
261 | 271 | |
|
262 | 272 | # class attribute to indicate whether the class supports threads or not. |
|
263 | 273 | # Subclasses with thread support should override this as needed. |
|
264 | 274 | isthreaded = False |
|
265 | 275 | |
|
266 | 276 | def __init__(self, name, parent=None, config=None, usage=None, |
|
267 |
user_ns=None, user_global_ns=None, |
|
|
277 | user_ns=None, user_global_ns=None, | |
|
278 | banner1='', banner2='', | |
|
268 | 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 | 285 | super(InteractiveShell, self).__init__(parent, config=config, name=name) |
|
271 | 286 | |
|
272 | 287 | self.init_instance_attrs() |
|
273 | 288 | self.init_usage(usage) |
|
274 | self.init_banner(banner2) | |
|
289 | self.init_banner(banner1, banner2) | |
|
275 | 290 | self.init_embedded(embedded) |
|
276 | 291 | self.init_create_namespaces(user_ns, user_global_ns) |
|
277 | 292 | self.init_history() |
|
278 | 293 | self.init_encoding() |
|
279 | 294 | self.init_handlers() |
|
280 | 295 | |
|
281 | 296 | Magic.__init__(self, self) |
|
282 | 297 | |
|
283 | 298 | self.init_syntax_highlighting() |
|
284 | 299 | self.init_hooks() |
|
285 | 300 | self.init_pushd_popd_magic() |
|
286 | 301 | self.init_traceback_handlers(custom_exceptions) |
|
287 | 302 | |
|
288 | 303 | # Produce a public API instance |
|
289 | 304 | self.api = ipapi.IPApi(self) |
|
290 | 305 | |
|
291 | 306 | self.init_namespaces() |
|
292 | 307 | self.init_logger() |
|
293 | 308 | self.init_aliases() |
|
294 | 309 | self.init_builtins() |
|
310 | ||
|
311 | # pre_config_initialization | |
|
295 | 312 | self.init_shadow_hist() |
|
313 | ||
|
314 | # The next section should contain averything that was in ipmaker. | |
|
296 | 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 | 350 | def init_instance_attrs(self): |
|
300 | 351 | self.jobs = BackgroundJobManager() |
|
301 | 352 | self.more = False |
|
302 | 353 | |
|
303 | 354 | # command compiler |
|
304 | 355 | self.compile = codeop.CommandCompiler() |
|
305 | 356 | |
|
306 | 357 | # User input buffer |
|
307 | 358 | self.buffer = [] |
|
308 | 359 | |
|
309 | 360 | # Make an empty namespace, which extension writers can rely on both |
|
310 | 361 | # existing and NEVER being used by ipython itself. This gives them a |
|
311 | 362 | # convenient location for storing additional information and state |
|
312 | 363 | # their extensions may require, without fear of collisions with other |
|
313 | 364 | # ipython names that may develop later. |
|
314 | 365 | self.meta = Struct() |
|
315 | 366 | |
|
316 | 367 | # Object variable to store code object waiting execution. This is |
|
317 | 368 | # used mainly by the multithreaded shells, but it can come in handy in |
|
318 | 369 | # other situations. No need to use a Queue here, since it's a single |
|
319 | 370 | # item which gets cleared once run. |
|
320 | 371 | self.code_to_run = None |
|
321 | 372 | |
|
322 | 373 | # Flag to mark unconditional exit |
|
323 | 374 | self.exit_now = False |
|
324 | 375 | |
|
325 | 376 | # Temporary files used for various purposes. Deleted at exit. |
|
326 | 377 | self.tempfiles = [] |
|
327 | 378 | |
|
328 | 379 | # Keep track of readline usage (later set by init_readline) |
|
329 | 380 | self.has_readline = False |
|
330 | 381 | |
|
331 | 382 | # keep track of where we started running (mainly for crash post-mortem) |
|
332 | 383 | # This is not being used anywhere currently. |
|
333 | 384 | self.starting_dir = os.getcwd() |
|
334 | 385 | |
|
335 | 386 | # Indentation management |
|
336 | 387 | self.indent_current_nsp = 0 |
|
337 | 388 | |
|
338 | 389 | def init_usage(self, usage=None): |
|
339 | 390 | if usage is None: |
|
340 | 391 | self.usage = interactive_usage |
|
341 | 392 | else: |
|
342 | 393 | self.usage = usage |
|
343 | 394 | |
|
344 | def init_banner(self, banner2): | |
|
395 | def init_banner(self, banner1, banner2): | |
|
345 | 396 | if self.c: # regular python doesn't print the banner with -c |
|
346 | 397 | self.display_banner = False |
|
347 |
|
|
|
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 | 406 | if self.profile: |
|
349 |
|
|
|
350 |
if banner2 |
|
|
351 | bp.append(banner2) | |
|
352 | self.banner = '\n'.join(bp) | |
|
407 | self.banner += '\nIPython profile: %s\n' % self.profile | |
|
408 | if self.banner2: | |
|
409 | self.banner += '\n' + self.banner2 + '\n' | |
|
353 | 410 | |
|
354 | 411 | def init_embedded(self, embedded): |
|
355 | 412 | # We need to know whether the instance is meant for embedding, since |
|
356 | 413 | # global/local namespaces need to be handled differently in that case |
|
357 | 414 | self.embedded = embedded |
|
358 | 415 | if embedded: |
|
359 | 416 | # Control variable so users can, from within the embedded instance, |
|
360 | 417 | # permanently deactivate it. |
|
361 | 418 | self.embedded_active = True |
|
362 | 419 | |
|
363 | 420 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
364 | 421 | # Create the namespace where the user will operate. user_ns is |
|
365 | 422 | # normally the only one used, and it is passed to the exec calls as |
|
366 | 423 | # the locals argument. But we do carry a user_global_ns namespace |
|
367 | 424 | # given as the exec 'globals' argument, This is useful in embedding |
|
368 | 425 | # situations where the ipython shell opens in a context where the |
|
369 | 426 | # distinction between locals and globals is meaningful. For |
|
370 | 427 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
371 | 428 | |
|
372 | 429 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
373 | 430 | # level as a dict instead of a module. This is a manual fix, but I |
|
374 | 431 | # should really track down where the problem is coming from. Alex |
|
375 | 432 | # Schmolck reported this problem first. |
|
376 | 433 | |
|
377 | 434 | # A useful post by Alex Martelli on this topic: |
|
378 | 435 | # Re: inconsistent value from __builtins__ |
|
379 | 436 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
380 | 437 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
381 | 438 | # Gruppen: comp.lang.python |
|
382 | 439 | |
|
383 | 440 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
384 | 441 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
385 | 442 | # > <type 'dict'> |
|
386 | 443 | # > >>> print type(__builtins__) |
|
387 | 444 | # > <type 'module'> |
|
388 | 445 | # > Is this difference in return value intentional? |
|
389 | 446 | |
|
390 | 447 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
391 | 448 | # or a module, and it's been that way for a long time. Whether it's |
|
392 | 449 | # intentional (or sensible), I don't know. In any case, the idea is |
|
393 | 450 | # that if you need to access the built-in namespace directly, you |
|
394 | 451 | # should start with "import __builtin__" (note, no 's') which will |
|
395 | 452 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
396 | 453 | |
|
397 | 454 | # These routines return properly built dicts as needed by the rest of |
|
398 | 455 | # the code, and can also be used by extension writers to generate |
|
399 | 456 | # properly initialized namespaces. |
|
400 | 457 | user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns, |
|
401 | 458 | user_global_ns) |
|
402 | 459 | |
|
403 | 460 | # Assign namespaces |
|
404 | 461 | # This is the namespace where all normal user variables live |
|
405 | 462 | self.user_ns = user_ns |
|
406 | 463 | self.user_global_ns = user_global_ns |
|
407 | 464 | |
|
408 | 465 | # An auxiliary namespace that checks what parts of the user_ns were |
|
409 | 466 | # loaded at startup, so we can list later only variables defined in |
|
410 | 467 | # actual interactive use. Since it is always a subset of user_ns, it |
|
411 | 468 | # doesn't need to be seaparately tracked in the ns_table |
|
412 | 469 | self.user_config_ns = {} |
|
413 | 470 | |
|
414 | 471 | # A namespace to keep track of internal data structures to prevent |
|
415 | 472 | # them from cluttering user-visible stuff. Will be updated later |
|
416 | 473 | self.internal_ns = {} |
|
417 | 474 | |
|
418 | 475 | # Namespace of system aliases. Each entry in the alias |
|
419 | 476 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
420 | 477 | # of positional arguments of the alias. |
|
421 | 478 | self.alias_table = {} |
|
422 | 479 | |
|
423 | 480 | # Now that FakeModule produces a real module, we've run into a nasty |
|
424 | 481 | # problem: after script execution (via %run), the module where the user |
|
425 | 482 | # code ran is deleted. Now that this object is a true module (needed |
|
426 | 483 | # so docetst and other tools work correctly), the Python module |
|
427 | 484 | # teardown mechanism runs over it, and sets to None every variable |
|
428 | 485 | # present in that module. Top-level references to objects from the |
|
429 | 486 | # script survive, because the user_ns is updated with them. However, |
|
430 | 487 | # calling functions defined in the script that use other things from |
|
431 | 488 | # the script will fail, because the function's closure had references |
|
432 | 489 | # to the original objects, which are now all None. So we must protect |
|
433 | 490 | # these modules from deletion by keeping a cache. |
|
434 | 491 | # |
|
435 | 492 | # To avoid keeping stale modules around (we only need the one from the |
|
436 | 493 | # last run), we use a dict keyed with the full path to the script, so |
|
437 | 494 | # only the last version of the module is held in the cache. Note, |
|
438 | 495 | # however, that we must cache the module *namespace contents* (their |
|
439 | 496 | # __dict__). Because if we try to cache the actual modules, old ones |
|
440 | 497 | # (uncached) could be destroyed while still holding references (such as |
|
441 | 498 | # those held by GUI objects that tend to be long-lived)> |
|
442 | 499 | # |
|
443 | 500 | # The %reset command will flush this cache. See the cache_main_mod() |
|
444 | 501 | # and clear_main_mod_cache() methods for details on use. |
|
445 | 502 | |
|
446 | 503 | # This is the cache used for 'main' namespaces |
|
447 | 504 | self._main_ns_cache = {} |
|
448 | 505 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
449 | 506 | # copying and clearing for reuse on each %run |
|
450 | 507 | self._user_main_module = FakeModule() |
|
451 | 508 | |
|
452 | 509 | # A table holding all the namespaces IPython deals with, so that |
|
453 | 510 | # introspection facilities can search easily. |
|
454 | 511 | self.ns_table = {'user':user_ns, |
|
455 | 512 | 'user_global':user_global_ns, |
|
456 | 513 | 'alias':self.alias_table, |
|
457 | 514 | 'internal':self.internal_ns, |
|
458 | 515 | 'builtin':__builtin__.__dict__ |
|
459 | 516 | } |
|
460 | 517 | |
|
461 | 518 | # Similarly, track all namespaces where references can be held and that |
|
462 | 519 | # we can safely clear (so it can NOT include builtin). This one can be |
|
463 | 520 | # a simple list. |
|
464 | 521 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
465 | 522 | self.alias_table, self.internal_ns, |
|
466 | 523 | self._main_ns_cache ] |
|
467 | 524 | |
|
468 | 525 | # We need to insert into sys.modules something that looks like a |
|
469 | 526 | # module but which accesses the IPython namespace, for shelve and |
|
470 | 527 | # pickle to work interactively. Normally they rely on getting |
|
471 | 528 | # everything out of __main__, but for embedding purposes each IPython |
|
472 | 529 | # instance has its own private namespace, so we can't go shoving |
|
473 | 530 | # everything into __main__. |
|
474 | 531 | |
|
475 | 532 | # note, however, that we should only do this for non-embedded |
|
476 | 533 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
477 | 534 | # namespace. Embedded instances, on the other hand, should not do |
|
478 | 535 | # this because they need to manage the user local/global namespaces |
|
479 | 536 | # only, but they live within a 'normal' __main__ (meaning, they |
|
480 | 537 | # shouldn't overtake the execution environment of the script they're |
|
481 | 538 | # embedded in). |
|
482 | 539 | |
|
483 | 540 | if not self.embedded: |
|
484 | 541 | try: |
|
485 | 542 | main_name = self.user_ns['__name__'] |
|
486 | 543 | except KeyError: |
|
487 | 544 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
488 | 545 | else: |
|
489 | 546 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
490 | 547 | |
|
491 | 548 | def init_history(self): |
|
492 | 549 | # List of input with multi-line handling. |
|
493 | 550 | self.input_hist = InputList() |
|
494 | 551 | # This one will hold the 'raw' input history, without any |
|
495 | 552 | # pre-processing. This will allow users to retrieve the input just as |
|
496 | 553 | # it was exactly typed in by the user, with %hist -r. |
|
497 | 554 | self.input_hist_raw = InputList() |
|
498 | 555 | |
|
499 | 556 | # list of visited directories |
|
500 | 557 | try: |
|
501 | 558 | self.dir_hist = [os.getcwd()] |
|
502 | 559 | except OSError: |
|
503 | 560 | self.dir_hist = [] |
|
504 | 561 | |
|
505 | 562 | # dict of output history |
|
506 | 563 | self.output_hist = {} |
|
507 | 564 | |
|
508 | 565 | # Now the history file |
|
509 | 566 | try: |
|
510 | 567 | histfname = 'history-%s' % self.config.PROFILE |
|
511 | 568 | except AttributeError: |
|
512 | 569 | histfname = 'history' |
|
513 | 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 | 576 | def init_encoding(self): |
|
516 | 577 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
517 | 578 | # under Win32 have it set to None, and we need to have a known valid |
|
518 | 579 | # encoding to use in the raw_input() method |
|
519 | 580 | try: |
|
520 | 581 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
521 | 582 | except AttributeError: |
|
522 | 583 | self.stdin_encoding = 'ascii' |
|
523 | 584 | |
|
524 | 585 | def init_handlers(self): |
|
525 | 586 | # escapes for automatic behavior on the command line |
|
526 | 587 | self.ESC_SHELL = '!' |
|
527 | 588 | self.ESC_SH_CAP = '!!' |
|
528 | 589 | self.ESC_HELP = '?' |
|
529 | 590 | self.ESC_MAGIC = '%' |
|
530 | 591 | self.ESC_QUOTE = ',' |
|
531 | 592 | self.ESC_QUOTE2 = ';' |
|
532 | 593 | self.ESC_PAREN = '/' |
|
533 | 594 | |
|
534 | 595 | # And their associated handlers |
|
535 | 596 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
536 | 597 | self.ESC_QUOTE : self.handle_auto, |
|
537 | 598 | self.ESC_QUOTE2 : self.handle_auto, |
|
538 | 599 | self.ESC_MAGIC : self.handle_magic, |
|
539 | 600 | self.ESC_HELP : self.handle_help, |
|
540 | 601 | self.ESC_SHELL : self.handle_shell_escape, |
|
541 | 602 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
542 | 603 | } |
|
543 | 604 | |
|
544 | 605 | def init_syntax_highlighting(self): |
|
545 | 606 | # Python source parser/formatter for syntax highlighting |
|
546 | 607 | pyformat = PyColorize.Parser().format |
|
547 | 608 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
548 | 609 | |
|
549 | 610 | def init_hooks(self): |
|
550 | 611 | # hooks holds pointers used for user-side customizations |
|
551 | 612 | self.hooks = Struct() |
|
552 | 613 | |
|
553 | 614 | self.strdispatchers = {} |
|
554 | 615 | |
|
555 | 616 | # Set all default hooks, defined in the IPython.hooks module. |
|
556 | 617 | import IPython.core.hooks |
|
557 | 618 | hooks = IPython.core.hooks |
|
558 | 619 | for hook_name in hooks.__all__: |
|
559 | 620 | # default hooks have priority 100, i.e. low; user hooks should have |
|
560 | 621 | # 0-100 priority |
|
561 | 622 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
562 | 623 | |
|
563 | 624 | def init_pushd_popd_magic(self): |
|
564 | 625 | # for pushd/popd management |
|
565 | 626 | try: |
|
566 | 627 | self.home_dir = get_home_dir() |
|
567 | 628 | except HomeDirError, msg: |
|
568 | 629 | fatal(msg) |
|
569 | 630 | |
|
570 | 631 | self.dir_stack = [] |
|
571 | 632 | |
|
572 | 633 | def init_traceback_handlers(self, custom_exceptions): |
|
573 | 634 | # Syntax error handler. |
|
574 | 635 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
575 | 636 | |
|
576 | 637 | # The interactive one is initialized with an offset, meaning we always |
|
577 | 638 | # want to remove the topmost item in the traceback, which is our own |
|
578 | 639 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
579 | 640 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
580 | 641 | color_scheme='NoColor', |
|
581 | 642 | tb_offset = 1) |
|
582 | 643 | |
|
583 | 644 | # IPython itself shouldn't crash. This will produce a detailed |
|
584 | 645 | # post-mortem if it does. But we only install the crash handler for |
|
585 | 646 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
586 | 647 | # and lose the crash handler. This is because exceptions in the main |
|
587 | 648 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
588 | 649 | # and there's no point in printing crash dumps for every user exception. |
|
589 | 650 | if self.isthreaded: |
|
590 | 651 | ipCrashHandler = ultratb.FormattedTB() |
|
591 | 652 | else: |
|
592 | 653 | from IPython.core import crashhandler |
|
593 | 654 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
594 | 655 | self.set_crash_handler(ipCrashHandler) |
|
595 | 656 | |
|
596 | 657 | # and add any custom exception handlers the user may have specified |
|
597 | 658 | self.set_custom_exc(*custom_exceptions) |
|
598 | 659 | |
|
599 | 660 | def init_logger(self): |
|
600 | 661 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
601 | 662 | # local shortcut, this is used a LOT |
|
602 | 663 | self.log = self.logger.log |
|
603 | 664 | # template for logfile headers. It gets resolved at runtime by the |
|
604 | 665 | # logstart method. |
|
605 | 666 | self.loghead_tpl = \ |
|
606 | 667 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
607 | 668 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
608 | 669 | #log# opts = %s |
|
609 | 670 | #log# args = %s |
|
610 | 671 | #log# It is safe to make manual edits below here. |
|
611 | 672 | #log#----------------------------------------------------------------------- |
|
612 | 673 | """ |
|
613 | 674 | |
|
614 | 675 | def init_logstart(self): |
|
615 | 676 | if self.logplay: |
|
616 |
|
|
|
677 | self.magic_logstart(self.logplay + ' append') | |
|
617 | 678 | elif self.logfile: |
|
618 |
|
|
|
679 | self.magic_logstart(self.logfile) | |
|
619 | 680 | elif self.logstart: |
|
620 | 681 | self.magic_logstart() |
|
621 | 682 | |
|
622 | 683 | def init_aliases(self): |
|
623 | 684 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
624 | 685 | no_alias = {} |
|
625 | 686 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
626 | 687 | for key in keyword.kwlist + no_alias_magics: |
|
627 | 688 | no_alias[key] = 1 |
|
628 | 689 | no_alias.update(__builtin__.__dict__) |
|
629 | 690 | self.no_alias = no_alias |
|
630 | 691 | |
|
631 | 692 | # Make some aliases automatically |
|
632 | 693 | # Prepare list of shell aliases to auto-define |
|
633 | 694 | if os.name == 'posix': |
|
634 | 695 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
635 | 696 | 'mv mv -i','rm rm -i','cp cp -i', |
|
636 | 697 | 'cat cat','less less','clear clear', |
|
637 | 698 | # a better ls |
|
638 | 699 | 'ls ls -F', |
|
639 | 700 | # long ls |
|
640 | 701 | 'll ls -lF') |
|
641 | 702 | # Extra ls aliases with color, which need special treatment on BSD |
|
642 | 703 | # variants |
|
643 | 704 | ls_extra = ( # color ls |
|
644 | 705 | 'lc ls -F -o --color', |
|
645 | 706 | # ls normal files only |
|
646 | 707 | 'lf ls -F -o --color %l | grep ^-', |
|
647 | 708 | # ls symbolic links |
|
648 | 709 | 'lk ls -F -o --color %l | grep ^l', |
|
649 | 710 | # directories or links to directories, |
|
650 | 711 | 'ldir ls -F -o --color %l | grep /$', |
|
651 | 712 | # things which are executable |
|
652 | 713 | 'lx ls -F -o --color %l | grep ^-..x', |
|
653 | 714 | ) |
|
654 | 715 | # The BSDs don't ship GNU ls, so they don't understand the |
|
655 | 716 | # --color switch out of the box |
|
656 | 717 | if 'bsd' in sys.platform: |
|
657 | 718 | ls_extra = ( # ls normal files only |
|
658 | 719 | 'lf ls -lF | grep ^-', |
|
659 | 720 | # ls symbolic links |
|
660 | 721 | 'lk ls -lF | grep ^l', |
|
661 | 722 | # directories or links to directories, |
|
662 | 723 | 'ldir ls -lF | grep /$', |
|
663 | 724 | # things which are executable |
|
664 | 725 | 'lx ls -lF | grep ^-..x', |
|
665 | 726 | ) |
|
666 | 727 | auto_alias = auto_alias + ls_extra |
|
667 | 728 | elif os.name in ['nt','dos']: |
|
668 | 729 | auto_alias = ('ls dir /on', |
|
669 | 730 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
670 | 731 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
671 | 732 | 'ren ren','cls cls','copy copy') |
|
672 | 733 | else: |
|
673 | 734 | auto_alias = () |
|
674 | 735 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
675 | 736 | |
|
676 | 737 | # Load default aliases |
|
677 | 738 | for alias, cmd in self.auto_alias: |
|
678 | 739 | self.define_alias(alias,cmd) |
|
679 | 740 | |
|
680 | 741 | # Load user aliases |
|
681 | 742 | for alias in self.alias: |
|
682 | 743 | self.magic_alias(alias) |
|
683 | 744 | |
|
684 | 745 | def init_builtins(self): |
|
685 | 746 | # track which builtins we add, so we can clean up later |
|
686 | 747 | self.builtins_added = {} |
|
687 | 748 | # This method will add the necessary builtins for operation, but |
|
688 | 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 | 753 | self.add_builtins() |
|
692 | 754 | |
|
693 | 755 | def init_shadow_hist(self): |
|
694 | 756 | try: |
|
695 | 757 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") |
|
696 | 758 | except exceptions.UnicodeDecodeError: |
|
697 | 759 | print "Your ipythondir can't be decoded to unicode!" |
|
698 | 760 | print "Please set HOME environment variable to something that" |
|
699 | 761 | print r"only has ASCII characters, e.g. c:\home" |
|
700 | 762 | print "Now it is", self.config.IPYTHONDIR |
|
701 | 763 | sys.exit() |
|
702 | 764 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
703 | 765 | |
|
704 |
def |
|
|
705 | """Post configuration init method | |
|
706 | ||
|
707 | This is called after the configuration files have been processed to | |
|
708 | 'finalize' the initialization.""" | |
|
709 | ||
|
766 | def init_inspector(self): | |
|
710 | 767 | # Object inspector |
|
711 | 768 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
712 | 769 | PyColorize.ANSICodeColors, |
|
713 | 770 | 'NoColor', |
|
714 | 771 | self.object_info_string_level) |
|
715 | ||
|
772 | ||
|
773 | def init_readline(self): | |
|
774 | """Command history completion/saving/reloading.""" | |
|
775 | ||
|
716 | 776 | self.rl_next_input = None |
|
717 | 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 | 860 | # Initialize cache, set in/out prompts and printing system |
|
723 | 861 | self.outputcache = CachedOutput(self, |
|
724 | 862 | self.cache_size, |
|
725 | 863 | self.pprint, |
|
726 | 864 | input_sep = self.separate_in, |
|
727 | 865 | output_sep = self.separate_out, |
|
728 | 866 | output_sep2 = self.separate_out2, |
|
729 | 867 | ps1 = self.prompt_in1, |
|
730 | 868 | ps2 = self.prompt_in2, |
|
731 | 869 | ps_out = self.prompt_out, |
|
732 | 870 | pad_left = self.prompts_pad_left) |
|
733 | 871 | |
|
734 | 872 | # user may have over-ridden the default print hook: |
|
735 | 873 | try: |
|
736 | 874 | self.outputcache.__class__.display = self.hooks.display |
|
737 | 875 | except AttributeError: |
|
738 | 876 | pass |
|
739 | 877 | |
|
878 | def init_displayhook(self): | |
|
740 | 879 | # I don't like assigning globally to sys, because it means when |
|
741 | 880 | # embedding instances, each embedded instance overrides the previous |
|
742 | 881 | # choice. But sys.displayhook seems to be called internally by exec, |
|
743 | 882 | # so I don't see a way around it. We first save the original and then |
|
744 | 883 | # overwrite it. |
|
745 | 884 | self.sys_displayhook = sys.displayhook |
|
746 | 885 | sys.displayhook = self.outputcache |
|
747 | 886 | |
|
887 | def init_reload_doctest(self): | |
|
748 | 888 | # Do a proper resetting of doctest, including the necessary displayhook |
|
749 | 889 | # monkeypatching |
|
750 | 890 | try: |
|
751 | 891 | doctest_reload() |
|
752 | 892 | except ImportError: |
|
753 | 893 | warn("doctest module does not exist.") |
|
754 | ||
|
894 | ||
|
895 | def init_magics(self): | |
|
755 | 896 | # Set user colors (don't do it in the constructor above so that it |
|
756 | 897 | # doesn't crash if colors option is invalid) |
|
757 | 898 | self.magic_colors(self.colors) |
|
758 | 899 | |
|
900 | def init_pdb(self): | |
|
759 | 901 | # Set calling of pdb on exceptions |
|
902 | # self.call_pdb is a property | |
|
760 | 903 | self.call_pdb = self.pdb |
|
761 | 904 | |
|
762 | ||
|
763 | ||
|
764 | self.hooks.late_startup_hook() | |
|
765 | ||
|
905 | def init_exec_commands(self): | |
|
766 | 906 | for cmd in self.autoexec: |
|
767 | 907 | #print "autoexec>",cmd #dbg |
|
768 | 908 | self.api.runlines(cmd) |
|
769 | 909 | |
|
770 | 910 | batchrun = False |
|
771 | 911 | if self.config.has_key('EXECFILE'): |
|
772 | 912 | for batchfile in [path(arg) for arg in self.config.EXECFILE |
|
773 | 913 | if arg.lower().endswith('.ipy')]: |
|
774 | 914 | if not batchfile.isfile(): |
|
775 | 915 | print "No such batch file:", batchfile |
|
776 | 916 | continue |
|
777 | 917 | self.api.runlines(batchfile.text()) |
|
778 | 918 | batchrun = True |
|
779 | 919 | # without -i option, exit after running the batch file |
|
780 | 920 | if batchrun and not self.interactive: |
|
781 | 921 | self.ask_exit() |
|
782 | 922 | |
|
783 | 923 | def init_namespaces(self): |
|
784 | 924 | """Initialize all user-visible namespaces to their minimum defaults. |
|
785 | 925 | |
|
786 | 926 | Certain history lists are also initialized here, as they effectively |
|
787 | 927 | act as user namespaces. |
|
788 | 928 | |
|
789 | 929 | Notes |
|
790 | 930 | ----- |
|
791 | 931 | All data structures here are only filled in, they are NOT reset by this |
|
792 | 932 | method. If they were not empty before, data will simply be added to |
|
793 | 933 | therm. |
|
794 | 934 | """ |
|
795 | 935 | # The user namespace MUST have a pointer to the shell itself. |
|
796 | 936 | self.user_ns[self.name] = self |
|
797 | 937 | |
|
798 | 938 | # Store the public api instance |
|
799 | 939 | self.user_ns['_ip'] = self.api |
|
800 | 940 | |
|
801 | 941 | # make global variables for user access to the histories |
|
802 | 942 | self.user_ns['_ih'] = self.input_hist |
|
803 | 943 | self.user_ns['_oh'] = self.output_hist |
|
804 | 944 | self.user_ns['_dh'] = self.dir_hist |
|
805 | 945 | |
|
806 | 946 | # user aliases to input and output histories |
|
807 | 947 | self.user_ns['In'] = self.input_hist |
|
808 | 948 | self.user_ns['Out'] = self.output_hist |
|
809 | 949 | |
|
810 | 950 | self.user_ns['_sh'] = shadowns |
|
811 | 951 | |
|
812 | # Fill the history zero entry, user counter starts at 1 | |
|
813 | self.input_hist.append('\n') | |
|
814 | self.input_hist_raw.append('\n') | |
|
952 | # Put 'help' in the user namespace | |
|
953 | try: | |
|
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 | 959 | def add_builtins(self): |
|
817 | 960 | """Store ipython references into the builtin namespace. |
|
818 | 961 | |
|
819 | 962 | Some parts of ipython operate via builtins injected here, which hold a |
|
820 | 963 | reference to IPython itself.""" |
|
821 | 964 | |
|
822 | 965 | # Install our own quitter instead of the builtins. |
|
823 | 966 | # This used to be in the __init__ method, but this is a better |
|
824 | 967 | # place for it. These can be incorporated to the logic below |
|
825 | 968 | # when it is refactored. |
|
826 | 969 | __builtin__.exit = Quitter(self,'exit') |
|
827 | 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 | 983 | # TODO: deprecate all of these, they are unsafe. Why though? |
|
830 | 984 | builtins_new = dict(__IPYTHON__ = self, |
|
831 | 985 | ip_set_hook = self.set_hook, |
|
832 | 986 | jobs = self.jobs, |
|
833 | 987 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
834 | 988 | ipalias = wrap_deprecated(self.ipalias), |
|
835 | 989 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
836 | 990 | #_ip = self.api |
|
837 | 991 | ) |
|
838 | 992 | for biname,bival in builtins_new.items(): |
|
839 | 993 | try: |
|
840 | 994 | # store the orignal value so we can restore it |
|
841 | 995 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
842 | 996 | except KeyError: |
|
843 | 997 | # or mark that it wasn't defined, and we'll just delete it at |
|
844 | 998 | # cleanup |
|
845 | 999 | self.builtins_added[biname] = Undefined |
|
846 | 1000 | __builtin__.__dict__[biname] = bival |
|
847 | 1001 | |
|
848 | 1002 | # Keep in the builtins a flag for when IPython is active. We set it |
|
849 | 1003 | # with setdefault so that multiple nested IPythons don't clobber one |
|
850 | 1004 | # another. Each will increase its value by one upon being activated, |
|
851 | 1005 | # which also gives us a way to determine the nesting level. |
|
852 | 1006 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
853 | 1007 | |
|
854 | 1008 | def clean_builtins(self): |
|
855 | 1009 | """Remove any builtins which might have been added by add_builtins, or |
|
856 | 1010 | restore overwritten ones to their previous values.""" |
|
857 | 1011 | for biname,bival in self.builtins_added.items(): |
|
858 | 1012 | if bival is Undefined: |
|
859 | 1013 | del __builtin__.__dict__[biname] |
|
860 | 1014 | else: |
|
861 | 1015 | __builtin__.__dict__[biname] = bival |
|
862 | 1016 | self.builtins_added.clear() |
|
863 | 1017 | |
|
864 | 1018 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
865 | 1019 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
866 | 1020 | |
|
867 | 1021 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
868 | 1022 | adding your function to one of these hooks, you can modify IPython's |
|
869 | 1023 | behavior to call at runtime your own routines.""" |
|
870 | 1024 | |
|
871 | 1025 | # At some point in the future, this should validate the hook before it |
|
872 | 1026 | # accepts it. Probably at least check that the hook takes the number |
|
873 | 1027 | # of args it's supposed to. |
|
874 | 1028 | |
|
875 | 1029 | f = new.instancemethod(hook,self,self.__class__) |
|
876 | 1030 | |
|
877 | 1031 | # check if the hook is for strdispatcher first |
|
878 | 1032 | if str_key is not None: |
|
879 | 1033 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
880 | 1034 | sdp.add_s(str_key, f, priority ) |
|
881 | 1035 | self.strdispatchers[name] = sdp |
|
882 | 1036 | return |
|
883 | 1037 | if re_key is not None: |
|
884 | 1038 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
885 | 1039 | sdp.add_re(re.compile(re_key), f, priority ) |
|
886 | 1040 | self.strdispatchers[name] = sdp |
|
887 | 1041 | return |
|
888 | 1042 | |
|
889 | 1043 | dp = getattr(self.hooks, name, None) |
|
890 | 1044 | if name not in IPython.core.hooks.__all__: |
|
891 | 1045 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
892 | 1046 | if not dp: |
|
893 | 1047 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
894 | 1048 | |
|
895 | 1049 | try: |
|
896 | 1050 | dp.add(f,priority) |
|
897 | 1051 | except AttributeError: |
|
898 | 1052 | # it was not commandchain, plain old func - replace |
|
899 | 1053 | dp = f |
|
900 | 1054 | |
|
901 | 1055 | setattr(self.hooks,name, dp) |
|
902 | 1056 | |
|
903 | 1057 | |
|
904 | 1058 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
905 | 1059 | |
|
906 | 1060 | def set_crash_handler(self,crashHandler): |
|
907 | 1061 | """Set the IPython crash handler. |
|
908 | 1062 | |
|
909 | 1063 | This must be a callable with a signature suitable for use as |
|
910 | 1064 | sys.excepthook.""" |
|
911 | 1065 | |
|
912 | 1066 | # Install the given crash handler as the Python exception hook |
|
913 | 1067 | sys.excepthook = crashHandler |
|
914 | 1068 | |
|
915 | 1069 | # The instance will store a pointer to this, so that runtime code |
|
916 | 1070 | # (such as magics) can access it. This is because during the |
|
917 | 1071 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
918 | 1072 | # frameworks). |
|
919 | 1073 | self.sys_excepthook = sys.excepthook |
|
920 | 1074 | |
|
921 | 1075 | |
|
922 | 1076 | def set_custom_exc(self,exc_tuple,handler): |
|
923 | 1077 | """set_custom_exc(exc_tuple,handler) |
|
924 | 1078 | |
|
925 | 1079 | Set a custom exception handler, which will be called if any of the |
|
926 | 1080 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
927 | 1081 | runcode() method. |
|
928 | 1082 | |
|
929 | 1083 | Inputs: |
|
930 | 1084 | |
|
931 | 1085 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
932 | 1086 | handler for. It is very important that you use a tuple, and NOT A |
|
933 | 1087 | LIST here, because of the way Python's except statement works. If |
|
934 | 1088 | you only want to trap a single exception, use a singleton tuple: |
|
935 | 1089 | |
|
936 | 1090 | exc_tuple == (MyCustomException,) |
|
937 | 1091 | |
|
938 | 1092 | - handler: this must be defined as a function with the following |
|
939 | 1093 | basic interface: def my_handler(self,etype,value,tb). |
|
940 | 1094 | |
|
941 | 1095 | This will be made into an instance method (via new.instancemethod) |
|
942 | 1096 | of IPython itself, and it will be called if any of the exceptions |
|
943 | 1097 | listed in the exc_tuple are caught. If the handler is None, an |
|
944 | 1098 | internal basic one is used, which just prints basic info. |
|
945 | 1099 | |
|
946 | 1100 | WARNING: by putting in your own exception handler into IPython's main |
|
947 | 1101 | execution loop, you run a very good chance of nasty crashes. This |
|
948 | 1102 | facility should only be used if you really know what you are doing.""" |
|
949 | 1103 | |
|
950 | 1104 | assert type(exc_tuple)==type(()) , \ |
|
951 | 1105 | "The custom exceptions must be given AS A TUPLE." |
|
952 | 1106 | |
|
953 | 1107 | def dummy_handler(self,etype,value,tb): |
|
954 | 1108 | print '*** Simple custom exception handler ***' |
|
955 | 1109 | print 'Exception type :',etype |
|
956 | 1110 | print 'Exception value:',value |
|
957 | 1111 | print 'Traceback :',tb |
|
958 | 1112 | print 'Source code :','\n'.join(self.buffer) |
|
959 | 1113 | |
|
960 | 1114 | if handler is None: handler = dummy_handler |
|
961 | 1115 | |
|
962 | 1116 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
963 | 1117 | self.custom_exceptions = exc_tuple |
|
964 | 1118 | |
|
965 | 1119 | def set_custom_completer(self,completer,pos=0): |
|
966 | 1120 | """set_custom_completer(completer,pos=0) |
|
967 | 1121 | |
|
968 | 1122 | Adds a new custom completer function. |
|
969 | 1123 | |
|
970 | 1124 | The position argument (defaults to 0) is the index in the completers |
|
971 | 1125 | list where you want the completer to be inserted.""" |
|
972 | 1126 | |
|
973 | 1127 | newcomp = new.instancemethod(completer,self.Completer, |
|
974 | 1128 | self.Completer.__class__) |
|
975 | 1129 | self.Completer.matchers.insert(pos,newcomp) |
|
976 | 1130 | |
|
977 | 1131 | def set_completer(self): |
|
978 | 1132 | """reset readline's completer to be our own.""" |
|
979 | 1133 | self.readline.set_completer(self.Completer.complete) |
|
980 | 1134 | |
|
981 | 1135 | def _get_call_pdb(self): |
|
982 | 1136 | return self._call_pdb |
|
983 | 1137 | |
|
984 | 1138 | def _set_call_pdb(self,val): |
|
985 | 1139 | |
|
986 | 1140 | if val not in (0,1,False,True): |
|
987 | 1141 | raise ValueError,'new call_pdb value must be boolean' |
|
988 | 1142 | |
|
989 | 1143 | # store value in instance |
|
990 | 1144 | self._call_pdb = val |
|
991 | 1145 | |
|
992 | 1146 | # notify the actual exception handlers |
|
993 | 1147 | self.InteractiveTB.call_pdb = val |
|
994 | 1148 | if self.isthreaded: |
|
995 | 1149 | try: |
|
996 | 1150 | self.sys_excepthook.call_pdb = val |
|
997 | 1151 | except: |
|
998 | 1152 | warn('Failed to activate pdb for threaded exception handler') |
|
999 | 1153 | |
|
1000 | 1154 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1001 | 1155 | 'Control auto-activation of pdb at exceptions') |
|
1002 | 1156 | |
|
1003 | 1157 | # These special functions get installed in the builtin namespace, to |
|
1004 | 1158 | # provide programmatic (pure python) access to magics, aliases and system |
|
1005 | 1159 | # calls. This is important for logging, user scripting, and more. |
|
1006 | 1160 | |
|
1007 | 1161 | # We are basically exposing, via normal python functions, the three |
|
1008 | 1162 | # mechanisms in which ipython offers special call modes (magics for |
|
1009 | 1163 | # internal control, aliases for direct system access via pre-selected |
|
1010 | 1164 | # names, and !cmd for calling arbitrary system commands). |
|
1011 | 1165 | |
|
1012 | 1166 | def ipmagic(self,arg_s): |
|
1013 | 1167 | """Call a magic function by name. |
|
1014 | 1168 | |
|
1015 | 1169 | Input: a string containing the name of the magic function to call and any |
|
1016 | 1170 | additional arguments to be passed to the magic. |
|
1017 | 1171 | |
|
1018 | 1172 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
1019 | 1173 | prompt: |
|
1020 | 1174 | |
|
1021 | 1175 | In[1]: %name -opt foo bar |
|
1022 | 1176 | |
|
1023 | 1177 | To call a magic without arguments, simply use ipmagic('name'). |
|
1024 | 1178 | |
|
1025 | 1179 | This provides a proper Python function to call IPython's magics in any |
|
1026 | 1180 | valid Python code you can type at the interpreter, including loops and |
|
1027 | 1181 | compound statements. It is added by IPython to the Python builtin |
|
1028 | 1182 | namespace upon initialization.""" |
|
1029 | 1183 | |
|
1030 | 1184 | args = arg_s.split(' ',1) |
|
1031 | 1185 | magic_name = args[0] |
|
1032 | 1186 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1033 | 1187 | |
|
1034 | 1188 | try: |
|
1035 | 1189 | magic_args = args[1] |
|
1036 | 1190 | except IndexError: |
|
1037 | 1191 | magic_args = '' |
|
1038 | 1192 | fn = getattr(self,'magic_'+magic_name,None) |
|
1039 | 1193 | if fn is None: |
|
1040 | 1194 | error("Magic function `%s` not found." % magic_name) |
|
1041 | 1195 | else: |
|
1042 | 1196 | magic_args = self.var_expand(magic_args,1) |
|
1043 | 1197 | return fn(magic_args) |
|
1044 | 1198 | |
|
1045 | 1199 | def define_alias(self, name, cmd): |
|
1046 | 1200 | """ Define a new alias.""" |
|
1047 | 1201 | |
|
1048 | 1202 | if callable(cmd): |
|
1049 | 1203 | self.alias_table[name] = cmd |
|
1050 | 1204 | from IPython.core import shadowns |
|
1051 | 1205 | setattr(shadowns, name, cmd) |
|
1052 | 1206 | return |
|
1053 | 1207 | |
|
1054 | 1208 | if isinstance(cmd, basestring): |
|
1055 | 1209 | nargs = cmd.count('%s') |
|
1056 | 1210 | if nargs>0 and cmd.find('%l')>=0: |
|
1057 | 1211 | raise Exception('The %s and %l specifiers are mutually ' |
|
1058 | 1212 | 'exclusive in alias definitions.') |
|
1059 | 1213 | |
|
1060 | 1214 | self.alias_table[name] = (nargs,cmd) |
|
1061 | 1215 | return |
|
1062 | 1216 | |
|
1063 | 1217 | self.alias_table[name] = cmd |
|
1064 | 1218 | |
|
1065 | 1219 | def ipalias(self,arg_s): |
|
1066 | 1220 | """Call an alias by name. |
|
1067 | 1221 | |
|
1068 | 1222 | Input: a string containing the name of the alias to call and any |
|
1069 | 1223 | additional arguments to be passed to the magic. |
|
1070 | 1224 | |
|
1071 | 1225 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1072 | 1226 | prompt: |
|
1073 | 1227 | |
|
1074 | 1228 | In[1]: name -opt foo bar |
|
1075 | 1229 | |
|
1076 | 1230 | To call an alias without arguments, simply use ipalias('name'). |
|
1077 | 1231 | |
|
1078 | 1232 | This provides a proper Python function to call IPython's aliases in any |
|
1079 | 1233 | valid Python code you can type at the interpreter, including loops and |
|
1080 | 1234 | compound statements. It is added by IPython to the Python builtin |
|
1081 | 1235 | namespace upon initialization.""" |
|
1082 | 1236 | |
|
1083 | 1237 | args = arg_s.split(' ',1) |
|
1084 | 1238 | alias_name = args[0] |
|
1085 | 1239 | try: |
|
1086 | 1240 | alias_args = args[1] |
|
1087 | 1241 | except IndexError: |
|
1088 | 1242 | alias_args = '' |
|
1089 | 1243 | if alias_name in self.alias_table: |
|
1090 | 1244 | self.call_alias(alias_name,alias_args) |
|
1091 | 1245 | else: |
|
1092 | 1246 | error("Alias `%s` not found." % alias_name) |
|
1093 | 1247 | |
|
1094 | 1248 | def system(self, cmd): |
|
1095 | 1249 | """Make a system call, using IPython.""" |
|
1096 | 1250 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1097 | 1251 | |
|
1098 | 1252 | ipsystem = system |
|
1099 | 1253 | |
|
1100 | 1254 | def getoutput(self, cmd): |
|
1101 | 1255 | return getoutput(self.var_expand(cmd,depth=2), |
|
1102 | 1256 | header=self.system_header, |
|
1103 | 1257 | verbose=self.system_verbose) |
|
1104 | 1258 | |
|
1105 | 1259 | def getoutputerror(self, cmd): |
|
1106 | 1260 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
1107 | 1261 | header=self.system_header, |
|
1108 | 1262 | verbose=self.system_verbose) |
|
1109 | 1263 | |
|
1110 | 1264 | def complete(self,text): |
|
1111 | 1265 | """Return a sorted list of all possible completions on text. |
|
1112 | 1266 | |
|
1113 | 1267 | Inputs: |
|
1114 | 1268 | |
|
1115 | 1269 | - text: a string of text to be completed on. |
|
1116 | 1270 | |
|
1117 | 1271 | This is a wrapper around the completion mechanism, similar to what |
|
1118 | 1272 | readline does at the command line when the TAB key is hit. By |
|
1119 | 1273 | exposing it as a method, it can be used by other non-readline |
|
1120 | 1274 | environments (such as GUIs) for text completion. |
|
1121 | 1275 | |
|
1122 | 1276 | Simple usage example: |
|
1123 | 1277 | |
|
1124 | 1278 | In [7]: x = 'hello' |
|
1125 | 1279 | |
|
1126 | 1280 | In [8]: x |
|
1127 | 1281 | Out[8]: 'hello' |
|
1128 | 1282 | |
|
1129 | 1283 | In [9]: print x |
|
1130 | 1284 | hello |
|
1131 | 1285 | |
|
1132 | 1286 | In [10]: _ip.IP.complete('x.l') |
|
1133 | 1287 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1134 | 1288 | """ |
|
1135 | 1289 | |
|
1136 | 1290 | complete = self.Completer.complete |
|
1137 | 1291 | state = 0 |
|
1138 | 1292 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1139 | 1293 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1140 | 1294 | # start using sets instead, which are faster. |
|
1141 | 1295 | comps = {} |
|
1142 | 1296 | while True: |
|
1143 | 1297 | newcomp = complete(text,state,line_buffer=text) |
|
1144 | 1298 | if newcomp is None: |
|
1145 | 1299 | break |
|
1146 | 1300 | comps[newcomp] = 1 |
|
1147 | 1301 | state += 1 |
|
1148 | 1302 | outcomps = comps.keys() |
|
1149 | 1303 | outcomps.sort() |
|
1150 | 1304 | #print "T:",text,"OC:",outcomps # dbg |
|
1151 | 1305 | #print "vars:",self.user_ns.keys() |
|
1152 | 1306 | return outcomps |
|
1153 | 1307 | |
|
1154 | 1308 | def set_completer_frame(self, frame=None): |
|
1155 | 1309 | if frame: |
|
1156 | 1310 | self.Completer.namespace = frame.f_locals |
|
1157 | 1311 | self.Completer.global_namespace = frame.f_globals |
|
1158 | 1312 | else: |
|
1159 | 1313 | self.Completer.namespace = self.user_ns |
|
1160 | 1314 | self.Completer.global_namespace = self.user_global_ns |
|
1161 | 1315 | |
|
1162 | 1316 | def init_auto_alias(self): |
|
1163 | 1317 | """Define some aliases automatically. |
|
1164 | 1318 | |
|
1165 | 1319 | These are ALL parameter-less aliases""" |
|
1166 | 1320 | |
|
1167 | 1321 | for alias,cmd in self.auto_alias: |
|
1168 | 1322 | self.getapi().defalias(alias,cmd) |
|
1169 | 1323 | |
|
1170 | 1324 | |
|
1171 | 1325 | def alias_table_validate(self,verbose=0): |
|
1172 | 1326 | """Update information about the alias table. |
|
1173 | 1327 | |
|
1174 | 1328 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1175 | 1329 | |
|
1176 | 1330 | no_alias = self.no_alias |
|
1177 | 1331 | for k in self.alias_table.keys(): |
|
1178 | 1332 | if k in no_alias: |
|
1179 | 1333 | del self.alias_table[k] |
|
1180 | 1334 | if verbose: |
|
1181 | 1335 | print ("Deleting alias <%s>, it's a Python " |
|
1182 | 1336 | "keyword or builtin." % k) |
|
1183 | 1337 | |
|
1184 | 1338 | def set_autoindent(self,value=None): |
|
1185 | 1339 | """Set the autoindent flag, checking for readline support. |
|
1186 | 1340 | |
|
1187 | 1341 | If called with no arguments, it acts as a toggle.""" |
|
1188 | 1342 | |
|
1189 | 1343 | if not self.has_readline: |
|
1190 | 1344 | if os.name == 'posix': |
|
1191 | 1345 | warn("The auto-indent feature requires the readline library") |
|
1192 | 1346 | self.autoindent = 0 |
|
1193 | 1347 | return |
|
1194 | 1348 | if value is None: |
|
1195 | 1349 | self.autoindent = not self.autoindent |
|
1196 | 1350 | else: |
|
1197 | 1351 | self.autoindent = value |
|
1198 | 1352 | |
|
1199 | 1353 | def atexit_operations(self): |
|
1200 | 1354 | """This will be executed at the time of exit. |
|
1201 | 1355 | |
|
1202 | 1356 | Saving of persistent data should be performed here. """ |
|
1203 | 1357 | |
|
1204 | 1358 | #print '*** IPython exit cleanup ***' # dbg |
|
1205 | 1359 | # input history |
|
1206 | 1360 | self.savehist() |
|
1207 | 1361 | |
|
1208 | 1362 | # Cleanup all tempfiles left around |
|
1209 | 1363 | for tfile in self.tempfiles: |
|
1210 | 1364 | try: |
|
1211 | 1365 | os.unlink(tfile) |
|
1212 | 1366 | except OSError: |
|
1213 | 1367 | pass |
|
1214 | 1368 | |
|
1215 | 1369 | # Clear all user namespaces to release all references cleanly. |
|
1216 | 1370 | self.reset() |
|
1217 | 1371 | |
|
1218 | 1372 | # Run user hooks |
|
1219 | 1373 | self.hooks.shutdown_hook() |
|
1220 | 1374 | |
|
1221 | 1375 | def reset(self): |
|
1222 | 1376 | """Clear all internal namespaces. |
|
1223 | 1377 | |
|
1224 | 1378 | Note that this is much more aggressive than %reset, since it clears |
|
1225 | 1379 | fully all namespaces, as well as all input/output lists. |
|
1226 | 1380 | """ |
|
1227 | 1381 | for ns in self.ns_refs_table: |
|
1228 | 1382 | ns.clear() |
|
1229 | 1383 | |
|
1230 | 1384 | # Clear input and output histories |
|
1231 | 1385 | self.input_hist[:] = [] |
|
1232 | 1386 | self.input_hist_raw[:] = [] |
|
1233 | 1387 | self.output_hist.clear() |
|
1234 | 1388 | # Restore the user namespaces to minimal usability |
|
1235 | 1389 | self.init_namespaces() |
|
1236 | 1390 | |
|
1237 | 1391 | def savehist(self): |
|
1238 | 1392 | """Save input history to a file (via readline library).""" |
|
1239 | 1393 | |
|
1240 | 1394 | if not self.has_readline: |
|
1241 | 1395 | return |
|
1242 | 1396 | |
|
1243 | 1397 | try: |
|
1244 | 1398 | self.readline.write_history_file(self.histfile) |
|
1245 | 1399 | except: |
|
1246 | 1400 | print 'Unable to save IPython command history to file: ' + \ |
|
1247 | 1401 | `self.histfile` |
|
1248 | 1402 | |
|
1249 | 1403 | def reloadhist(self): |
|
1250 | 1404 | """Reload the input history from disk file.""" |
|
1251 | 1405 | |
|
1252 | 1406 | if self.has_readline: |
|
1253 | 1407 | try: |
|
1254 | 1408 | self.readline.clear_history() |
|
1255 | 1409 | self.readline.read_history_file(self.shell.histfile) |
|
1256 | 1410 | except AttributeError: |
|
1257 | 1411 | pass |
|
1258 | 1412 | |
|
1259 | 1413 | |
|
1260 | 1414 | def history_saving_wrapper(self, func): |
|
1261 | 1415 | """ Wrap func for readline history saving |
|
1262 | 1416 | |
|
1263 | 1417 | Convert func into callable that saves & restores |
|
1264 | 1418 | history around the call """ |
|
1265 | 1419 | |
|
1266 | 1420 | if not self.has_readline: |
|
1267 | 1421 | return func |
|
1268 | 1422 | |
|
1269 | 1423 | def wrapper(): |
|
1270 | 1424 | self.savehist() |
|
1271 | 1425 | try: |
|
1272 | 1426 | func() |
|
1273 | 1427 | finally: |
|
1274 | 1428 | readline.read_history_file(self.histfile) |
|
1275 | 1429 | return wrapper |
|
1276 | 1430 | |
|
1277 | 1431 | def pre_readline(self): |
|
1278 | 1432 | """readline hook to be used at the start of each line. |
|
1279 | 1433 | |
|
1280 | 1434 | Currently it handles auto-indent only.""" |
|
1281 | 1435 | |
|
1282 | 1436 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1283 | 1437 | |
|
1284 | 1438 | if self.rl_do_indent: |
|
1285 | 1439 | self.readline.insert_text(self.indent_current_str()) |
|
1286 | 1440 | if self.rl_next_input is not None: |
|
1287 | 1441 | self.readline.insert_text(self.rl_next_input) |
|
1288 | 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 | 1444 | def ask_yes_no(self,prompt,default=True): |
|
1372 | 1445 | if self.quiet: |
|
1373 | 1446 | return True |
|
1374 | 1447 | return ask_yes_no(prompt,default) |
|
1375 | 1448 | |
|
1376 | 1449 | def new_main_mod(self,ns=None): |
|
1377 | 1450 | """Return a new 'main' module object for user code execution. |
|
1378 | 1451 | """ |
|
1379 | 1452 | main_mod = self._user_main_module |
|
1380 | 1453 | init_fakemod_dict(main_mod,ns) |
|
1381 | 1454 | return main_mod |
|
1382 | 1455 | |
|
1383 | 1456 | def cache_main_mod(self,ns,fname): |
|
1384 | 1457 | """Cache a main module's namespace. |
|
1385 | 1458 | |
|
1386 | 1459 | When scripts are executed via %run, we must keep a reference to the |
|
1387 | 1460 | namespace of their __main__ module (a FakeModule instance) around so |
|
1388 | 1461 | that Python doesn't clear it, rendering objects defined therein |
|
1389 | 1462 | useless. |
|
1390 | 1463 | |
|
1391 | 1464 | This method keeps said reference in a private dict, keyed by the |
|
1392 | 1465 | absolute path of the module object (which corresponds to the script |
|
1393 | 1466 | path). This way, for multiple executions of the same script we only |
|
1394 | 1467 | keep one copy of the namespace (the last one), thus preventing memory |
|
1395 | 1468 | leaks from old references while allowing the objects from the last |
|
1396 | 1469 | execution to be accessible. |
|
1397 | 1470 | |
|
1398 | 1471 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1399 | 1472 | because of how Python tears down modules (it hard-sets all their |
|
1400 | 1473 | references to None without regard for reference counts). This method |
|
1401 | 1474 | must therefore make a *copy* of the given namespace, to allow the |
|
1402 | 1475 | original module's __dict__ to be cleared and reused. |
|
1403 | 1476 | |
|
1404 | 1477 | |
|
1405 | 1478 | Parameters |
|
1406 | 1479 | ---------- |
|
1407 | 1480 | ns : a namespace (a dict, typically) |
|
1408 | 1481 | |
|
1409 | 1482 | fname : str |
|
1410 | 1483 | Filename associated with the namespace. |
|
1411 | 1484 | |
|
1412 | 1485 | Examples |
|
1413 | 1486 | -------- |
|
1414 | 1487 | |
|
1415 | 1488 | In [10]: import IPython |
|
1416 | 1489 | |
|
1417 | 1490 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1418 | 1491 | |
|
1419 | 1492 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache |
|
1420 | 1493 | Out[12]: True |
|
1421 | 1494 | """ |
|
1422 | 1495 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
1423 | 1496 | |
|
1424 | 1497 | def clear_main_mod_cache(self): |
|
1425 | 1498 | """Clear the cache of main modules. |
|
1426 | 1499 | |
|
1427 | 1500 | Mainly for use by utilities like %reset. |
|
1428 | 1501 | |
|
1429 | 1502 | Examples |
|
1430 | 1503 | -------- |
|
1431 | 1504 | |
|
1432 | 1505 | In [15]: import IPython |
|
1433 | 1506 | |
|
1434 | 1507 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1435 | 1508 | |
|
1436 | 1509 | In [17]: len(_ip.IP._main_ns_cache) > 0 |
|
1437 | 1510 | Out[17]: True |
|
1438 | 1511 | |
|
1439 | 1512 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1440 | 1513 | |
|
1441 | 1514 | In [19]: len(_ip.IP._main_ns_cache) == 0 |
|
1442 | 1515 | Out[19]: True |
|
1443 | 1516 | """ |
|
1444 | 1517 | self._main_ns_cache.clear() |
|
1445 | 1518 | |
|
1446 | 1519 | def _should_recompile(self,e): |
|
1447 | 1520 | """Utility routine for edit_syntax_error""" |
|
1448 | 1521 | |
|
1449 | 1522 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1450 | 1523 | '<console>','<BackgroundJob compilation>', |
|
1451 | 1524 | None): |
|
1452 | 1525 | |
|
1453 | 1526 | return False |
|
1454 | 1527 | try: |
|
1455 | 1528 | if (self.autoedit_syntax and |
|
1456 | 1529 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1457 | 1530 | '[Y/n] ','y')): |
|
1458 | 1531 | return False |
|
1459 | 1532 | except EOFError: |
|
1460 | 1533 | return False |
|
1461 | 1534 | |
|
1462 | 1535 | def int0(x): |
|
1463 | 1536 | try: |
|
1464 | 1537 | return int(x) |
|
1465 | 1538 | except TypeError: |
|
1466 | 1539 | return 0 |
|
1467 | 1540 | # always pass integer line and offset values to editor hook |
|
1468 | 1541 | try: |
|
1469 | 1542 | self.hooks.fix_error_editor(e.filename, |
|
1470 | 1543 | int0(e.lineno),int0(e.offset),e.msg) |
|
1471 | 1544 | except ipapi.TryNext: |
|
1472 | 1545 | warn('Could not open editor') |
|
1473 | 1546 | return False |
|
1474 | 1547 | return True |
|
1475 | 1548 | |
|
1476 | 1549 | def edit_syntax_error(self): |
|
1477 | 1550 | """The bottom half of the syntax error handler called in the main loop. |
|
1478 | 1551 | |
|
1479 | 1552 | Loop until syntax error is fixed or user cancels. |
|
1480 | 1553 | """ |
|
1481 | 1554 | |
|
1482 | 1555 | while self.SyntaxTB.last_syntax_error: |
|
1483 | 1556 | # copy and clear last_syntax_error |
|
1484 | 1557 | err = self.SyntaxTB.clear_err_state() |
|
1485 | 1558 | if not self._should_recompile(err): |
|
1486 | 1559 | return |
|
1487 | 1560 | try: |
|
1488 | 1561 | # may set last_syntax_error again if a SyntaxError is raised |
|
1489 | 1562 | self.safe_execfile(err.filename,self.user_ns) |
|
1490 | 1563 | except: |
|
1491 | 1564 | self.showtraceback() |
|
1492 | 1565 | else: |
|
1493 | 1566 | try: |
|
1494 | 1567 | f = file(err.filename) |
|
1495 | 1568 | try: |
|
1496 | 1569 | sys.displayhook(f.read()) |
|
1497 | 1570 | finally: |
|
1498 | 1571 | f.close() |
|
1499 | 1572 | except: |
|
1500 | 1573 | self.showtraceback() |
|
1501 | 1574 | |
|
1502 | 1575 | def showsyntaxerror(self, filename=None): |
|
1503 | 1576 | """Display the syntax error that just occurred. |
|
1504 | 1577 | |
|
1505 | 1578 | This doesn't display a stack trace because there isn't one. |
|
1506 | 1579 | |
|
1507 | 1580 | If a filename is given, it is stuffed in the exception instead |
|
1508 | 1581 | of what was there before (because Python's parser always uses |
|
1509 | 1582 | "<string>" when reading from a string). |
|
1510 | 1583 | """ |
|
1511 | 1584 | etype, value, last_traceback = sys.exc_info() |
|
1512 | 1585 | |
|
1513 | 1586 | # See note about these variables in showtraceback() below |
|
1514 | 1587 | sys.last_type = etype |
|
1515 | 1588 | sys.last_value = value |
|
1516 | 1589 | sys.last_traceback = last_traceback |
|
1517 | 1590 | |
|
1518 | 1591 | if filename and etype is SyntaxError: |
|
1519 | 1592 | # Work hard to stuff the correct filename in the exception |
|
1520 | 1593 | try: |
|
1521 | 1594 | msg, (dummy_filename, lineno, offset, line) = value |
|
1522 | 1595 | except: |
|
1523 | 1596 | # Not the format we expect; leave it alone |
|
1524 | 1597 | pass |
|
1525 | 1598 | else: |
|
1526 | 1599 | # Stuff in the right filename |
|
1527 | 1600 | try: |
|
1528 | 1601 | # Assume SyntaxError is a class exception |
|
1529 | 1602 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1530 | 1603 | except: |
|
1531 | 1604 | # If that failed, assume SyntaxError is a string |
|
1532 | 1605 | value = msg, (filename, lineno, offset, line) |
|
1533 | 1606 | self.SyntaxTB(etype,value,[]) |
|
1534 | 1607 | |
|
1535 | 1608 | def debugger(self,force=False): |
|
1536 | 1609 | """Call the pydb/pdb debugger. |
|
1537 | 1610 | |
|
1538 | 1611 | Keywords: |
|
1539 | 1612 | |
|
1540 | 1613 | - force(False): by default, this routine checks the instance call_pdb |
|
1541 | 1614 | flag and does not actually invoke the debugger if the flag is false. |
|
1542 | 1615 | The 'force' option forces the debugger to activate even if the flag |
|
1543 | 1616 | is false. |
|
1544 | 1617 | """ |
|
1545 | 1618 | |
|
1546 | 1619 | if not (force or self.call_pdb): |
|
1547 | 1620 | return |
|
1548 | 1621 | |
|
1549 | 1622 | if not hasattr(sys,'last_traceback'): |
|
1550 | 1623 | error('No traceback has been produced, nothing to debug.') |
|
1551 | 1624 | return |
|
1552 | 1625 | |
|
1553 | 1626 | # use pydb if available |
|
1554 | 1627 | if debugger.has_pydb: |
|
1555 | 1628 | from pydb import pm |
|
1556 | 1629 | else: |
|
1557 | 1630 | # fallback to our internal debugger |
|
1558 | 1631 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1559 | 1632 | self.history_saving_wrapper(pm)() |
|
1560 | 1633 | |
|
1561 | 1634 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1562 | 1635 | """Display the exception that just occurred. |
|
1563 | 1636 | |
|
1564 | 1637 | If nothing is known about the exception, this is the method which |
|
1565 | 1638 | should be used throughout the code for presenting user tracebacks, |
|
1566 | 1639 | rather than directly invoking the InteractiveTB object. |
|
1567 | 1640 | |
|
1568 | 1641 | A specific showsyntaxerror() also exists, but this method can take |
|
1569 | 1642 | care of calling it if needed, so unless you are explicitly catching a |
|
1570 | 1643 | SyntaxError exception, don't try to analyze the stack manually and |
|
1571 | 1644 | simply call this method.""" |
|
1572 | 1645 | |
|
1573 | 1646 | |
|
1574 | 1647 | # Though this won't be called by syntax errors in the input line, |
|
1575 | 1648 | # there may be SyntaxError cases whith imported code. |
|
1576 | 1649 | |
|
1577 | 1650 | try: |
|
1578 | 1651 | if exc_tuple is None: |
|
1579 | 1652 | etype, value, tb = sys.exc_info() |
|
1580 | 1653 | else: |
|
1581 | 1654 | etype, value, tb = exc_tuple |
|
1582 | 1655 | |
|
1583 | 1656 | if etype is SyntaxError: |
|
1584 | 1657 | self.showsyntaxerror(filename) |
|
1585 | 1658 | elif etype is ipapi.UsageError: |
|
1586 | 1659 | print "UsageError:", value |
|
1587 | 1660 | else: |
|
1588 | 1661 | # WARNING: these variables are somewhat deprecated and not |
|
1589 | 1662 | # necessarily safe to use in a threaded environment, but tools |
|
1590 | 1663 | # like pdb depend on their existence, so let's set them. If we |
|
1591 | 1664 | # find problems in the field, we'll need to revisit their use. |
|
1592 | 1665 | sys.last_type = etype |
|
1593 | 1666 | sys.last_value = value |
|
1594 | 1667 | sys.last_traceback = tb |
|
1595 | 1668 | |
|
1596 | 1669 | if etype in self.custom_exceptions: |
|
1597 | 1670 | self.CustomTB(etype,value,tb) |
|
1598 | 1671 | else: |
|
1599 | 1672 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1600 | 1673 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1601 | 1674 | # pdb mucks up readline, fix it back |
|
1602 | 1675 | self.set_completer() |
|
1603 | 1676 | except KeyboardInterrupt: |
|
1604 | 1677 | self.write("\nKeyboardInterrupt\n") |
|
1605 | 1678 | |
|
1606 | 1679 | def mainloop(self, banner=None): |
|
1607 | 1680 | """Start the mainloop. |
|
1608 | 1681 | |
|
1609 | 1682 | If an optional banner argument is given, it will override the |
|
1610 | 1683 | internally created default banner. |
|
1611 | 1684 | """ |
|
1612 | 1685 | if self.c: # Emulate Python's -c option |
|
1613 | 1686 | self.exec_init_cmd() |
|
1614 | 1687 | |
|
1615 | 1688 | if self.display_banner: |
|
1616 | 1689 | if banner is None: |
|
1617 | 1690 | banner = self.banner |
|
1618 | 1691 | |
|
1619 | 1692 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1620 | 1693 | # ensure that it's in sync |
|
1621 | 1694 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1622 | 1695 | self.input_hist_raw = InputList(self.input_hist) |
|
1623 | 1696 | |
|
1624 | 1697 | while 1: |
|
1625 | 1698 | try: |
|
1626 | 1699 | self.interact() |
|
1627 | 1700 | #self.interact_with_readline() |
|
1628 | 1701 | # XXX for testing of a readline-decoupled repl loop, call |
|
1629 | 1702 | # interact_with_readline above |
|
1630 | 1703 | break |
|
1631 | 1704 | except KeyboardInterrupt: |
|
1632 | 1705 | # this should not be necessary, but KeyboardInterrupt |
|
1633 | 1706 | # handling seems rather unpredictable... |
|
1634 | 1707 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1635 | 1708 | |
|
1636 | 1709 | def exec_init_cmd(self): |
|
1637 | 1710 | """Execute a command given at the command line. |
|
1638 | 1711 | |
|
1639 | 1712 | This emulates Python's -c option.""" |
|
1640 | 1713 | |
|
1641 | 1714 | #sys.argv = ['-c'] |
|
1642 | 1715 | self.push(self.prefilter(self.c, False)) |
|
1643 | 1716 | if not self.interactive: |
|
1644 | 1717 | self.ask_exit() |
|
1645 | 1718 | |
|
1646 | 1719 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1647 | 1720 | """Embeds IPython into a running python program. |
|
1648 | 1721 | |
|
1649 | 1722 | Input: |
|
1650 | 1723 | |
|
1651 | 1724 | - header: An optional header message can be specified. |
|
1652 | 1725 | |
|
1653 | 1726 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1654 | 1727 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1655 | 1728 | program variables become visible but user-specific configuration |
|
1656 | 1729 | remains possible. |
|
1657 | 1730 | |
|
1658 | 1731 | - stack_depth: specifies how many levels in the stack to go to |
|
1659 | 1732 | looking for namespaces (when local_ns and global_ns are None). This |
|
1660 | 1733 | allows an intermediate caller to make sure that this function gets |
|
1661 | 1734 | the namespace from the intended level in the stack. By default (0) |
|
1662 | 1735 | it will get its locals and globals from the immediate caller. |
|
1663 | 1736 | |
|
1664 | 1737 | Warning: it's possible to use this in a program which is being run by |
|
1665 | 1738 | IPython itself (via %run), but some funny things will happen (a few |
|
1666 | 1739 | globals get overwritten). In the future this will be cleaned up, as |
|
1667 | 1740 | there is no fundamental reason why it can't work perfectly.""" |
|
1668 | 1741 | |
|
1669 | 1742 | # Get locals and globals from caller |
|
1670 | 1743 | if local_ns is None or global_ns is None: |
|
1671 | 1744 | call_frame = sys._getframe(stack_depth).f_back |
|
1672 | 1745 | |
|
1673 | 1746 | if local_ns is None: |
|
1674 | 1747 | local_ns = call_frame.f_locals |
|
1675 | 1748 | if global_ns is None: |
|
1676 | 1749 | global_ns = call_frame.f_globals |
|
1677 | 1750 | |
|
1678 | 1751 | # Update namespaces and fire up interpreter |
|
1679 | 1752 | |
|
1680 | 1753 | # The global one is easy, we can just throw it in |
|
1681 | 1754 | self.user_global_ns = global_ns |
|
1682 | 1755 | |
|
1683 | 1756 | # but the user/local one is tricky: ipython needs it to store internal |
|
1684 | 1757 | # data, but we also need the locals. We'll copy locals in the user |
|
1685 | 1758 | # one, but will track what got copied so we can delete them at exit. |
|
1686 | 1759 | # This is so that a later embedded call doesn't see locals from a |
|
1687 | 1760 | # previous call (which most likely existed in a separate scope). |
|
1688 | 1761 | local_varnames = local_ns.keys() |
|
1689 | 1762 | self.user_ns.update(local_ns) |
|
1690 | 1763 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1691 | 1764 | |
|
1692 | 1765 | # Patch for global embedding to make sure that things don't overwrite |
|
1693 | 1766 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1694 | 1767 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1695 | 1768 | if local_ns is None and global_ns is None: |
|
1696 | 1769 | self.user_global_ns.update(__main__.__dict__) |
|
1697 | 1770 | |
|
1698 | 1771 | # make sure the tab-completer has the correct frame information, so it |
|
1699 | 1772 | # actually completes using the frame's locals/globals |
|
1700 | 1773 | self.set_completer_frame() |
|
1701 | 1774 | |
|
1702 | 1775 | # before activating the interactive mode, we need to make sure that |
|
1703 | 1776 | # all names in the builtin namespace needed by ipython point to |
|
1704 | 1777 | # ourselves, and not to other instances. |
|
1705 | 1778 | self.add_builtins() |
|
1706 | 1779 | |
|
1707 | 1780 | self.interact(header) |
|
1708 | 1781 | |
|
1709 | 1782 | # now, purge out the user namespace from anything we might have added |
|
1710 | 1783 | # from the caller's local namespace |
|
1711 | 1784 | delvar = self.user_ns.pop |
|
1712 | 1785 | for var in local_varnames: |
|
1713 | 1786 | delvar(var,None) |
|
1714 | 1787 | # and clean builtins we may have overridden |
|
1715 | 1788 | self.clean_builtins() |
|
1716 | 1789 | |
|
1717 | 1790 | def interact_prompt(self): |
|
1718 | 1791 | """ Print the prompt (in read-eval-print loop) |
|
1719 | 1792 | |
|
1720 | 1793 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1721 | 1794 | used in standard IPython flow. |
|
1722 | 1795 | """ |
|
1723 | 1796 | if self.more: |
|
1724 | 1797 | try: |
|
1725 | 1798 | prompt = self.hooks.generate_prompt(True) |
|
1726 | 1799 | except: |
|
1727 | 1800 | self.showtraceback() |
|
1728 | 1801 | if self.autoindent: |
|
1729 | 1802 | self.rl_do_indent = True |
|
1730 | 1803 | |
|
1731 | 1804 | else: |
|
1732 | 1805 | try: |
|
1733 | 1806 | prompt = self.hooks.generate_prompt(False) |
|
1734 | 1807 | except: |
|
1735 | 1808 | self.showtraceback() |
|
1736 | 1809 | self.write(prompt) |
|
1737 | 1810 | |
|
1738 | 1811 | def interact_handle_input(self,line): |
|
1739 | 1812 | """ Handle the input line (in read-eval-print loop) |
|
1740 | 1813 | |
|
1741 | 1814 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1742 | 1815 | used in standard IPython flow. |
|
1743 | 1816 | """ |
|
1744 | 1817 | if line.lstrip() == line: |
|
1745 | 1818 | self.shadowhist.add(line.strip()) |
|
1746 | 1819 | lineout = self.prefilter(line,self.more) |
|
1747 | 1820 | |
|
1748 | 1821 | if line.strip(): |
|
1749 | 1822 | if self.more: |
|
1750 | 1823 | self.input_hist_raw[-1] += '%s\n' % line |
|
1751 | 1824 | else: |
|
1752 | 1825 | self.input_hist_raw.append('%s\n' % line) |
|
1753 | 1826 | |
|
1754 | 1827 | |
|
1755 | 1828 | self.more = self.push(lineout) |
|
1756 | 1829 | if (self.SyntaxTB.last_syntax_error and |
|
1757 | 1830 | self.autoedit_syntax): |
|
1758 | 1831 | self.edit_syntax_error() |
|
1759 | 1832 | |
|
1760 | 1833 | def interact_with_readline(self): |
|
1761 | 1834 | """ Demo of using interact_handle_input, interact_prompt |
|
1762 | 1835 | |
|
1763 | 1836 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1764 | 1837 | it should work like this. |
|
1765 | 1838 | """ |
|
1766 | 1839 | self.readline_startup_hook(self.pre_readline) |
|
1767 | 1840 | while not self.exit_now: |
|
1768 | 1841 | self.interact_prompt() |
|
1769 | 1842 | if self.more: |
|
1770 | 1843 | self.rl_do_indent = True |
|
1771 | 1844 | else: |
|
1772 | 1845 | self.rl_do_indent = False |
|
1773 | 1846 | line = raw_input_original().decode(self.stdin_encoding) |
|
1774 | 1847 | self.interact_handle_input(line) |
|
1775 | 1848 | |
|
1776 | 1849 | def interact(self, banner=None): |
|
1777 | 1850 | """Closely emulate the interactive Python console.""" |
|
1778 | 1851 | |
|
1779 | 1852 | # batch run -> do not interact |
|
1780 | 1853 | if self.exit_now: |
|
1781 | 1854 | return |
|
1782 | 1855 | |
|
1783 | 1856 | if self.display_banner: |
|
1784 | 1857 | if banner is None: |
|
1785 | 1858 | banner = self.banner |
|
1786 | 1859 | self.write(banner) |
|
1787 | 1860 | |
|
1788 | 1861 | more = 0 |
|
1789 | 1862 | |
|
1790 | 1863 | # Mark activity in the builtins |
|
1791 | 1864 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1792 | 1865 | |
|
1793 | 1866 | if self.has_readline: |
|
1794 | 1867 | self.readline_startup_hook(self.pre_readline) |
|
1795 | 1868 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1796 | 1869 | # ask_exit callback. |
|
1797 | 1870 | |
|
1798 | 1871 | while not self.exit_now: |
|
1799 | 1872 | self.hooks.pre_prompt_hook() |
|
1800 | 1873 | if more: |
|
1801 | 1874 | try: |
|
1802 | 1875 | prompt = self.hooks.generate_prompt(True) |
|
1803 | 1876 | except: |
|
1804 | 1877 | self.showtraceback() |
|
1805 | 1878 | if self.autoindent: |
|
1806 | 1879 | self.rl_do_indent = True |
|
1807 | 1880 | |
|
1808 | 1881 | else: |
|
1809 | 1882 | try: |
|
1810 | 1883 | prompt = self.hooks.generate_prompt(False) |
|
1811 | 1884 | except: |
|
1812 | 1885 | self.showtraceback() |
|
1813 | 1886 | try: |
|
1814 | 1887 | line = self.raw_input(prompt, more) |
|
1815 | 1888 | if self.exit_now: |
|
1816 | 1889 | # quick exit on sys.std[in|out] close |
|
1817 | 1890 | break |
|
1818 | 1891 | if self.autoindent: |
|
1819 | 1892 | self.rl_do_indent = False |
|
1820 | 1893 | |
|
1821 | 1894 | except KeyboardInterrupt: |
|
1822 | 1895 | #double-guard against keyboardinterrupts during kbdint handling |
|
1823 | 1896 | try: |
|
1824 | 1897 | self.write('\nKeyboardInterrupt\n') |
|
1825 | 1898 | self.resetbuffer() |
|
1826 | 1899 | # keep cache in sync with the prompt counter: |
|
1827 | 1900 | self.outputcache.prompt_count -= 1 |
|
1828 | 1901 | |
|
1829 | 1902 | if self.autoindent: |
|
1830 | 1903 | self.indent_current_nsp = 0 |
|
1831 | 1904 | more = 0 |
|
1832 | 1905 | except KeyboardInterrupt: |
|
1833 | 1906 | pass |
|
1834 | 1907 | except EOFError: |
|
1835 | 1908 | if self.autoindent: |
|
1836 | 1909 | self.rl_do_indent = False |
|
1837 | 1910 | self.readline_startup_hook(None) |
|
1838 | 1911 | self.write('\n') |
|
1839 | 1912 | self.exit() |
|
1840 | 1913 | except bdb.BdbQuit: |
|
1841 | 1914 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1842 | 1915 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1843 | 1916 | 'for IPython to properly format this particular exception.\n' |
|
1844 | 1917 | 'IPython will resume normal operation.') |
|
1845 | 1918 | except: |
|
1846 | 1919 | # exceptions here are VERY RARE, but they can be triggered |
|
1847 | 1920 | # asynchronously by signal handlers, for example. |
|
1848 | 1921 | self.showtraceback() |
|
1849 | 1922 | else: |
|
1850 | 1923 | more = self.push(line) |
|
1851 | 1924 | if (self.SyntaxTB.last_syntax_error and |
|
1852 | 1925 | self.autoedit_syntax): |
|
1853 | 1926 | self.edit_syntax_error() |
|
1854 | 1927 | |
|
1855 | 1928 | # We are off again... |
|
1856 | 1929 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1857 | 1930 | |
|
1858 | 1931 | def excepthook(self, etype, value, tb): |
|
1859 | 1932 | """One more defense for GUI apps that call sys.excepthook. |
|
1860 | 1933 | |
|
1861 | 1934 | GUI frameworks like wxPython trap exceptions and call |
|
1862 | 1935 | sys.excepthook themselves. I guess this is a feature that |
|
1863 | 1936 | enables them to keep running after exceptions that would |
|
1864 | 1937 | otherwise kill their mainloop. This is a bother for IPython |
|
1865 | 1938 | which excepts to catch all of the program exceptions with a try: |
|
1866 | 1939 | except: statement. |
|
1867 | 1940 | |
|
1868 | 1941 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1869 | 1942 | any app directly invokes sys.excepthook, it will look to the user like |
|
1870 | 1943 | IPython crashed. In order to work around this, we can disable the |
|
1871 | 1944 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1872 | 1945 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1873 | 1946 | call sys.excepthook will generate a regular-looking exception from |
|
1874 | 1947 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1875 | 1948 | crashes. |
|
1876 | 1949 | |
|
1877 | 1950 | This hook should be used sparingly, only in places which are not likely |
|
1878 | 1951 | to be true IPython errors. |
|
1879 | 1952 | """ |
|
1880 | 1953 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1881 | 1954 | |
|
1882 | 1955 | def expand_aliases(self,fn,rest): |
|
1883 | 1956 | """ Expand multiple levels of aliases: |
|
1884 | 1957 | |
|
1885 | 1958 | if: |
|
1886 | 1959 | |
|
1887 | 1960 | alias foo bar /tmp |
|
1888 | 1961 | alias baz foo |
|
1889 | 1962 | |
|
1890 | 1963 | then: |
|
1891 | 1964 | |
|
1892 | 1965 | baz huhhahhei -> bar /tmp huhhahhei |
|
1893 | 1966 | |
|
1894 | 1967 | """ |
|
1895 | 1968 | line = fn + " " + rest |
|
1896 | 1969 | |
|
1897 | 1970 | done = set() |
|
1898 | 1971 | while 1: |
|
1899 | 1972 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1900 | 1973 | prefilter.shell_line_split) |
|
1901 | 1974 | if fn in self.alias_table: |
|
1902 | 1975 | if fn in done: |
|
1903 | 1976 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1904 | 1977 | return "" |
|
1905 | 1978 | done.add(fn) |
|
1906 | 1979 | |
|
1907 | 1980 | l2 = self.transform_alias(fn,rest) |
|
1908 | 1981 | # dir -> dir |
|
1909 | 1982 | # print "alias",line, "->",l2 #dbg |
|
1910 | 1983 | if l2 == line: |
|
1911 | 1984 | break |
|
1912 | 1985 | # ls -> ls -F should not recurse forever |
|
1913 | 1986 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1914 | 1987 | line = l2 |
|
1915 | 1988 | break |
|
1916 | 1989 | |
|
1917 | 1990 | line=l2 |
|
1918 | 1991 | |
|
1919 | 1992 | |
|
1920 | 1993 | # print "al expand to",line #dbg |
|
1921 | 1994 | else: |
|
1922 | 1995 | break |
|
1923 | 1996 | |
|
1924 | 1997 | return line |
|
1925 | 1998 | |
|
1926 | 1999 | def transform_alias(self, alias,rest=''): |
|
1927 | 2000 | """ Transform alias to system command string. |
|
1928 | 2001 | """ |
|
1929 | 2002 | trg = self.alias_table[alias] |
|
1930 | 2003 | |
|
1931 | 2004 | nargs,cmd = trg |
|
1932 | 2005 | # print trg #dbg |
|
1933 | 2006 | if ' ' in cmd and os.path.isfile(cmd): |
|
1934 | 2007 | cmd = '"%s"' % cmd |
|
1935 | 2008 | |
|
1936 | 2009 | # Expand the %l special to be the user's input line |
|
1937 | 2010 | if cmd.find('%l') >= 0: |
|
1938 | 2011 | cmd = cmd.replace('%l',rest) |
|
1939 | 2012 | rest = '' |
|
1940 | 2013 | if nargs==0: |
|
1941 | 2014 | # Simple, argument-less aliases |
|
1942 | 2015 | cmd = '%s %s' % (cmd,rest) |
|
1943 | 2016 | else: |
|
1944 | 2017 | # Handle aliases with positional arguments |
|
1945 | 2018 | args = rest.split(None,nargs) |
|
1946 | 2019 | if len(args)< nargs: |
|
1947 | 2020 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1948 | 2021 | (alias,nargs,len(args))) |
|
1949 | 2022 | return None |
|
1950 | 2023 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1951 | 2024 | # Now call the macro, evaluating in the user's namespace |
|
1952 | 2025 | #print 'new command: <%r>' % cmd # dbg |
|
1953 | 2026 | return cmd |
|
1954 | 2027 | |
|
1955 | 2028 | def call_alias(self,alias,rest=''): |
|
1956 | 2029 | """Call an alias given its name and the rest of the line. |
|
1957 | 2030 | |
|
1958 | 2031 | This is only used to provide backwards compatibility for users of |
|
1959 | 2032 | ipalias(), use of which is not recommended for anymore.""" |
|
1960 | 2033 | |
|
1961 | 2034 | # Now call the macro, evaluating in the user's namespace |
|
1962 | 2035 | cmd = self.transform_alias(alias, rest) |
|
1963 | 2036 | try: |
|
1964 | 2037 | self.system(cmd) |
|
1965 | 2038 | except: |
|
1966 | 2039 | self.showtraceback() |
|
1967 | 2040 | |
|
1968 | 2041 | def indent_current_str(self): |
|
1969 | 2042 | """return the current level of indentation as a string""" |
|
1970 | 2043 | return self.indent_current_nsp * ' ' |
|
1971 | 2044 | |
|
1972 | 2045 | def autoindent_update(self,line): |
|
1973 | 2046 | """Keep track of the indent level.""" |
|
1974 | 2047 | |
|
1975 | 2048 | #debugx('line') |
|
1976 | 2049 | #debugx('self.indent_current_nsp') |
|
1977 | 2050 | if self.autoindent: |
|
1978 | 2051 | if line: |
|
1979 | 2052 | inisp = num_ini_spaces(line) |
|
1980 | 2053 | if inisp < self.indent_current_nsp: |
|
1981 | 2054 | self.indent_current_nsp = inisp |
|
1982 | 2055 | |
|
1983 | 2056 | if line[-1] == ':': |
|
1984 | 2057 | self.indent_current_nsp += 4 |
|
1985 | 2058 | elif dedent_re.match(line): |
|
1986 | 2059 | self.indent_current_nsp -= 4 |
|
1987 | 2060 | else: |
|
1988 | 2061 | self.indent_current_nsp = 0 |
|
1989 | 2062 | |
|
1990 | 2063 | def runlines(self,lines): |
|
1991 | 2064 | """Run a string of one or more lines of source. |
|
1992 | 2065 | |
|
1993 | 2066 | This method is capable of running a string containing multiple source |
|
1994 | 2067 | lines, as if they had been entered at the IPython prompt. Since it |
|
1995 | 2068 | exposes IPython's processing machinery, the given strings can contain |
|
1996 | 2069 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1997 | 2070 | |
|
1998 | 2071 | # We must start with a clean buffer, in case this is run from an |
|
1999 | 2072 | # interactive IPython session (via a magic, for example). |
|
2000 | 2073 | self.resetbuffer() |
|
2001 | 2074 | lines = lines.split('\n') |
|
2002 | 2075 | more = 0 |
|
2003 | 2076 | |
|
2004 | 2077 | for line in lines: |
|
2005 | 2078 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2006 | 2079 | # NOT skip even a blank line if we are in a code block (more is |
|
2007 | 2080 | # true) |
|
2008 | 2081 | |
|
2009 | 2082 | if line or more: |
|
2010 | 2083 | # push to raw history, so hist line numbers stay in sync |
|
2011 | 2084 | self.input_hist_raw.append("# " + line + "\n") |
|
2012 | 2085 | more = self.push(self.prefilter(line,more)) |
|
2013 | 2086 | # IPython's runsource returns None if there was an error |
|
2014 | 2087 | # compiling the code. This allows us to stop processing right |
|
2015 | 2088 | # away, so the user gets the error message at the right place. |
|
2016 | 2089 | if more is None: |
|
2017 | 2090 | break |
|
2018 | 2091 | else: |
|
2019 | 2092 | self.input_hist_raw.append("\n") |
|
2020 | 2093 | # final newline in case the input didn't have it, so that the code |
|
2021 | 2094 | # actually does get executed |
|
2022 | 2095 | if more: |
|
2023 | 2096 | self.push('\n') |
|
2024 | 2097 | |
|
2025 | 2098 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2026 | 2099 | """Compile and run some source in the interpreter. |
|
2027 | 2100 | |
|
2028 | 2101 | Arguments are as for compile_command(). |
|
2029 | 2102 | |
|
2030 | 2103 | One several things can happen: |
|
2031 | 2104 | |
|
2032 | 2105 | 1) The input is incorrect; compile_command() raised an |
|
2033 | 2106 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2034 | 2107 | will be printed by calling the showsyntaxerror() method. |
|
2035 | 2108 | |
|
2036 | 2109 | 2) The input is incomplete, and more input is required; |
|
2037 | 2110 | compile_command() returned None. Nothing happens. |
|
2038 | 2111 | |
|
2039 | 2112 | 3) The input is complete; compile_command() returned a code |
|
2040 | 2113 | object. The code is executed by calling self.runcode() (which |
|
2041 | 2114 | also handles run-time exceptions, except for SystemExit). |
|
2042 | 2115 | |
|
2043 | 2116 | The return value is: |
|
2044 | 2117 | |
|
2045 | 2118 | - True in case 2 |
|
2046 | 2119 | |
|
2047 | 2120 | - False in the other cases, unless an exception is raised, where |
|
2048 | 2121 | None is returned instead. This can be used by external callers to |
|
2049 | 2122 | know whether to continue feeding input or not. |
|
2050 | 2123 | |
|
2051 | 2124 | The return value can be used to decide whether to use sys.ps1 or |
|
2052 | 2125 | sys.ps2 to prompt the next line.""" |
|
2053 | 2126 | |
|
2054 | 2127 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2055 | 2128 | # this allows execution of indented pasted code. It is tempting |
|
2056 | 2129 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2057 | 2130 | # directly, but this fails for more complicated scenarios |
|
2058 | 2131 | source=source.encode(self.stdin_encoding) |
|
2059 | 2132 | if source[:1] in [' ', '\t']: |
|
2060 | 2133 | source = 'if 1:\n%s' % source |
|
2061 | 2134 | |
|
2062 | 2135 | try: |
|
2063 | 2136 | code = self.compile(source,filename,symbol) |
|
2064 | 2137 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2065 | 2138 | # Case 1 |
|
2066 | 2139 | self.showsyntaxerror(filename) |
|
2067 | 2140 | return None |
|
2068 | 2141 | |
|
2069 | 2142 | if code is None: |
|
2070 | 2143 | # Case 2 |
|
2071 | 2144 | return True |
|
2072 | 2145 | |
|
2073 | 2146 | # Case 3 |
|
2074 | 2147 | # We store the code object so that threaded shells and |
|
2075 | 2148 | # custom exception handlers can access all this info if needed. |
|
2076 | 2149 | # The source corresponding to this can be obtained from the |
|
2077 | 2150 | # buffer attribute as '\n'.join(self.buffer). |
|
2078 | 2151 | self.code_to_run = code |
|
2079 | 2152 | # now actually execute the code object |
|
2080 | 2153 | if self.runcode(code) == 0: |
|
2081 | 2154 | return False |
|
2082 | 2155 | else: |
|
2083 | 2156 | return None |
|
2084 | 2157 | |
|
2085 | 2158 | def runcode(self,code_obj): |
|
2086 | 2159 | """Execute a code object. |
|
2087 | 2160 | |
|
2088 | 2161 | When an exception occurs, self.showtraceback() is called to display a |
|
2089 | 2162 | traceback. |
|
2090 | 2163 | |
|
2091 | 2164 | Return value: a flag indicating whether the code to be run completed |
|
2092 | 2165 | successfully: |
|
2093 | 2166 | |
|
2094 | 2167 | - 0: successful execution. |
|
2095 | 2168 | - 1: an error occurred. |
|
2096 | 2169 | """ |
|
2097 | 2170 | |
|
2098 | 2171 | # Set our own excepthook in case the user code tries to call it |
|
2099 | 2172 | # directly, so that the IPython crash handler doesn't get triggered |
|
2100 | 2173 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2101 | 2174 | |
|
2102 | 2175 | # we save the original sys.excepthook in the instance, in case config |
|
2103 | 2176 | # code (such as magics) needs access to it. |
|
2104 | 2177 | self.sys_excepthook = old_excepthook |
|
2105 | 2178 | outflag = 1 # happens in more places, so it's easier as default |
|
2106 | 2179 | try: |
|
2107 | 2180 | try: |
|
2108 | 2181 | self.hooks.pre_runcode_hook() |
|
2109 | 2182 | exec code_obj in self.user_global_ns, self.user_ns |
|
2110 | 2183 | finally: |
|
2111 | 2184 | # Reset our crash handler in place |
|
2112 | 2185 | sys.excepthook = old_excepthook |
|
2113 | 2186 | except SystemExit: |
|
2114 | 2187 | self.resetbuffer() |
|
2115 | 2188 | self.showtraceback() |
|
2116 | 2189 | warn("Type %exit or %quit to exit IPython " |
|
2117 | 2190 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2118 | 2191 | except self.custom_exceptions: |
|
2119 | 2192 | etype,value,tb = sys.exc_info() |
|
2120 | 2193 | self.CustomTB(etype,value,tb) |
|
2121 | 2194 | except: |
|
2122 | 2195 | self.showtraceback() |
|
2123 | 2196 | else: |
|
2124 | 2197 | outflag = 0 |
|
2125 | 2198 | if softspace(sys.stdout, 0): |
|
2126 | 2199 | |
|
2127 | 2200 | # Flush out code object which has been run (and source) |
|
2128 | 2201 | self.code_to_run = None |
|
2129 | 2202 | return outflag |
|
2130 | 2203 | |
|
2131 | 2204 | def push(self, line): |
|
2132 | 2205 | """Push a line to the interpreter. |
|
2133 | 2206 | |
|
2134 | 2207 | The line should not have a trailing newline; it may have |
|
2135 | 2208 | internal newlines. The line is appended to a buffer and the |
|
2136 | 2209 | interpreter's runsource() method is called with the |
|
2137 | 2210 | concatenated contents of the buffer as source. If this |
|
2138 | 2211 | indicates that the command was executed or invalid, the buffer |
|
2139 | 2212 | is reset; otherwise, the command is incomplete, and the buffer |
|
2140 | 2213 | is left as it was after the line was appended. The return |
|
2141 | 2214 | value is 1 if more input is required, 0 if the line was dealt |
|
2142 | 2215 | with in some way (this is the same as runsource()). |
|
2143 | 2216 | """ |
|
2144 | 2217 | |
|
2145 | 2218 | # autoindent management should be done here, and not in the |
|
2146 | 2219 | # interactive loop, since that one is only seen by keyboard input. We |
|
2147 | 2220 | # need this done correctly even for code run via runlines (which uses |
|
2148 | 2221 | # push). |
|
2149 | 2222 | |
|
2150 | 2223 | #print 'push line: <%s>' % line # dbg |
|
2151 | 2224 | for subline in line.splitlines(): |
|
2152 | 2225 | self.autoindent_update(subline) |
|
2153 | 2226 | self.buffer.append(line) |
|
2154 | 2227 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2155 | 2228 | if not more: |
|
2156 | 2229 | self.resetbuffer() |
|
2157 | 2230 | return more |
|
2158 | 2231 | |
|
2159 | 2232 | def split_user_input(self, line): |
|
2160 | 2233 | # This is really a hold-over to support ipapi and some extensions |
|
2161 | 2234 | return prefilter.splitUserInput(line) |
|
2162 | 2235 | |
|
2163 | 2236 | def resetbuffer(self): |
|
2164 | 2237 | """Reset the input buffer.""" |
|
2165 | 2238 | self.buffer[:] = [] |
|
2166 | 2239 | |
|
2167 | 2240 | def raw_input(self,prompt='',continue_prompt=False): |
|
2168 | 2241 | """Write a prompt and read a line. |
|
2169 | 2242 | |
|
2170 | 2243 | The returned line does not include the trailing newline. |
|
2171 | 2244 | When the user enters the EOF key sequence, EOFError is raised. |
|
2172 | 2245 | |
|
2173 | 2246 | Optional inputs: |
|
2174 | 2247 | |
|
2175 | 2248 | - prompt(''): a string to be printed to prompt the user. |
|
2176 | 2249 | |
|
2177 | 2250 | - continue_prompt(False): whether this line is the first one or a |
|
2178 | 2251 | continuation in a sequence of inputs. |
|
2179 | 2252 | """ |
|
2180 | 2253 | |
|
2181 | 2254 | # Code run by the user may have modified the readline completer state. |
|
2182 | 2255 | # We must ensure that our completer is back in place. |
|
2183 | 2256 | if self.has_readline: |
|
2184 | 2257 | self.set_completer() |
|
2185 | 2258 | |
|
2186 | 2259 | try: |
|
2187 | 2260 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2188 | 2261 | except ValueError: |
|
2189 | 2262 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2190 | 2263 | " or sys.stdout.close()!\nExiting IPython!") |
|
2191 | 2264 | self.ask_exit() |
|
2192 | 2265 | return "" |
|
2193 | 2266 | |
|
2194 | 2267 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2195 | 2268 | # than necessary. We do this by trimming out the auto-indent initial |
|
2196 | 2269 | # spaces, if the user's actual input started itself with whitespace. |
|
2197 | 2270 | #debugx('self.buffer[-1]') |
|
2198 | 2271 | |
|
2199 | 2272 | if self.autoindent: |
|
2200 | 2273 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2201 | 2274 | line = line[self.indent_current_nsp:] |
|
2202 | 2275 | self.indent_current_nsp = 0 |
|
2203 | 2276 | |
|
2204 | 2277 | # store the unfiltered input before the user has any chance to modify |
|
2205 | 2278 | # it. |
|
2206 | 2279 | if line.strip(): |
|
2207 | 2280 | if continue_prompt: |
|
2208 | 2281 | self.input_hist_raw[-1] += '%s\n' % line |
|
2209 | 2282 | if self.has_readline: # and some config option is set? |
|
2210 | 2283 | try: |
|
2211 | 2284 | histlen = self.readline.get_current_history_length() |
|
2212 | 2285 | if histlen > 1: |
|
2213 | 2286 | newhist = self.input_hist_raw[-1].rstrip() |
|
2214 | 2287 | self.readline.remove_history_item(histlen-1) |
|
2215 | 2288 | self.readline.replace_history_item(histlen-2, |
|
2216 | 2289 | newhist.encode(self.stdin_encoding)) |
|
2217 | 2290 | except AttributeError: |
|
2218 | 2291 | pass # re{move,place}_history_item are new in 2.4. |
|
2219 | 2292 | else: |
|
2220 | 2293 | self.input_hist_raw.append('%s\n' % line) |
|
2221 | 2294 | # only entries starting at first column go to shadow history |
|
2222 | 2295 | if line.lstrip() == line: |
|
2223 | 2296 | self.shadowhist.add(line.strip()) |
|
2224 | 2297 | elif not continue_prompt: |
|
2225 | 2298 | self.input_hist_raw.append('\n') |
|
2226 | 2299 | try: |
|
2227 | 2300 | lineout = self.prefilter(line,continue_prompt) |
|
2228 | 2301 | except: |
|
2229 | 2302 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2230 | 2303 | # can't take all of ipython with it. |
|
2231 | 2304 | self.showtraceback() |
|
2232 | 2305 | return '' |
|
2233 | 2306 | else: |
|
2234 | 2307 | return lineout |
|
2235 | 2308 | |
|
2236 | 2309 | def _prefilter(self, line, continue_prompt): |
|
2237 | 2310 | """Calls different preprocessors, depending on the form of line.""" |
|
2238 | 2311 | |
|
2239 | 2312 | # All handlers *must* return a value, even if it's blank (''). |
|
2240 | 2313 | |
|
2241 | 2314 | # Lines are NOT logged here. Handlers should process the line as |
|
2242 | 2315 | # needed, update the cache AND log it (so that the input cache array |
|
2243 | 2316 | # stays synced). |
|
2244 | 2317 | |
|
2245 | 2318 | #..................................................................... |
|
2246 | 2319 | # Code begins |
|
2247 | 2320 | |
|
2248 | 2321 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2249 | 2322 | |
|
2250 | 2323 | # save the line away in case we crash, so the post-mortem handler can |
|
2251 | 2324 | # record it |
|
2252 | 2325 | self._last_input_line = line |
|
2253 | 2326 | |
|
2254 | 2327 | #print '***line: <%s>' % line # dbg |
|
2255 | 2328 | |
|
2256 | 2329 | if not line: |
|
2257 | 2330 | # Return immediately on purely empty lines, so that if the user |
|
2258 | 2331 | # previously typed some whitespace that started a continuation |
|
2259 | 2332 | # prompt, he can break out of that loop with just an empty line. |
|
2260 | 2333 | # This is how the default python prompt works. |
|
2261 | 2334 | |
|
2262 | 2335 | # Only return if the accumulated input buffer was just whitespace! |
|
2263 | 2336 | if ''.join(self.buffer).isspace(): |
|
2264 | 2337 | self.buffer[:] = [] |
|
2265 | 2338 | return '' |
|
2266 | 2339 | |
|
2267 | 2340 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2268 | 2341 | |
|
2269 | 2342 | # the input history needs to track even empty lines |
|
2270 | 2343 | stripped = line.strip() |
|
2271 | 2344 | |
|
2272 | 2345 | if not stripped: |
|
2273 | 2346 | if not continue_prompt: |
|
2274 | 2347 | self.outputcache.prompt_count -= 1 |
|
2275 | 2348 | return self.handle_normal(line_info) |
|
2276 | 2349 | |
|
2277 | 2350 | # print '***cont',continue_prompt # dbg |
|
2278 | 2351 | # special handlers are only allowed for single line statements |
|
2279 | 2352 | if continue_prompt and not self.multi_line_specials: |
|
2280 | 2353 | return self.handle_normal(line_info) |
|
2281 | 2354 | |
|
2282 | 2355 | |
|
2283 | 2356 | # See whether any pre-existing handler can take care of it |
|
2284 | 2357 | rewritten = self.hooks.input_prefilter(stripped) |
|
2285 | 2358 | if rewritten != stripped: # ok, some prefilter did something |
|
2286 | 2359 | rewritten = line_info.pre + rewritten # add indentation |
|
2287 | 2360 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2288 | 2361 | continue_prompt)) |
|
2289 | 2362 | |
|
2290 | 2363 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2291 | 2364 | |
|
2292 | 2365 | return prefilter.prefilter(line_info, self) |
|
2293 | 2366 | |
|
2294 | 2367 | |
|
2295 | 2368 | def _prefilter_dumb(self, line, continue_prompt): |
|
2296 | 2369 | """simple prefilter function, for debugging""" |
|
2297 | 2370 | return self.handle_normal(line,continue_prompt) |
|
2298 | 2371 | |
|
2299 | 2372 | |
|
2300 | 2373 | def multiline_prefilter(self, line, continue_prompt): |
|
2301 | 2374 | """ Run _prefilter for each line of input |
|
2302 | 2375 | |
|
2303 | 2376 | Covers cases where there are multiple lines in the user entry, |
|
2304 | 2377 | which is the case when the user goes back to a multiline history |
|
2305 | 2378 | entry and presses enter. |
|
2306 | 2379 | |
|
2307 | 2380 | """ |
|
2308 | 2381 | out = [] |
|
2309 | 2382 | for l in line.rstrip('\n').split('\n'): |
|
2310 | 2383 | out.append(self._prefilter(l, continue_prompt)) |
|
2311 | 2384 | return '\n'.join(out) |
|
2312 | 2385 | |
|
2313 | 2386 | # Set the default prefilter() function (this can be user-overridden) |
|
2314 | 2387 | prefilter = multiline_prefilter |
|
2315 | 2388 | |
|
2316 | 2389 | def handle_normal(self,line_info): |
|
2317 | 2390 | """Handle normal input lines. Use as a template for handlers.""" |
|
2318 | 2391 | |
|
2319 | 2392 | # With autoindent on, we need some way to exit the input loop, and I |
|
2320 | 2393 | # don't want to force the user to have to backspace all the way to |
|
2321 | 2394 | # clear the line. The rule will be in this case, that either two |
|
2322 | 2395 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2323 | 2396 | # of a size different to the indent level, will exit the input loop. |
|
2324 | 2397 | line = line_info.line |
|
2325 | 2398 | continue_prompt = line_info.continue_prompt |
|
2326 | 2399 | |
|
2327 | 2400 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2328 | 2401 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2329 | 2402 | (self.buffer[-1]).isspace() )): |
|
2330 | 2403 | line = '' |
|
2331 | 2404 | |
|
2332 | 2405 | self.log(line,line,continue_prompt) |
|
2333 | 2406 | return line |
|
2334 | 2407 | |
|
2335 | 2408 | def handle_alias(self,line_info): |
|
2336 | 2409 | """Handle alias input lines. """ |
|
2337 | 2410 | tgt = self.alias_table[line_info.iFun] |
|
2338 | 2411 | # print "=>",tgt #dbg |
|
2339 | 2412 | if callable(tgt): |
|
2340 | 2413 | if '$' in line_info.line: |
|
2341 | 2414 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2342 | 2415 | else: |
|
2343 | 2416 | call_meth = '(_ip,%s)' |
|
2344 | 2417 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2345 | 2418 | line_info.iFun, |
|
2346 | 2419 | make_quoted_expr(line_info.line)) |
|
2347 | 2420 | else: |
|
2348 | 2421 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2349 | 2422 | |
|
2350 | 2423 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2351 | 2424 | # aliases won't work in indented sections. |
|
2352 | 2425 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2353 | 2426 | make_quoted_expr( transformed )) |
|
2354 | 2427 | |
|
2355 | 2428 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2356 | 2429 | #print 'line out:',line_out # dbg |
|
2357 | 2430 | return line_out |
|
2358 | 2431 | |
|
2359 | 2432 | def handle_shell_escape(self, line_info): |
|
2360 | 2433 | """Execute the line in a shell, empty return value""" |
|
2361 | 2434 | #print 'line in :', `line` # dbg |
|
2362 | 2435 | line = line_info.line |
|
2363 | 2436 | if line.lstrip().startswith('!!'): |
|
2364 | 2437 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2365 | 2438 | # call to %sx and the actual command to be executed, so |
|
2366 | 2439 | # handle_magic can work correctly. Note that this works even if |
|
2367 | 2440 | # the line is indented, so it handles multi_line_specials |
|
2368 | 2441 | # properly. |
|
2369 | 2442 | new_rest = line.lstrip()[2:] |
|
2370 | 2443 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2371 | 2444 | line_info.iFun = 'sx' |
|
2372 | 2445 | line_info.theRest = new_rest |
|
2373 | 2446 | return self.handle_magic(line_info) |
|
2374 | 2447 | else: |
|
2375 | 2448 | cmd = line.lstrip().lstrip('!') |
|
2376 | 2449 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2377 | 2450 | make_quoted_expr(cmd)) |
|
2378 | 2451 | # update cache/log and return |
|
2379 | 2452 | self.log(line,line_out,line_info.continue_prompt) |
|
2380 | 2453 | return line_out |
|
2381 | 2454 | |
|
2382 | 2455 | def handle_magic(self, line_info): |
|
2383 | 2456 | """Execute magic functions.""" |
|
2384 | 2457 | iFun = line_info.iFun |
|
2385 | 2458 | theRest = line_info.theRest |
|
2386 | 2459 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2387 | 2460 | make_quoted_expr(iFun + " " + theRest)) |
|
2388 | 2461 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2389 | 2462 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2390 | 2463 | return cmd |
|
2391 | 2464 | |
|
2392 | 2465 | def handle_auto(self, line_info): |
|
2393 | 2466 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2394 | 2467 | |
|
2395 | 2468 | line = line_info.line |
|
2396 | 2469 | iFun = line_info.iFun |
|
2397 | 2470 | theRest = line_info.theRest |
|
2398 | 2471 | pre = line_info.pre |
|
2399 | 2472 | continue_prompt = line_info.continue_prompt |
|
2400 | 2473 | obj = line_info.ofind(self)['obj'] |
|
2401 | 2474 | |
|
2402 | 2475 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2403 | 2476 | |
|
2404 | 2477 | # This should only be active for single-line input! |
|
2405 | 2478 | if continue_prompt: |
|
2406 | 2479 | self.log(line,line,continue_prompt) |
|
2407 | 2480 | return line |
|
2408 | 2481 | |
|
2409 | 2482 | force_auto = isinstance(obj, ipapi.IPyAutocall) |
|
2410 | 2483 | auto_rewrite = True |
|
2411 | 2484 | |
|
2412 | 2485 | if pre == self.ESC_QUOTE: |
|
2413 | 2486 | # Auto-quote splitting on whitespace |
|
2414 | 2487 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2415 | 2488 | elif pre == self.ESC_QUOTE2: |
|
2416 | 2489 | # Auto-quote whole string |
|
2417 | 2490 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2418 | 2491 | elif pre == self.ESC_PAREN: |
|
2419 | 2492 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2420 | 2493 | else: |
|
2421 | 2494 | # Auto-paren. |
|
2422 | 2495 | # We only apply it to argument-less calls if the autocall |
|
2423 | 2496 | # parameter is set to 2. We only need to check that autocall is < |
|
2424 | 2497 | # 2, since this function isn't called unless it's at least 1. |
|
2425 | 2498 | if not theRest and (self.autocall < 2) and not force_auto: |
|
2426 | 2499 | newcmd = '%s %s' % (iFun,theRest) |
|
2427 | 2500 | auto_rewrite = False |
|
2428 | 2501 | else: |
|
2429 | 2502 | if not force_auto and theRest.startswith('['): |
|
2430 | 2503 | if hasattr(obj,'__getitem__'): |
|
2431 | 2504 | # Don't autocall in this case: item access for an object |
|
2432 | 2505 | # which is BOTH callable and implements __getitem__. |
|
2433 | 2506 | newcmd = '%s %s' % (iFun,theRest) |
|
2434 | 2507 | auto_rewrite = False |
|
2435 | 2508 | else: |
|
2436 | 2509 | # if the object doesn't support [] access, go ahead and |
|
2437 | 2510 | # autocall |
|
2438 | 2511 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2439 | 2512 | elif theRest.endswith(';'): |
|
2440 | 2513 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2441 | 2514 | else: |
|
2442 | 2515 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2443 | 2516 | |
|
2444 | 2517 | if auto_rewrite: |
|
2445 | 2518 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2446 | 2519 | |
|
2447 | 2520 | try: |
|
2448 | 2521 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2449 | 2522 | # we use it and only print uncolored rewrite if we have unicode |
|
2450 | 2523 | rw = str(rw) |
|
2451 | 2524 | print >>Term.cout, rw |
|
2452 | 2525 | except UnicodeEncodeError: |
|
2453 | 2526 | print "-------------->" + newcmd |
|
2454 | 2527 | |
|
2455 | 2528 | # log what is now valid Python, not the actual user input (without the |
|
2456 | 2529 | # final newline) |
|
2457 | 2530 | self.log(line,newcmd,continue_prompt) |
|
2458 | 2531 | return newcmd |
|
2459 | 2532 | |
|
2460 | 2533 | def handle_help(self, line_info): |
|
2461 | 2534 | """Try to get some help for the object. |
|
2462 | 2535 | |
|
2463 | 2536 | obj? or ?obj -> basic information. |
|
2464 | 2537 | obj?? or ??obj -> more details. |
|
2465 | 2538 | """ |
|
2466 | 2539 | |
|
2467 | 2540 | line = line_info.line |
|
2468 | 2541 | # We need to make sure that we don't process lines which would be |
|
2469 | 2542 | # otherwise valid python, such as "x=1 # what?" |
|
2470 | 2543 | try: |
|
2471 | 2544 | codeop.compile_command(line) |
|
2472 | 2545 | except SyntaxError: |
|
2473 | 2546 | # We should only handle as help stuff which is NOT valid syntax |
|
2474 | 2547 | if line[0]==self.ESC_HELP: |
|
2475 | 2548 | line = line[1:] |
|
2476 | 2549 | elif line[-1]==self.ESC_HELP: |
|
2477 | 2550 | line = line[:-1] |
|
2478 | 2551 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2479 | 2552 | if line: |
|
2480 | 2553 | #print 'line:<%r>' % line # dbg |
|
2481 | 2554 | self.magic_pinfo(line) |
|
2482 | 2555 | else: |
|
2483 | page(self.usage,screen_lines=self.screen_length) | |
|
2556 | page(self.usage,screen_lines=self.usable_screen_length) | |
|
2484 | 2557 | return '' # Empty string is needed here! |
|
2485 | 2558 | except: |
|
2486 | 2559 | # Pass any other exceptions through to the normal handler |
|
2487 | 2560 | return self.handle_normal(line_info) |
|
2488 | 2561 | else: |
|
2489 | 2562 | # If the code compiles ok, we should handle it normally |
|
2490 | 2563 | return self.handle_normal(line_info) |
|
2491 | 2564 | |
|
2492 | 2565 | def getapi(self): |
|
2493 | 2566 | """ Get an IPApi object for this shell instance |
|
2494 | 2567 | |
|
2495 | 2568 | Getting an IPApi object is always preferable to accessing the shell |
|
2496 | 2569 | directly, but this holds true especially for extensions. |
|
2497 | 2570 | |
|
2498 | 2571 | It should always be possible to implement an extension with IPApi |
|
2499 | 2572 | alone. If not, contact maintainer to request an addition. |
|
2500 | 2573 | |
|
2501 | 2574 | """ |
|
2502 | 2575 | return self.api |
|
2503 | 2576 | |
|
2504 | 2577 | def handle_emacs(self, line_info): |
|
2505 | 2578 | """Handle input lines marked by python-mode.""" |
|
2506 | 2579 | |
|
2507 | 2580 | # Currently, nothing is done. Later more functionality can be added |
|
2508 | 2581 | # here if needed. |
|
2509 | 2582 | |
|
2510 | 2583 | # The input cache shouldn't be updated |
|
2511 | 2584 | return line_info.line |
|
2512 | 2585 | |
|
2513 | 2586 | def var_expand(self,cmd,depth=0): |
|
2514 | 2587 | """Expand python variables in a string. |
|
2515 | 2588 | |
|
2516 | 2589 | The depth argument indicates how many frames above the caller should |
|
2517 | 2590 | be walked to look for the local namespace where to expand variables. |
|
2518 | 2591 | |
|
2519 | 2592 | The global namespace for expansion is always the user's interactive |
|
2520 | 2593 | namespace. |
|
2521 | 2594 | """ |
|
2522 | 2595 | |
|
2523 | 2596 | return str(ItplNS(cmd, |
|
2524 | 2597 | self.user_ns, # globals |
|
2525 | 2598 | # Skip our own frame in searching for locals: |
|
2526 | 2599 | sys._getframe(depth+1).f_locals # locals |
|
2527 | 2600 | )) |
|
2528 | 2601 | |
|
2529 | 2602 | def mktempfile(self,data=None): |
|
2530 | 2603 | """Make a new tempfile and return its filename. |
|
2531 | 2604 | |
|
2532 | 2605 | This makes a call to tempfile.mktemp, but it registers the created |
|
2533 | 2606 | filename internally so ipython cleans it up at exit time. |
|
2534 | 2607 | |
|
2535 | 2608 | Optional inputs: |
|
2536 | 2609 | |
|
2537 | 2610 | - data(None): if data is given, it gets written out to the temp file |
|
2538 | 2611 | immediately, and the file is closed again.""" |
|
2539 | 2612 | |
|
2540 | 2613 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2541 | 2614 | self.tempfiles.append(filename) |
|
2542 | 2615 | |
|
2543 | 2616 | if data: |
|
2544 | 2617 | tmp_file = open(filename,'w') |
|
2545 | 2618 | tmp_file.write(data) |
|
2546 | 2619 | tmp_file.close() |
|
2547 | 2620 | return filename |
|
2548 | 2621 | |
|
2549 | 2622 | def write(self,data): |
|
2550 | 2623 | """Write a string to the default output""" |
|
2551 | 2624 | Term.cout.write(data) |
|
2552 | 2625 | |
|
2553 | 2626 | def write_err(self,data): |
|
2554 | 2627 | """Write a string to the default error output""" |
|
2555 | 2628 | Term.cerr.write(data) |
|
2556 | 2629 | |
|
2557 | 2630 | def ask_exit(self): |
|
2558 | 2631 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2559 | 2632 | self.exit_now = True |
|
2560 | 2633 | |
|
2561 | 2634 | def exit(self): |
|
2562 | 2635 | """Handle interactive exit. |
|
2563 | 2636 | |
|
2564 | 2637 | This method calls the ask_exit callback.""" |
|
2565 | print "IN self.exit", self.confirm_exit | |
|
2566 | 2638 | if self.confirm_exit: |
|
2567 | 2639 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2568 | 2640 | self.ask_exit() |
|
2569 | 2641 | else: |
|
2570 | 2642 | self.ask_exit() |
|
2571 | 2643 | |
|
2572 | 2644 | def safe_execfile(self,fname,*where,**kw): |
|
2573 | 2645 | """A safe version of the builtin execfile(). |
|
2574 | 2646 | |
|
2575 | 2647 | This version will never throw an exception, and knows how to handle |
|
2576 | 2648 | ipython logs as well. |
|
2577 | 2649 | |
|
2578 | 2650 | :Parameters: |
|
2579 | 2651 | fname : string |
|
2580 | 2652 | Name of the file to be executed. |
|
2581 | 2653 | |
|
2582 | 2654 | where : tuple |
|
2583 | 2655 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2584 | 2656 | If only one is given, it is passed as both. |
|
2585 | 2657 | |
|
2586 | 2658 | :Keywords: |
|
2587 | 2659 | islog : boolean (False) |
|
2588 | 2660 | |
|
2589 | 2661 | quiet : boolean (True) |
|
2590 | 2662 | |
|
2591 | 2663 | exit_ignore : boolean (False) |
|
2592 | 2664 | """ |
|
2593 | 2665 | |
|
2594 | 2666 | def syspath_cleanup(): |
|
2595 | 2667 | """Internal cleanup routine for sys.path.""" |
|
2596 | 2668 | if add_dname: |
|
2597 | 2669 | try: |
|
2598 | 2670 | sys.path.remove(dname) |
|
2599 | 2671 | except ValueError: |
|
2600 | 2672 | # For some reason the user has already removed it, ignore. |
|
2601 | 2673 | pass |
|
2602 | 2674 | |
|
2603 | 2675 | fname = os.path.expanduser(fname) |
|
2604 | 2676 | |
|
2605 | 2677 | # Find things also in current directory. This is needed to mimic the |
|
2606 | 2678 | # behavior of running a script from the system command line, where |
|
2607 | 2679 | # Python inserts the script's directory into sys.path |
|
2608 | 2680 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2609 | 2681 | add_dname = False |
|
2610 | 2682 | if dname not in sys.path: |
|
2611 | 2683 | sys.path.insert(0,dname) |
|
2612 | 2684 | add_dname = True |
|
2613 | 2685 | |
|
2614 | 2686 | try: |
|
2615 | 2687 | xfile = open(fname) |
|
2616 | 2688 | except: |
|
2617 | 2689 | print >> Term.cerr, \ |
|
2618 | 2690 | 'Could not open file <%s> for safe execution.' % fname |
|
2619 | 2691 | syspath_cleanup() |
|
2620 | 2692 | return None |
|
2621 | 2693 | |
|
2622 | 2694 | kw.setdefault('islog',0) |
|
2623 | 2695 | kw.setdefault('quiet',1) |
|
2624 | 2696 | kw.setdefault('exit_ignore',0) |
|
2625 | 2697 | |
|
2626 | 2698 | first = xfile.readline() |
|
2627 | 2699 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2628 | 2700 | xfile.close() |
|
2629 | 2701 | # line by line execution |
|
2630 | 2702 | if first.startswith(loghead) or kw['islog']: |
|
2631 | 2703 | print 'Loading log file <%s> one line at a time...' % fname |
|
2632 | 2704 | if kw['quiet']: |
|
2633 | 2705 | stdout_save = sys.stdout |
|
2634 | 2706 | sys.stdout = StringIO.StringIO() |
|
2635 | 2707 | try: |
|
2636 | 2708 | globs,locs = where[0:2] |
|
2637 | 2709 | except: |
|
2638 | 2710 | try: |
|
2639 | 2711 | globs = locs = where[0] |
|
2640 | 2712 | except: |
|
2641 | 2713 | globs = locs = globals() |
|
2642 | 2714 | badblocks = [] |
|
2643 | 2715 | |
|
2644 | 2716 | # we also need to identify indented blocks of code when replaying |
|
2645 | 2717 | # logs and put them together before passing them to an exec |
|
2646 | 2718 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2647 | 2719 | # file. It's easiest if we swallow the whole thing in memory |
|
2648 | 2720 | # first, and manually walk through the lines list moving the |
|
2649 | 2721 | # counter ourselves. |
|
2650 | 2722 | indent_re = re.compile('\s+\S') |
|
2651 | 2723 | xfile = open(fname) |
|
2652 | 2724 | filelines = xfile.readlines() |
|
2653 | 2725 | xfile.close() |
|
2654 | 2726 | nlines = len(filelines) |
|
2655 | 2727 | lnum = 0 |
|
2656 | 2728 | while lnum < nlines: |
|
2657 | 2729 | line = filelines[lnum] |
|
2658 | 2730 | lnum += 1 |
|
2659 | 2731 | # don't re-insert logger status info into cache |
|
2660 | 2732 | if line.startswith('#log#'): |
|
2661 | 2733 | continue |
|
2662 | 2734 | else: |
|
2663 | 2735 | # build a block of code (maybe a single line) for execution |
|
2664 | 2736 | block = line |
|
2665 | 2737 | try: |
|
2666 | 2738 | next = filelines[lnum] # lnum has already incremented |
|
2667 | 2739 | except: |
|
2668 | 2740 | next = None |
|
2669 | 2741 | while next and indent_re.match(next): |
|
2670 | 2742 | block += next |
|
2671 | 2743 | lnum += 1 |
|
2672 | 2744 | try: |
|
2673 | 2745 | next = filelines[lnum] |
|
2674 | 2746 | except: |
|
2675 | 2747 | next = None |
|
2676 | 2748 | # now execute the block of one or more lines |
|
2677 | 2749 | try: |
|
2678 | 2750 | exec block in globs,locs |
|
2679 | 2751 | except SystemExit: |
|
2680 | 2752 | pass |
|
2681 | 2753 | except: |
|
2682 | 2754 | badblocks.append(block.rstrip()) |
|
2683 | 2755 | if kw['quiet']: # restore stdout |
|
2684 | 2756 | sys.stdout.close() |
|
2685 | 2757 | sys.stdout = stdout_save |
|
2686 | 2758 | print 'Finished replaying log file <%s>' % fname |
|
2687 | 2759 | if badblocks: |
|
2688 | 2760 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2689 | 2761 | '<%s> reported errors:' % fname) |
|
2690 | 2762 | |
|
2691 | 2763 | for badline in badblocks: |
|
2692 | 2764 | print >> sys.stderr, badline |
|
2693 | 2765 | else: # regular file execution |
|
2694 | 2766 | try: |
|
2695 | 2767 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2696 | 2768 | # Work around a bug in Python for Windows. The bug was |
|
2697 | 2769 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2698 | 2770 | # SVN Python as of March/07. For details, see: |
|
2699 | 2771 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2700 | 2772 | try: |
|
2701 | 2773 | globs,locs = where[0:2] |
|
2702 | 2774 | except: |
|
2703 | 2775 | try: |
|
2704 | 2776 | globs = locs = where[0] |
|
2705 | 2777 | except: |
|
2706 | 2778 | globs = locs = globals() |
|
2707 | 2779 | exec file(fname) in globs,locs |
|
2708 | 2780 | else: |
|
2709 | 2781 | execfile(fname,*where) |
|
2710 | 2782 | except SyntaxError: |
|
2711 | 2783 | self.showsyntaxerror() |
|
2712 | 2784 | warn('Failure executing file: <%s>' % fname) |
|
2713 | 2785 | except SystemExit,status: |
|
2714 | 2786 | # Code that correctly sets the exit status flag to success (0) |
|
2715 | 2787 | # shouldn't be bothered with a traceback. Note that a plain |
|
2716 | 2788 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2717 | 2789 | # will still get a traceback. Note that the structure of the |
|
2718 | 2790 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2719 | 2791 | # the checks must be done in a version-dependent way. |
|
2720 | 2792 | show = False |
|
2721 | 2793 | |
|
2722 | 2794 | if sys.version_info[:2] > (2,5): |
|
2723 | 2795 | if status.message!=0 and not kw['exit_ignore']: |
|
2724 | 2796 | show = True |
|
2725 | 2797 | else: |
|
2726 | 2798 | if status.code and not kw['exit_ignore']: |
|
2727 | 2799 | show = True |
|
2728 | 2800 | if show: |
|
2729 | 2801 | self.showtraceback() |
|
2730 | 2802 | warn('Failure executing file: <%s>' % fname) |
|
2731 | 2803 | except: |
|
2732 | 2804 | self.showtraceback() |
|
2733 | 2805 | warn('Failure executing file: <%s>' % fname) |
|
2734 | 2806 | |
|
2735 | 2807 | syspath_cleanup() |
|
2736 | 2808 | |
|
2737 | 2809 | #************************* end of file <iplib.py> ***************************** |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,586 +1,588 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | #***************************************************************************** |
|
3 | 3 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
4 | 4 | # |
|
5 | 5 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | 6 | # the file COPYING, distributed as part of this software. |
|
7 | 7 | #***************************************************************************** |
|
8 | 8 | |
|
9 | 9 | import sys |
|
10 | 10 | from IPython.core import release |
|
11 | 11 | |
|
12 | 12 | __doc__ = """ |
|
13 | 13 | IPython -- An enhanced Interactive Python |
|
14 | 14 | ========================================= |
|
15 | 15 | |
|
16 | 16 | A Python shell with automatic history (input and output), dynamic object |
|
17 | 17 | introspection, easier configuration, command completion, access to the system |
|
18 | 18 | shell and more. |
|
19 | 19 | |
|
20 | 20 | IPython can also be embedded in running programs. See EMBEDDING below. |
|
21 | 21 | |
|
22 | 22 | |
|
23 | 23 | USAGE |
|
24 | 24 | ipython [options] files |
|
25 | 25 | |
|
26 | 26 | If invoked with no options, it executes all the files listed in |
|
27 | 27 | sequence and drops you into the interpreter while still acknowledging |
|
28 | 28 | any options you may have set in your ipythonrc file. This behavior is |
|
29 | 29 | different from standard Python, which when called as python -i will |
|
30 | 30 | only execute one file and will ignore your configuration setup. |
|
31 | 31 | |
|
32 | 32 | Please note that some of the configuration options are not available at |
|
33 | 33 | the command line, simply because they are not practical here. Look into |
|
34 | 34 | your ipythonrc configuration file for details on those. This file |
|
35 | 35 | typically installed in the $HOME/.ipython directory. |
|
36 | 36 | |
|
37 | 37 | For Windows users, $HOME resolves to C:\\Documents and |
|
38 | 38 | Settings\\YourUserName in most instances, and _ipython is used instead |
|
39 | 39 | of .ipython, since some Win32 programs have problems with dotted names |
|
40 | 40 | in directories. |
|
41 | 41 | |
|
42 | 42 | In the rest of this text, we will refer to this directory as |
|
43 | 43 | IPYTHONDIR. |
|
44 | 44 | |
|
45 | 45 | REGULAR OPTIONS |
|
46 | 46 | After the above threading options have been given, regular options can |
|
47 | 47 | follow in any order. All options can be abbreviated to their shortest |
|
48 | 48 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
49 | 49 | used. Some options have an alternate short form, indicated after a |. |
|
50 | 50 | |
|
51 | 51 | Most options can also be set from your ipythonrc configuration file. |
|
52 | 52 | See the provided examples for assistance. Options given on the comman- |
|
53 | 53 | dline override the values set in the ipythonrc file. |
|
54 | 54 | |
|
55 | 55 | All options with a [no] prepended can be specified in negated form |
|
56 | 56 | (using -nooption instead of -option) to turn the feature off. |
|
57 | 57 | |
|
58 | 58 | -h, --help |
|
59 | 59 | Show summary of options. |
|
60 | 60 | |
|
61 | 61 | -autocall <val> |
|
62 | 62 | Make IPython automatically call any callable object even if you |
|
63 | 63 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
64 | 64 | 'str(43)' automatically. The value can be '0' to disable the |
|
65 | 65 | feature, '1' for 'smart' autocall, where it is not applied if |
|
66 | 66 | there are no more arguments on the line, and '2' for 'full' |
|
67 | 67 | autocall, where all callable objects are automatically called |
|
68 | 68 | (even if no arguments are present). The default is '1'. |
|
69 | 69 | |
|
70 | 70 | -[no]autoindent |
|
71 | 71 | Turn automatic indentation on/off. |
|
72 | 72 | |
|
73 | 73 | -[no]automagic |
|
74 | 74 | Make magic commands automatic (without needing their first char- |
|
75 | 75 | acter to be %). Type %magic at the IPython prompt for more |
|
76 | 76 | information. |
|
77 | 77 | |
|
78 | 78 | -[no]autoedit_syntax |
|
79 | 79 | When a syntax error occurs after editing a file, automatically |
|
80 | 80 | open the file to the trouble causing line for convenient fixing. |
|
81 | 81 | |
|
82 | 82 | -[no]banner |
|
83 | 83 | Print the intial information banner (default on). |
|
84 | 84 | |
|
85 | 85 | -c <command> |
|
86 | 86 | Execute the given command string, and set sys.argv to ['c']. |
|
87 | 87 | This is similar to the -c option in the normal Python inter- |
|
88 | 88 | preter. |
|
89 | 89 | |
|
90 | 90 | -cache_size|cs <n> |
|
91 | 91 | Size of the output cache (maximum number of entries to hold in |
|
92 | 92 | memory). The default is 1000, you can change it permanently in |
|
93 | 93 | your config file. Setting it to 0 completely disables the |
|
94 | 94 | caching system, and the minimum value accepted is 20 (if you |
|
95 | 95 | provide a value less than 20, it is reset to 0 and a warning is |
|
96 | 96 | issued). This limit is defined because otherwise you'll spend |
|
97 | 97 | more time re-flushing a too small cache than working. |
|
98 | 98 | |
|
99 | 99 | -classic|cl |
|
100 | 100 | Gives IPython a similar feel to the classic Python prompt. |
|
101 | 101 | |
|
102 | 102 | -colors <scheme> |
|
103 | 103 | Color scheme for prompts and exception reporting. Currently |
|
104 | 104 | implemented: NoColor, Linux, and LightBG. |
|
105 | 105 | |
|
106 | 106 | -[no]color_info |
|
107 | 107 | IPython can display information about objects via a set of func- |
|
108 | 108 | tions, and optionally can use colors for this, syntax highlight- |
|
109 | 109 | ing source code and various other elements. However, because |
|
110 | 110 | this information is passed through a pager (like 'less') and |
|
111 | 111 | many pagers get confused with color codes, this option is off by |
|
112 | 112 | default. You can test it and turn it on permanently in your |
|
113 | 113 | ipythonrc file if it works for you. As a reference, the 'less' |
|
114 | 114 | pager supplied with Mandrake 8.2 works ok, but that in RedHat |
|
115 | 115 | 7.2 doesn't. |
|
116 | 116 | |
|
117 | 117 | Test it and turn it on permanently if it works with your system. |
|
118 | 118 | The magic function @color_info allows you to toggle this inter- |
|
119 | 119 | actively for testing. |
|
120 | 120 | |
|
121 | 121 | -[no]confirm_exit |
|
122 | 122 | Set to confirm when you try to exit IPython with an EOF (Con- |
|
123 | 123 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the |
|
124 | 124 | magic functions @Exit or @Quit you can force a direct exit, |
|
125 | 125 | bypassing any confirmation. |
|
126 | 126 | |
|
127 | 127 | -[no]debug |
|
128 | 128 | Show information about the loading process. Very useful to pin |
|
129 | 129 | down problems with your configuration files or to get details |
|
130 | 130 | about session restores. |
|
131 | 131 | |
|
132 | 132 | -[no]deep_reload |
|
133 | 133 | IPython can use the deep_reload module which reloads changes in |
|
134 | 134 | modules recursively (it replaces the reload() function, so you |
|
135 | 135 | don't need to change anything to use it). deep_reload() forces a |
|
136 | 136 | full reload of modules whose code may have changed, which the |
|
137 | 137 | default reload() function does not. |
|
138 | 138 | |
|
139 | 139 | When deep_reload is off, IPython will use the normal reload(), |
|
140 | 140 | but deep_reload will still be available as dreload(). This fea- |
|
141 | 141 | ture is off by default [which means that you have both normal |
|
142 | 142 | reload() and dreload()]. |
|
143 | 143 | |
|
144 | 144 | -editor <name> |
|
145 | 145 | Which editor to use with the @edit command. By default, IPython |
|
146 | 146 | will honor your EDITOR environment variable (if not set, vi is |
|
147 | 147 | the Unix default and notepad the Windows one). Since this editor |
|
148 | 148 | is invoked on the fly by IPython and is meant for editing small |
|
149 | 149 | code snippets, you may want to use a small, lightweight editor |
|
150 | 150 | here (in case your default EDITOR is something like Emacs). |
|
151 | 151 | |
|
152 | 152 | -ipythondir <name> |
|
153 | 153 | The name of your IPython configuration directory IPYTHONDIR. |
|
154 | 154 | This can also be specified through the environment variable |
|
155 | 155 | IPYTHONDIR. |
|
156 | 156 | |
|
157 | 157 | -log|l Generate a log file of all input. The file is named |
|
158 | 158 | ipython_log.py in your current directory (which prevents logs |
|
159 | 159 | from multiple IPython sessions from trampling each other). You |
|
160 | 160 | can use this to later restore a session by loading your logfile |
|
161 | 161 | as a file to be executed with option -logplay (see below). |
|
162 | 162 | |
|
163 | 163 | -logfile|lf |
|
164 | 164 | Specify the name of your logfile. |
|
165 | 165 | |
|
166 | 166 | -logplay|lp |
|
167 | 167 | Replay a previous log. For restoring a session as close as pos- |
|
168 | 168 | sible to the state you left it in, use this option (don't just |
|
169 | 169 | run the logfile). With -logplay, IPython will try to reconstruct |
|
170 | 170 | the previous working environment in full, not just execute the |
|
171 | 171 | commands in the logfile. |
|
172 | 172 | When a session is restored, logging is automatically turned on |
|
173 | 173 | again with the name of the logfile it was invoked with (it is |
|
174 | 174 | read from the log header). So once you've turned logging on for |
|
175 | 175 | a session, you can quit IPython and reload it as many times as |
|
176 | 176 | you want and it will continue to log its history and restore |
|
177 | 177 | from the beginning every time. |
|
178 | 178 | |
|
179 | 179 | Caveats: there are limitations in this option. The history vari- |
|
180 | 180 | ables _i*,_* and _dh don't get restored properly. In the future |
|
181 | 181 | we will try to implement full session saving by writing and |
|
182 | 182 | retrieving a failed because of inherent limitations of Python's |
|
183 | 183 | Pickle module, so this may have to wait. |
|
184 | 184 | |
|
185 | 185 | -[no]messages |
|
186 | 186 | Print messages which IPython collects about its startup process |
|
187 | 187 | (default on). |
|
188 | 188 | |
|
189 | 189 | -[no]pdb |
|
190 | 190 | Automatically call the pdb debugger after every uncaught excep- |
|
191 | 191 | tion. If you are used to debugging using pdb, this puts you |
|
192 | 192 | automatically inside of it after any call (either in IPython or |
|
193 | 193 | in code called by it) which triggers an exception which goes |
|
194 | 194 | uncaught. |
|
195 | 195 | |
|
196 | 196 | -[no]pprint |
|
197 | 197 | IPython can optionally use the pprint (pretty printer) module |
|
198 | 198 | for displaying results. pprint tends to give a nicer display of |
|
199 | 199 | nested data structures. If you like it, you can turn it on per- |
|
200 | 200 | manently in your config file (default off). |
|
201 | 201 | |
|
202 | 202 | -profile|p <name> |
|
203 | 203 | Assume that your config file is ipythonrc-<name> (looks in cur- |
|
204 | 204 | rent dir first, then in IPYTHONDIR). This is a quick way to keep |
|
205 | 205 | and load multiple config files for different tasks, especially |
|
206 | 206 | if you use the include option of config files. You can keep a |
|
207 | 207 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' |
|
208 | 208 | which include this one and load extra things for particular |
|
209 | 209 | tasks. For example: |
|
210 | 210 | |
|
211 | 211 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. |
|
212 | 212 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- |
|
213 | 213 | related modules. |
|
214 | 214 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and |
|
215 | 215 | plotting modules. |
|
216 | 216 | |
|
217 | 217 | Since it is possible to create an endless loop by having circu- |
|
218 | 218 | lar file inclusions, IPython will stop if it reaches 15 recur- |
|
219 | 219 | sive inclusions. |
|
220 | 220 | |
|
221 | 221 | -prompt_in1|pi1 <string> |
|
222 | 222 | Specify the string used for input prompts. Note that if you are |
|
223 | 223 | using numbered prompts, the number is represented with a '\#' in |
|
224 | 224 | the string. Don't forget to quote strings with spaces embedded |
|
225 | 225 | in them. Default: 'In [\#]: '. |
|
226 | 226 | |
|
227 | 227 | Most bash-like escapes can be used to customize IPython's |
|
228 | 228 | prompts, as well as a few additional ones which are IPython-spe- |
|
229 | 229 | cific. All valid prompt escapes are described in detail in the |
|
230 | 230 | Customization section of the IPython HTML/PDF manual. |
|
231 | 231 | |
|
232 | 232 | -prompt_in2|pi2 <string> |
|
233 | 233 | Similar to the previous option, but used for the continuation |
|
234 | 234 | prompts. The special sequence '\D' is similar to '\#', but with |
|
235 | 235 | all digits replaced dots (so you can have your continuation |
|
236 | 236 | prompt aligned with your input prompt). Default: ' .\D.: ' |
|
237 | 237 | (note three spaces at the start for alignment with 'In [\#]'). |
|
238 | 238 | |
|
239 | 239 | -prompt_out|po <string> |
|
240 | 240 | String used for output prompts, also uses numbers like |
|
241 | 241 | prompt_in1. Default: 'Out[\#]:'. |
|
242 | 242 | |
|
243 | 243 | -quick Start in bare bones mode (no config file loaded). |
|
244 | 244 | |
|
245 | 245 | -rcfile <name> |
|
246 | 246 | Name of your IPython resource configuration file. normally |
|
247 | 247 | IPython loads ipythonrc (from current directory) or |
|
248 | 248 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, |
|
249 | 249 | IPython starts with a bare bones configuration (no modules |
|
250 | 250 | loaded at all). |
|
251 | 251 | |
|
252 | 252 | -[no]readline |
|
253 | 253 | Use the readline library, which is needed to support name com- |
|
254 | 254 | pletion and command history, among other things. It is enabled |
|
255 | 255 | by default, but may cause problems for users of X/Emacs in |
|
256 | 256 | Python comint or shell buffers. |
|
257 | 257 | |
|
258 | 258 | Note that emacs 'eterm' buffers (opened with M-x term) support |
|
259 | 259 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
260 | 260 | shell and C-c !) buffers do not. |
|
261 | 261 | |
|
262 | 262 | -screen_length|sl <n> |
|
263 | 263 | Number of lines of your screen. This is used to control print- |
|
264 | 264 | ing of very long strings. Strings longer than this number of |
|
265 | 265 | lines will be sent through a pager instead of directly printed. |
|
266 | 266 | |
|
267 | 267 | The default value for this is 0, which means IPython will auto- |
|
268 | 268 | detect your screen size every time it needs to print certain |
|
269 | 269 | potentially long strings (this doesn't change the behavior of |
|
270 | 270 | the 'print' keyword, it's only triggered internally). If for |
|
271 | 271 | some reason this isn't working well (it needs curses support), |
|
272 | 272 | specify it yourself. Otherwise don't change the default. |
|
273 | 273 | |
|
274 | 274 | -separate_in|si <string> |
|
275 | 275 | Separator before input prompts. Default '0. |
|
276 | 276 | |
|
277 | 277 | -separate_out|so <string> |
|
278 | 278 | Separator before output prompts. Default: 0 (nothing). |
|
279 | 279 | |
|
280 | 280 | -separate_out2|so2 <string> |
|
281 | 281 | Separator after output prompts. Default: 0 (nothing). |
|
282 | 282 | |
|
283 | 283 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. |
|
284 | 284 | Simply removes all input/output separators. |
|
285 | 285 | |
|
286 | 286 | -upgrade |
|
287 | 287 | Allows you to upgrade your IPYTHONDIR configuration when you |
|
288 | 288 | install a new version of IPython. Since new versions may |
|
289 | 289 | include new command lines options or example files, this copies |
|
290 | 290 | updated ipythonrc-type files. However, it backs up (with a .old |
|
291 | 291 | extension) all files which it overwrites so that you can merge |
|
292 | 292 | back any custimizations you might have in your personal files. |
|
293 | 293 | |
|
294 | 294 | -Version |
|
295 | 295 | Print version information and exit. |
|
296 | 296 | |
|
297 | 297 | -wxversion <string> |
|
298 | 298 | Select a specific version of wxPython (used in conjunction with |
|
299 | 299 | -wthread). Requires the wxversion module, part of recent |
|
300 | 300 | wxPython distributions. |
|
301 | 301 | |
|
302 | 302 | -xmode <modename> |
|
303 | 303 | Mode for exception reporting. The valid modes are Plain, Con- |
|
304 | 304 | text, and Verbose. |
|
305 | 305 | |
|
306 | 306 | - Plain: similar to python's normal traceback printing. |
|
307 | 307 | |
|
308 | 308 | - Context: prints 5 lines of context source code around each |
|
309 | 309 | line in the traceback. |
|
310 | 310 | |
|
311 | 311 | - Verbose: similar to Context, but additionally prints the vari- |
|
312 | 312 | ables currently visible where the exception happened (shortening |
|
313 | 313 | their strings if too long). This can potentially be very slow, |
|
314 | 314 | if you happen to have a huge data structure whose string repre- |
|
315 | 315 | sentation is complex to compute. Your computer may appear to |
|
316 | 316 | freeze for a while with cpu usage at 100%. If this occurs, you |
|
317 | 317 | can cancel the traceback with Ctrl-C (maybe hitting it more than |
|
318 | 318 | once). |
|
319 | 319 | |
|
320 | 320 | |
|
321 | 321 | EMBEDDING |
|
322 | 322 | It is possible to start an IPython instance inside your own Python pro- |
|
323 | 323 | grams. In the documentation example files there are some illustrations |
|
324 | 324 | on how to do this. |
|
325 | 325 | |
|
326 | 326 | This feature allows you to evalutate dynamically the state of your |
|
327 | 327 | code, operate with your variables, analyze them, etc. Note however |
|
328 | 328 | that any changes you make to values while in the shell do NOT propagate |
|
329 | 329 | back to the running code, so it is safe to modify your values because |
|
330 | 330 | you won't break your code in bizarre ways by doing so. |
|
331 | 331 | """ |
|
332 | 332 | |
|
333 | 333 | cmd_line_usage = __doc__ |
|
334 | 334 | |
|
335 | 335 | #--------------------------------------------------------------------------- |
|
336 | 336 | interactive_usage = """ |
|
337 | 337 | IPython -- An enhanced Interactive Python |
|
338 | 338 | ========================================= |
|
339 | 339 | |
|
340 | 340 | IPython offers a combination of convenient shell features, special commands |
|
341 | 341 | and a history mechanism for both input (command history) and output (results |
|
342 | 342 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
343 | 343 | replacement for the standard Python interpreter, while offering vastly |
|
344 | 344 | improved functionality and flexibility. |
|
345 | 345 | |
|
346 | 346 | At your system command line, type 'ipython -help' to see the command line |
|
347 | 347 | options available. This document only describes interactive features. |
|
348 | 348 | |
|
349 | 349 | Warning: IPython relies on the existence of a global variable called __IP which |
|
350 | 350 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
351 | 351 | will quickly occur. |
|
352 | 352 | |
|
353 | 353 | MAIN FEATURES |
|
354 | 354 | |
|
355 | 355 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
356 | 356 | available with access to object docstrings and the Python manuals. Simply |
|
357 | 357 | type 'help' (no quotes) to access it. |
|
358 | 358 | |
|
359 | 359 | * Magic commands: type %magic for information on the magic subsystem. |
|
360 | 360 | |
|
361 | 361 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
362 | 362 | |
|
363 | 363 | * Dynamic object information: |
|
364 | 364 | |
|
365 | 365 | Typing ?word or word? prints detailed information about an object. If |
|
366 | 366 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
367 | 367 | snipped in the center for brevity. |
|
368 | 368 | |
|
369 | 369 | Typing ??word or word?? gives access to the full information without |
|
370 | 370 | snipping long strings. Long strings are sent to the screen through the less |
|
371 | 371 | pager if longer than the screen, printed otherwise. |
|
372 | 372 | |
|
373 | 373 | The ?/?? system gives access to the full source code for any object (if |
|
374 | 374 | available), shows function prototypes and other useful information. |
|
375 | 375 | |
|
376 | 376 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
377 | 377 | quotes, and without % if you have automagic on). |
|
378 | 378 | |
|
379 | 379 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
380 | 380 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
381 | 381 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
382 | 382 | similarly. |
|
383 | 383 | |
|
384 | 384 | * Completion in the local namespace, by typing TAB at the prompt. |
|
385 | 385 | |
|
386 | 386 | At any time, hitting tab will complete any available python commands or |
|
387 | 387 | variable names, and show you a list of the possible completions if there's |
|
388 | 388 | no unambiguous one. It will also complete filenames in the current directory. |
|
389 | 389 | |
|
390 | 390 | This feature requires the readline and rlcomplete modules, so it won't work |
|
391 | 391 | if your Python lacks readline support (such as under Windows). |
|
392 | 392 | |
|
393 | 393 | * Search previous command history in two ways (also requires readline): |
|
394 | 394 | |
|
395 | 395 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
396 | 396 | search through only the history items that match what you've typed so |
|
397 | 397 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
398 | 398 | normal arrow keys. |
|
399 | 399 | |
|
400 | 400 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
401 | 401 | your history for lines that match what you've typed so far, completing as |
|
402 | 402 | much as it can. |
|
403 | 403 | |
|
404 | 404 | * Persistent command history across sessions (readline required). |
|
405 | 405 | |
|
406 | 406 | * Logging of input with the ability to save and restore a working session. |
|
407 | 407 | |
|
408 | 408 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
409 | 409 | |
|
410 | 410 | * The reload command does a 'deep' reload of a module: changes made to the |
|
411 | 411 | module since you imported will actually be available without having to exit. |
|
412 | 412 | |
|
413 | 413 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
414 | 414 | xcolor functions for details (just type %magic). |
|
415 | 415 | |
|
416 | 416 | * Input caching system: |
|
417 | 417 | |
|
418 | 418 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
419 | 419 | input is saved and can be retrieved as variables (besides the usual arrow |
|
420 | 420 | key recall). |
|
421 | 421 | |
|
422 | 422 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
423 | 423 | _i: stores previous input. |
|
424 | 424 | _ii: next previous. |
|
425 | 425 | _iii: next-next previous. |
|
426 | 426 | _ih : a list of all input _ih[n] is the input from line n. |
|
427 | 427 | |
|
428 | 428 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
429 | 429 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
430 | 430 | |
|
431 | 431 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
432 | 432 | |
|
433 | 433 | You can create macros which contain multiple input lines from this history, |
|
434 | 434 | for later re-execution, with the %macro function. |
|
435 | 435 | |
|
436 | 436 | The history function %hist allows you to see any part of your input history |
|
437 | 437 | by printing a range of the _i variables. Note that inputs which contain |
|
438 | 438 | magic functions (%) appear in the history with a prepended comment. This is |
|
439 | 439 | because they aren't really valid Python code, so you can't exec them. |
|
440 | 440 | |
|
441 | 441 | * Output caching system: |
|
442 | 442 | |
|
443 | 443 | For output that is returned from actions, a system similar to the input |
|
444 | 444 | cache exists but using _ instead of _i. Only actions that produce a result |
|
445 | 445 | (NOT assignments, for example) are cached. If you are familiar with |
|
446 | 446 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
447 | 447 | variables. |
|
448 | 448 | |
|
449 | 449 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
450 | 450 | _ (one underscore): previous output. |
|
451 | 451 | __ (two underscores): next previous. |
|
452 | 452 | ___ (three underscores): next-next previous. |
|
453 | 453 | |
|
454 | 454 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
455 | 455 | counter), such that the result of output <n> is always available as _<n>. |
|
456 | 456 | |
|
457 | 457 | Finally, a global dictionary named _oh exists with entries for all lines |
|
458 | 458 | which generated output. |
|
459 | 459 | |
|
460 | 460 | * Directory history: |
|
461 | 461 | |
|
462 | 462 | Your history of visited directories is kept in the global list _dh, and the |
|
463 | 463 | magic %cd command can be used to go to any entry in that list. |
|
464 | 464 | |
|
465 | 465 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
466 | 466 | |
|
467 | 467 | 1. Auto-parentheses |
|
468 | 468 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
469 | 469 | this (notice the commas between the arguments): |
|
470 | 470 | >>> callable_ob arg1, arg2, arg3 |
|
471 | 471 | and the input will be translated to this: |
|
472 | 472 | --> callable_ob(arg1, arg2, arg3) |
|
473 | 473 | You can force auto-parentheses by using '/' as the first character |
|
474 | 474 | of a line. For example: |
|
475 | 475 | >>> /globals # becomes 'globals()' |
|
476 | 476 | Note that the '/' MUST be the first character on the line! This |
|
477 | 477 | won't work: |
|
478 | 478 | >>> print /globals # syntax error |
|
479 | 479 | |
|
480 | 480 | In most cases the automatic algorithm should work, so you should |
|
481 | 481 | rarely need to explicitly invoke /. One notable exception is if you |
|
482 | 482 | are trying to call a function with a list of tuples as arguments (the |
|
483 | 483 | parenthesis will confuse IPython): |
|
484 | 484 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
485 | 485 | but this will work: |
|
486 | 486 | In [2]: /zip (1,2,3),(4,5,6) |
|
487 | 487 | ------> zip ((1,2,3),(4,5,6)) |
|
488 | 488 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
489 | 489 | |
|
490 | 490 | IPython tells you that it has altered your command line by |
|
491 | 491 | displaying the new command line preceded by -->. e.g.: |
|
492 | 492 | In [18]: callable list |
|
493 | 493 | -------> callable (list) |
|
494 | 494 | |
|
495 | 495 | 2. Auto-Quoting |
|
496 | 496 | You can force auto-quoting of a function's arguments by using ',' as |
|
497 | 497 | the first character of a line. For example: |
|
498 | 498 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
499 | 499 | |
|
500 | 500 | If you use ';' instead, the whole argument is quoted as a single |
|
501 | 501 | string (while ',' splits on whitespace): |
|
502 | 502 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
503 | 503 | >>> ;my_function a b c # becomes my_function("a b c") |
|
504 | 504 | |
|
505 | 505 | Note that the ',' MUST be the first character on the line! This |
|
506 | 506 | won't work: |
|
507 | 507 | >>> x = ,my_function /home/me # syntax error |
|
508 | 508 | """ |
|
509 | 509 | |
|
510 | 510 | interactive_usage_min = """\ |
|
511 | 511 | An enhanced console for Python. |
|
512 | 512 | Some of its features are: |
|
513 | 513 | - Readline support if the readline library is present. |
|
514 | 514 | - Tab completion in the local namespace. |
|
515 | 515 | - Logging of input, see command-line options. |
|
516 | 516 | - System shell escape via ! , eg !ls. |
|
517 | 517 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
518 | 518 | - Keeps track of locally defined variables via %who, %whos. |
|
519 | 519 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
520 | 520 | """ |
|
521 | 521 | |
|
522 | 522 | quick_reference = r""" |
|
523 | 523 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
524 | 524 | ================================================================ |
|
525 | 525 | |
|
526 | 526 | obj?, obj?? : Get help, or more help for object (also works as |
|
527 | 527 | ?obj, ??obj). |
|
528 | 528 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
529 | 529 | %magic : Information about IPython's 'magic' % functions. |
|
530 | 530 | |
|
531 | 531 | Magic functions are prefixed by %, and typically take their arguments without |
|
532 | 532 | parentheses, quotes or even commas for convenience. |
|
533 | 533 | |
|
534 | 534 | Example magic function calls: |
|
535 | 535 | |
|
536 | 536 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
537 | 537 | alias d ls -F : Works if 'alias' not a python name |
|
538 | 538 | alist = %alias : Get list of aliases to 'alist' |
|
539 | 539 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
540 | 540 | %cd?? : See help AND source for magic %cd |
|
541 | 541 | |
|
542 | 542 | System commands: |
|
543 | 543 | |
|
544 | 544 | !cp a.txt b/ : System command escape, calls os.system() |
|
545 | 545 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
546 | 546 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
547 | 547 | files = !ls /usr : Capture sytem command output |
|
548 | 548 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
549 | 549 | |
|
550 | 550 | History: |
|
551 | 551 | |
|
552 | 552 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
553 | 553 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
554 | 554 | exec _i81 : Execute input history line #81 again |
|
555 | 555 | %rep 81 : Edit input history line #81 |
|
556 | 556 | _, __, ___ : previous, next previous, next next previous output |
|
557 | 557 | _dh : Directory history |
|
558 | 558 | _oh : Output history |
|
559 | 559 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
560 | 560 | |
|
561 | 561 | Autocall: |
|
562 | 562 | |
|
563 | 563 | f 1,2 : f(1,2) |
|
564 | 564 | /f 1,2 : f(1,2) (forced autoparen) |
|
565 | 565 | ,f 1 2 : f("1","2") |
|
566 | 566 | ;f 1 2 : f("1 2") |
|
567 | 567 | |
|
568 | 568 | Remember: TAB completion works in many contexts, not just file names |
|
569 | 569 | or python names. |
|
570 | 570 | |
|
571 | 571 | The following magic functions are currently available: |
|
572 | 572 | |
|
573 | 573 | """ |
|
574 | 574 | |
|
575 | 575 | quick_guide = """\ |
|
576 | 576 | ? -> Introduction and overview of IPython's features. |
|
577 | 577 | %quickref -> Quick reference. |
|
578 | 578 | help -> Python's own help system. |
|
579 | 579 | object? -> Details about 'object'. ?object also works, ?? prints more.""" |
|
580 | 580 | |
|
581 | banner_parts = [ | |
|
581 | default_banner_parts = [ | |
|
582 | 582 | 'Python %s' % (sys.version.split('\n')[0],), |
|
583 | 583 | 'Type "copyright", "credits" or "license" for more information.\n', |
|
584 | 584 | 'IPython %s -- An enhanced Interactive Python.' % (release.version,), |
|
585 | 585 | quick_guide |
|
586 | 586 | ] |
|
587 | ||
|
588 | default_banner = '\n'.join(default_banner_parts) |
@@ -1,861 +1,899 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | A lightweight Traits like module. |
|
5 | 5 | |
|
6 | 6 | This is designed to provide a lightweight, simple, pure Python version of |
|
7 | 7 | many of the capabilities of enthought.traits. This includes: |
|
8 | 8 | |
|
9 | 9 | * Validation |
|
10 | 10 | * Type specification with defaults |
|
11 | 11 | * Static and dynamic notification |
|
12 | 12 | * Basic predefined types |
|
13 | 13 | * An API that is similar to enthought.traits |
|
14 | 14 | |
|
15 | 15 | We don't support: |
|
16 | 16 | |
|
17 | 17 | * Delegation |
|
18 | 18 | * Automatic GUI generation |
|
19 | 19 | * A full set of trait types. Most importantly, we don't provide container |
|
20 | 20 | traitlets (list, dict, tuple) that can trigger notifications if their |
|
21 | 21 | contents change. |
|
22 | 22 | * API compatibility with enthought.traits |
|
23 | 23 | |
|
24 | 24 | There are also some important difference in our design: |
|
25 | 25 | |
|
26 | 26 | * enthought.traits does not validate default values. We do. |
|
27 | 27 | |
|
28 | 28 | We choose to create this module because we need these capabilities, but |
|
29 | 29 | we need them to be pure Python so they work in all Python implementations, |
|
30 | 30 | including Jython and IronPython. |
|
31 | 31 | |
|
32 | 32 | Authors: |
|
33 | 33 | |
|
34 | 34 | * Brian Granger |
|
35 | 35 | * Enthought, Inc. Some of the code in this file comes from enthought.traits |
|
36 | 36 | and is licensed under the BSD license. Also, many of the ideas also come |
|
37 | 37 | from enthought.traits even though our implementation is very different. |
|
38 | 38 | """ |
|
39 | 39 | |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | # Copyright (C) 2008-2009 The IPython Development Team |
|
42 | 42 | # |
|
43 | 43 | # Distributed under the terms of the BSD License. The full license is in |
|
44 | 44 | # the file COPYING, distributed as part of this software. |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | # Imports |
|
49 | 49 | #----------------------------------------------------------------------------- |
|
50 | 50 | |
|
51 | 51 | |
|
52 | 52 | import inspect |
|
53 | 53 | import sys |
|
54 | 54 | import types |
|
55 | 55 | from types import InstanceType, ClassType, FunctionType |
|
56 | 56 | |
|
57 | 57 | ClassTypes = (ClassType, type) |
|
58 | 58 | |
|
59 | 59 | #----------------------------------------------------------------------------- |
|
60 | 60 | # Basic classes |
|
61 | 61 | #----------------------------------------------------------------------------- |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | class NoDefaultSpecified ( object ): pass |
|
65 | 65 | NoDefaultSpecified = NoDefaultSpecified() |
|
66 | 66 | |
|
67 | 67 | |
|
68 | 68 | class Undefined ( object ): pass |
|
69 | 69 | Undefined = Undefined() |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class TraitletError(Exception): |
|
73 | 73 | pass |
|
74 | 74 | |
|
75 | 75 | |
|
76 | 76 | #----------------------------------------------------------------------------- |
|
77 | 77 | # Utilities |
|
78 | 78 | #----------------------------------------------------------------------------- |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | def class_of ( object ): |
|
82 | 82 | """ Returns a string containing the class name of an object with the |
|
83 | 83 | correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', |
|
84 | 84 | 'a PlotValue'). |
|
85 | 85 | """ |
|
86 | 86 | if isinstance( object, basestring ): |
|
87 | 87 | return add_article( object ) |
|
88 | 88 | |
|
89 | 89 | return add_article( object.__class__.__name__ ) |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | def add_article ( name ): |
|
93 | 93 | """ Returns a string containing the correct indefinite article ('a' or 'an') |
|
94 | 94 | prefixed to the specified string. |
|
95 | 95 | """ |
|
96 | 96 | if name[:1].lower() in 'aeiou': |
|
97 | 97 | return 'an ' + name |
|
98 | 98 | |
|
99 | 99 | return 'a ' + name |
|
100 | 100 | |
|
101 | 101 | |
|
102 | 102 | def repr_type(obj): |
|
103 | 103 | """ Return a string representation of a value and its type for readable |
|
104 | 104 | error messages. |
|
105 | 105 | """ |
|
106 | 106 | the_type = type(obj) |
|
107 | 107 | if the_type is InstanceType: |
|
108 | 108 | # Old-style class. |
|
109 | 109 | the_type = obj.__class__ |
|
110 | 110 | msg = '%r %r' % (obj, the_type) |
|
111 | 111 | return msg |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | def parse_notifier_name(name): |
|
115 | 115 | """Convert the name argument to a list of names. |
|
116 | 116 | |
|
117 | 117 | Examples |
|
118 | 118 | -------- |
|
119 | 119 | |
|
120 | 120 | >>> parse_notifier_name('a') |
|
121 | 121 | ['a'] |
|
122 | 122 | >>> parse_notifier_name(['a','b']) |
|
123 | 123 | ['a', 'b'] |
|
124 | 124 | >>> parse_notifier_name(None) |
|
125 | 125 | ['anytraitlet'] |
|
126 | 126 | """ |
|
127 | 127 | if isinstance(name, str): |
|
128 | 128 | return [name] |
|
129 | 129 | elif name is None: |
|
130 | 130 | return ['anytraitlet'] |
|
131 | 131 | elif isinstance(name, (list, tuple)): |
|
132 | 132 | for n in name: |
|
133 | 133 | assert isinstance(n, str), "names must be strings" |
|
134 | 134 | return name |
|
135 | 135 | |
|
136 | 136 | |
|
137 | 137 | class _SimpleTest: |
|
138 | 138 | def __init__ ( self, value ): self.value = value |
|
139 | 139 | def __call__ ( self, test ): |
|
140 | 140 | print test, self.value |
|
141 | 141 | return test == self.value |
|
142 | 142 | def __repr__(self): |
|
143 | 143 | return "<SimpleTest(%r)" % self.value |
|
144 | 144 | def __str__(self): |
|
145 | 145 | return self.__repr__() |
|
146 | 146 | |
|
147 | 147 | |
|
148 | 148 | #----------------------------------------------------------------------------- |
|
149 | 149 | # Base TraitletType for all traitlets |
|
150 | 150 | #----------------------------------------------------------------------------- |
|
151 | 151 | |
|
152 | 152 | |
|
153 | 153 | class TraitletType(object): |
|
154 | 154 | """A base class for all traitlet descriptors. |
|
155 | 155 | |
|
156 | 156 | Notes |
|
157 | 157 | ----- |
|
158 | 158 | Our implementation of traitlets is based on Python's descriptor |
|
159 | 159 | prototol. This class is the base class for all such descriptors. The |
|
160 | 160 | only magic we use is a custom metaclass for the main :class:`HasTraitlets` |
|
161 | 161 | class that does the following: |
|
162 | 162 | |
|
163 | 163 | 1. Sets the :attr:`name` attribute of every :class:`TraitletType` |
|
164 | 164 | instance in the class dict to the name of the attribute. |
|
165 | 165 | 2. Sets the :attr:`this_class` attribute of every :class:`TraitletType` |
|
166 | 166 | instance in the class dict to the *class* that declared the traitlet. |
|
167 | 167 | This is used by the :class:`This` traitlet to allow subclasses to |
|
168 | 168 | accept superclasses for :class:`This` values. |
|
169 | 169 | """ |
|
170 | 170 | |
|
171 | 171 | |
|
172 | 172 | metadata = {} |
|
173 | 173 | default_value = Undefined |
|
174 | 174 | info_text = 'any value' |
|
175 | 175 | |
|
176 | 176 | def __init__(self, default_value=NoDefaultSpecified, **metadata): |
|
177 | 177 | """Create a TraitletType. |
|
178 | 178 | """ |
|
179 | 179 | if default_value is not NoDefaultSpecified: |
|
180 | 180 | self.default_value = default_value |
|
181 | 181 | |
|
182 | 182 | if len(metadata) > 0: |
|
183 | 183 | if len(self.metadata) > 0: |
|
184 | 184 | self._metadata = self.metadata.copy() |
|
185 | 185 | self._metadata.update(metadata) |
|
186 | 186 | else: |
|
187 | 187 | self._metadata = metadata |
|
188 | 188 | else: |
|
189 | 189 | self._metadata = self.metadata |
|
190 | 190 | |
|
191 | 191 | self.init() |
|
192 | 192 | |
|
193 | 193 | def init(self): |
|
194 | 194 | pass |
|
195 | 195 | |
|
196 | 196 | def get_default_value(self): |
|
197 | 197 | """Create a new instance of the default value.""" |
|
198 | 198 | dv = self.default_value |
|
199 | 199 | return dv |
|
200 | 200 | |
|
201 | 201 | def set_default_value(self, obj): |
|
202 | 202 | dv = self.get_default_value() |
|
203 | 203 | newdv = self._validate(obj, dv) |
|
204 | 204 | obj._traitlet_values[self.name] = newdv |
|
205 | 205 | |
|
206 | 206 | |
|
207 | 207 | def __get__(self, obj, cls=None): |
|
208 | 208 | """Get the value of the traitlet by self.name for the instance. |
|
209 | 209 | |
|
210 | 210 | Default values are instantiated when :meth:`HasTraitlets.__new__` |
|
211 | 211 | is called. Thus by the time this method gets called either the |
|
212 | 212 | default value or a user defined value (they called :meth:`__set__`) |
|
213 | 213 | is in the :class:`HasTraitlets` instance. |
|
214 | 214 | """ |
|
215 | 215 | if obj is None: |
|
216 | 216 | return self |
|
217 | 217 | else: |
|
218 | 218 | try: |
|
219 | 219 | value = obj._traitlet_values[self.name] |
|
220 | 220 | except: |
|
221 | 221 | # HasTraitlets should call set_default_value to populate |
|
222 | 222 | # this. So this should never be reached. |
|
223 | 223 | raise TraitletError('Unexpected error in TraitletType: ' |
|
224 | 224 | 'default value not set properly') |
|
225 | 225 | else: |
|
226 | 226 | return value |
|
227 | 227 | |
|
228 | 228 | def __set__(self, obj, value): |
|
229 | 229 | new_value = self._validate(obj, value) |
|
230 | 230 | old_value = self.__get__(obj) |
|
231 | 231 | if old_value != new_value: |
|
232 | 232 | obj._traitlet_values[self.name] = new_value |
|
233 | 233 | obj._notify_traitlet(self.name, old_value, new_value) |
|
234 | 234 | |
|
235 | 235 | def _validate(self, obj, value): |
|
236 | 236 | if hasattr(self, 'validate'): |
|
237 | 237 | return self.validate(obj, value) |
|
238 | 238 | elif hasattr(self, 'is_valid_for'): |
|
239 | 239 | valid = self.is_valid_for(value) |
|
240 | 240 | if valid: |
|
241 | 241 | return value |
|
242 | 242 | else: |
|
243 | 243 | raise TraitletError('invalid value for type: %r' % value) |
|
244 | 244 | elif hasattr(self, 'value_for'): |
|
245 | 245 | return self.value_for(value) |
|
246 | 246 | else: |
|
247 | 247 | return value |
|
248 | 248 | |
|
249 | 249 | def info(self): |
|
250 | 250 | return self.info_text |
|
251 | 251 | |
|
252 | 252 | def error(self, obj, value): |
|
253 | 253 | if obj is not None: |
|
254 | 254 | e = "The '%s' traitlet of %s instance must be %s, but a value of %s was specified." \ |
|
255 | 255 | % (self.name, class_of(obj), |
|
256 | 256 | self.info(), repr_type(value)) |
|
257 | 257 | else: |
|
258 | 258 | e = "The '%s' traitlet must be %s, but a value of %r was specified." \ |
|
259 | 259 | % (self.name, self.info(), repr_type(value)) |
|
260 | 260 | raise TraitletError(e) |
|
261 | 261 | |
|
262 | 262 | def get_metadata(self, key): |
|
263 | 263 | return getattr(self, '_metadata', {}).get(key, None) |
|
264 | 264 | |
|
265 | 265 | def set_metadata(self, key, value): |
|
266 | 266 | getattr(self, '_metadata', {})[key] = value |
|
267 | 267 | |
|
268 | 268 | |
|
269 | 269 | #----------------------------------------------------------------------------- |
|
270 | 270 | # The HasTraitlets implementation |
|
271 | 271 | #----------------------------------------------------------------------------- |
|
272 | 272 | |
|
273 | 273 | |
|
274 | 274 | class MetaHasTraitlets(type): |
|
275 | 275 | """A metaclass for HasTraitlets. |
|
276 | 276 | |
|
277 | 277 | This metaclass makes sure that any TraitletType class attributes are |
|
278 | 278 | instantiated and sets their name attribute. |
|
279 | 279 | """ |
|
280 | 280 | |
|
281 | 281 | def __new__(mcls, name, bases, classdict): |
|
282 | 282 | """Create the HasTraitlets class. |
|
283 | 283 | |
|
284 | 284 | This instantiates all TraitletTypes in the class dict and sets their |
|
285 | 285 | :attr:`name` attribute. |
|
286 | 286 | """ |
|
287 | 287 | # print "=========================" |
|
288 | 288 | # print "MetaHasTraitlets.__new__" |
|
289 | 289 | # print "mcls, ", mcls |
|
290 | 290 | # print "name, ", name |
|
291 | 291 | # print "bases, ", bases |
|
292 | 292 | # print "classdict, ", classdict |
|
293 | 293 | for k,v in classdict.iteritems(): |
|
294 | 294 | if isinstance(v, TraitletType): |
|
295 | 295 | v.name = k |
|
296 | 296 | elif inspect.isclass(v): |
|
297 | 297 | if issubclass(v, TraitletType): |
|
298 | 298 | vinst = v() |
|
299 | 299 | vinst.name = k |
|
300 | 300 | classdict[k] = vinst |
|
301 | 301 | return super(MetaHasTraitlets, mcls).__new__(mcls, name, bases, classdict) |
|
302 | 302 | |
|
303 | 303 | def __init__(cls, name, bases, classdict): |
|
304 | 304 | """Finish initializing the HasTraitlets class. |
|
305 | 305 | |
|
306 | 306 | This sets the :attr:`this_class` attribute of each TraitletType in the |
|
307 | 307 | class dict to the newly created class ``cls``. |
|
308 | 308 | """ |
|
309 | 309 | # print "=========================" |
|
310 | 310 | # print "MetaHasTraitlets.__init__" |
|
311 | 311 | # print "cls, ", cls |
|
312 | 312 | # print "name, ", name |
|
313 | 313 | # print "bases, ", bases |
|
314 | 314 | # print "classdict, ", classdict |
|
315 | 315 | for k, v in classdict.iteritems(): |
|
316 | 316 | if isinstance(v, TraitletType): |
|
317 | 317 | v.this_class = cls |
|
318 | 318 | super(MetaHasTraitlets, cls).__init__(name, bases, classdict) |
|
319 | 319 | |
|
320 | 320 | class HasTraitlets(object): |
|
321 | 321 | |
|
322 | 322 | __metaclass__ = MetaHasTraitlets |
|
323 | 323 | |
|
324 | 324 | def __new__(cls, *args, **kw): |
|
325 | 325 | inst = super(HasTraitlets, cls).__new__(cls, *args, **kw) |
|
326 | 326 | inst._traitlet_values = {} |
|
327 | 327 | inst._traitlet_notifiers = {} |
|
328 | 328 | # Here we tell all the TraitletType instances to set their default |
|
329 | 329 | # values on the instance. |
|
330 | 330 | for key in dir(cls): |
|
331 | 331 | value = getattr(cls, key) |
|
332 | 332 | if isinstance(value, TraitletType): |
|
333 | 333 | value.set_default_value(inst) |
|
334 | 334 | return inst |
|
335 | 335 | |
|
336 | 336 | # def __init__(self): |
|
337 | 337 | # self._traitlet_values = {} |
|
338 | 338 | # self._traitlet_notifiers = {} |
|
339 | 339 | |
|
340 | 340 | def _notify_traitlet(self, name, old_value, new_value): |
|
341 | 341 | |
|
342 | 342 | # First dynamic ones |
|
343 | 343 | callables = self._traitlet_notifiers.get(name,[]) |
|
344 | 344 | more_callables = self._traitlet_notifiers.get('anytraitlet',[]) |
|
345 | 345 | callables.extend(more_callables) |
|
346 | 346 | |
|
347 | 347 | # Now static ones |
|
348 | 348 | try: |
|
349 | 349 | cb = getattr(self, '_%s_changed' % name) |
|
350 | 350 | except: |
|
351 | 351 | pass |
|
352 | 352 | else: |
|
353 | 353 | callables.append(cb) |
|
354 | 354 | |
|
355 | 355 | # Call them all now |
|
356 | 356 | for c in callables: |
|
357 | 357 | # Traits catches and logs errors here. I allow them to raise |
|
358 | 358 | if callable(c): |
|
359 | 359 | argspec = inspect.getargspec(c) |
|
360 | 360 | nargs = len(argspec[0]) |
|
361 | 361 | # Bound methods have an additional 'self' argument |
|
362 | 362 | # I don't know how to treat unbound methods, but they |
|
363 | 363 | # can't really be used for callbacks. |
|
364 | 364 | if isinstance(c, types.MethodType): |
|
365 | 365 | offset = -1 |
|
366 | 366 | else: |
|
367 | 367 | offset = 0 |
|
368 | 368 | if nargs + offset == 0: |
|
369 | 369 | c() |
|
370 | 370 | elif nargs + offset == 1: |
|
371 | 371 | c(name) |
|
372 | 372 | elif nargs + offset == 2: |
|
373 | 373 | c(name, new_value) |
|
374 | 374 | elif nargs + offset == 3: |
|
375 | 375 | c(name, old_value, new_value) |
|
376 | 376 | else: |
|
377 | 377 | raise TraitletError('a traitlet changed callback ' |
|
378 | 378 | 'must have 0-3 arguments.') |
|
379 | 379 | else: |
|
380 | 380 | raise TraitletError('a traitlet changed callback ' |
|
381 | 381 | 'must be callable.') |
|
382 | 382 | |
|
383 | 383 | |
|
384 | 384 | def _add_notifiers(self, handler, name): |
|
385 | 385 | if not self._traitlet_notifiers.has_key(name): |
|
386 | 386 | nlist = [] |
|
387 | 387 | self._traitlet_notifiers[name] = nlist |
|
388 | 388 | else: |
|
389 | 389 | nlist = self._traitlet_notifiers[name] |
|
390 | 390 | if handler not in nlist: |
|
391 | 391 | nlist.append(handler) |
|
392 | 392 | |
|
393 | 393 | def _remove_notifiers(self, handler, name): |
|
394 | 394 | if self._traitlet_notifiers.has_key(name): |
|
395 | 395 | nlist = self._traitlet_notifiers[name] |
|
396 | 396 | try: |
|
397 | 397 | index = nlist.index(handler) |
|
398 | 398 | except ValueError: |
|
399 | 399 | pass |
|
400 | 400 | else: |
|
401 | 401 | del nlist[index] |
|
402 | 402 | |
|
403 | 403 | def on_traitlet_change(self, handler, name=None, remove=False): |
|
404 | 404 | """Setup a handler to be called when a traitlet changes. |
|
405 | 405 | |
|
406 | 406 | This is used to setup dynamic notifications of traitlet changes. |
|
407 | 407 | |
|
408 | 408 | Static handlers can be created by creating methods on a HasTraitlets |
|
409 | 409 | subclass with the naming convention '_[traitletname]_changed'. Thus, |
|
410 | 410 | to create static handler for the traitlet 'a', create the method |
|
411 | 411 | _a_changed(self, name, old, new) (fewer arguments can be used, see |
|
412 | 412 | below). |
|
413 | 413 | |
|
414 | 414 | Parameters |
|
415 | 415 | ---------- |
|
416 | 416 | handler : callable |
|
417 | 417 | A callable that is called when a traitlet changes. Its |
|
418 | 418 | signature can be handler(), handler(name), handler(name, new) |
|
419 | 419 | or handler(name, old, new). |
|
420 | 420 | name : list, str, None |
|
421 | 421 | If None, the handler will apply to all traitlets. If a list |
|
422 | 422 | of str, handler will apply to all names in the list. If a |
|
423 | 423 | str, the handler will apply just to that name. |
|
424 | 424 | remove : bool |
|
425 | 425 | If False (the default), then install the handler. If True |
|
426 | 426 | then unintall it. |
|
427 | 427 | """ |
|
428 | 428 | if remove: |
|
429 | 429 | names = parse_notifier_name(name) |
|
430 | 430 | for n in names: |
|
431 | 431 | self._remove_notifiers(handler, n) |
|
432 | 432 | else: |
|
433 | 433 | names = parse_notifier_name(name) |
|
434 | 434 | for n in names: |
|
435 | 435 | self._add_notifiers(handler, n) |
|
436 | 436 | |
|
437 | 437 | def traitlet_names(self, **metadata): |
|
438 | 438 | """Get a list of all the names of this classes traitlets.""" |
|
439 | 439 | return self.traitlets(**metadata).keys() |
|
440 | 440 | |
|
441 | 441 | def traitlets(self, *args, **metadata): |
|
442 | 442 | """Get a list of all the traitlets of this class. |
|
443 | 443 | |
|
444 | 444 | The TraitletTypes returned don't know anything about the values |
|
445 | 445 | that the various HasTraitlet's instances are holding. |
|
446 | 446 | """ |
|
447 | 447 | traitlets = dict([memb for memb in inspect.getmembers(self.__class__) if \ |
|
448 | 448 | isinstance(memb[1], TraitletType)]) |
|
449 | 449 | if len(metadata) == 0 and len(args) == 0: |
|
450 | 450 | return traitlets |
|
451 | 451 | |
|
452 | 452 | for meta_name in args: |
|
453 | 453 | metadata[meta_name] = lambda _: True |
|
454 | 454 | |
|
455 | 455 | for meta_name, meta_eval in metadata.items(): |
|
456 | 456 | if type(meta_eval) is not FunctionType: |
|
457 | 457 | metadata[meta_name] = _SimpleTest(meta_eval) |
|
458 | 458 | |
|
459 | 459 | result = {} |
|
460 | 460 | for name, traitlet in traitlets.items(): |
|
461 | 461 | for meta_name, meta_eval in metadata.items(): |
|
462 | 462 | if not meta_eval(traitlet.get_metadata(meta_name)): |
|
463 | 463 | break |
|
464 | 464 | else: |
|
465 | 465 | result[name] = traitlet |
|
466 | 466 | |
|
467 | 467 | return result |
|
468 | 468 | |
|
469 | 469 | def traitlet_metadata(self, traitletname, key): |
|
470 | 470 | """Get metadata values for traitlet by key.""" |
|
471 | 471 | try: |
|
472 | 472 | traitlet = getattr(self.__class__, traitletname) |
|
473 | 473 | except AttributeError: |
|
474 | 474 | raise TraitletError("Class %s does not have a traitlet named %s" % |
|
475 | 475 | (self.__class__.__name__, traitletname)) |
|
476 | 476 | else: |
|
477 | 477 | return traitlet.get_metadata(key) |
|
478 | 478 | |
|
479 | 479 | #----------------------------------------------------------------------------- |
|
480 | 480 | # Actual TraitletTypes implementations/subclasses |
|
481 | 481 | #----------------------------------------------------------------------------- |
|
482 | 482 | |
|
483 | 483 | #----------------------------------------------------------------------------- |
|
484 | 484 | # TraitletTypes subclasses for handling classes and instances of classes |
|
485 | 485 | #----------------------------------------------------------------------------- |
|
486 | 486 | |
|
487 | 487 | |
|
488 | 488 | class ClassBasedTraitletType(TraitletType): |
|
489 | 489 | """A traitlet with error reporting for Type, Instance and This.""" |
|
490 | 490 | |
|
491 | 491 | def error(self, obj, value): |
|
492 | 492 | kind = type(value) |
|
493 | 493 | if kind is InstanceType: |
|
494 | 494 | msg = 'class %s' % value.__class__.__name__ |
|
495 | 495 | else: |
|
496 | 496 | msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) ) |
|
497 | 497 | |
|
498 | 498 | super(ClassBasedTraitletType, self).error(obj, msg) |
|
499 | 499 | |
|
500 | 500 | |
|
501 | 501 | class Type(ClassBasedTraitletType): |
|
502 | 502 | """A traitlet whose value must be a subclass of a specified class.""" |
|
503 | 503 | |
|
504 | 504 | def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ): |
|
505 | 505 | """Construct a Type traitlet |
|
506 | 506 | |
|
507 | 507 | A Type traitlet specifies that its values must be subclasses of |
|
508 | 508 | a particular class. |
|
509 | 509 | |
|
510 | 510 | Parameters |
|
511 | 511 | ---------- |
|
512 | 512 | default_value : class |
|
513 | 513 | The default value must be a subclass of klass. |
|
514 | 514 | klass : class, str, None |
|
515 | 515 | Values of this traitlet must be a subclass of klass. The klass |
|
516 | 516 | may be specified in a string like: 'foo.bar.MyClass'. |
|
517 | 517 | allow_none : boolean |
|
518 | 518 | Indicates whether None is allowed as an assignable value. Even if |
|
519 | 519 | ``False``, the default value may be ``None``. |
|
520 | 520 | """ |
|
521 | 521 | if default_value is None: |
|
522 | 522 | if klass is None: |
|
523 | 523 | klass = object |
|
524 | 524 | elif klass is None: |
|
525 | 525 | klass = default_value |
|
526 | 526 | |
|
527 | 527 | if not inspect.isclass(klass): |
|
528 | 528 | raise TraitletError("A Type traitlet must specify a class.") |
|
529 | 529 | |
|
530 | 530 | self.klass = klass |
|
531 | 531 | self._allow_none = allow_none |
|
532 | 532 | |
|
533 | 533 | super(Type, self).__init__(default_value, **metadata) |
|
534 | 534 | |
|
535 | 535 | def validate(self, obj, value): |
|
536 | 536 | """Validates that the value is a valid object instance.""" |
|
537 | 537 | try: |
|
538 | 538 | if issubclass(value, self.klass): |
|
539 | 539 | return value |
|
540 | 540 | except: |
|
541 | 541 | if (value is None) and (self._allow_none): |
|
542 | 542 | return value |
|
543 | 543 | |
|
544 | 544 | self.error(obj, value) |
|
545 | 545 | |
|
546 | 546 | def info(self): |
|
547 | 547 | """ Returns a description of the trait.""" |
|
548 | 548 | klass = self.klass.__name__ |
|
549 | 549 | result = 'a subclass of ' + klass |
|
550 | 550 | if self._allow_none: |
|
551 | 551 | return result + ' or None' |
|
552 | 552 | return result |
|
553 | 553 | |
|
554 | 554 | |
|
555 | 555 | class DefaultValueGenerator(object): |
|
556 | 556 | """A class for generating new default value instances.""" |
|
557 | 557 | |
|
558 | 558 | def __init__(self, klass, *args, **kw): |
|
559 | 559 | self.klass = klass |
|
560 | 560 | self.args = args |
|
561 | 561 | self.kw = kw |
|
562 | 562 | |
|
563 | 563 | def generate(self): |
|
564 | 564 | return self.klass(*self.args, **self.kw) |
|
565 | 565 | |
|
566 | 566 | |
|
567 | 567 | class Instance(ClassBasedTraitletType): |
|
568 | 568 | """A trait whose value must be an instance of a specified class. |
|
569 | 569 | |
|
570 | 570 | The value can also be an instance of a subclass of the specified class. |
|
571 | 571 | """ |
|
572 | 572 | |
|
573 | 573 | def __init__(self, klass=None, args=None, kw=None, |
|
574 | 574 | allow_none=True, **metadata ): |
|
575 | 575 | """Construct an Instance traitlet. |
|
576 | 576 | |
|
577 | 577 | This traitlet allows values that are instances of a particular |
|
578 | 578 | class or its sublclasses. Our implementation is quite different |
|
579 | 579 | from that of enthough.traits as we don't allow instances to be used |
|
580 | 580 | for klass and we handle the ``args`` and ``kw`` arguments differently. |
|
581 | 581 | |
|
582 | 582 | Parameters |
|
583 | 583 | ---------- |
|
584 | 584 | klass : class |
|
585 | 585 | The class that forms the basis for the traitlet. Instances |
|
586 | 586 | and strings are not allowed. |
|
587 | 587 | args : tuple |
|
588 | 588 | Positional arguments for generating the default value. |
|
589 | 589 | kw : dict |
|
590 | 590 | Keyword arguments for generating the default value. |
|
591 | 591 | allow_none : bool |
|
592 | 592 | Indicates whether None is allowed as a value. |
|
593 | 593 | |
|
594 | 594 | Default Value |
|
595 | 595 | ------------- |
|
596 | 596 | If both ``args`` and ``kw`` are None, then the default value is None. |
|
597 | 597 | If ``args`` is a tuple and ``kw`` is a dict, then the default is |
|
598 | 598 | created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is |
|
599 | 599 | not (but not both), None is replace by ``()`` or ``{}``. |
|
600 | 600 | """ |
|
601 | 601 | |
|
602 | 602 | self._allow_none = allow_none |
|
603 | 603 | |
|
604 | 604 | if (klass is None) or (not inspect.isclass(klass)): |
|
605 | 605 | raise TraitletError('The klass argument must be a class' |
|
606 | 606 | ' you gave: %r' % klass) |
|
607 | 607 | self.klass = klass |
|
608 | 608 | |
|
609 | 609 | # self.klass is a class, so handle default_value |
|
610 | 610 | if args is None and kw is None: |
|
611 | 611 | default_value = None |
|
612 | 612 | else: |
|
613 | 613 | if args is None: |
|
614 | 614 | # kw is not None |
|
615 | 615 | args = () |
|
616 | 616 | elif kw is None: |
|
617 | 617 | # args is not None |
|
618 | 618 | kw = {} |
|
619 | 619 | |
|
620 | 620 | if not isinstance(kw, dict): |
|
621 | 621 | raise TraitletError("The 'kw' argument must be a dict or None.") |
|
622 | 622 | if not isinstance(args, tuple): |
|
623 | 623 | raise TraitletError("The 'args' argument must be a tuple or None.") |
|
624 | 624 | |
|
625 | 625 | default_value = DefaultValueGenerator(self.klass, *args, **kw) |
|
626 | 626 | |
|
627 | 627 | super(Instance, self).__init__(default_value, **metadata) |
|
628 | 628 | |
|
629 | 629 | def validate(self, obj, value): |
|
630 | 630 | if value is None: |
|
631 | 631 | if self._allow_none: |
|
632 | 632 | return value |
|
633 | 633 | self.error(obj, value) |
|
634 | 634 | |
|
635 | 635 | if isinstance(value, self.klass): |
|
636 | 636 | return value |
|
637 | 637 | else: |
|
638 | 638 | self.error(obj, value) |
|
639 | 639 | |
|
640 | 640 | def info(self): |
|
641 | 641 | klass = self.klass.__name__ |
|
642 | 642 | result = class_of(klass) |
|
643 | 643 | if self._allow_none: |
|
644 | 644 | return result + ' or None' |
|
645 | 645 | |
|
646 | 646 | return result |
|
647 | 647 | |
|
648 | 648 | def get_default_value(self): |
|
649 | 649 | """Instantiate a default value instance. |
|
650 | 650 | |
|
651 | 651 | This is called when the containing HasTraitlets classes' |
|
652 | 652 | :meth:`__new__` method is called to ensure that a unique instance |
|
653 | 653 | is created for each HasTraitlets instance. |
|
654 | 654 | """ |
|
655 | 655 | dv = self.default_value |
|
656 | 656 | if isinstance(dv, DefaultValueGenerator): |
|
657 | 657 | return dv.generate() |
|
658 | 658 | else: |
|
659 | 659 | return dv |
|
660 | 660 | |
|
661 | 661 | |
|
662 | 662 | class This(ClassBasedTraitletType): |
|
663 | 663 | """A traitlet for instances of the class containing this trait. |
|
664 | 664 | |
|
665 | 665 | Because how how and when class bodies are executed, the ``This`` |
|
666 | 666 | traitlet can only have a default value of None. This, and because we |
|
667 | 667 | always validate default values, ``allow_none`` is *always* true. |
|
668 | 668 | """ |
|
669 | 669 | |
|
670 | 670 | info_text = 'an instance of the same type as the receiver or None' |
|
671 | 671 | |
|
672 | 672 | def __init__(self, **metadata): |
|
673 | 673 | super(This, self).__init__(None, **metadata) |
|
674 | 674 | |
|
675 | 675 | def validate(self, obj, value): |
|
676 | 676 | # What if value is a superclass of obj.__class__? This is |
|
677 | 677 | # complicated if it was the superclass that defined the This |
|
678 | 678 | # traitlet. |
|
679 | 679 | if isinstance(value, self.this_class) or (value is None): |
|
680 | 680 | return value |
|
681 | 681 | else: |
|
682 | 682 | self.error(obj, value) |
|
683 | 683 | |
|
684 | 684 | |
|
685 | 685 | #----------------------------------------------------------------------------- |
|
686 | 686 | # Basic TraitletTypes implementations/subclasses |
|
687 | 687 | #----------------------------------------------------------------------------- |
|
688 | 688 | |
|
689 | 689 | |
|
690 | 690 | class Any(TraitletType): |
|
691 | 691 | default_value = None |
|
692 | 692 | info_text = 'any value' |
|
693 | 693 | |
|
694 | 694 | |
|
695 | 695 | class Int(TraitletType): |
|
696 | 696 | """A integer traitlet.""" |
|
697 | 697 | |
|
698 | 698 | evaluate = int |
|
699 | 699 | default_value = 0 |
|
700 | 700 | info_text = 'an integer' |
|
701 | 701 | |
|
702 | 702 | def validate(self, obj, value): |
|
703 | 703 | if isinstance(value, int): |
|
704 | 704 | return value |
|
705 | 705 | self.error(obj, value) |
|
706 | 706 | |
|
707 | 707 | class CInt(Int): |
|
708 | 708 | """A casting version of the int traitlet.""" |
|
709 | 709 | |
|
710 | 710 | def validate(self, obj, value): |
|
711 | 711 | try: |
|
712 | 712 | return int(value) |
|
713 | 713 | except: |
|
714 | 714 | self.error(obj, value) |
|
715 | 715 | |
|
716 | 716 | |
|
717 | 717 | class Long(TraitletType): |
|
718 | 718 | """A long integer traitlet.""" |
|
719 | 719 | |
|
720 | 720 | evaluate = long |
|
721 | 721 | default_value = 0L |
|
722 | 722 | info_text = 'a long' |
|
723 | 723 | |
|
724 | 724 | def validate(self, obj, value): |
|
725 | 725 | if isinstance(value, long): |
|
726 | 726 | return value |
|
727 | 727 | if isinstance(value, int): |
|
728 | 728 | return long(value) |
|
729 | 729 | self.error(obj, value) |
|
730 | 730 | |
|
731 | 731 | |
|
732 | 732 | class CLong(Long): |
|
733 | 733 | """A casting version of the long integer traitlet.""" |
|
734 | 734 | |
|
735 | 735 | def validate(self, obj, value): |
|
736 | 736 | try: |
|
737 | 737 | return long(value) |
|
738 | 738 | except: |
|
739 | 739 | self.error(obj, value) |
|
740 | 740 | |
|
741 | 741 | |
|
742 | 742 | class Float(TraitletType): |
|
743 | 743 | """A float traitlet.""" |
|
744 | 744 | |
|
745 | 745 | evaluate = float |
|
746 | 746 | default_value = 0.0 |
|
747 | 747 | info_text = 'a float' |
|
748 | 748 | |
|
749 | 749 | def validate(self, obj, value): |
|
750 | 750 | if isinstance(value, float): |
|
751 | 751 | return value |
|
752 | 752 | if isinstance(value, int): |
|
753 | 753 | return float(value) |
|
754 | 754 | self.error(obj, value) |
|
755 | 755 | |
|
756 | 756 | |
|
757 | 757 | class CFloat(Float): |
|
758 | 758 | """A casting version of the float traitlet.""" |
|
759 | 759 | |
|
760 | 760 | def validate(self, obj, value): |
|
761 | 761 | try: |
|
762 | 762 | return float(value) |
|
763 | 763 | except: |
|
764 | 764 | self.error(obj, value) |
|
765 | 765 | |
|
766 | 766 | class Complex(TraitletType): |
|
767 | 767 | """A traitlet for complex numbers.""" |
|
768 | 768 | |
|
769 | 769 | evaluate = complex |
|
770 | 770 | default_value = 0.0 + 0.0j |
|
771 | 771 | info_text = 'a complex number' |
|
772 | 772 | |
|
773 | 773 | def validate(self, obj, value): |
|
774 | 774 | if isinstance(value, complex): |
|
775 | 775 | return value |
|
776 | 776 | if isinstance(value, (float, int)): |
|
777 | 777 | return complex(value) |
|
778 | 778 | self.error(obj, value) |
|
779 | 779 | |
|
780 | 780 | |
|
781 | 781 | class CComplex(Complex): |
|
782 | 782 | """A casting version of the complex number traitlet.""" |
|
783 | 783 | |
|
784 | 784 | def validate (self, obj, value): |
|
785 | 785 | try: |
|
786 | 786 | return complex(value) |
|
787 | 787 | except: |
|
788 | 788 | self.error(obj, value) |
|
789 | 789 | |
|
790 | 790 | |
|
791 | 791 | class Str(TraitletType): |
|
792 | 792 | """A traitlet for strings.""" |
|
793 | 793 | |
|
794 | 794 | evaluate = lambda x: x |
|
795 | 795 | default_value = '' |
|
796 | 796 | info_text = 'a string' |
|
797 | 797 | |
|
798 | 798 | def validate(self, obj, value): |
|
799 | 799 | if isinstance(value, str): |
|
800 | 800 | return value |
|
801 | 801 | self.error(obj, value) |
|
802 | 802 | |
|
803 | 803 | |
|
804 | 804 | class CStr(Str): |
|
805 | 805 | """A casting version of the string traitlet.""" |
|
806 | 806 | |
|
807 | 807 | def validate(self, obj, value): |
|
808 | 808 | try: |
|
809 | 809 | return str(value) |
|
810 | 810 | except: |
|
811 | 811 | try: |
|
812 | 812 | return unicode(value) |
|
813 | 813 | except: |
|
814 | 814 | self.error(obj, value) |
|
815 | 815 | |
|
816 | 816 | |
|
817 | 817 | class Unicode(TraitletType): |
|
818 | 818 | """A traitlet for unicode strings.""" |
|
819 | 819 | |
|
820 | 820 | evaluate = unicode |
|
821 | 821 | default_value = u'' |
|
822 | 822 | info_text = 'a unicode string' |
|
823 | 823 | |
|
824 | 824 | def validate(self, obj, value): |
|
825 | 825 | if isinstance(value, unicode): |
|
826 | 826 | return value |
|
827 | 827 | if isinstance(value, str): |
|
828 | 828 | return unicode(value) |
|
829 | 829 | self.error(obj, value) |
|
830 | 830 | |
|
831 | 831 | |
|
832 | 832 | class CUnicode(Unicode): |
|
833 | 833 | """A casting version of the unicode traitlet.""" |
|
834 | 834 | |
|
835 | 835 | def validate(self, obj, value): |
|
836 | 836 | try: |
|
837 | 837 | return unicode(value) |
|
838 | 838 | except: |
|
839 | 839 | self.error(obj, value) |
|
840 | 840 | |
|
841 | 841 | |
|
842 | 842 | class Bool(TraitletType): |
|
843 | 843 | """A boolean (True, False) traitlet.""" |
|
844 | 844 | evaluate = bool |
|
845 | 845 | default_value = False |
|
846 | 846 | info_text = 'a boolean' |
|
847 | 847 | |
|
848 | 848 | def validate(self, obj, value): |
|
849 | 849 | if isinstance(value, bool): |
|
850 | 850 | return value |
|
851 | 851 | self.error(obj, value) |
|
852 | 852 | |
|
853 | 853 | |
|
854 | 854 | class CBool(Bool): |
|
855 | 855 | """A casting version of the boolean traitlet.""" |
|
856 | 856 | |
|
857 | 857 | def validate(self, obj, value): |
|
858 | 858 | try: |
|
859 | 859 | return bool(value) |
|
860 | 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