Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,148 +1,148 b'' | |||
|
1 | 1 | # Get the config being loaded so we can set attributes on it |
|
2 | 2 | c = get_config() |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Global options |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | |
|
8 | 8 | # c.Global.display_banner = True |
|
9 | 9 | |
|
10 | 10 | # c.Global.classic = False |
|
11 | 11 | |
|
12 | 12 | # c.Global.nosep = True |
|
13 | 13 | |
|
14 | 14 | # Set this to determine the detail of what is logged at startup. |
|
15 | 15 | # The default is 30 and possible values are 0,10,20,30,40,50. |
|
16 | 16 | # c.Global.log_level = 20 |
|
17 | 17 | |
|
18 | 18 | # This should be a list of importable Python modules that have an |
|
19 | 19 | # load_in_ipython(ip) method. This method gets called when the extension |
|
20 | 20 | # is loaded. You can put your extensions anywhere they can be imported |
|
21 | 21 | # but we add the extensions subdir of the ipython directory to sys.path |
|
22 | 22 | # during extension loading, so you can put them there as well. |
|
23 | 23 | # c.Global.extensions = [ |
|
24 | 24 | # 'myextension' |
|
25 | 25 | # ] |
|
26 | 26 | |
|
27 | 27 | # These lines are run in IPython in the user's namespace after extensions |
|
28 | 28 | # are loaded. They can contain full IPython syntax with magics etc. |
|
29 | 29 | # c.Global.exec_lines = [ |
|
30 | 30 | # 'import numpy', |
|
31 | 31 | # 'a = 10; b = 20', |
|
32 | 32 | # '1/0' |
|
33 | 33 | # ] |
|
34 | 34 | |
|
35 | 35 | # These files are run in IPython in the user's namespace. Files with a .py |
|
36 | 36 | # extension need to be pure Python. Files with a .ipy extension can have |
|
37 | 37 | # custom IPython syntax (like magics, etc.). |
|
38 | # These files need to be in the cwd, the ipythondir or be absolute paths. | |
|
38 | # These files need to be in the cwd, the ipython_dir or be absolute paths. | |
|
39 | 39 | # c.Global.exec_files = [ |
|
40 | 40 | # 'mycode.py', |
|
41 | 41 | # 'fancy.ipy' |
|
42 | 42 | # ] |
|
43 | 43 | |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | # InteractiveShell options |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | |
|
48 | 48 | # c.InteractiveShell.autocall = 1 |
|
49 | 49 | |
|
50 | 50 | # c.InteractiveShell.autoedit_syntax = False |
|
51 | 51 | |
|
52 | 52 | # c.InteractiveShell.autoindent = True |
|
53 | 53 | |
|
54 | 54 | # c.InteractiveShell.automagic = False |
|
55 | 55 | |
|
56 | 56 | # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner' |
|
57 | 57 | |
|
58 | 58 | # c.InteractiveShell.banner2 = "This is for extra banner text" |
|
59 | 59 | |
|
60 | 60 | # c.InteractiveShell.cache_size = 1000 |
|
61 | 61 | |
|
62 | 62 | # c.InteractiveShell.colors = 'LightBG' |
|
63 | 63 | |
|
64 | 64 | # c.InteractiveShell.color_info = True |
|
65 | 65 | |
|
66 | 66 | # c.InteractiveShell.confirm_exit = True |
|
67 | 67 | |
|
68 | 68 | # c.InteractiveShell.deep_reload = False |
|
69 | 69 | |
|
70 | 70 | # c.InteractiveShell.editor = 'nano' |
|
71 | 71 | |
|
72 | 72 | # c.InteractiveShell.logstart = True |
|
73 | 73 | |
|
74 | 74 | # c.InteractiveShell.logfile = 'ipython_log.py' |
|
75 | 75 | |
|
76 | 76 | # c.InteractiveShell.logappend = 'mylog.py' |
|
77 | 77 | |
|
78 | 78 | # c.InteractiveShell.object_info_string_level = 0 |
|
79 | 79 | |
|
80 | 80 | # c.InteractiveShell.pager = 'less' |
|
81 | 81 | |
|
82 | 82 | # c.InteractiveShell.pdb = False |
|
83 | 83 | |
|
84 | 84 | # c.InteractiveShell.pprint = True |
|
85 | 85 | |
|
86 | 86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' |
|
87 | 87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' |
|
88 | 88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' |
|
89 | 89 | # c.InteractiveShell.prompts_pad_left = True |
|
90 | 90 | |
|
91 | 91 | # c.InteractiveShell.quiet = False |
|
92 | 92 | |
|
93 | 93 | # Readline |
|
94 | 94 | # c.InteractiveShell.readline_use = True |
|
95 | 95 | |
|
96 | 96 | # c.InteractiveShell.readline_parse_and_bind = [ |
|
97 | 97 | # 'tab: complete', |
|
98 | 98 | # '"\C-l": possible-completions', |
|
99 | 99 | # 'set show-all-if-ambiguous on', |
|
100 | 100 | # '"\C-o": tab-insert', |
|
101 | 101 | # '"\M-i": " "', |
|
102 | 102 | # '"\M-o": "\d\d\d\d"', |
|
103 | 103 | # '"\M-I": "\d\d\d\d"', |
|
104 | 104 | # '"\C-r": reverse-search-history', |
|
105 | 105 | # '"\C-s": forward-search-history', |
|
106 | 106 | # '"\C-p": history-search-backward', |
|
107 | 107 | # '"\C-n": history-search-forward', |
|
108 | 108 | # '"\e[A": history-search-backward', |
|
109 | 109 | # '"\e[B": history-search-forward', |
|
110 | 110 | # '"\C-k": kill-line', |
|
111 | 111 | # '"\C-u": unix-line-discard', |
|
112 | 112 | # ] |
|
113 | 113 | # c.InteractiveShell.readline_remove_delims = '-/~' |
|
114 | 114 | # c.InteractiveShell.readline_merge_completions = True |
|
115 | 115 | # c.InteractiveShell.readline_omit_names = 0 |
|
116 | 116 | |
|
117 | 117 | # c.InteractiveShell.screen_length = 0 |
|
118 | 118 | |
|
119 | 119 | # c.InteractiveShell.separate_in = '\n' |
|
120 | 120 | # c.InteractiveShell.separate_out = '' |
|
121 | 121 | # c.InteractiveShell.separate_out2 = '' |
|
122 | 122 | |
|
123 | 123 | # c.InteractiveShell.system_header = "IPython system call: " |
|
124 | 124 | |
|
125 | 125 | # c.InteractiveShell.system_verbose = True |
|
126 | 126 | |
|
127 | 127 | # c.InteractiveShell.term_title = False |
|
128 | 128 | |
|
129 | 129 | # c.InteractiveShell.wildcards_case_sensitive = True |
|
130 | 130 | |
|
131 | 131 | # c.InteractiveShell.xmode = 'Context' |
|
132 | 132 | |
|
133 | 133 | #----------------------------------------------------------------------------- |
|
134 | 134 | # PrefilterManager options |
|
135 | 135 | #----------------------------------------------------------------------------- |
|
136 | 136 | |
|
137 | 137 | # c.PrefilterManager.multi_line_specials = True |
|
138 | 138 | |
|
139 | 139 | #----------------------------------------------------------------------------- |
|
140 | 140 | # AliasManager options |
|
141 | 141 | #----------------------------------------------------------------------------- |
|
142 | 142 | |
|
143 | 143 | # Do this to disable all defaults |
|
144 | 144 | # c.AliasManager.default_aliases = [] |
|
145 | 145 | |
|
146 | 146 | # c.AliasManager.user_aliases = [ |
|
147 | 147 | # ('foo', 'echo Hi') |
|
148 | 148 | # ] No newline at end of file |
@@ -1,364 +1,364 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | An application for IPython. |
|
5 | 5 | |
|
6 | 6 | All top-level applications should use the classes in this module for |
|
7 | 7 | handling configuration and creating componenets. |
|
8 | 8 | |
|
9 | 9 | The job of an :class:`Application` is to create the master configuration |
|
10 | 10 | object and then create the components, passing the config to them. |
|
11 | 11 | |
|
12 | 12 | Authors: |
|
13 | 13 | |
|
14 | 14 | * Brian Granger |
|
15 | 15 | * Fernando Perez |
|
16 | 16 | |
|
17 | 17 | Notes |
|
18 | 18 | ----- |
|
19 | 19 | """ |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Copyright (C) 2008-2009 The IPython Development Team |
|
23 | 23 | # |
|
24 | 24 | # Distributed under the terms of the BSD License. The full license is in |
|
25 | 25 | # the file COPYING, distributed as part of this software. |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | # Imports |
|
30 | 30 | #----------------------------------------------------------------------------- |
|
31 | 31 | |
|
32 | 32 | import logging |
|
33 | 33 | import os |
|
34 | 34 | import sys |
|
35 | 35 | |
|
36 | 36 | from IPython.core import release |
|
37 | 37 | from IPython.utils.genutils import get_ipython_dir |
|
38 | 38 | from IPython.config.loader import ( |
|
39 | 39 | PyFileConfigLoader, |
|
40 | 40 | ArgParseConfigLoader, |
|
41 | 41 | Config, |
|
42 | 42 | NoConfigDefault |
|
43 | 43 | ) |
|
44 | 44 | |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | # Classes and functions |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | class BaseAppArgParseConfigLoader(ArgParseConfigLoader): |
|
51 | 51 | """Default command line options for IPython based applications.""" |
|
52 | 52 | |
|
53 | 53 | def _add_other_arguments(self): |
|
54 |
self.parser.add_argument(' |
|
|
55 | dest='Global.ipythondir',type=str, | |
|
56 | help='Set to override default location of Global.ipythondir.', | |
|
54 | self.parser.add_argument('--ipython-dir', | |
|
55 | dest='Global.ipython_dir',type=str, | |
|
56 | help='Set to override default location of Global.ipython_dir.', | |
|
57 | 57 | default=NoConfigDefault, |
|
58 | metavar='Global.ipythondir') | |
|
59 |
self.parser.add_argument('-p', |
|
|
58 | metavar='Global.ipython_dir') | |
|
59 | self.parser.add_argument('-p', '--profile', | |
|
60 | 60 | dest='Global.profile',type=str, |
|
61 | 61 | help='The string name of the ipython profile to be used.', |
|
62 | 62 | default=NoConfigDefault, |
|
63 | 63 | metavar='Global.profile') |
|
64 |
self.parser.add_argument(' |
|
|
64 | self.parser.add_argument('--log-level', | |
|
65 | 65 | dest="Global.log_level",type=int, |
|
66 | 66 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
67 | 67 | default=NoConfigDefault, |
|
68 | 68 | metavar='Global.log_level') |
|
69 |
self.parser.add_argument(' |
|
|
69 | self.parser.add_argument('--config-file', | |
|
70 | 70 | dest='Global.config_file',type=str, |
|
71 | 71 | help='Set the config file name to override default.', |
|
72 | 72 | default=NoConfigDefault, |
|
73 | 73 | metavar='Global.config_file') |
|
74 | 74 | |
|
75 | 75 | |
|
76 | 76 | class ApplicationError(Exception): |
|
77 | 77 | pass |
|
78 | 78 | |
|
79 | 79 | |
|
80 | 80 | class Application(object): |
|
81 | 81 | """Load a config, construct components and set them running.""" |
|
82 | 82 | |
|
83 | 83 | name = 'ipython' |
|
84 | 84 | description = 'IPython: an enhanced interactive Python shell.' |
|
85 | 85 | config_file_name = 'ipython_config.py' |
|
86 | 86 | default_log_level = logging.WARN |
|
87 | 87 | |
|
88 | 88 | def __init__(self): |
|
89 | 89 | self._exiting = False |
|
90 | 90 | self.init_logger() |
|
91 | 91 | # Track the default and actual separately because some messages are |
|
92 | 92 | # only printed if we aren't using the default. |
|
93 | 93 | self.default_config_file_name = self.config_file_name |
|
94 | 94 | |
|
95 | 95 | def init_logger(self): |
|
96 | 96 | self.log = logging.getLogger(self.__class__.__name__) |
|
97 | 97 | # This is used as the default until the command line arguments are read. |
|
98 | 98 | self.log.setLevel(self.default_log_level) |
|
99 | 99 | self._log_handler = logging.StreamHandler() |
|
100 | 100 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
101 | 101 | self._log_handler.setFormatter(self._log_formatter) |
|
102 | 102 | self.log.addHandler(self._log_handler) |
|
103 | 103 | |
|
104 | 104 | def _set_log_level(self, level): |
|
105 | 105 | self.log.setLevel(level) |
|
106 | 106 | |
|
107 | 107 | def _get_log_level(self): |
|
108 | 108 | return self.log.level |
|
109 | 109 | |
|
110 | 110 | log_level = property(_get_log_level, _set_log_level) |
|
111 | 111 | |
|
112 | 112 | def start(self): |
|
113 | 113 | """Start the application.""" |
|
114 | 114 | self.attempt(self.create_default_config) |
|
115 | 115 | self.log_default_config() |
|
116 | 116 | self.set_default_config_log_level() |
|
117 | 117 | self.attempt(self.pre_load_command_line_config) |
|
118 | 118 | self.attempt(self.load_command_line_config, action='abort') |
|
119 | 119 | self.set_command_line_config_log_level() |
|
120 | 120 | self.attempt(self.post_load_command_line_config) |
|
121 | 121 | self.log_command_line_config() |
|
122 | self.attempt(self.find_ipythondir) | |
|
122 | self.attempt(self.find_ipython_dir) | |
|
123 | 123 | self.attempt(self.find_resources) |
|
124 | 124 | self.attempt(self.find_config_file_name) |
|
125 | 125 | self.attempt(self.find_config_file_paths) |
|
126 | 126 | self.attempt(self.pre_load_file_config) |
|
127 | 127 | self.attempt(self.load_file_config) |
|
128 | 128 | self.set_file_config_log_level() |
|
129 | 129 | self.attempt(self.post_load_file_config) |
|
130 | 130 | self.log_file_config() |
|
131 | 131 | self.attempt(self.merge_configs) |
|
132 | 132 | self.log_master_config() |
|
133 | 133 | self.attempt(self.pre_construct) |
|
134 | 134 | self.attempt(self.construct) |
|
135 | 135 | self.attempt(self.post_construct) |
|
136 | 136 | self.attempt(self.start_app) |
|
137 | 137 | |
|
138 | 138 | #------------------------------------------------------------------------- |
|
139 | 139 | # Various stages of Application creation |
|
140 | 140 | #------------------------------------------------------------------------- |
|
141 | 141 | |
|
142 | 142 | def create_default_config(self): |
|
143 | 143 | """Create defaults that can't be set elsewhere. |
|
144 | 144 | |
|
145 | 145 | For the most part, we try to set default in the class attributes |
|
146 | 146 | of Components. But, defaults the top-level Application (which is |
|
147 | 147 | not a HasTraitlets or Component) are not set in this way. Instead |
|
148 | 148 | we set them here. The Global section is for variables like this that |
|
149 | 149 | don't belong to a particular component. |
|
150 | 150 | """ |
|
151 | 151 | self.default_config = Config() |
|
152 | self.default_config.Global.ipythondir = get_ipython_dir() | |
|
152 | self.default_config.Global.ipython_dir = get_ipython_dir() | |
|
153 | 153 | self.default_config.Global.log_level = self.log_level |
|
154 | 154 | |
|
155 | 155 | def log_default_config(self): |
|
156 | 156 | self.log.debug('Default config loaded:') |
|
157 | 157 | self.log.debug(repr(self.default_config)) |
|
158 | 158 | |
|
159 | 159 | def set_default_config_log_level(self): |
|
160 | 160 | try: |
|
161 | 161 | self.log_level = self.default_config.Global.log_level |
|
162 | 162 | except AttributeError: |
|
163 | 163 | # Fallback to the default_log_level class attribute |
|
164 | 164 | pass |
|
165 | 165 | |
|
166 | 166 | def create_command_line_config(self): |
|
167 | 167 | """Create and return a command line config loader.""" |
|
168 | 168 | return BaseAppArgParseConfigLoader( |
|
169 | 169 | description=self.description, |
|
170 | 170 | version=release.version |
|
171 | 171 | ) |
|
172 | 172 | |
|
173 | 173 | def pre_load_command_line_config(self): |
|
174 | 174 | """Do actions just before loading the command line config.""" |
|
175 | 175 | pass |
|
176 | 176 | |
|
177 | 177 | def load_command_line_config(self): |
|
178 | 178 | """Load the command line config.""" |
|
179 | 179 | loader = self.create_command_line_config() |
|
180 | 180 | self.command_line_config = loader.load_config() |
|
181 | 181 | self.extra_args = loader.get_extra_args() |
|
182 | 182 | |
|
183 | 183 | def set_command_line_config_log_level(self): |
|
184 | 184 | try: |
|
185 | 185 | self.log_level = self.command_line_config.Global.log_level |
|
186 | 186 | except AttributeError: |
|
187 | 187 | pass |
|
188 | 188 | |
|
189 | 189 | def post_load_command_line_config(self): |
|
190 | 190 | """Do actions just after loading the command line config.""" |
|
191 | 191 | pass |
|
192 | 192 | |
|
193 | 193 | def log_command_line_config(self): |
|
194 | 194 | self.log.debug("Command line config loaded:") |
|
195 | 195 | self.log.debug(repr(self.command_line_config)) |
|
196 | 196 | |
|
197 | def find_ipythondir(self): | |
|
197 | def find_ipython_dir(self): | |
|
198 | 198 | """Set the IPython directory. |
|
199 | 199 | |
|
200 | This sets ``self.ipythondir``, but the actual value that is passed | |
|
200 | This sets ``self.ipython_dir``, but the actual value that is passed | |
|
201 | 201 | to the application is kept in either ``self.default_config`` or |
|
202 | ``self.command_line_config``. This also adds ``self.ipythondir`` to | |
|
202 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to | |
|
203 | 203 | ``sys.path`` so config files there can be references by other config |
|
204 | 204 | files. |
|
205 | 205 | """ |
|
206 | 206 | |
|
207 | 207 | try: |
|
208 | self.ipythondir = self.command_line_config.Global.ipythondir | |
|
208 | self.ipython_dir = self.command_line_config.Global.ipython_dir | |
|
209 | 209 | except AttributeError: |
|
210 | self.ipythondir = self.default_config.Global.ipythondir | |
|
211 | sys.path.append(os.path.abspath(self.ipythondir)) | |
|
212 | if not os.path.isdir(self.ipythondir): | |
|
213 | os.makedirs(self.ipythondir, mode=0777) | |
|
214 | self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir) | |
|
210 | self.ipython_dir = self.default_config.Global.ipython_dir | |
|
211 | sys.path.append(os.path.abspath(self.ipython_dir)) | |
|
212 | if not os.path.isdir(self.ipython_dir): | |
|
213 | os.makedirs(self.ipython_dir, mode=0777) | |
|
214 | self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir) | |
|
215 | 215 | |
|
216 | 216 | def find_resources(self): |
|
217 | 217 | """Find other resources that need to be in place. |
|
218 | 218 | |
|
219 | 219 | Things like cluster directories need to be in place to find the |
|
220 | 220 | config file. These happen right after the IPython directory has |
|
221 | 221 | been set. |
|
222 | 222 | """ |
|
223 | 223 | pass |
|
224 | 224 | |
|
225 | 225 | def find_config_file_name(self): |
|
226 | 226 | """Find the config file name for this application. |
|
227 | 227 | |
|
228 | 228 | This must set ``self.config_file_name`` to the filename of the |
|
229 | 229 | config file to use (just the filename). The search paths for the |
|
230 | 230 | config file are set in :meth:`find_config_file_paths` and then passed |
|
231 | 231 | to the config file loader where they are resolved to an absolute path. |
|
232 | 232 | |
|
233 | 233 | If a profile has been set at the command line, this will resolve |
|
234 | 234 | it. |
|
235 | 235 | """ |
|
236 | 236 | |
|
237 | 237 | try: |
|
238 | 238 | self.config_file_name = self.command_line_config.Global.config_file |
|
239 | 239 | except AttributeError: |
|
240 | 240 | pass |
|
241 | 241 | |
|
242 | 242 | try: |
|
243 | 243 | self.profile_name = self.command_line_config.Global.profile |
|
244 | 244 | name_parts = self.config_file_name.split('.') |
|
245 | 245 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
246 | 246 | self.config_file_name = ''.join(name_parts) |
|
247 | 247 | except AttributeError: |
|
248 | 248 | pass |
|
249 | 249 | |
|
250 | 250 | def find_config_file_paths(self): |
|
251 | 251 | """Set the search paths for resolving the config file. |
|
252 | 252 | |
|
253 | 253 | This must set ``self.config_file_paths`` to a sequence of search |
|
254 | 254 | paths to pass to the config file loader. |
|
255 | 255 | """ |
|
256 | self.config_file_paths = (os.getcwd(), self.ipythondir) | |
|
256 | self.config_file_paths = (os.getcwd(), self.ipython_dir) | |
|
257 | 257 | |
|
258 | 258 | def pre_load_file_config(self): |
|
259 | 259 | """Do actions before the config file is loaded.""" |
|
260 | 260 | pass |
|
261 | 261 | |
|
262 | 262 | def load_file_config(self): |
|
263 | 263 | """Load the config file. |
|
264 | 264 | |
|
265 | 265 | This tries to load the config file from disk. If successful, the |
|
266 | 266 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
267 | 267 | location. If not successful, an empty config is used. |
|
268 | 268 | """ |
|
269 | 269 | self.log.debug("Attempting to load config file: %s" % self.config_file_name) |
|
270 | 270 | loader = PyFileConfigLoader(self.config_file_name, |
|
271 | 271 | path=self.config_file_paths) |
|
272 | 272 | try: |
|
273 | 273 | self.file_config = loader.load_config() |
|
274 | 274 | self.file_config.Global.config_file = loader.full_filename |
|
275 | 275 | except IOError: |
|
276 | 276 | # Only warn if the default config file was NOT being used. |
|
277 | 277 | if not self.config_file_name==self.default_config_file_name: |
|
278 | 278 | self.log.warn("Config file not found, skipping: %s" % \ |
|
279 | 279 | self.config_file_name, exc_info=True) |
|
280 | 280 | self.file_config = Config() |
|
281 | 281 | except: |
|
282 | 282 | self.log.warn("Error loading config file: %s" % \ |
|
283 | 283 | self.config_file_name, exc_info=True) |
|
284 | 284 | self.file_config = Config() |
|
285 | 285 | |
|
286 | 286 | def set_file_config_log_level(self): |
|
287 | 287 | # We need to keeep self.log_level updated. But we only use the value |
|
288 | 288 | # of the file_config if a value was not specified at the command |
|
289 | 289 | # line, because the command line overrides everything. |
|
290 | 290 | if not hasattr(self.command_line_config.Global, 'log_level'): |
|
291 | 291 | try: |
|
292 | 292 | self.log_level = self.file_config.Global.log_level |
|
293 | 293 | except AttributeError: |
|
294 | 294 | pass # Use existing value |
|
295 | 295 | |
|
296 | 296 | def post_load_file_config(self): |
|
297 | 297 | """Do actions after the config file is loaded.""" |
|
298 | 298 | pass |
|
299 | 299 | |
|
300 | 300 | def log_file_config(self): |
|
301 | 301 | if hasattr(self.file_config.Global, 'config_file'): |
|
302 | 302 | self.log.debug("Config file loaded: %s" % self.file_config.Global.config_file) |
|
303 | 303 | self.log.debug(repr(self.file_config)) |
|
304 | 304 | |
|
305 | 305 | def merge_configs(self): |
|
306 | 306 | """Merge the default, command line and file config objects.""" |
|
307 | 307 | config = Config() |
|
308 | 308 | config._merge(self.default_config) |
|
309 | 309 | config._merge(self.file_config) |
|
310 | 310 | config._merge(self.command_line_config) |
|
311 | 311 | self.master_config = config |
|
312 | 312 | |
|
313 | 313 | def log_master_config(self): |
|
314 | 314 | self.log.debug("Master config created:") |
|
315 | 315 | self.log.debug(repr(self.master_config)) |
|
316 | 316 | |
|
317 | 317 | def pre_construct(self): |
|
318 | 318 | """Do actions after the config has been built, but before construct.""" |
|
319 | 319 | pass |
|
320 | 320 | |
|
321 | 321 | def construct(self): |
|
322 | 322 | """Construct the main components that make up this app.""" |
|
323 | 323 | self.log.debug("Constructing components for application") |
|
324 | 324 | |
|
325 | 325 | def post_construct(self): |
|
326 | 326 | """Do actions after construct, but before starting the app.""" |
|
327 | 327 | pass |
|
328 | 328 | |
|
329 | 329 | def start_app(self): |
|
330 | 330 | """Actually start the app.""" |
|
331 | 331 | self.log.debug("Starting application") |
|
332 | 332 | |
|
333 | 333 | #------------------------------------------------------------------------- |
|
334 | 334 | # Utility methods |
|
335 | 335 | #------------------------------------------------------------------------- |
|
336 | 336 | |
|
337 | 337 | def abort(self): |
|
338 | 338 | """Abort the starting of the application.""" |
|
339 | 339 | if self._exiting: |
|
340 | 340 | pass |
|
341 | 341 | else: |
|
342 | 342 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) |
|
343 | 343 | self._exiting = True |
|
344 | 344 | sys.exit(1) |
|
345 | 345 | |
|
346 | 346 | def exit(self): |
|
347 | 347 | if self._exiting: |
|
348 | 348 | pass |
|
349 | 349 | else: |
|
350 | 350 | self.log.debug("Exiting application: %s" % self.name) |
|
351 | 351 | self._exiting = True |
|
352 | 352 | sys.exit(1) |
|
353 | 353 | |
|
354 | 354 | def attempt(self, func, action='abort'): |
|
355 | 355 | try: |
|
356 | 356 | func() |
|
357 | 357 | except SystemExit: |
|
358 | 358 | raise |
|
359 | 359 | except: |
|
360 | 360 | if action == 'abort': |
|
361 | 361 | self.abort() |
|
362 | 362 | elif action == 'exit': |
|
363 | 363 | self.exit() |
|
364 | 364 |
@@ -1,229 +1,229 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
3 | 3 | |
|
4 | 4 | |
|
5 | 5 | Authors |
|
6 | 6 | ------- |
|
7 | 7 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | 12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #***************************************************************************** |
|
17 | 17 | |
|
18 | 18 | #**************************************************************************** |
|
19 | 19 | # Required modules |
|
20 | 20 | |
|
21 | 21 | # From the standard library |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | from pprint import pformat |
|
25 | 25 | |
|
26 | 26 | # Our own |
|
27 | 27 | from IPython.core import release |
|
28 | 28 | from IPython.core import ultratb |
|
29 | 29 | from IPython.external.Itpl import itpl |
|
30 | 30 | |
|
31 | 31 | from IPython.utils.genutils import * |
|
32 | 32 | |
|
33 | 33 | #**************************************************************************** |
|
34 | 34 | class CrashHandler: |
|
35 | 35 | """Customizable crash handlers for IPython-based systems. |
|
36 | 36 | |
|
37 | 37 | Instances of this class provide a __call__ method which can be used as a |
|
38 | 38 | sys.excepthook, i.e., the __call__ signature is: |
|
39 | 39 | |
|
40 | 40 | def __call__(self,etype, evalue, etb) |
|
41 | 41 | |
|
42 | 42 | """ |
|
43 | 43 | |
|
44 | 44 | def __init__(self,IP,app_name,contact_name,contact_email, |
|
45 | 45 | bug_tracker,crash_report_fname, |
|
46 | 46 | show_crash_traceback=True): |
|
47 | 47 | """New crash handler. |
|
48 | 48 | |
|
49 | 49 | Inputs: |
|
50 | 50 | |
|
51 | 51 | - IP: a running IPython instance, which will be queried at crash time |
|
52 | 52 | for internal information. |
|
53 | 53 | |
|
54 | 54 | - app_name: a string containing the name of your application. |
|
55 | 55 | |
|
56 | 56 | - contact_name: a string with the name of the person to contact. |
|
57 | 57 | |
|
58 | 58 | - contact_email: a string with the email address of the contact. |
|
59 | 59 | |
|
60 | 60 | - bug_tracker: a string with the URL for your project's bug tracker. |
|
61 | 61 | |
|
62 | 62 | - crash_report_fname: a string with the filename for the crash report |
|
63 | 63 | to be saved in. These reports are left in the ipython user directory |
|
64 | 64 | as determined by the running IPython instance. |
|
65 | 65 | |
|
66 | 66 | Optional inputs: |
|
67 | 67 | |
|
68 | 68 | - show_crash_traceback(True): if false, don't print the crash |
|
69 | 69 | traceback on stderr, only generate the on-disk report |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | Non-argument instance attributes: |
|
73 | 73 | |
|
74 | 74 | These instances contain some non-argument attributes which allow for |
|
75 | 75 | further customization of the crash handler's behavior. Please see the |
|
76 | 76 | source for further details. |
|
77 | 77 | """ |
|
78 | 78 | |
|
79 | 79 | # apply args into instance |
|
80 | 80 | self.IP = IP # IPython instance |
|
81 | 81 | self.app_name = app_name |
|
82 | 82 | self.contact_name = contact_name |
|
83 | 83 | self.contact_email = contact_email |
|
84 | 84 | self.bug_tracker = bug_tracker |
|
85 | 85 | self.crash_report_fname = crash_report_fname |
|
86 | 86 | self.show_crash_traceback = show_crash_traceback |
|
87 | 87 | |
|
88 | 88 | # Hardcoded defaults, which can be overridden either by subclasses or |
|
89 | 89 | # at runtime for the instance. |
|
90 | 90 | |
|
91 | 91 | # Template for the user message. Subclasses which completely override |
|
92 | 92 | # this, or user apps, can modify it to suit their tastes. It gets |
|
93 | 93 | # expanded using itpl, so calls of the kind $self.foo are valid. |
|
94 | 94 | self.user_message_template = """ |
|
95 | 95 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
96 | 96 | |
|
97 | 97 | A crash report was automatically generated with the following information: |
|
98 | 98 | - A verbatim copy of the crash traceback. |
|
99 | 99 | - A copy of your input history during this session. |
|
100 | 100 | - Data on your current $self.app_name configuration. |
|
101 | 101 | |
|
102 | 102 | It was left in the file named: |
|
103 | 103 | \t'$self.crash_report_fname' |
|
104 | 104 | If you can email this file to the developers, the information in it will help |
|
105 | 105 | them in understanding and correcting the problem. |
|
106 | 106 | |
|
107 | 107 | You can mail it to: $self.contact_name at $self.contact_email |
|
108 | 108 | with the subject '$self.app_name Crash Report'. |
|
109 | 109 | |
|
110 | 110 | If you want to do it now, the following command will work (under Unix): |
|
111 | 111 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
112 | 112 | |
|
113 | 113 | To ensure accurate tracking of this issue, please file a report about it at: |
|
114 | 114 | $self.bug_tracker |
|
115 | 115 | """ |
|
116 | 116 | |
|
117 | 117 | def __call__(self,etype, evalue, etb): |
|
118 | 118 | """Handle an exception, call for compatible with sys.excepthook""" |
|
119 | 119 | |
|
120 | 120 | # Report tracebacks shouldn't use color in general (safer for users) |
|
121 | 121 | color_scheme = 'NoColor' |
|
122 | 122 | |
|
123 | 123 | # Use this ONLY for developer debugging (keep commented out for release) |
|
124 | 124 | #color_scheme = 'Linux' # dbg |
|
125 | 125 | |
|
126 | 126 | try: |
|
127 |
rptdir = self.IP. |
|
|
127 | rptdir = self.IP.ipython_dir | |
|
128 | 128 | except: |
|
129 | 129 | rptdir = os.getcwd() |
|
130 | 130 | if not os.path.isdir(rptdir): |
|
131 | 131 | rptdir = os.getcwd() |
|
132 | 132 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
133 | 133 | # write the report filename into the instance dict so it can get |
|
134 | 134 | # properly expanded out in the user message template |
|
135 | 135 | self.crash_report_fname = report_name |
|
136 | 136 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, |
|
137 | 137 | long_header=1) |
|
138 | 138 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
139 | 139 | |
|
140 | 140 | # print traceback to screen |
|
141 | 141 | if self.show_crash_traceback: |
|
142 | 142 | print >> sys.stderr, traceback |
|
143 | 143 | |
|
144 | 144 | # and generate a complete report on disk |
|
145 | 145 | try: |
|
146 | 146 | report = open(report_name,'w') |
|
147 | 147 | except: |
|
148 | 148 | print >> sys.stderr, 'Could not create crash report on disk.' |
|
149 | 149 | return |
|
150 | 150 | |
|
151 | 151 | # Inform user on stderr of what happened |
|
152 | 152 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) |
|
153 | 153 | print >> sys.stderr, msg |
|
154 | 154 | |
|
155 | 155 | # Construct report on disk |
|
156 | 156 | report.write(self.make_report(traceback)) |
|
157 | 157 | report.close() |
|
158 | 158 | raw_input("Press enter to exit:") |
|
159 | 159 | |
|
160 | 160 | def make_report(self,traceback): |
|
161 | 161 | """Return a string containing a crash report.""" |
|
162 | 162 | |
|
163 | 163 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
164 | 164 | |
|
165 | 165 | report = [] |
|
166 | 166 | rpt_add = report.append |
|
167 | 167 | |
|
168 | 168 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
169 | 169 | rpt_add('IPython version: %s \n\n' % release.version) |
|
170 | 170 | rpt_add('BZR revision : %s \n\n' % release.revision) |
|
171 | 171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
172 | 172 | (os.name,sys.platform) ) |
|
173 | 173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
174 | 174 | rpt_add(pformat(self.IP.dict())) |
|
175 | 175 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
176 | 176 | try: |
|
177 | 177 | rpt_add(sec_sep+"History of session input:") |
|
178 | 178 | for line in self.IP.user_ns['_ih']: |
|
179 | 179 | rpt_add(line) |
|
180 | 180 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
181 | 181 | rpt_add(self.IP._last_input_line+'\n') |
|
182 | 182 | except: |
|
183 | 183 | pass |
|
184 | 184 | |
|
185 | 185 | return ''.join(report) |
|
186 | 186 | |
|
187 | 187 | class IPythonCrashHandler(CrashHandler): |
|
188 | 188 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
189 | 189 | |
|
190 | 190 | def __init__(self,IP): |
|
191 | 191 | |
|
192 | 192 | # Set here which of the IPython authors should be listed as contact |
|
193 | 193 | AUTHOR_CONTACT = 'Fernando' |
|
194 | 194 | |
|
195 | 195 | # Set argument defaults |
|
196 | 196 | app_name = 'IPython' |
|
197 | 197 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
198 | 198 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] |
|
199 | 199 | crash_report_fname = 'IPython_crash_report.txt' |
|
200 | 200 | # Call parent constructor |
|
201 | 201 | CrashHandler.__init__(self,IP,app_name,contact_name,contact_email, |
|
202 | 202 | bug_tracker,crash_report_fname) |
|
203 | 203 | |
|
204 | 204 | def make_report(self,traceback): |
|
205 | 205 | """Return a string containing a crash report.""" |
|
206 | 206 | |
|
207 | 207 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
208 | 208 | |
|
209 | 209 | report = [] |
|
210 | 210 | rpt_add = report.append |
|
211 | 211 | |
|
212 | 212 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
213 | 213 | rpt_add('IPython version: %s \n\n' % release.version) |
|
214 | 214 | rpt_add('BZR revision : %s \n\n' % release.revision) |
|
215 | 215 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
216 | 216 | (os.name,sys.platform) ) |
|
217 | 217 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
218 | 218 | # rpt_add(pformat(self.IP.dict())) |
|
219 | 219 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
220 | 220 | try: |
|
221 | 221 | rpt_add(sec_sep+"History of session input:") |
|
222 | 222 | for line in self.IP.user_ns['_ih']: |
|
223 | 223 | rpt_add(line) |
|
224 | 224 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
225 | 225 | rpt_add(self.IP._last_input_line+'\n') |
|
226 | 226 | except: |
|
227 | 227 | pass |
|
228 | 228 | |
|
229 | 229 | return ''.join(report) |
@@ -1,272 +1,272 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | An embedded IPython shell. |
|
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 | from __future__ import with_statement |
|
27 | 27 | |
|
28 | 28 | import sys |
|
29 | 29 | from contextlib import nested |
|
30 | 30 | |
|
31 | 31 | from IPython.core import ultratb |
|
32 | 32 | from IPython.core.iplib import InteractiveShell |
|
33 | 33 | from IPython.core.ipapp import load_default_config |
|
34 | 34 | |
|
35 | 35 | from IPython.utils.traitlets import Bool, Str, CBool |
|
36 | 36 | from IPython.utils.genutils import ask_yes_no |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | #----------------------------------------------------------------------------- |
|
40 | 40 | # Classes and functions |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | |
|
43 | 43 | # This is an additional magic that is exposed in embedded shells. |
|
44 | 44 | def kill_embedded(self,parameter_s=''): |
|
45 | 45 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
46 | 46 | |
|
47 | 47 | This function (after asking for confirmation) sets an internal flag so that |
|
48 | 48 | an embedded IPython will never activate again. This is useful to |
|
49 | 49 | permanently disable a shell that is being called inside a loop: once you've |
|
50 | 50 | figured out what you needed from it, you may then kill it and the program |
|
51 | 51 | will then continue to run without the interactive shell interfering again. |
|
52 | 52 | """ |
|
53 | 53 | |
|
54 | 54 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
55 | 55 | "(y/n)? [y/N] ",'n') |
|
56 | 56 | if kill: |
|
57 | 57 | self.embedded_active = False |
|
58 | 58 | print "This embedded IPython will not reactivate anymore once you exit." |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | class InteractiveShellEmbed(InteractiveShell): |
|
62 | 62 | |
|
63 | 63 | dummy_mode = Bool(False) |
|
64 | 64 | exit_msg = Str('') |
|
65 | 65 | embedded = CBool(True) |
|
66 | 66 | embedded_active = CBool(True) |
|
67 | 67 | # Like the base class display_banner is not configurable, but here it |
|
68 | 68 | # is True by default. |
|
69 | 69 | display_banner = CBool(True) |
|
70 | 70 | |
|
71 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
|
71 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, | |
|
72 | 72 | user_ns=None, user_global_ns=None, |
|
73 | 73 | banner1=None, banner2=None, display_banner=None, |
|
74 | 74 | custom_exceptions=((),None), exit_msg=''): |
|
75 | 75 | |
|
76 | 76 | self.save_sys_ipcompleter() |
|
77 | 77 | |
|
78 | 78 | super(InteractiveShellEmbed,self).__init__( |
|
79 | parent=parent, config=config, ipythondir=ipythondir, usage=usage, | |
|
79 | parent=parent, config=config, ipython_dir=ipython_dir, usage=usage, | |
|
80 | 80 | user_ns=user_ns, user_global_ns=user_global_ns, |
|
81 | 81 | banner1=banner1, banner2=banner2, display_banner=display_banner, |
|
82 | 82 | custom_exceptions=custom_exceptions) |
|
83 | 83 | |
|
84 | 84 | self.exit_msg = exit_msg |
|
85 | 85 | self.define_magic("kill_embedded", kill_embedded) |
|
86 | 86 | |
|
87 | 87 | # don't use the ipython crash handler so that user exceptions aren't |
|
88 | 88 | # trapped |
|
89 | 89 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
90 | 90 | mode=self.xmode, |
|
91 | 91 | call_pdb=self.pdb) |
|
92 | 92 | |
|
93 | 93 | self.restore_sys_ipcompleter() |
|
94 | 94 | |
|
95 | 95 | def init_sys_modules(self): |
|
96 | 96 | pass |
|
97 | 97 | |
|
98 | 98 | def save_sys_ipcompleter(self): |
|
99 | 99 | """Save readline completer status.""" |
|
100 | 100 | try: |
|
101 | 101 | #print 'Save completer',sys.ipcompleter # dbg |
|
102 | 102 | self.sys_ipcompleter_orig = sys.ipcompleter |
|
103 | 103 | except: |
|
104 | 104 | pass # not nested with IPython |
|
105 | 105 | |
|
106 | 106 | def restore_sys_ipcompleter(self): |
|
107 | 107 | """Restores the readline completer which was in place. |
|
108 | 108 | |
|
109 | 109 | This allows embedded IPython within IPython not to disrupt the |
|
110 | 110 | parent's completion. |
|
111 | 111 | """ |
|
112 | 112 | try: |
|
113 | 113 | self.readline.set_completer(self.sys_ipcompleter_orig) |
|
114 | 114 | sys.ipcompleter = self.sys_ipcompleter_orig |
|
115 | 115 | except: |
|
116 | 116 | pass |
|
117 | 117 | |
|
118 | 118 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, |
|
119 | 119 | stack_depth=1): |
|
120 | 120 | """Activate the interactive interpreter. |
|
121 | 121 | |
|
122 | 122 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
123 | 123 | the interpreter shell with the given local and global namespaces, and |
|
124 | 124 | optionally print a header string at startup. |
|
125 | 125 | |
|
126 | 126 | The shell can be globally activated/deactivated using the |
|
127 | 127 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
128 | 128 | for debugging globally. |
|
129 | 129 | |
|
130 | 130 | However, *each* time you call the shell you can override the current |
|
131 | 131 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
132 | 132 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
133 | 133 | can still have a specific call work by making it as IPShell(dummy=0). |
|
134 | 134 | |
|
135 | 135 | The optional keyword parameter dummy controls whether the call |
|
136 | 136 | actually does anything. |
|
137 | 137 | """ |
|
138 | 138 | |
|
139 | 139 | # If the user has turned it off, go away |
|
140 | 140 | if not self.embedded_active: |
|
141 | 141 | return |
|
142 | 142 | |
|
143 | 143 | # Normal exits from interactive mode set this flag, so the shell can't |
|
144 | 144 | # re-enter (it checks this variable at the start of interactive mode). |
|
145 | 145 | self.exit_now = False |
|
146 | 146 | |
|
147 | 147 | # Allow the dummy parameter to override the global __dummy_mode |
|
148 | 148 | if dummy or (dummy != 0 and self.dummy_mode): |
|
149 | 149 | return |
|
150 | 150 | |
|
151 | 151 | if self.has_readline: |
|
152 | 152 | self.set_completer() |
|
153 | 153 | |
|
154 | 154 | # self.banner is auto computed |
|
155 | 155 | if header: |
|
156 | 156 | self.old_banner2 = self.banner2 |
|
157 | 157 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
158 | 158 | |
|
159 | 159 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
160 | 160 | # our call and get the original caller's namespaces. |
|
161 | 161 | self.mainloop(local_ns, global_ns, stack_depth=stack_depth) |
|
162 | 162 | |
|
163 | 163 | self.banner2 = self.old_banner2 |
|
164 | 164 | |
|
165 | 165 | if self.exit_msg is not None: |
|
166 | 166 | print self.exit_msg |
|
167 | 167 | |
|
168 | 168 | self.restore_sys_ipcompleter() |
|
169 | 169 | |
|
170 | 170 | def mainloop(self, local_ns=None, global_ns=None, stack_depth=0, |
|
171 | 171 | display_banner=None): |
|
172 | 172 | """Embeds IPython into a running python program. |
|
173 | 173 | |
|
174 | 174 | Input: |
|
175 | 175 | |
|
176 | 176 | - header: An optional header message can be specified. |
|
177 | 177 | |
|
178 | 178 | - local_ns, global_ns: working namespaces. If given as None, the |
|
179 | 179 | IPython-initialized one is updated with __main__.__dict__, so that |
|
180 | 180 | program variables become visible but user-specific configuration |
|
181 | 181 | remains possible. |
|
182 | 182 | |
|
183 | 183 | - stack_depth: specifies how many levels in the stack to go to |
|
184 | 184 | looking for namespaces (when local_ns and global_ns are None). This |
|
185 | 185 | allows an intermediate caller to make sure that this function gets |
|
186 | 186 | the namespace from the intended level in the stack. By default (0) |
|
187 | 187 | it will get its locals and globals from the immediate caller. |
|
188 | 188 | |
|
189 | 189 | Warning: it's possible to use this in a program which is being run by |
|
190 | 190 | IPython itself (via %run), but some funny things will happen (a few |
|
191 | 191 | globals get overwritten). In the future this will be cleaned up, as |
|
192 | 192 | there is no fundamental reason why it can't work perfectly.""" |
|
193 | 193 | |
|
194 | 194 | # Get locals and globals from caller |
|
195 | 195 | if local_ns is None or global_ns is None: |
|
196 | 196 | call_frame = sys._getframe(stack_depth).f_back |
|
197 | 197 | |
|
198 | 198 | if local_ns is None: |
|
199 | 199 | local_ns = call_frame.f_locals |
|
200 | 200 | if global_ns is None: |
|
201 | 201 | global_ns = call_frame.f_globals |
|
202 | 202 | |
|
203 | 203 | # Update namespaces and fire up interpreter |
|
204 | 204 | |
|
205 | 205 | # The global one is easy, we can just throw it in |
|
206 | 206 | self.user_global_ns = global_ns |
|
207 | 207 | |
|
208 | 208 | # but the user/local one is tricky: ipython needs it to store internal |
|
209 | 209 | # data, but we also need the locals. We'll copy locals in the user |
|
210 | 210 | # one, but will track what got copied so we can delete them at exit. |
|
211 | 211 | # This is so that a later embedded call doesn't see locals from a |
|
212 | 212 | # previous call (which most likely existed in a separate scope). |
|
213 | 213 | local_varnames = local_ns.keys() |
|
214 | 214 | self.user_ns.update(local_ns) |
|
215 | 215 | #self.user_ns['local_ns'] = local_ns # dbg |
|
216 | 216 | |
|
217 | 217 | # Patch for global embedding to make sure that things don't overwrite |
|
218 | 218 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
219 | 219 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
220 | 220 | if local_ns is None and global_ns is None: |
|
221 | 221 | self.user_global_ns.update(__main__.__dict__) |
|
222 | 222 | |
|
223 | 223 | # make sure the tab-completer has the correct frame information, so it |
|
224 | 224 | # actually completes using the frame's locals/globals |
|
225 | 225 | self.set_completer_frame() |
|
226 | 226 | |
|
227 | 227 | with nested(self.builtin_trap, self.display_trap): |
|
228 | 228 | self.interact(display_banner=display_banner) |
|
229 | 229 | |
|
230 | 230 | # now, purge out the user namespace from anything we might have added |
|
231 | 231 | # from the caller's local namespace |
|
232 | 232 | delvar = self.user_ns.pop |
|
233 | 233 | for var in local_varnames: |
|
234 | 234 | delvar(var,None) |
|
235 | 235 | |
|
236 | 236 | |
|
237 | 237 | _embedded_shell = None |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, |
|
241 | 241 | display_banner=True, exit_msg=''): |
|
242 | 242 | """Call this to embed IPython at the current point in your program. |
|
243 | 243 | |
|
244 | 244 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
245 | 245 | instance and then call it. Consecutive calls just call the already |
|
246 | 246 | created instance. |
|
247 | 247 | |
|
248 | 248 | Here is a simple example:: |
|
249 | 249 | |
|
250 | 250 | from IPython import embed |
|
251 | 251 | a = 10 |
|
252 | 252 | b = 20 |
|
253 | 253 | embed('First time') |
|
254 | 254 | c = 30 |
|
255 | 255 | d = 40 |
|
256 | 256 | embed |
|
257 | 257 | |
|
258 | 258 | Full customization can be done by passing a :class:`Struct` in as the |
|
259 | 259 | config argument. |
|
260 | 260 | """ |
|
261 | 261 | if config is None: |
|
262 | 262 | config = load_default_config() |
|
263 | 263 | config.InteractiveShellEmbed = config.InteractiveShell |
|
264 | 264 | global _embedded_shell |
|
265 | 265 | if _embedded_shell is None: |
|
266 | 266 | _embedded_shell = InteractiveShellEmbed( |
|
267 | 267 | config=config, usage=usage, |
|
268 | 268 | banner1=banner1, banner2=banner2, |
|
269 | 269 | display_banner=display_banner, exit_msg=exit_msg |
|
270 | 270 | ) |
|
271 | 271 | _embedded_shell(header=header, stack_depth=2) |
|
272 | 272 |
@@ -1,544 +1,544 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The :class:`~IPython.core.application.Application` object for the command |
|
5 | 5 | line :command:`ipython` program. |
|
6 | 6 | |
|
7 | 7 | Authors: |
|
8 | 8 | |
|
9 | 9 | * Brian Granger |
|
10 | 10 | * Fernando Perez |
|
11 | 11 | |
|
12 | 12 | Notes |
|
13 | 13 | ----- |
|
14 | 14 | """ |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Copyright (C) 2008-2009 The IPython Development Team |
|
18 | 18 | # |
|
19 | 19 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | 20 | # the file COPYING, distributed as part of this software. |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Imports |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | import logging |
|
28 | 28 | import os |
|
29 | 29 | import sys |
|
30 | 30 | import warnings |
|
31 | 31 | |
|
32 | 32 | from IPython.core.application import Application, BaseAppArgParseConfigLoader |
|
33 | 33 | from IPython.core import release |
|
34 | 34 | from IPython.core.iplib import InteractiveShell |
|
35 | 35 | from IPython.config.loader import ( |
|
36 | 36 | NoConfigDefault, |
|
37 | 37 | Config, |
|
38 | 38 | PyFileConfigLoader |
|
39 | 39 | ) |
|
40 | 40 | |
|
41 | 41 | from IPython.lib import inputhook |
|
42 | 42 | |
|
43 | 43 | from IPython.utils.genutils import filefind, get_ipython_dir |
|
44 | 44 | |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | # Utilities and helpers |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | ipython_desc = """ |
|
51 | 51 | A Python shell with automatic history (input and output), dynamic object |
|
52 | 52 | introspection, easier configuration, command completion, access to the system |
|
53 | 53 | shell and more. |
|
54 | 54 | """ |
|
55 | 55 | |
|
56 | 56 | def pylab_warning(): |
|
57 | 57 | msg = """ |
|
58 | 58 | |
|
59 | 59 | IPython's -pylab mode has been disabled until matplotlib supports this version |
|
60 | 60 | of IPython. This version of IPython has greatly improved GUI integration that |
|
61 | 61 | matplotlib will soon be able to take advantage of. This will eventually |
|
62 | 62 | result in greater stability and a richer API for matplotlib under IPython. |
|
63 | 63 | However during this transition, you will either need to use an older version |
|
64 | 64 | of IPython, or do the following to use matplotlib interactively:: |
|
65 | 65 | |
|
66 | 66 | import matplotlib |
|
67 | 67 | matplotlib.interactive(True) |
|
68 | 68 | matplotlib.use('wxagg') # adjust for your backend |
|
69 | 69 | %gui -a wx # adjust for your GUI |
|
70 | 70 | from matplotlib import pyplot as plt |
|
71 | 71 | |
|
72 | 72 | See the %gui magic for information on the new interface. |
|
73 | 73 | """ |
|
74 | 74 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | #----------------------------------------------------------------------------- |
|
78 | 78 | # Main classes and functions |
|
79 | 79 | #----------------------------------------------------------------------------- |
|
80 | 80 | |
|
81 | 81 | cl_args = ( |
|
82 | (('-autocall',), dict( | |
|
82 | (('--autocall',), dict( | |
|
83 | 83 | type=int, dest='InteractiveShell.autocall', default=NoConfigDefault, |
|
84 | 84 | help='Set the autocall value (0,1,2).', |
|
85 | 85 | metavar='InteractiveShell.autocall') |
|
86 | 86 | ), |
|
87 | (('-autoindent',), dict( | |
|
87 | (('--autoindent',), dict( | |
|
88 | 88 | action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault, |
|
89 | 89 | help='Turn on autoindenting.') |
|
90 | 90 | ), |
|
91 | (('-noautoindent',), dict( | |
|
91 | (('--no-autoindent',), dict( | |
|
92 | 92 | action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault, |
|
93 | 93 | help='Turn off autoindenting.') |
|
94 | 94 | ), |
|
95 | (('-automagic',), dict( | |
|
95 | (('--automagic',), dict( | |
|
96 | 96 | action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault, |
|
97 | 97 | help='Turn on the auto calling of magic commands.') |
|
98 | 98 | ), |
|
99 | (('-noautomagic',), dict( | |
|
99 | (('--no-automagic',), dict( | |
|
100 | 100 | action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault, |
|
101 | 101 | help='Turn off the auto calling of magic commands.') |
|
102 | 102 | ), |
|
103 |
(('-autoedit |
|
|
103 | (('--autoedit-syntax',), dict( | |
|
104 | 104 | action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, |
|
105 | 105 | help='Turn on auto editing of files with syntax errors.') |
|
106 | 106 | ), |
|
107 |
(('-noautoedit |
|
|
107 | (('--no-autoedit-syntax',), dict( | |
|
108 | 108 | action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, |
|
109 | 109 | help='Turn off auto editing of files with syntax errors.') |
|
110 | 110 | ), |
|
111 | (('-banner',), dict( | |
|
111 | (('--banner',), dict( | |
|
112 | 112 | action='store_true', dest='Global.display_banner', default=NoConfigDefault, |
|
113 | 113 | help='Display a banner upon starting IPython.') |
|
114 | 114 | ), |
|
115 | (('-nobanner',), dict( | |
|
115 | (('--no-banner',), dict( | |
|
116 | 116 | action='store_false', dest='Global.display_banner', default=NoConfigDefault, |
|
117 | 117 | help="Don't display a banner upon starting IPython.") |
|
118 | 118 | ), |
|
119 |
(('-cache |
|
|
119 | (('--cache-size',), dict( | |
|
120 | 120 | type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault, |
|
121 | 121 | help="Set the size of the output cache.", |
|
122 | 122 | metavar='InteractiveShell.cache_size') |
|
123 | 123 | ), |
|
124 | (('-classic',), dict( | |
|
124 | (('--classic',), dict( | |
|
125 | 125 | action='store_true', dest='Global.classic', default=NoConfigDefault, |
|
126 | 126 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
127 | 127 | ), |
|
128 | (('-colors',), dict( | |
|
128 | (('--colors',), dict( | |
|
129 | 129 | type=str, dest='InteractiveShell.colors', default=NoConfigDefault, |
|
130 | 130 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
131 | 131 | metavar='InteractiveShell.colors') |
|
132 | 132 | ), |
|
133 |
(('-color |
|
|
133 | (('--color-info',), dict( | |
|
134 | 134 | action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault, |
|
135 | 135 | help="Enable using colors for info related things.") |
|
136 | 136 | ), |
|
137 |
(('- |
|
|
137 | (('--no-color-info',), dict( | |
|
138 | 138 | action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault, |
|
139 | 139 | help="Disable using colors for info related things.") |
|
140 | 140 | ), |
|
141 |
(('-confirm |
|
|
141 | (('--confirm-exit',), dict( | |
|
142 | 142 | action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, |
|
143 | 143 | help="Prompt the user when existing.") |
|
144 | 144 | ), |
|
145 |
(('-noconfirm |
|
|
145 | (('--no-confirm-exit',), dict( | |
|
146 | 146 | action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, |
|
147 | 147 | help="Don't prompt the user when existing.") |
|
148 | 148 | ), |
|
149 |
(('- |
|
|
149 | (('--deep-reload',), dict( | |
|
150 | 150 | action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault, |
|
151 | 151 | help="Enable deep (recursive) reloading by default.") |
|
152 | 152 | ), |
|
153 |
(('- |
|
|
153 | (('--no-deep-reload',), dict( | |
|
154 | 154 | action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault, |
|
155 | 155 | help="Disable deep (recursive) reloading by default.") |
|
156 | 156 | ), |
|
157 | (('-editor',), dict( | |
|
157 | (('--editor',), dict( | |
|
158 | 158 | type=str, dest='InteractiveShell.editor', default=NoConfigDefault, |
|
159 | 159 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
160 | 160 | metavar='InteractiveShell.editor') |
|
161 | 161 | ), |
|
162 | (('-log','-l'), dict( | |
|
162 | (('--log','-l'), dict( | |
|
163 | 163 | action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault, |
|
164 | 164 | help="Start logging to the default file (./ipython_log.py).") |
|
165 | 165 | ), |
|
166 | (('-logfile','-lf'), dict( | |
|
166 | (('--logfile','-lf'), dict( | |
|
167 | 167 | type=str, dest='InteractiveShell.logfile', default=NoConfigDefault, |
|
168 | 168 | help="Start logging to logfile.", |
|
169 | 169 | metavar='InteractiveShell.logfile') |
|
170 | 170 | ), |
|
171 | (('-logappend','-la'), dict( | |
|
171 | (('--log-append','-la'), dict( | |
|
172 | 172 | type=str, dest='InteractiveShell.logappend', default=NoConfigDefault, |
|
173 | 173 | help="Start logging to logappend in append mode.", |
|
174 | 174 | metavar='InteractiveShell.logfile') |
|
175 | 175 | ), |
|
176 | (('-pdb',), dict( | |
|
176 | (('--pdb',), dict( | |
|
177 | 177 | action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault, |
|
178 | 178 | help="Enable auto calling the pdb debugger after every exception.") |
|
179 | 179 | ), |
|
180 | (('-nopdb',), dict( | |
|
180 | (('--nopdb',), dict( | |
|
181 | 181 | action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault, |
|
182 | 182 | help="Disable auto calling the pdb debugger after every exception.") |
|
183 | 183 | ), |
|
184 | (('-pprint',), dict( | |
|
184 | (('--pprint',), dict( | |
|
185 | 185 | action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault, |
|
186 | 186 | help="Enable auto pretty printing of results.") |
|
187 | 187 | ), |
|
188 | (('-nopprint',), dict( | |
|
188 | (('--no-pprint',), dict( | |
|
189 | 189 | action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault, |
|
190 | 190 | help="Disable auto auto pretty printing of results.") |
|
191 | 191 | ), |
|
192 |
(('-prompt |
|
|
192 | (('--prompt-in1','-pi1'), dict( | |
|
193 | 193 | type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault, |
|
194 | 194 | help="Set the main input prompt ('In [\#]: ')", |
|
195 | 195 | metavar='InteractiveShell.prompt_in1') |
|
196 | 196 | ), |
|
197 |
(('-prompt |
|
|
197 | (('--prompt-in2','-pi2'), dict( | |
|
198 | 198 | type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault, |
|
199 | 199 | help="Set the secondary input prompt (' .\D.: ')", |
|
200 | 200 | metavar='InteractiveShell.prompt_in2') |
|
201 | 201 | ), |
|
202 |
(('-prompt |
|
|
202 | (('--prompt-out','-po'), dict( | |
|
203 | 203 | type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault, |
|
204 | 204 | help="Set the output prompt ('Out[\#]:')", |
|
205 | 205 | metavar='InteractiveShell.prompt_out') |
|
206 | 206 | ), |
|
207 | (('-quick',), dict( | |
|
207 | (('--quick',), dict( | |
|
208 | 208 | action='store_true', dest='Global.quick', default=NoConfigDefault, |
|
209 | 209 | help="Enable quick startup with no config files.") |
|
210 | 210 | ), |
|
211 | (('-readline',), dict( | |
|
211 | (('--readline',), dict( | |
|
212 | 212 | action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault, |
|
213 | 213 | help="Enable readline for command line usage.") |
|
214 | 214 | ), |
|
215 | (('-noreadline',), dict( | |
|
215 | (('--no-readline',), dict( | |
|
216 | 216 | action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault, |
|
217 | 217 | help="Disable readline for command line usage.") |
|
218 | 218 | ), |
|
219 |
(('-screen |
|
|
219 | (('--screen-length','-sl'), dict( | |
|
220 | 220 | type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault, |
|
221 | 221 | help='Number of lines on screen, used to control printing of long strings.', |
|
222 | 222 | metavar='InteractiveShell.screen_length') |
|
223 | 223 | ), |
|
224 |
(('-separate |
|
|
224 | (('--separate-in','-si'), dict( | |
|
225 | 225 | type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault, |
|
226 | 226 | help="Separator before input prompts. Default '\n'.", |
|
227 | 227 | metavar='InteractiveShell.separate_in') |
|
228 | 228 | ), |
|
229 |
(('-separate |
|
|
229 | (('--separate-out','-so'), dict( | |
|
230 | 230 | type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault, |
|
231 | 231 | help="Separator before output prompts. Default 0 (nothing).", |
|
232 | 232 | metavar='InteractiveShell.separate_out') |
|
233 | 233 | ), |
|
234 |
(('-separate |
|
|
234 | (('--separate-out2','-so2'), dict( | |
|
235 | 235 | type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault, |
|
236 | 236 | help="Separator after output prompts. Default 0 (nonight).", |
|
237 | 237 | metavar='InteractiveShell.separate_out2') |
|
238 | 238 | ), |
|
239 | (('-nosep',), dict( | |
|
239 | (('-no-sep',), dict( | |
|
240 | 240 | action='store_true', dest='Global.nosep', default=NoConfigDefault, |
|
241 | 241 | help="Eliminate all spacing between prompts.") |
|
242 | 242 | ), |
|
243 |
(('- |
|
|
243 | (('--term-title',), dict( | |
|
244 | 244 | action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault, |
|
245 | 245 | help="Enable auto setting the terminal title.") |
|
246 | 246 | ), |
|
247 |
(('- |
|
|
247 | (('--no-term-title',), dict( | |
|
248 | 248 | action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault, |
|
249 | 249 | help="Disable auto setting the terminal title.") |
|
250 | 250 | ), |
|
251 | (('-xmode',), dict( | |
|
251 | (('--xmode',), dict( | |
|
252 | 252 | type=str, dest='InteractiveShell.xmode', default=NoConfigDefault, |
|
253 | 253 | help="Exception mode ('Plain','Context','Verbose')", |
|
254 | 254 | metavar='InteractiveShell.xmode') |
|
255 | 255 | ), |
|
256 | (('-ext',), dict( | |
|
256 | (('--ext',), dict( | |
|
257 | 257 | type=str, dest='Global.extra_extension', default=NoConfigDefault, |
|
258 | 258 | help="The dotted module name of an IPython extension to load.", |
|
259 | 259 | metavar='Global.extra_extension') |
|
260 | 260 | ), |
|
261 | 261 | (('-c',), dict( |
|
262 | 262 | type=str, dest='Global.code_to_run', default=NoConfigDefault, |
|
263 | 263 | help="Execute the given command string.", |
|
264 | 264 | metavar='Global.code_to_run') |
|
265 | 265 | ), |
|
266 | 266 | (('-i',), dict( |
|
267 | 267 | action='store_true', dest='Global.force_interact', default=NoConfigDefault, |
|
268 | 268 | help="If running code from the command line, become interactive afterwards.") |
|
269 | 269 | ), |
|
270 | (('-wthread',), dict( | |
|
270 | (('--wthread',), dict( | |
|
271 | 271 | action='store_true', dest='Global.wthread', default=NoConfigDefault, |
|
272 | 272 | help="Enable wxPython event loop integration.") |
|
273 | 273 | ), |
|
274 | (('-q4thread','-qthread'), dict( | |
|
274 | (('--q4thread','--qthread'), dict( | |
|
275 | 275 | action='store_true', dest='Global.q4thread', default=NoConfigDefault, |
|
276 | 276 | help="Enable Qt4 event loop integration. Qt3 is no longer supported.") |
|
277 | 277 | ), |
|
278 | (('-gthread',), dict( | |
|
278 | (('--gthread',), dict( | |
|
279 | 279 | action='store_true', dest='Global.gthread', default=NoConfigDefault, |
|
280 | 280 | help="Enable GTK event loop integration.") |
|
281 | 281 | ), |
|
282 | 282 | # # These are only here to get the proper deprecation warnings |
|
283 | (('-pylab',), dict( | |
|
283 | (('--pylab',), dict( | |
|
284 | 284 | action='store_true', dest='Global.pylab', default=NoConfigDefault, |
|
285 | 285 | help="Disabled. Pylab has been disabled until matplotlib " |
|
286 | 286 | "supports this version of IPython.") |
|
287 | 287 | ) |
|
288 | 288 | ) |
|
289 | 289 | |
|
290 | 290 | |
|
291 | 291 | class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader): |
|
292 | 292 | |
|
293 | 293 | arguments = cl_args |
|
294 | 294 | |
|
295 | 295 | |
|
296 | 296 | default_config_file_name = 'ipython_config.py' |
|
297 | 297 | |
|
298 | 298 | |
|
299 | 299 | class IPythonApp(Application): |
|
300 | 300 | name = 'ipython' |
|
301 | 301 | description = 'IPython: an enhanced interactive Python shell.' |
|
302 | 302 | config_file_name = default_config_file_name |
|
303 | 303 | |
|
304 | 304 | def create_default_config(self): |
|
305 | 305 | super(IPythonApp, self).create_default_config() |
|
306 | 306 | self.default_config.Global.display_banner = True |
|
307 | 307 | |
|
308 | 308 | # If the -c flag is given or a file is given to run at the cmd line |
|
309 | 309 | # like "ipython foo.py", normally we exit without starting the main |
|
310 | 310 | # loop. The force_interact config variable allows a user to override |
|
311 | 311 | # this and interact. It is also set by the -i cmd line flag, just |
|
312 | 312 | # like Python. |
|
313 | 313 | self.default_config.Global.force_interact = False |
|
314 | 314 | |
|
315 | 315 | # By default always interact by starting the IPython mainloop. |
|
316 | 316 | self.default_config.Global.interact = True |
|
317 | 317 | |
|
318 | 318 | # No GUI integration by default |
|
319 | 319 | self.default_config.Global.wthread = False |
|
320 | 320 | self.default_config.Global.q4thread = False |
|
321 | 321 | self.default_config.Global.gthread = False |
|
322 | 322 | |
|
323 | 323 | def create_command_line_config(self): |
|
324 | 324 | """Create and return a command line config loader.""" |
|
325 | 325 | return IPythonAppCLConfigLoader( |
|
326 | 326 | description=self.description, |
|
327 | 327 | version=release.version |
|
328 | 328 | ) |
|
329 | 329 | |
|
330 | 330 | def post_load_command_line_config(self): |
|
331 | 331 | """Do actions after loading cl config.""" |
|
332 | 332 | clc = self.command_line_config |
|
333 | 333 | |
|
334 | 334 | # Display the deprecation warnings about threaded shells |
|
335 | 335 | if hasattr(clc.Global, 'pylab'): |
|
336 | 336 | pylab_warning() |
|
337 | 337 | del clc.Global['pylab'] |
|
338 | 338 | |
|
339 | 339 | def load_file_config(self): |
|
340 | 340 | if hasattr(self.command_line_config.Global, 'quick'): |
|
341 | 341 | if self.command_line_config.Global.quick: |
|
342 | 342 | self.file_config = Config() |
|
343 | 343 | return |
|
344 | 344 | super(IPythonApp, self).load_file_config() |
|
345 | 345 | |
|
346 | 346 | def post_load_file_config(self): |
|
347 | 347 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
348 | 348 | if not hasattr(self.file_config.Global, 'extensions'): |
|
349 | 349 | self.file_config.Global.extensions = [] |
|
350 | 350 | self.file_config.Global.extensions.append( |
|
351 | 351 | self.command_line_config.Global.extra_extension) |
|
352 | 352 | del self.command_line_config.Global.extra_extension |
|
353 | 353 | |
|
354 | 354 | def pre_construct(self): |
|
355 | 355 | config = self.master_config |
|
356 | 356 | |
|
357 | 357 | if hasattr(config.Global, 'classic'): |
|
358 | 358 | if config.Global.classic: |
|
359 | 359 | config.InteractiveShell.cache_size = 0 |
|
360 | 360 | config.InteractiveShell.pprint = 0 |
|
361 | 361 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
362 | 362 | config.InteractiveShell.prompt_in2 = '... ' |
|
363 | 363 | config.InteractiveShell.prompt_out = '' |
|
364 | 364 | config.InteractiveShell.separate_in = \ |
|
365 | 365 | config.InteractiveShell.separate_out = \ |
|
366 | 366 | config.InteractiveShell.separate_out2 = '' |
|
367 | 367 | config.InteractiveShell.colors = 'NoColor' |
|
368 | 368 | config.InteractiveShell.xmode = 'Plain' |
|
369 | 369 | |
|
370 | 370 | if hasattr(config.Global, 'nosep'): |
|
371 | 371 | if config.Global.nosep: |
|
372 | 372 | config.InteractiveShell.separate_in = \ |
|
373 | 373 | config.InteractiveShell.separate_out = \ |
|
374 | 374 | config.InteractiveShell.separate_out2 = '' |
|
375 | 375 | |
|
376 | 376 | # if there is code of files to run from the cmd line, don't interact |
|
377 | 377 | # unless the -i flag (Global.force_interact) is true. |
|
378 | 378 | code_to_run = config.Global.get('code_to_run','') |
|
379 | 379 | file_to_run = False |
|
380 | 380 | if len(self.extra_args)>=1: |
|
381 | 381 | if self.extra_args[0]: |
|
382 | 382 | file_to_run = True |
|
383 | 383 | if file_to_run or code_to_run: |
|
384 | 384 | if not config.Global.force_interact: |
|
385 | 385 | config.Global.interact = False |
|
386 | 386 | |
|
387 | 387 | def construct(self): |
|
388 | 388 | # I am a little hesitant to put these into InteractiveShell itself. |
|
389 | 389 | # But that might be the place for them |
|
390 | 390 | sys.path.insert(0, '') |
|
391 | 391 | |
|
392 | 392 | # Create an InteractiveShell instance |
|
393 | 393 | self.shell = InteractiveShell( |
|
394 | 394 | parent=None, |
|
395 | 395 | config=self.master_config |
|
396 | 396 | ) |
|
397 | 397 | |
|
398 | 398 | def post_construct(self): |
|
399 | 399 | """Do actions after construct, but before starting the app.""" |
|
400 | 400 | config = self.master_config |
|
401 | 401 | |
|
402 | 402 | # shell.display_banner should always be False for the terminal |
|
403 | 403 | # based app, because we call shell.show_banner() by hand below |
|
404 | 404 | # so the banner shows *before* all extension loading stuff. |
|
405 | 405 | self.shell.display_banner = False |
|
406 | 406 | |
|
407 | 407 | if config.Global.display_banner and \ |
|
408 | 408 | config.Global.interact: |
|
409 | 409 | self.shell.show_banner() |
|
410 | 410 | |
|
411 | 411 | # Make sure there is a space below the banner. |
|
412 | 412 | if self.log_level <= logging.INFO: print |
|
413 | 413 | |
|
414 | 414 | # Now a variety of things that happen after the banner is printed. |
|
415 | 415 | self._enable_gui() |
|
416 | 416 | self._load_extensions() |
|
417 | 417 | self._run_exec_lines() |
|
418 | 418 | self._run_exec_files() |
|
419 | 419 | self._run_cmd_line_code() |
|
420 | 420 | |
|
421 | 421 | def _enable_gui(self): |
|
422 | 422 | """Enable GUI event loop integration.""" |
|
423 | 423 | config = self.master_config |
|
424 | 424 | try: |
|
425 | 425 | # Enable GUI integration |
|
426 | 426 | if config.Global.wthread: |
|
427 | 427 | self.log.info("Enabling wx GUI event loop integration") |
|
428 | 428 | inputhook.enable_wx(app=True) |
|
429 | 429 | elif config.Global.q4thread: |
|
430 | 430 | self.log.info("Enabling Qt4 GUI event loop integration") |
|
431 | 431 | inputhook.enable_qt4(app=True) |
|
432 | 432 | elif config.Global.gthread: |
|
433 | 433 | self.log.info("Enabling GTK GUI event loop integration") |
|
434 | 434 | inputhook.enable_gtk(app=True) |
|
435 | 435 | except: |
|
436 | 436 | self.log.warn("Error in enabling GUI event loop integration:") |
|
437 | 437 | self.shell.showtraceback() |
|
438 | 438 | |
|
439 | 439 | def _load_extensions(self): |
|
440 | 440 | """Load all IPython extensions in Global.extensions. |
|
441 | 441 | |
|
442 | 442 | This uses the :meth:`InteractiveShell.load_extensions` to load all |
|
443 | 443 | the extensions listed in ``self.master_config.Global.extensions``. |
|
444 | 444 | """ |
|
445 | 445 | try: |
|
446 | 446 | if hasattr(self.master_config.Global, 'extensions'): |
|
447 | 447 | self.log.debug("Loading IPython extensions...") |
|
448 | 448 | extensions = self.master_config.Global.extensions |
|
449 | 449 | for ext in extensions: |
|
450 | 450 | try: |
|
451 | 451 | self.log.info("Loading IPython extension: %s" % ext) |
|
452 | 452 | self.shell.load_extension(ext) |
|
453 | 453 | except: |
|
454 | 454 | self.log.warn("Error in loading extension: %s" % ext) |
|
455 | 455 | self.shell.showtraceback() |
|
456 | 456 | except: |
|
457 | 457 | self.log.warn("Unknown error in loading extensions:") |
|
458 | 458 | self.shell.showtraceback() |
|
459 | 459 | |
|
460 | 460 | def _run_exec_lines(self): |
|
461 | 461 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
462 | 462 | try: |
|
463 | 463 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
464 | 464 | self.log.debug("Running code from Global.exec_lines...") |
|
465 | 465 | exec_lines = self.master_config.Global.exec_lines |
|
466 | 466 | for line in exec_lines: |
|
467 | 467 | try: |
|
468 | 468 | self.log.info("Running code in user namespace: %s" % line) |
|
469 | 469 | self.shell.runlines(line) |
|
470 | 470 | except: |
|
471 | 471 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
472 | 472 | self.shell.showtraceback() |
|
473 | 473 | except: |
|
474 | 474 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
475 | 475 | self.shell.showtraceback() |
|
476 | 476 | |
|
477 | 477 | def _exec_file(self, fname): |
|
478 | full_filename = filefind(fname, ['.', self.ipythondir]) | |
|
478 | full_filename = filefind(fname, ['.', self.ipython_dir]) | |
|
479 | 479 | if os.path.isfile(full_filename): |
|
480 | 480 | if full_filename.endswith('.py'): |
|
481 | 481 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
482 | 482 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
483 | 483 | elif full_filename.endswith('.ipy'): |
|
484 | 484 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
485 | 485 | self.shell.safe_execfile_ipy(full_filename) |
|
486 | 486 | else: |
|
487 | 487 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) |
|
488 | 488 | |
|
489 | 489 | def _run_exec_files(self): |
|
490 | 490 | try: |
|
491 | 491 | if hasattr(self.master_config.Global, 'exec_files'): |
|
492 | 492 | self.log.debug("Running files in Global.exec_files...") |
|
493 | 493 | exec_files = self.master_config.Global.exec_files |
|
494 | 494 | for fname in exec_files: |
|
495 | 495 | self._exec_file(fname) |
|
496 | 496 | except: |
|
497 | 497 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
498 | 498 | self.shell.showtraceback() |
|
499 | 499 | |
|
500 | 500 | def _run_cmd_line_code(self): |
|
501 | 501 | if hasattr(self.master_config.Global, 'code_to_run'): |
|
502 | 502 | line = self.master_config.Global.code_to_run |
|
503 | 503 | try: |
|
504 | 504 | self.log.info("Running code given at command line (-c): %s" % line) |
|
505 | 505 | self.shell.runlines(line) |
|
506 | 506 | except: |
|
507 | 507 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
508 | 508 | self.shell.showtraceback() |
|
509 | 509 | return |
|
510 | 510 | # Like Python itself, ignore the second if the first of these is present |
|
511 | 511 | try: |
|
512 | 512 | fname = self.extra_args[0] |
|
513 | 513 | except: |
|
514 | 514 | pass |
|
515 | 515 | else: |
|
516 | 516 | try: |
|
517 | 517 | self._exec_file(fname) |
|
518 | 518 | except: |
|
519 | 519 | self.log.warn("Error in executing file in user namespace: %s" % fname) |
|
520 | 520 | self.shell.showtraceback() |
|
521 | 521 | |
|
522 | 522 | def start_app(self): |
|
523 | 523 | if self.master_config.Global.interact: |
|
524 | 524 | self.log.debug("Starting IPython's mainloop...") |
|
525 | 525 | self.shell.mainloop() |
|
526 | 526 | |
|
527 | 527 | |
|
528 | def load_default_config(ipythondir=None): | |
|
529 | """Load the default config file from the default ipythondir. | |
|
528 | def load_default_config(ipython_dir=None): | |
|
529 | """Load the default config file from the default ipython_dir. | |
|
530 | 530 | |
|
531 | 531 | This is useful for embedded shells. |
|
532 | 532 | """ |
|
533 | if ipythondir is None: | |
|
534 | ipythondir = get_ipython_dir() | |
|
535 | cl = PyFileConfigLoader(default_config_file_name, ipythondir) | |
|
533 | if ipython_dir is None: | |
|
534 | ipython_dir = get_ipython_dir() | |
|
535 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) | |
|
536 | 536 | config = cl.load_config() |
|
537 | 537 | return config |
|
538 | 538 | |
|
539 | 539 | |
|
540 | 540 | def launch_new_instance(): |
|
541 | 541 | """Create and run a full blown IPython instance""" |
|
542 | 542 | app = IPythonApp() |
|
543 | 543 | app.start() |
|
544 | 544 |
@@ -1,2488 +1,2488 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Main IPython Component |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
8 | 8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
9 | 9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | from __future__ import with_statement |
|
20 | 20 | |
|
21 | 21 | import __builtin__ |
|
22 | 22 | import StringIO |
|
23 | 23 | import bdb |
|
24 | 24 | import codeop |
|
25 | 25 | import exceptions |
|
26 | 26 | import new |
|
27 | 27 | import os |
|
28 | 28 | import re |
|
29 | 29 | import string |
|
30 | 30 | import sys |
|
31 | 31 | import tempfile |
|
32 | 32 | from contextlib import nested |
|
33 | 33 | |
|
34 | 34 | from IPython.core import ultratb |
|
35 | 35 | from IPython.core import debugger, oinspect |
|
36 | 36 | from IPython.core import shadowns |
|
37 | 37 | from IPython.core import history as ipcorehist |
|
38 | 38 | from IPython.core import prefilter |
|
39 | 39 | from IPython.core.alias import AliasManager |
|
40 | 40 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | 41 | from IPython.core.display_trap import DisplayTrap |
|
42 | 42 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
43 | 43 | from IPython.core.logger import Logger |
|
44 | 44 | from IPython.core.magic import Magic |
|
45 | 45 | from IPython.core.prompts import CachedOutput |
|
46 | 46 | from IPython.core.prefilter import PrefilterManager |
|
47 | 47 | from IPython.core.component import Component |
|
48 | 48 | from IPython.core.usage import interactive_usage, default_banner |
|
49 | 49 | from IPython.core.error import TryNext, UsageError |
|
50 | 50 | |
|
51 | 51 | from IPython.utils import pickleshare |
|
52 | 52 | from IPython.external.Itpl import ItplNS |
|
53 | 53 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
54 | 54 | from IPython.utils.ipstruct import Struct |
|
55 | 55 | from IPython.utils import PyColorize |
|
56 | 56 | from IPython.utils.genutils import * |
|
57 | 57 | from IPython.utils.genutils import get_ipython_dir |
|
58 | 58 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
59 | 59 | from IPython.utils.strdispatch import StrDispatch |
|
60 | 60 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
61 | 61 | |
|
62 | 62 | # from IPython.utils import growl |
|
63 | 63 | # growl.start("IPython") |
|
64 | 64 | |
|
65 | 65 | from IPython.utils.traitlets import ( |
|
66 | 66 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
67 | 67 | ) |
|
68 | 68 | |
|
69 | 69 | #----------------------------------------------------------------------------- |
|
70 | 70 | # Globals |
|
71 | 71 | #----------------------------------------------------------------------------- |
|
72 | 72 | |
|
73 | 73 | |
|
74 | 74 | # store the builtin raw_input globally, and use this always, in case user code |
|
75 | 75 | # overwrites it (like wx.py.PyShell does) |
|
76 | 76 | raw_input_original = raw_input |
|
77 | 77 | |
|
78 | 78 | # compiled regexps for autoindent management |
|
79 | 79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | #----------------------------------------------------------------------------- |
|
83 | 83 | # Utilities |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | |
|
86 | 86 | |
|
87 | 87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | def num_ini_spaces(strng): |
|
91 | 91 | """Return the number of initial spaces in a string""" |
|
92 | 92 | |
|
93 | 93 | ini_spaces = ini_spaces_re.match(strng) |
|
94 | 94 | if ini_spaces: |
|
95 | 95 | return ini_spaces.end() |
|
96 | 96 | else: |
|
97 | 97 | return 0 |
|
98 | 98 | |
|
99 | 99 | |
|
100 | 100 | def softspace(file, newvalue): |
|
101 | 101 | """Copied from code.py, to remove the dependency""" |
|
102 | 102 | |
|
103 | 103 | oldvalue = 0 |
|
104 | 104 | try: |
|
105 | 105 | oldvalue = file.softspace |
|
106 | 106 | except AttributeError: |
|
107 | 107 | pass |
|
108 | 108 | try: |
|
109 | 109 | file.softspace = newvalue |
|
110 | 110 | except (AttributeError, TypeError): |
|
111 | 111 | # "attribute-less object" or "read-only attributes" |
|
112 | 112 | pass |
|
113 | 113 | return oldvalue |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | class SpaceInInput(exceptions.Exception): pass |
|
117 | 117 | |
|
118 | 118 | class Bunch: pass |
|
119 | 119 | |
|
120 | 120 | class InputList(list): |
|
121 | 121 | """Class to store user input. |
|
122 | 122 | |
|
123 | 123 | It's basically a list, but slices return a string instead of a list, thus |
|
124 | 124 | allowing things like (assuming 'In' is an instance): |
|
125 | 125 | |
|
126 | 126 | exec In[4:7] |
|
127 | 127 | |
|
128 | 128 | or |
|
129 | 129 | |
|
130 | 130 | exec In[5:9] + In[14] + In[21:25]""" |
|
131 | 131 | |
|
132 | 132 | def __getslice__(self,i,j): |
|
133 | 133 | return ''.join(list.__getslice__(self,i,j)) |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | class SyntaxTB(ultratb.ListTB): |
|
137 | 137 | """Extension which holds some state: the last exception value""" |
|
138 | 138 | |
|
139 | 139 | def __init__(self,color_scheme = 'NoColor'): |
|
140 | 140 | ultratb.ListTB.__init__(self,color_scheme) |
|
141 | 141 | self.last_syntax_error = None |
|
142 | 142 | |
|
143 | 143 | def __call__(self, etype, value, elist): |
|
144 | 144 | self.last_syntax_error = value |
|
145 | 145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
146 | 146 | |
|
147 | 147 | def clear_err_state(self): |
|
148 | 148 | """Return the current error state and clear it""" |
|
149 | 149 | e = self.last_syntax_error |
|
150 | 150 | self.last_syntax_error = None |
|
151 | 151 | return e |
|
152 | 152 | |
|
153 | 153 | |
|
154 | 154 | def get_default_editor(): |
|
155 | 155 | try: |
|
156 | 156 | ed = os.environ['EDITOR'] |
|
157 | 157 | except KeyError: |
|
158 | 158 | if os.name == 'posix': |
|
159 | 159 | ed = 'vi' # the only one guaranteed to be there! |
|
160 | 160 | else: |
|
161 | 161 | ed = 'notepad' # same in Windows! |
|
162 | 162 | return ed |
|
163 | 163 | |
|
164 | 164 | |
|
165 | 165 | def get_default_colors(): |
|
166 | 166 | if sys.platform=='darwin': |
|
167 | 167 | return "LightBG" |
|
168 | 168 | elif os.name=='nt': |
|
169 | 169 | return 'Linux' |
|
170 | 170 | else: |
|
171 | 171 | return 'Linux' |
|
172 | 172 | |
|
173 | 173 | |
|
174 | 174 | class SeparateStr(Str): |
|
175 | 175 | """A Str subclass to validate separate_in, separate_out, etc. |
|
176 | 176 | |
|
177 | 177 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
178 | 178 | """ |
|
179 | 179 | |
|
180 | 180 | def validate(self, obj, value): |
|
181 | 181 | if value == '0': value = '' |
|
182 | 182 | value = value.replace('\\n','\n') |
|
183 | 183 | return super(SeparateStr, self).validate(obj, value) |
|
184 | 184 | |
|
185 | 185 | |
|
186 | 186 | #----------------------------------------------------------------------------- |
|
187 | 187 | # Main IPython class |
|
188 | 188 | #----------------------------------------------------------------------------- |
|
189 | 189 | |
|
190 | 190 | |
|
191 | 191 | class InteractiveShell(Component, Magic): |
|
192 | 192 | """An enhanced, interactive shell for Python.""" |
|
193 | 193 | |
|
194 | 194 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
195 | 195 | autoedit_syntax = CBool(False, config=True) |
|
196 | 196 | autoindent = CBool(True, config=True) |
|
197 | 197 | automagic = CBool(True, config=True) |
|
198 | 198 | banner = Str('') |
|
199 | 199 | banner1 = Str(default_banner, config=True) |
|
200 | 200 | banner2 = Str('', config=True) |
|
201 | 201 | cache_size = Int(1000, config=True) |
|
202 | 202 | color_info = CBool(True, config=True) |
|
203 | 203 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
204 | 204 | default_value=get_default_colors(), config=True) |
|
205 | 205 | confirm_exit = CBool(True, config=True) |
|
206 | 206 | debug = CBool(False, config=True) |
|
207 | 207 | deep_reload = CBool(False, config=True) |
|
208 | 208 | # This display_banner only controls whether or not self.show_banner() |
|
209 | 209 | # is called when mainloop/interact are called. The default is False |
|
210 | 210 | # because for the terminal based application, the banner behavior |
|
211 | 211 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
212 | 212 | # to determine if *it* should call show_banner() by hand or not. |
|
213 | 213 | display_banner = CBool(False) # This isn't configurable! |
|
214 | 214 | embedded = CBool(False) |
|
215 | 215 | embedded_active = CBool(False) |
|
216 | 216 | editor = Str(get_default_editor(), config=True) |
|
217 | 217 | filename = Str("<ipython console>") |
|
218 | ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
|
218 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
|
219 | 219 | logstart = CBool(False, config=True) |
|
220 | 220 | logfile = Str('', config=True) |
|
221 | 221 | logappend = Str('', config=True) |
|
222 | 222 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
223 | 223 | config=True) |
|
224 | 224 | pager = Str('less', config=True) |
|
225 | 225 | pdb = CBool(False, config=True) |
|
226 | 226 | pprint = CBool(True, config=True) |
|
227 | 227 | profile = Str('', config=True) |
|
228 | 228 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
229 | 229 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
230 | 230 | prompt_out = Str('Out[\\#]: ', config=True) |
|
231 | 231 | prompts_pad_left = CBool(True, config=True) |
|
232 | 232 | quiet = CBool(False, config=True) |
|
233 | 233 | |
|
234 | 234 | readline_use = CBool(True, config=True) |
|
235 | 235 | readline_merge_completions = CBool(True, config=True) |
|
236 | 236 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
237 | 237 | readline_remove_delims = Str('-/~', config=True) |
|
238 | 238 | readline_parse_and_bind = List([ |
|
239 | 239 | 'tab: complete', |
|
240 | 240 | '"\C-l": possible-completions', |
|
241 | 241 | 'set show-all-if-ambiguous on', |
|
242 | 242 | '"\C-o": tab-insert', |
|
243 | 243 | '"\M-i": " "', |
|
244 | 244 | '"\M-o": "\d\d\d\d"', |
|
245 | 245 | '"\M-I": "\d\d\d\d"', |
|
246 | 246 | '"\C-r": reverse-search-history', |
|
247 | 247 | '"\C-s": forward-search-history', |
|
248 | 248 | '"\C-p": history-search-backward', |
|
249 | 249 | '"\C-n": history-search-forward', |
|
250 | 250 | '"\e[A": history-search-backward', |
|
251 | 251 | '"\e[B": history-search-forward', |
|
252 | 252 | '"\C-k": kill-line', |
|
253 | 253 | '"\C-u": unix-line-discard', |
|
254 | 254 | ], allow_none=False, config=True) |
|
255 | 255 | |
|
256 | 256 | screen_length = Int(0, config=True) |
|
257 | 257 | |
|
258 | 258 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
259 | 259 | separate_in = SeparateStr('\n', config=True) |
|
260 | 260 | separate_out = SeparateStr('', config=True) |
|
261 | 261 | separate_out2 = SeparateStr('', config=True) |
|
262 | 262 | |
|
263 | 263 | system_header = Str('IPython system call: ', config=True) |
|
264 | 264 | system_verbose = CBool(False, config=True) |
|
265 | 265 | term_title = CBool(False, config=True) |
|
266 | 266 | wildcards_case_sensitive = CBool(True, config=True) |
|
267 | 267 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
268 | 268 | default_value='Context', config=True) |
|
269 | 269 | |
|
270 | 270 | autoexec = List(allow_none=False) |
|
271 | 271 | |
|
272 | 272 | # class attribute to indicate whether the class supports threads or not. |
|
273 | 273 | # Subclasses with thread support should override this as needed. |
|
274 | 274 | isthreaded = False |
|
275 | 275 | |
|
276 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
|
276 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, | |
|
277 | 277 | user_ns=None, user_global_ns=None, |
|
278 | 278 | banner1=None, banner2=None, display_banner=None, |
|
279 | 279 | custom_exceptions=((),None)): |
|
280 | 280 | |
|
281 | 281 | # This is where traitlets with a config_key argument are updated |
|
282 | 282 | # from the values on config. |
|
283 | 283 | super(InteractiveShell, self).__init__(parent, config=config) |
|
284 | 284 | |
|
285 | 285 | # These are relatively independent and stateless |
|
286 | self.init_ipythondir(ipythondir) | |
|
286 | self.init_ipython_dir(ipython_dir) | |
|
287 | 287 | self.init_instance_attrs() |
|
288 | 288 | self.init_term_title() |
|
289 | 289 | self.init_usage(usage) |
|
290 | 290 | self.init_banner(banner1, banner2, display_banner) |
|
291 | 291 | |
|
292 | 292 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
293 | 293 | self.init_create_namespaces(user_ns, user_global_ns) |
|
294 | 294 | # This has to be done after init_create_namespaces because it uses |
|
295 | 295 | # something in self.user_ns, but before init_sys_modules, which |
|
296 | 296 | # is the first thing to modify sys. |
|
297 | 297 | self.save_sys_module_state() |
|
298 | 298 | self.init_sys_modules() |
|
299 | 299 | |
|
300 | 300 | self.init_history() |
|
301 | 301 | self.init_encoding() |
|
302 | 302 | self.init_prefilter() |
|
303 | 303 | |
|
304 | 304 | Magic.__init__(self, self) |
|
305 | 305 | |
|
306 | 306 | self.init_syntax_highlighting() |
|
307 | 307 | self.init_hooks() |
|
308 | 308 | self.init_pushd_popd_magic() |
|
309 | 309 | self.init_traceback_handlers(custom_exceptions) |
|
310 | 310 | self.init_user_ns() |
|
311 | 311 | self.init_logger() |
|
312 | 312 | self.init_alias() |
|
313 | 313 | self.init_builtins() |
|
314 | 314 | |
|
315 | 315 | # pre_config_initialization |
|
316 | 316 | self.init_shadow_hist() |
|
317 | 317 | |
|
318 | 318 | # The next section should contain averything that was in ipmaker. |
|
319 | 319 | self.init_logstart() |
|
320 | 320 | |
|
321 | 321 | # The following was in post_config_initialization |
|
322 | 322 | self.init_inspector() |
|
323 | 323 | self.init_readline() |
|
324 | 324 | self.init_prompts() |
|
325 | 325 | self.init_displayhook() |
|
326 | 326 | self.init_reload_doctest() |
|
327 | 327 | self.init_magics() |
|
328 | 328 | self.init_pdb() |
|
329 | 329 | self.hooks.late_startup_hook() |
|
330 | 330 | |
|
331 | 331 | def get_ipython(self): |
|
332 | 332 | return self |
|
333 | 333 | |
|
334 | 334 | #------------------------------------------------------------------------- |
|
335 | 335 | # Traitlet changed handlers |
|
336 | 336 | #------------------------------------------------------------------------- |
|
337 | 337 | |
|
338 | 338 | def _banner1_changed(self): |
|
339 | 339 | self.compute_banner() |
|
340 | 340 | |
|
341 | 341 | def _banner2_changed(self): |
|
342 | 342 | self.compute_banner() |
|
343 | 343 | |
|
344 | def _ipythondir_changed(self, name, new): | |
|
344 | def _ipython_dir_changed(self, name, new): | |
|
345 | 345 | if not os.path.isdir(new): |
|
346 | 346 | os.makedirs(new, mode = 0777) |
|
347 | 347 | if not os.path.isdir(self.ipython_extension_dir): |
|
348 | 348 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
349 | 349 | |
|
350 | 350 | @property |
|
351 | 351 | def ipython_extension_dir(self): |
|
352 | return os.path.join(self.ipythondir, 'extensions') | |
|
352 | return os.path.join(self.ipython_dir, 'extensions') | |
|
353 | 353 | |
|
354 | 354 | @property |
|
355 | 355 | def usable_screen_length(self): |
|
356 | 356 | if self.screen_length == 0: |
|
357 | 357 | return 0 |
|
358 | 358 | else: |
|
359 | 359 | num_lines_bot = self.separate_in.count('\n')+1 |
|
360 | 360 | return self.screen_length - num_lines_bot |
|
361 | 361 | |
|
362 | 362 | def _term_title_changed(self, name, new_value): |
|
363 | 363 | self.init_term_title() |
|
364 | 364 | |
|
365 | 365 | def set_autoindent(self,value=None): |
|
366 | 366 | """Set the autoindent flag, checking for readline support. |
|
367 | 367 | |
|
368 | 368 | If called with no arguments, it acts as a toggle.""" |
|
369 | 369 | |
|
370 | 370 | if not self.has_readline: |
|
371 | 371 | if os.name == 'posix': |
|
372 | 372 | warn("The auto-indent feature requires the readline library") |
|
373 | 373 | self.autoindent = 0 |
|
374 | 374 | return |
|
375 | 375 | if value is None: |
|
376 | 376 | self.autoindent = not self.autoindent |
|
377 | 377 | else: |
|
378 | 378 | self.autoindent = value |
|
379 | 379 | |
|
380 | 380 | #------------------------------------------------------------------------- |
|
381 | 381 | # init_* methods called by __init__ |
|
382 | 382 | #------------------------------------------------------------------------- |
|
383 | 383 | |
|
384 | def init_ipythondir(self, ipythondir): | |
|
385 | if ipythondir is not None: | |
|
386 | self.ipythondir = ipythondir | |
|
387 | self.config.Global.ipythondir = self.ipythondir | |
|
384 | def init_ipython_dir(self, ipython_dir): | |
|
385 | if ipython_dir is not None: | |
|
386 | self.ipython_dir = ipython_dir | |
|
387 | self.config.Global.ipython_dir = self.ipython_dir | |
|
388 | 388 | return |
|
389 | 389 | |
|
390 | if hasattr(self.config.Global, 'ipythondir'): | |
|
391 | self.ipythondir = self.config.Global.ipythondir | |
|
390 | if hasattr(self.config.Global, 'ipython_dir'): | |
|
391 | self.ipython_dir = self.config.Global.ipython_dir | |
|
392 | 392 | else: |
|
393 | self.ipythondir = get_ipython_dir() | |
|
393 | self.ipython_dir = get_ipython_dir() | |
|
394 | 394 | |
|
395 | 395 | # All children can just read this |
|
396 | self.config.Global.ipythondir = self.ipythondir | |
|
396 | self.config.Global.ipython_dir = self.ipython_dir | |
|
397 | 397 | |
|
398 | 398 | def init_instance_attrs(self): |
|
399 | 399 | self.jobs = BackgroundJobManager() |
|
400 | 400 | self.more = False |
|
401 | 401 | |
|
402 | 402 | # command compiler |
|
403 | 403 | self.compile = codeop.CommandCompiler() |
|
404 | 404 | |
|
405 | 405 | # User input buffer |
|
406 | 406 | self.buffer = [] |
|
407 | 407 | |
|
408 | 408 | # Make an empty namespace, which extension writers can rely on both |
|
409 | 409 | # existing and NEVER being used by ipython itself. This gives them a |
|
410 | 410 | # convenient location for storing additional information and state |
|
411 | 411 | # their extensions may require, without fear of collisions with other |
|
412 | 412 | # ipython names that may develop later. |
|
413 | 413 | self.meta = Struct() |
|
414 | 414 | |
|
415 | 415 | # Object variable to store code object waiting execution. This is |
|
416 | 416 | # used mainly by the multithreaded shells, but it can come in handy in |
|
417 | 417 | # other situations. No need to use a Queue here, since it's a single |
|
418 | 418 | # item which gets cleared once run. |
|
419 | 419 | self.code_to_run = None |
|
420 | 420 | |
|
421 | 421 | # Flag to mark unconditional exit |
|
422 | 422 | self.exit_now = False |
|
423 | 423 | |
|
424 | 424 | # Temporary files used for various purposes. Deleted at exit. |
|
425 | 425 | self.tempfiles = [] |
|
426 | 426 | |
|
427 | 427 | # Keep track of readline usage (later set by init_readline) |
|
428 | 428 | self.has_readline = False |
|
429 | 429 | |
|
430 | 430 | # keep track of where we started running (mainly for crash post-mortem) |
|
431 | 431 | # This is not being used anywhere currently. |
|
432 | 432 | self.starting_dir = os.getcwd() |
|
433 | 433 | |
|
434 | 434 | # Indentation management |
|
435 | 435 | self.indent_current_nsp = 0 |
|
436 | 436 | |
|
437 | 437 | def init_term_title(self): |
|
438 | 438 | # Enable or disable the terminal title. |
|
439 | 439 | if self.term_title: |
|
440 | 440 | toggle_set_term_title(True) |
|
441 | 441 | set_term_title('IPython: ' + abbrev_cwd()) |
|
442 | 442 | else: |
|
443 | 443 | toggle_set_term_title(False) |
|
444 | 444 | |
|
445 | 445 | def init_usage(self, usage=None): |
|
446 | 446 | if usage is None: |
|
447 | 447 | self.usage = interactive_usage |
|
448 | 448 | else: |
|
449 | 449 | self.usage = usage |
|
450 | 450 | |
|
451 | 451 | def init_encoding(self): |
|
452 | 452 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
453 | 453 | # under Win32 have it set to None, and we need to have a known valid |
|
454 | 454 | # encoding to use in the raw_input() method |
|
455 | 455 | try: |
|
456 | 456 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
457 | 457 | except AttributeError: |
|
458 | 458 | self.stdin_encoding = 'ascii' |
|
459 | 459 | |
|
460 | 460 | def init_syntax_highlighting(self): |
|
461 | 461 | # Python source parser/formatter for syntax highlighting |
|
462 | 462 | pyformat = PyColorize.Parser().format |
|
463 | 463 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
464 | 464 | |
|
465 | 465 | def init_pushd_popd_magic(self): |
|
466 | 466 | # for pushd/popd management |
|
467 | 467 | try: |
|
468 | 468 | self.home_dir = get_home_dir() |
|
469 | 469 | except HomeDirError, msg: |
|
470 | 470 | fatal(msg) |
|
471 | 471 | |
|
472 | 472 | self.dir_stack = [] |
|
473 | 473 | |
|
474 | 474 | def init_logger(self): |
|
475 | 475 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
476 | 476 | # local shortcut, this is used a LOT |
|
477 | 477 | self.log = self.logger.log |
|
478 | 478 | |
|
479 | 479 | def init_logstart(self): |
|
480 | 480 | if self.logappend: |
|
481 | 481 | self.magic_logstart(self.logappend + ' append') |
|
482 | 482 | elif self.logfile: |
|
483 | 483 | self.magic_logstart(self.logfile) |
|
484 | 484 | elif self.logstart: |
|
485 | 485 | self.magic_logstart() |
|
486 | 486 | |
|
487 | 487 | def init_builtins(self): |
|
488 | 488 | self.builtin_trap = BuiltinTrap(self) |
|
489 | 489 | |
|
490 | 490 | def init_inspector(self): |
|
491 | 491 | # Object inspector |
|
492 | 492 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
493 | 493 | PyColorize.ANSICodeColors, |
|
494 | 494 | 'NoColor', |
|
495 | 495 | self.object_info_string_level) |
|
496 | 496 | |
|
497 | 497 | def init_prompts(self): |
|
498 | 498 | # Initialize cache, set in/out prompts and printing system |
|
499 | 499 | self.outputcache = CachedOutput(self, |
|
500 | 500 | self.cache_size, |
|
501 | 501 | self.pprint, |
|
502 | 502 | input_sep = self.separate_in, |
|
503 | 503 | output_sep = self.separate_out, |
|
504 | 504 | output_sep2 = self.separate_out2, |
|
505 | 505 | ps1 = self.prompt_in1, |
|
506 | 506 | ps2 = self.prompt_in2, |
|
507 | 507 | ps_out = self.prompt_out, |
|
508 | 508 | pad_left = self.prompts_pad_left) |
|
509 | 509 | |
|
510 | 510 | # user may have over-ridden the default print hook: |
|
511 | 511 | try: |
|
512 | 512 | self.outputcache.__class__.display = self.hooks.display |
|
513 | 513 | except AttributeError: |
|
514 | 514 | pass |
|
515 | 515 | |
|
516 | 516 | def init_displayhook(self): |
|
517 | 517 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
518 | 518 | |
|
519 | 519 | def init_reload_doctest(self): |
|
520 | 520 | # Do a proper resetting of doctest, including the necessary displayhook |
|
521 | 521 | # monkeypatching |
|
522 | 522 | try: |
|
523 | 523 | doctest_reload() |
|
524 | 524 | except ImportError: |
|
525 | 525 | warn("doctest module does not exist.") |
|
526 | 526 | |
|
527 | 527 | #------------------------------------------------------------------------- |
|
528 | 528 | # Things related to the banner |
|
529 | 529 | #------------------------------------------------------------------------- |
|
530 | 530 | |
|
531 | 531 | def init_banner(self, banner1, banner2, display_banner): |
|
532 | 532 | if banner1 is not None: |
|
533 | 533 | self.banner1 = banner1 |
|
534 | 534 | if banner2 is not None: |
|
535 | 535 | self.banner2 = banner2 |
|
536 | 536 | if display_banner is not None: |
|
537 | 537 | self.display_banner = display_banner |
|
538 | 538 | self.compute_banner() |
|
539 | 539 | |
|
540 | 540 | def show_banner(self, banner=None): |
|
541 | 541 | if banner is None: |
|
542 | 542 | banner = self.banner |
|
543 | 543 | self.write(banner) |
|
544 | 544 | |
|
545 | 545 | def compute_banner(self): |
|
546 | 546 | self.banner = self.banner1 + '\n' |
|
547 | 547 | if self.profile: |
|
548 | 548 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
549 | 549 | if self.banner2: |
|
550 | 550 | self.banner += '\n' + self.banner2 + '\n' |
|
551 | 551 | |
|
552 | 552 | #------------------------------------------------------------------------- |
|
553 | 553 | # Things related to injections into the sys module |
|
554 | 554 | #------------------------------------------------------------------------- |
|
555 | 555 | |
|
556 | 556 | def save_sys_module_state(self): |
|
557 | 557 | """Save the state of hooks in the sys module. |
|
558 | 558 | |
|
559 | 559 | This has to be called after self.user_ns is created. |
|
560 | 560 | """ |
|
561 | 561 | self._orig_sys_module_state = {} |
|
562 | 562 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
563 | 563 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
564 | 564 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
565 | 565 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
566 | 566 | try: |
|
567 | 567 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
568 | 568 | except KeyError: |
|
569 | 569 | pass |
|
570 | 570 | |
|
571 | 571 | def restore_sys_module_state(self): |
|
572 | 572 | """Restore the state of the sys module.""" |
|
573 | 573 | try: |
|
574 | 574 | for k, v in self._orig_sys_module_state.items(): |
|
575 | 575 | setattr(sys, k, v) |
|
576 | 576 | except AttributeError: |
|
577 | 577 | pass |
|
578 | 578 | try: |
|
579 | 579 | delattr(sys, 'ipcompleter') |
|
580 | 580 | except AttributeError: |
|
581 | 581 | pass |
|
582 | 582 | # Reset what what done in self.init_sys_modules |
|
583 | 583 | try: |
|
584 | 584 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
585 | 585 | except (AttributeError, KeyError): |
|
586 | 586 | pass |
|
587 | 587 | |
|
588 | 588 | #------------------------------------------------------------------------- |
|
589 | 589 | # Things related to hooks |
|
590 | 590 | #------------------------------------------------------------------------- |
|
591 | 591 | |
|
592 | 592 | def init_hooks(self): |
|
593 | 593 | # hooks holds pointers used for user-side customizations |
|
594 | 594 | self.hooks = Struct() |
|
595 | 595 | |
|
596 | 596 | self.strdispatchers = {} |
|
597 | 597 | |
|
598 | 598 | # Set all default hooks, defined in the IPython.hooks module. |
|
599 | 599 | import IPython.core.hooks |
|
600 | 600 | hooks = IPython.core.hooks |
|
601 | 601 | for hook_name in hooks.__all__: |
|
602 | 602 | # default hooks have priority 100, i.e. low; user hooks should have |
|
603 | 603 | # 0-100 priority |
|
604 | 604 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
605 | 605 | |
|
606 | 606 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
607 | 607 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
608 | 608 | |
|
609 | 609 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
610 | 610 | adding your function to one of these hooks, you can modify IPython's |
|
611 | 611 | behavior to call at runtime your own routines.""" |
|
612 | 612 | |
|
613 | 613 | # At some point in the future, this should validate the hook before it |
|
614 | 614 | # accepts it. Probably at least check that the hook takes the number |
|
615 | 615 | # of args it's supposed to. |
|
616 | 616 | |
|
617 | 617 | f = new.instancemethod(hook,self,self.__class__) |
|
618 | 618 | |
|
619 | 619 | # check if the hook is for strdispatcher first |
|
620 | 620 | if str_key is not None: |
|
621 | 621 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
622 | 622 | sdp.add_s(str_key, f, priority ) |
|
623 | 623 | self.strdispatchers[name] = sdp |
|
624 | 624 | return |
|
625 | 625 | if re_key is not None: |
|
626 | 626 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
627 | 627 | sdp.add_re(re.compile(re_key), f, priority ) |
|
628 | 628 | self.strdispatchers[name] = sdp |
|
629 | 629 | return |
|
630 | 630 | |
|
631 | 631 | dp = getattr(self.hooks, name, None) |
|
632 | 632 | if name not in IPython.core.hooks.__all__: |
|
633 | 633 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
634 | 634 | if not dp: |
|
635 | 635 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
636 | 636 | |
|
637 | 637 | try: |
|
638 | 638 | dp.add(f,priority) |
|
639 | 639 | except AttributeError: |
|
640 | 640 | # it was not commandchain, plain old func - replace |
|
641 | 641 | dp = f |
|
642 | 642 | |
|
643 | 643 | setattr(self.hooks,name, dp) |
|
644 | 644 | |
|
645 | 645 | #------------------------------------------------------------------------- |
|
646 | 646 | # Things related to the "main" module |
|
647 | 647 | #------------------------------------------------------------------------- |
|
648 | 648 | |
|
649 | 649 | def new_main_mod(self,ns=None): |
|
650 | 650 | """Return a new 'main' module object for user code execution. |
|
651 | 651 | """ |
|
652 | 652 | main_mod = self._user_main_module |
|
653 | 653 | init_fakemod_dict(main_mod,ns) |
|
654 | 654 | return main_mod |
|
655 | 655 | |
|
656 | 656 | def cache_main_mod(self,ns,fname): |
|
657 | 657 | """Cache a main module's namespace. |
|
658 | 658 | |
|
659 | 659 | When scripts are executed via %run, we must keep a reference to the |
|
660 | 660 | namespace of their __main__ module (a FakeModule instance) around so |
|
661 | 661 | that Python doesn't clear it, rendering objects defined therein |
|
662 | 662 | useless. |
|
663 | 663 | |
|
664 | 664 | This method keeps said reference in a private dict, keyed by the |
|
665 | 665 | absolute path of the module object (which corresponds to the script |
|
666 | 666 | path). This way, for multiple executions of the same script we only |
|
667 | 667 | keep one copy of the namespace (the last one), thus preventing memory |
|
668 | 668 | leaks from old references while allowing the objects from the last |
|
669 | 669 | execution to be accessible. |
|
670 | 670 | |
|
671 | 671 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
672 | 672 | because of how Python tears down modules (it hard-sets all their |
|
673 | 673 | references to None without regard for reference counts). This method |
|
674 | 674 | must therefore make a *copy* of the given namespace, to allow the |
|
675 | 675 | original module's __dict__ to be cleared and reused. |
|
676 | 676 | |
|
677 | 677 | |
|
678 | 678 | Parameters |
|
679 | 679 | ---------- |
|
680 | 680 | ns : a namespace (a dict, typically) |
|
681 | 681 | |
|
682 | 682 | fname : str |
|
683 | 683 | Filename associated with the namespace. |
|
684 | 684 | |
|
685 | 685 | Examples |
|
686 | 686 | -------- |
|
687 | 687 | |
|
688 | 688 | In [10]: import IPython |
|
689 | 689 | |
|
690 | 690 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
691 | 691 | |
|
692 | 692 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
693 | 693 | Out[12]: True |
|
694 | 694 | """ |
|
695 | 695 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
696 | 696 | |
|
697 | 697 | def clear_main_mod_cache(self): |
|
698 | 698 | """Clear the cache of main modules. |
|
699 | 699 | |
|
700 | 700 | Mainly for use by utilities like %reset. |
|
701 | 701 | |
|
702 | 702 | Examples |
|
703 | 703 | -------- |
|
704 | 704 | |
|
705 | 705 | In [15]: import IPython |
|
706 | 706 | |
|
707 | 707 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
708 | 708 | |
|
709 | 709 | In [17]: len(_ip._main_ns_cache) > 0 |
|
710 | 710 | Out[17]: True |
|
711 | 711 | |
|
712 | 712 | In [18]: _ip.clear_main_mod_cache() |
|
713 | 713 | |
|
714 | 714 | In [19]: len(_ip._main_ns_cache) == 0 |
|
715 | 715 | Out[19]: True |
|
716 | 716 | """ |
|
717 | 717 | self._main_ns_cache.clear() |
|
718 | 718 | |
|
719 | 719 | #------------------------------------------------------------------------- |
|
720 | 720 | # Things related to debugging |
|
721 | 721 | #------------------------------------------------------------------------- |
|
722 | 722 | |
|
723 | 723 | def init_pdb(self): |
|
724 | 724 | # Set calling of pdb on exceptions |
|
725 | 725 | # self.call_pdb is a property |
|
726 | 726 | self.call_pdb = self.pdb |
|
727 | 727 | |
|
728 | 728 | def _get_call_pdb(self): |
|
729 | 729 | return self._call_pdb |
|
730 | 730 | |
|
731 | 731 | def _set_call_pdb(self,val): |
|
732 | 732 | |
|
733 | 733 | if val not in (0,1,False,True): |
|
734 | 734 | raise ValueError,'new call_pdb value must be boolean' |
|
735 | 735 | |
|
736 | 736 | # store value in instance |
|
737 | 737 | self._call_pdb = val |
|
738 | 738 | |
|
739 | 739 | # notify the actual exception handlers |
|
740 | 740 | self.InteractiveTB.call_pdb = val |
|
741 | 741 | if self.isthreaded: |
|
742 | 742 | try: |
|
743 | 743 | self.sys_excepthook.call_pdb = val |
|
744 | 744 | except: |
|
745 | 745 | warn('Failed to activate pdb for threaded exception handler') |
|
746 | 746 | |
|
747 | 747 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
748 | 748 | 'Control auto-activation of pdb at exceptions') |
|
749 | 749 | |
|
750 | 750 | def debugger(self,force=False): |
|
751 | 751 | """Call the pydb/pdb debugger. |
|
752 | 752 | |
|
753 | 753 | Keywords: |
|
754 | 754 | |
|
755 | 755 | - force(False): by default, this routine checks the instance call_pdb |
|
756 | 756 | flag and does not actually invoke the debugger if the flag is false. |
|
757 | 757 | The 'force' option forces the debugger to activate even if the flag |
|
758 | 758 | is false. |
|
759 | 759 | """ |
|
760 | 760 | |
|
761 | 761 | if not (force or self.call_pdb): |
|
762 | 762 | return |
|
763 | 763 | |
|
764 | 764 | if not hasattr(sys,'last_traceback'): |
|
765 | 765 | error('No traceback has been produced, nothing to debug.') |
|
766 | 766 | return |
|
767 | 767 | |
|
768 | 768 | # use pydb if available |
|
769 | 769 | if debugger.has_pydb: |
|
770 | 770 | from pydb import pm |
|
771 | 771 | else: |
|
772 | 772 | # fallback to our internal debugger |
|
773 | 773 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
774 | 774 | self.history_saving_wrapper(pm)() |
|
775 | 775 | |
|
776 | 776 | #------------------------------------------------------------------------- |
|
777 | 777 | # Things related to IPython's various namespaces |
|
778 | 778 | #------------------------------------------------------------------------- |
|
779 | 779 | |
|
780 | 780 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
781 | 781 | # Create the namespace where the user will operate. user_ns is |
|
782 | 782 | # normally the only one used, and it is passed to the exec calls as |
|
783 | 783 | # the locals argument. But we do carry a user_global_ns namespace |
|
784 | 784 | # given as the exec 'globals' argument, This is useful in embedding |
|
785 | 785 | # situations where the ipython shell opens in a context where the |
|
786 | 786 | # distinction between locals and globals is meaningful. For |
|
787 | 787 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
788 | 788 | |
|
789 | 789 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
790 | 790 | # level as a dict instead of a module. This is a manual fix, but I |
|
791 | 791 | # should really track down where the problem is coming from. Alex |
|
792 | 792 | # Schmolck reported this problem first. |
|
793 | 793 | |
|
794 | 794 | # A useful post by Alex Martelli on this topic: |
|
795 | 795 | # Re: inconsistent value from __builtins__ |
|
796 | 796 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
797 | 797 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
798 | 798 | # Gruppen: comp.lang.python |
|
799 | 799 | |
|
800 | 800 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
801 | 801 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
802 | 802 | # > <type 'dict'> |
|
803 | 803 | # > >>> print type(__builtins__) |
|
804 | 804 | # > <type 'module'> |
|
805 | 805 | # > Is this difference in return value intentional? |
|
806 | 806 | |
|
807 | 807 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
808 | 808 | # or a module, and it's been that way for a long time. Whether it's |
|
809 | 809 | # intentional (or sensible), I don't know. In any case, the idea is |
|
810 | 810 | # that if you need to access the built-in namespace directly, you |
|
811 | 811 | # should start with "import __builtin__" (note, no 's') which will |
|
812 | 812 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
813 | 813 | |
|
814 | 814 | # These routines return properly built dicts as needed by the rest of |
|
815 | 815 | # the code, and can also be used by extension writers to generate |
|
816 | 816 | # properly initialized namespaces. |
|
817 | 817 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
818 | 818 | user_global_ns) |
|
819 | 819 | |
|
820 | 820 | # Assign namespaces |
|
821 | 821 | # This is the namespace where all normal user variables live |
|
822 | 822 | self.user_ns = user_ns |
|
823 | 823 | self.user_global_ns = user_global_ns |
|
824 | 824 | |
|
825 | 825 | # An auxiliary namespace that checks what parts of the user_ns were |
|
826 | 826 | # loaded at startup, so we can list later only variables defined in |
|
827 | 827 | # actual interactive use. Since it is always a subset of user_ns, it |
|
828 | 828 | # doesn't need to be seaparately tracked in the ns_table |
|
829 | 829 | self.user_config_ns = {} |
|
830 | 830 | |
|
831 | 831 | # A namespace to keep track of internal data structures to prevent |
|
832 | 832 | # them from cluttering user-visible stuff. Will be updated later |
|
833 | 833 | self.internal_ns = {} |
|
834 | 834 | |
|
835 | 835 | # Now that FakeModule produces a real module, we've run into a nasty |
|
836 | 836 | # problem: after script execution (via %run), the module where the user |
|
837 | 837 | # code ran is deleted. Now that this object is a true module (needed |
|
838 | 838 | # so docetst and other tools work correctly), the Python module |
|
839 | 839 | # teardown mechanism runs over it, and sets to None every variable |
|
840 | 840 | # present in that module. Top-level references to objects from the |
|
841 | 841 | # script survive, because the user_ns is updated with them. However, |
|
842 | 842 | # calling functions defined in the script that use other things from |
|
843 | 843 | # the script will fail, because the function's closure had references |
|
844 | 844 | # to the original objects, which are now all None. So we must protect |
|
845 | 845 | # these modules from deletion by keeping a cache. |
|
846 | 846 | # |
|
847 | 847 | # To avoid keeping stale modules around (we only need the one from the |
|
848 | 848 | # last run), we use a dict keyed with the full path to the script, so |
|
849 | 849 | # only the last version of the module is held in the cache. Note, |
|
850 | 850 | # however, that we must cache the module *namespace contents* (their |
|
851 | 851 | # __dict__). Because if we try to cache the actual modules, old ones |
|
852 | 852 | # (uncached) could be destroyed while still holding references (such as |
|
853 | 853 | # those held by GUI objects that tend to be long-lived)> |
|
854 | 854 | # |
|
855 | 855 | # The %reset command will flush this cache. See the cache_main_mod() |
|
856 | 856 | # and clear_main_mod_cache() methods for details on use. |
|
857 | 857 | |
|
858 | 858 | # This is the cache used for 'main' namespaces |
|
859 | 859 | self._main_ns_cache = {} |
|
860 | 860 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
861 | 861 | # copying and clearing for reuse on each %run |
|
862 | 862 | self._user_main_module = FakeModule() |
|
863 | 863 | |
|
864 | 864 | # A table holding all the namespaces IPython deals with, so that |
|
865 | 865 | # introspection facilities can search easily. |
|
866 | 866 | self.ns_table = {'user':user_ns, |
|
867 | 867 | 'user_global':user_global_ns, |
|
868 | 868 | 'internal':self.internal_ns, |
|
869 | 869 | 'builtin':__builtin__.__dict__ |
|
870 | 870 | } |
|
871 | 871 | |
|
872 | 872 | # Similarly, track all namespaces where references can be held and that |
|
873 | 873 | # we can safely clear (so it can NOT include builtin). This one can be |
|
874 | 874 | # a simple list. |
|
875 | 875 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
876 | 876 | self.internal_ns, self._main_ns_cache ] |
|
877 | 877 | |
|
878 | 878 | def init_sys_modules(self): |
|
879 | 879 | # We need to insert into sys.modules something that looks like a |
|
880 | 880 | # module but which accesses the IPython namespace, for shelve and |
|
881 | 881 | # pickle to work interactively. Normally they rely on getting |
|
882 | 882 | # everything out of __main__, but for embedding purposes each IPython |
|
883 | 883 | # instance has its own private namespace, so we can't go shoving |
|
884 | 884 | # everything into __main__. |
|
885 | 885 | |
|
886 | 886 | # note, however, that we should only do this for non-embedded |
|
887 | 887 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
888 | 888 | # namespace. Embedded instances, on the other hand, should not do |
|
889 | 889 | # this because they need to manage the user local/global namespaces |
|
890 | 890 | # only, but they live within a 'normal' __main__ (meaning, they |
|
891 | 891 | # shouldn't overtake the execution environment of the script they're |
|
892 | 892 | # embedded in). |
|
893 | 893 | |
|
894 | 894 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
895 | 895 | |
|
896 | 896 | try: |
|
897 | 897 | main_name = self.user_ns['__name__'] |
|
898 | 898 | except KeyError: |
|
899 | 899 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
900 | 900 | else: |
|
901 | 901 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
902 | 902 | |
|
903 | 903 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
904 | 904 | """Return a valid local and global user interactive namespaces. |
|
905 | 905 | |
|
906 | 906 | This builds a dict with the minimal information needed to operate as a |
|
907 | 907 | valid IPython user namespace, which you can pass to the various |
|
908 | 908 | embedding classes in ipython. The default implementation returns the |
|
909 | 909 | same dict for both the locals and the globals to allow functions to |
|
910 | 910 | refer to variables in the namespace. Customized implementations can |
|
911 | 911 | return different dicts. The locals dictionary can actually be anything |
|
912 | 912 | following the basic mapping protocol of a dict, but the globals dict |
|
913 | 913 | must be a true dict, not even a subclass. It is recommended that any |
|
914 | 914 | custom object for the locals namespace synchronize with the globals |
|
915 | 915 | dict somehow. |
|
916 | 916 | |
|
917 | 917 | Raises TypeError if the provided globals namespace is not a true dict. |
|
918 | 918 | |
|
919 | 919 | :Parameters: |
|
920 | 920 | user_ns : dict-like, optional |
|
921 | 921 | The current user namespace. The items in this namespace should |
|
922 | 922 | be included in the output. If None, an appropriate blank |
|
923 | 923 | namespace should be created. |
|
924 | 924 | user_global_ns : dict, optional |
|
925 | 925 | The current user global namespace. The items in this namespace |
|
926 | 926 | should be included in the output. If None, an appropriate |
|
927 | 927 | blank namespace should be created. |
|
928 | 928 | |
|
929 | 929 | :Returns: |
|
930 | 930 | A tuple pair of dictionary-like object to be used as the local namespace |
|
931 | 931 | of the interpreter and a dict to be used as the global namespace. |
|
932 | 932 | """ |
|
933 | 933 | |
|
934 | 934 | if user_ns is None: |
|
935 | 935 | # Set __name__ to __main__ to better match the behavior of the |
|
936 | 936 | # normal interpreter. |
|
937 | 937 | user_ns = {'__name__' :'__main__', |
|
938 | 938 | '__builtins__' : __builtin__, |
|
939 | 939 | } |
|
940 | 940 | else: |
|
941 | 941 | user_ns.setdefault('__name__','__main__') |
|
942 | 942 | user_ns.setdefault('__builtins__',__builtin__) |
|
943 | 943 | |
|
944 | 944 | if user_global_ns is None: |
|
945 | 945 | user_global_ns = user_ns |
|
946 | 946 | if type(user_global_ns) is not dict: |
|
947 | 947 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
948 | 948 | % type(user_global_ns)) |
|
949 | 949 | |
|
950 | 950 | return user_ns, user_global_ns |
|
951 | 951 | |
|
952 | 952 | def init_user_ns(self): |
|
953 | 953 | """Initialize all user-visible namespaces to their minimum defaults. |
|
954 | 954 | |
|
955 | 955 | Certain history lists are also initialized here, as they effectively |
|
956 | 956 | act as user namespaces. |
|
957 | 957 | |
|
958 | 958 | Notes |
|
959 | 959 | ----- |
|
960 | 960 | All data structures here are only filled in, they are NOT reset by this |
|
961 | 961 | method. If they were not empty before, data will simply be added to |
|
962 | 962 | therm. |
|
963 | 963 | """ |
|
964 | 964 | # Store myself as the public api!!! |
|
965 | 965 | self.user_ns['get_ipython'] = self.get_ipython |
|
966 | 966 | |
|
967 | 967 | # make global variables for user access to the histories |
|
968 | 968 | self.user_ns['_ih'] = self.input_hist |
|
969 | 969 | self.user_ns['_oh'] = self.output_hist |
|
970 | 970 | self.user_ns['_dh'] = self.dir_hist |
|
971 | 971 | |
|
972 | 972 | # user aliases to input and output histories |
|
973 | 973 | self.user_ns['In'] = self.input_hist |
|
974 | 974 | self.user_ns['Out'] = self.output_hist |
|
975 | 975 | |
|
976 | 976 | self.user_ns['_sh'] = shadowns |
|
977 | 977 | |
|
978 | 978 | # Put 'help' in the user namespace |
|
979 | 979 | try: |
|
980 | 980 | from site import _Helper |
|
981 | 981 | self.user_ns['help'] = _Helper() |
|
982 | 982 | except ImportError: |
|
983 | 983 | warn('help() not available - check site.py') |
|
984 | 984 | |
|
985 | 985 | def reset(self): |
|
986 | 986 | """Clear all internal namespaces. |
|
987 | 987 | |
|
988 | 988 | Note that this is much more aggressive than %reset, since it clears |
|
989 | 989 | fully all namespaces, as well as all input/output lists. |
|
990 | 990 | """ |
|
991 | 991 | for ns in self.ns_refs_table: |
|
992 | 992 | ns.clear() |
|
993 | 993 | |
|
994 | 994 | self.alias_manager.clear_aliases() |
|
995 | 995 | |
|
996 | 996 | # Clear input and output histories |
|
997 | 997 | self.input_hist[:] = [] |
|
998 | 998 | self.input_hist_raw[:] = [] |
|
999 | 999 | self.output_hist.clear() |
|
1000 | 1000 | |
|
1001 | 1001 | # Restore the user namespaces to minimal usability |
|
1002 | 1002 | self.init_user_ns() |
|
1003 | 1003 | |
|
1004 | 1004 | # Restore the default and user aliases |
|
1005 | 1005 | self.alias_manager.init_aliases() |
|
1006 | 1006 | |
|
1007 | 1007 | def push(self, variables, interactive=True): |
|
1008 | 1008 | """Inject a group of variables into the IPython user namespace. |
|
1009 | 1009 | |
|
1010 | 1010 | Parameters |
|
1011 | 1011 | ---------- |
|
1012 | 1012 | variables : dict, str or list/tuple of str |
|
1013 | 1013 | The variables to inject into the user's namespace. If a dict, |
|
1014 | 1014 | a simple update is done. If a str, the string is assumed to |
|
1015 | 1015 | have variable names separated by spaces. A list/tuple of str |
|
1016 | 1016 | can also be used to give the variable names. If just the variable |
|
1017 | 1017 | names are give (list/tuple/str) then the variable values looked |
|
1018 | 1018 | up in the callers frame. |
|
1019 | 1019 | interactive : bool |
|
1020 | 1020 | If True (default), the variables will be listed with the ``who`` |
|
1021 | 1021 | magic. |
|
1022 | 1022 | """ |
|
1023 | 1023 | vdict = None |
|
1024 | 1024 | |
|
1025 | 1025 | # We need a dict of name/value pairs to do namespace updates. |
|
1026 | 1026 | if isinstance(variables, dict): |
|
1027 | 1027 | vdict = variables |
|
1028 | 1028 | elif isinstance(variables, (basestring, list, tuple)): |
|
1029 | 1029 | if isinstance(variables, basestring): |
|
1030 | 1030 | vlist = variables.split() |
|
1031 | 1031 | else: |
|
1032 | 1032 | vlist = variables |
|
1033 | 1033 | vdict = {} |
|
1034 | 1034 | cf = sys._getframe(1) |
|
1035 | 1035 | for name in vlist: |
|
1036 | 1036 | try: |
|
1037 | 1037 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1038 | 1038 | except: |
|
1039 | 1039 | print ('Could not get variable %s from %s' % |
|
1040 | 1040 | (name,cf.f_code.co_name)) |
|
1041 | 1041 | else: |
|
1042 | 1042 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1043 | 1043 | |
|
1044 | 1044 | # Propagate variables to user namespace |
|
1045 | 1045 | self.user_ns.update(vdict) |
|
1046 | 1046 | |
|
1047 | 1047 | # And configure interactive visibility |
|
1048 | 1048 | config_ns = self.user_config_ns |
|
1049 | 1049 | if interactive: |
|
1050 | 1050 | for name, val in vdict.iteritems(): |
|
1051 | 1051 | config_ns.pop(name, None) |
|
1052 | 1052 | else: |
|
1053 | 1053 | for name,val in vdict.iteritems(): |
|
1054 | 1054 | config_ns[name] = val |
|
1055 | 1055 | |
|
1056 | 1056 | #------------------------------------------------------------------------- |
|
1057 | 1057 | # Things related to history management |
|
1058 | 1058 | #------------------------------------------------------------------------- |
|
1059 | 1059 | |
|
1060 | 1060 | def init_history(self): |
|
1061 | 1061 | # List of input with multi-line handling. |
|
1062 | 1062 | self.input_hist = InputList() |
|
1063 | 1063 | # This one will hold the 'raw' input history, without any |
|
1064 | 1064 | # pre-processing. This will allow users to retrieve the input just as |
|
1065 | 1065 | # it was exactly typed in by the user, with %hist -r. |
|
1066 | 1066 | self.input_hist_raw = InputList() |
|
1067 | 1067 | |
|
1068 | 1068 | # list of visited directories |
|
1069 | 1069 | try: |
|
1070 | 1070 | self.dir_hist = [os.getcwd()] |
|
1071 | 1071 | except OSError: |
|
1072 | 1072 | self.dir_hist = [] |
|
1073 | 1073 | |
|
1074 | 1074 | # dict of output history |
|
1075 | 1075 | self.output_hist = {} |
|
1076 | 1076 | |
|
1077 | 1077 | # Now the history file |
|
1078 | 1078 | if self.profile: |
|
1079 | 1079 | histfname = 'history-%s' % self.profile |
|
1080 | 1080 | else: |
|
1081 | 1081 | histfname = 'history' |
|
1082 | self.histfile = os.path.join(self.ipythondir, histfname) | |
|
1082 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
|
1083 | 1083 | |
|
1084 | 1084 | # Fill the history zero entry, user counter starts at 1 |
|
1085 | 1085 | self.input_hist.append('\n') |
|
1086 | 1086 | self.input_hist_raw.append('\n') |
|
1087 | 1087 | |
|
1088 | 1088 | def init_shadow_hist(self): |
|
1089 | 1089 | try: |
|
1090 | self.db = pickleshare.PickleShareDB(self.ipythondir + "/db") | |
|
1090 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
|
1091 | 1091 | except exceptions.UnicodeDecodeError: |
|
1092 | print "Your ipythondir can't be decoded to unicode!" | |
|
1092 | print "Your ipython_dir can't be decoded to unicode!" | |
|
1093 | 1093 | print "Please set HOME environment variable to something that" |
|
1094 | 1094 | print r"only has ASCII characters, e.g. c:\home" |
|
1095 | print "Now it is", self.ipythondir | |
|
1095 | print "Now it is", self.ipython_dir | |
|
1096 | 1096 | sys.exit() |
|
1097 | 1097 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1098 | 1098 | |
|
1099 | 1099 | def savehist(self): |
|
1100 | 1100 | """Save input history to a file (via readline library).""" |
|
1101 | 1101 | |
|
1102 | 1102 | if not self.has_readline: |
|
1103 | 1103 | return |
|
1104 | 1104 | |
|
1105 | 1105 | try: |
|
1106 | 1106 | self.readline.write_history_file(self.histfile) |
|
1107 | 1107 | except: |
|
1108 | 1108 | print 'Unable to save IPython command history to file: ' + \ |
|
1109 | 1109 | `self.histfile` |
|
1110 | 1110 | |
|
1111 | 1111 | def reloadhist(self): |
|
1112 | 1112 | """Reload the input history from disk file.""" |
|
1113 | 1113 | |
|
1114 | 1114 | if self.has_readline: |
|
1115 | 1115 | try: |
|
1116 | 1116 | self.readline.clear_history() |
|
1117 | 1117 | self.readline.read_history_file(self.shell.histfile) |
|
1118 | 1118 | except AttributeError: |
|
1119 | 1119 | pass |
|
1120 | 1120 | |
|
1121 | 1121 | def history_saving_wrapper(self, func): |
|
1122 | 1122 | """ Wrap func for readline history saving |
|
1123 | 1123 | |
|
1124 | 1124 | Convert func into callable that saves & restores |
|
1125 | 1125 | history around the call """ |
|
1126 | 1126 | |
|
1127 | 1127 | if not self.has_readline: |
|
1128 | 1128 | return func |
|
1129 | 1129 | |
|
1130 | 1130 | def wrapper(): |
|
1131 | 1131 | self.savehist() |
|
1132 | 1132 | try: |
|
1133 | 1133 | func() |
|
1134 | 1134 | finally: |
|
1135 | 1135 | readline.read_history_file(self.histfile) |
|
1136 | 1136 | return wrapper |
|
1137 | 1137 | |
|
1138 | 1138 | #------------------------------------------------------------------------- |
|
1139 | 1139 | # Things related to exception handling and tracebacks (not debugging) |
|
1140 | 1140 | #------------------------------------------------------------------------- |
|
1141 | 1141 | |
|
1142 | 1142 | def init_traceback_handlers(self, custom_exceptions): |
|
1143 | 1143 | # Syntax error handler. |
|
1144 | 1144 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1145 | 1145 | |
|
1146 | 1146 | # The interactive one is initialized with an offset, meaning we always |
|
1147 | 1147 | # want to remove the topmost item in the traceback, which is our own |
|
1148 | 1148 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1149 | 1149 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1150 | 1150 | color_scheme='NoColor', |
|
1151 | 1151 | tb_offset = 1) |
|
1152 | 1152 | |
|
1153 | 1153 | # IPython itself shouldn't crash. This will produce a detailed |
|
1154 | 1154 | # post-mortem if it does. But we only install the crash handler for |
|
1155 | 1155 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
1156 | 1156 | # and lose the crash handler. This is because exceptions in the main |
|
1157 | 1157 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
1158 | 1158 | # and there's no point in printing crash dumps for every user exception. |
|
1159 | 1159 | if self.isthreaded: |
|
1160 | 1160 | ipCrashHandler = ultratb.FormattedTB() |
|
1161 | 1161 | else: |
|
1162 | 1162 | from IPython.core import crashhandler |
|
1163 | 1163 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
1164 | 1164 | self.set_crash_handler(ipCrashHandler) |
|
1165 | 1165 | |
|
1166 | 1166 | # and add any custom exception handlers the user may have specified |
|
1167 | 1167 | self.set_custom_exc(*custom_exceptions) |
|
1168 | 1168 | |
|
1169 | 1169 | def set_crash_handler(self, crashHandler): |
|
1170 | 1170 | """Set the IPython crash handler. |
|
1171 | 1171 | |
|
1172 | 1172 | This must be a callable with a signature suitable for use as |
|
1173 | 1173 | sys.excepthook.""" |
|
1174 | 1174 | |
|
1175 | 1175 | # Install the given crash handler as the Python exception hook |
|
1176 | 1176 | sys.excepthook = crashHandler |
|
1177 | 1177 | |
|
1178 | 1178 | # The instance will store a pointer to this, so that runtime code |
|
1179 | 1179 | # (such as magics) can access it. This is because during the |
|
1180 | 1180 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1181 | 1181 | # frameworks). |
|
1182 | 1182 | self.sys_excepthook = sys.excepthook |
|
1183 | 1183 | |
|
1184 | 1184 | def set_custom_exc(self,exc_tuple,handler): |
|
1185 | 1185 | """set_custom_exc(exc_tuple,handler) |
|
1186 | 1186 | |
|
1187 | 1187 | Set a custom exception handler, which will be called if any of the |
|
1188 | 1188 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1189 | 1189 | runcode() method. |
|
1190 | 1190 | |
|
1191 | 1191 | Inputs: |
|
1192 | 1192 | |
|
1193 | 1193 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1194 | 1194 | handler for. It is very important that you use a tuple, and NOT A |
|
1195 | 1195 | LIST here, because of the way Python's except statement works. If |
|
1196 | 1196 | you only want to trap a single exception, use a singleton tuple: |
|
1197 | 1197 | |
|
1198 | 1198 | exc_tuple == (MyCustomException,) |
|
1199 | 1199 | |
|
1200 | 1200 | - handler: this must be defined as a function with the following |
|
1201 | 1201 | basic interface: def my_handler(self,etype,value,tb). |
|
1202 | 1202 | |
|
1203 | 1203 | This will be made into an instance method (via new.instancemethod) |
|
1204 | 1204 | of IPython itself, and it will be called if any of the exceptions |
|
1205 | 1205 | listed in the exc_tuple are caught. If the handler is None, an |
|
1206 | 1206 | internal basic one is used, which just prints basic info. |
|
1207 | 1207 | |
|
1208 | 1208 | WARNING: by putting in your own exception handler into IPython's main |
|
1209 | 1209 | execution loop, you run a very good chance of nasty crashes. This |
|
1210 | 1210 | facility should only be used if you really know what you are doing.""" |
|
1211 | 1211 | |
|
1212 | 1212 | assert type(exc_tuple)==type(()) , \ |
|
1213 | 1213 | "The custom exceptions must be given AS A TUPLE." |
|
1214 | 1214 | |
|
1215 | 1215 | def dummy_handler(self,etype,value,tb): |
|
1216 | 1216 | print '*** Simple custom exception handler ***' |
|
1217 | 1217 | print 'Exception type :',etype |
|
1218 | 1218 | print 'Exception value:',value |
|
1219 | 1219 | print 'Traceback :',tb |
|
1220 | 1220 | print 'Source code :','\n'.join(self.buffer) |
|
1221 | 1221 | |
|
1222 | 1222 | if handler is None: handler = dummy_handler |
|
1223 | 1223 | |
|
1224 | 1224 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1225 | 1225 | self.custom_exceptions = exc_tuple |
|
1226 | 1226 | |
|
1227 | 1227 | def excepthook(self, etype, value, tb): |
|
1228 | 1228 | """One more defense for GUI apps that call sys.excepthook. |
|
1229 | 1229 | |
|
1230 | 1230 | GUI frameworks like wxPython trap exceptions and call |
|
1231 | 1231 | sys.excepthook themselves. I guess this is a feature that |
|
1232 | 1232 | enables them to keep running after exceptions that would |
|
1233 | 1233 | otherwise kill their mainloop. This is a bother for IPython |
|
1234 | 1234 | which excepts to catch all of the program exceptions with a try: |
|
1235 | 1235 | except: statement. |
|
1236 | 1236 | |
|
1237 | 1237 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1238 | 1238 | any app directly invokes sys.excepthook, it will look to the user like |
|
1239 | 1239 | IPython crashed. In order to work around this, we can disable the |
|
1240 | 1240 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1241 | 1241 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1242 | 1242 | call sys.excepthook will generate a regular-looking exception from |
|
1243 | 1243 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1244 | 1244 | crashes. |
|
1245 | 1245 | |
|
1246 | 1246 | This hook should be used sparingly, only in places which are not likely |
|
1247 | 1247 | to be true IPython errors. |
|
1248 | 1248 | """ |
|
1249 | 1249 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1250 | 1250 | |
|
1251 | 1251 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1252 | 1252 | """Display the exception that just occurred. |
|
1253 | 1253 | |
|
1254 | 1254 | If nothing is known about the exception, this is the method which |
|
1255 | 1255 | should be used throughout the code for presenting user tracebacks, |
|
1256 | 1256 | rather than directly invoking the InteractiveTB object. |
|
1257 | 1257 | |
|
1258 | 1258 | A specific showsyntaxerror() also exists, but this method can take |
|
1259 | 1259 | care of calling it if needed, so unless you are explicitly catching a |
|
1260 | 1260 | SyntaxError exception, don't try to analyze the stack manually and |
|
1261 | 1261 | simply call this method.""" |
|
1262 | 1262 | |
|
1263 | 1263 | |
|
1264 | 1264 | # Though this won't be called by syntax errors in the input line, |
|
1265 | 1265 | # there may be SyntaxError cases whith imported code. |
|
1266 | 1266 | |
|
1267 | 1267 | try: |
|
1268 | 1268 | if exc_tuple is None: |
|
1269 | 1269 | etype, value, tb = sys.exc_info() |
|
1270 | 1270 | else: |
|
1271 | 1271 | etype, value, tb = exc_tuple |
|
1272 | 1272 | |
|
1273 | 1273 | if etype is SyntaxError: |
|
1274 | 1274 | self.showsyntaxerror(filename) |
|
1275 | 1275 | elif etype is UsageError: |
|
1276 | 1276 | print "UsageError:", value |
|
1277 | 1277 | else: |
|
1278 | 1278 | # WARNING: these variables are somewhat deprecated and not |
|
1279 | 1279 | # necessarily safe to use in a threaded environment, but tools |
|
1280 | 1280 | # like pdb depend on their existence, so let's set them. If we |
|
1281 | 1281 | # find problems in the field, we'll need to revisit their use. |
|
1282 | 1282 | sys.last_type = etype |
|
1283 | 1283 | sys.last_value = value |
|
1284 | 1284 | sys.last_traceback = tb |
|
1285 | 1285 | |
|
1286 | 1286 | if etype in self.custom_exceptions: |
|
1287 | 1287 | self.CustomTB(etype,value,tb) |
|
1288 | 1288 | else: |
|
1289 | 1289 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1290 | 1290 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1291 | 1291 | # pdb mucks up readline, fix it back |
|
1292 | 1292 | self.set_completer() |
|
1293 | 1293 | except KeyboardInterrupt: |
|
1294 | 1294 | self.write("\nKeyboardInterrupt\n") |
|
1295 | 1295 | |
|
1296 | 1296 | def showsyntaxerror(self, filename=None): |
|
1297 | 1297 | """Display the syntax error that just occurred. |
|
1298 | 1298 | |
|
1299 | 1299 | This doesn't display a stack trace because there isn't one. |
|
1300 | 1300 | |
|
1301 | 1301 | If a filename is given, it is stuffed in the exception instead |
|
1302 | 1302 | of what was there before (because Python's parser always uses |
|
1303 | 1303 | "<string>" when reading from a string). |
|
1304 | 1304 | """ |
|
1305 | 1305 | etype, value, last_traceback = sys.exc_info() |
|
1306 | 1306 | |
|
1307 | 1307 | # See note about these variables in showtraceback() below |
|
1308 | 1308 | sys.last_type = etype |
|
1309 | 1309 | sys.last_value = value |
|
1310 | 1310 | sys.last_traceback = last_traceback |
|
1311 | 1311 | |
|
1312 | 1312 | if filename and etype is SyntaxError: |
|
1313 | 1313 | # Work hard to stuff the correct filename in the exception |
|
1314 | 1314 | try: |
|
1315 | 1315 | msg, (dummy_filename, lineno, offset, line) = value |
|
1316 | 1316 | except: |
|
1317 | 1317 | # Not the format we expect; leave it alone |
|
1318 | 1318 | pass |
|
1319 | 1319 | else: |
|
1320 | 1320 | # Stuff in the right filename |
|
1321 | 1321 | try: |
|
1322 | 1322 | # Assume SyntaxError is a class exception |
|
1323 | 1323 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1324 | 1324 | except: |
|
1325 | 1325 | # If that failed, assume SyntaxError is a string |
|
1326 | 1326 | value = msg, (filename, lineno, offset, line) |
|
1327 | 1327 | self.SyntaxTB(etype,value,[]) |
|
1328 | 1328 | |
|
1329 | 1329 | def edit_syntax_error(self): |
|
1330 | 1330 | """The bottom half of the syntax error handler called in the main loop. |
|
1331 | 1331 | |
|
1332 | 1332 | Loop until syntax error is fixed or user cancels. |
|
1333 | 1333 | """ |
|
1334 | 1334 | |
|
1335 | 1335 | while self.SyntaxTB.last_syntax_error: |
|
1336 | 1336 | # copy and clear last_syntax_error |
|
1337 | 1337 | err = self.SyntaxTB.clear_err_state() |
|
1338 | 1338 | if not self._should_recompile(err): |
|
1339 | 1339 | return |
|
1340 | 1340 | try: |
|
1341 | 1341 | # may set last_syntax_error again if a SyntaxError is raised |
|
1342 | 1342 | self.safe_execfile(err.filename,self.user_ns) |
|
1343 | 1343 | except: |
|
1344 | 1344 | self.showtraceback() |
|
1345 | 1345 | else: |
|
1346 | 1346 | try: |
|
1347 | 1347 | f = file(err.filename) |
|
1348 | 1348 | try: |
|
1349 | 1349 | # This should be inside a display_trap block and I |
|
1350 | 1350 | # think it is. |
|
1351 | 1351 | sys.displayhook(f.read()) |
|
1352 | 1352 | finally: |
|
1353 | 1353 | f.close() |
|
1354 | 1354 | except: |
|
1355 | 1355 | self.showtraceback() |
|
1356 | 1356 | |
|
1357 | 1357 | def _should_recompile(self,e): |
|
1358 | 1358 | """Utility routine for edit_syntax_error""" |
|
1359 | 1359 | |
|
1360 | 1360 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1361 | 1361 | '<console>','<BackgroundJob compilation>', |
|
1362 | 1362 | None): |
|
1363 | 1363 | |
|
1364 | 1364 | return False |
|
1365 | 1365 | try: |
|
1366 | 1366 | if (self.autoedit_syntax and |
|
1367 | 1367 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1368 | 1368 | '[Y/n] ','y')): |
|
1369 | 1369 | return False |
|
1370 | 1370 | except EOFError: |
|
1371 | 1371 | return False |
|
1372 | 1372 | |
|
1373 | 1373 | def int0(x): |
|
1374 | 1374 | try: |
|
1375 | 1375 | return int(x) |
|
1376 | 1376 | except TypeError: |
|
1377 | 1377 | return 0 |
|
1378 | 1378 | # always pass integer line and offset values to editor hook |
|
1379 | 1379 | try: |
|
1380 | 1380 | self.hooks.fix_error_editor(e.filename, |
|
1381 | 1381 | int0(e.lineno),int0(e.offset),e.msg) |
|
1382 | 1382 | except TryNext: |
|
1383 | 1383 | warn('Could not open editor') |
|
1384 | 1384 | return False |
|
1385 | 1385 | return True |
|
1386 | 1386 | |
|
1387 | 1387 | #------------------------------------------------------------------------- |
|
1388 | 1388 | # Things related to tab completion |
|
1389 | 1389 | #------------------------------------------------------------------------- |
|
1390 | 1390 | |
|
1391 | 1391 | def complete(self, text): |
|
1392 | 1392 | """Return a sorted list of all possible completions on text. |
|
1393 | 1393 | |
|
1394 | 1394 | Inputs: |
|
1395 | 1395 | |
|
1396 | 1396 | - text: a string of text to be completed on. |
|
1397 | 1397 | |
|
1398 | 1398 | This is a wrapper around the completion mechanism, similar to what |
|
1399 | 1399 | readline does at the command line when the TAB key is hit. By |
|
1400 | 1400 | exposing it as a method, it can be used by other non-readline |
|
1401 | 1401 | environments (such as GUIs) for text completion. |
|
1402 | 1402 | |
|
1403 | 1403 | Simple usage example: |
|
1404 | 1404 | |
|
1405 | 1405 | In [7]: x = 'hello' |
|
1406 | 1406 | |
|
1407 | 1407 | In [8]: x |
|
1408 | 1408 | Out[8]: 'hello' |
|
1409 | 1409 | |
|
1410 | 1410 | In [9]: print x |
|
1411 | 1411 | hello |
|
1412 | 1412 | |
|
1413 | 1413 | In [10]: _ip.complete('x.l') |
|
1414 | 1414 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1415 | 1415 | """ |
|
1416 | 1416 | |
|
1417 | 1417 | # Inject names into __builtin__ so we can complete on the added names. |
|
1418 | 1418 | with self.builtin_trap: |
|
1419 | 1419 | complete = self.Completer.complete |
|
1420 | 1420 | state = 0 |
|
1421 | 1421 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1422 | 1422 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1423 | 1423 | # start using sets instead, which are faster. |
|
1424 | 1424 | comps = {} |
|
1425 | 1425 | while True: |
|
1426 | 1426 | newcomp = complete(text,state,line_buffer=text) |
|
1427 | 1427 | if newcomp is None: |
|
1428 | 1428 | break |
|
1429 | 1429 | comps[newcomp] = 1 |
|
1430 | 1430 | state += 1 |
|
1431 | 1431 | outcomps = comps.keys() |
|
1432 | 1432 | outcomps.sort() |
|
1433 | 1433 | #print "T:",text,"OC:",outcomps # dbg |
|
1434 | 1434 | #print "vars:",self.user_ns.keys() |
|
1435 | 1435 | return outcomps |
|
1436 | 1436 | |
|
1437 | 1437 | def set_custom_completer(self,completer,pos=0): |
|
1438 | 1438 | """Adds a new custom completer function. |
|
1439 | 1439 | |
|
1440 | 1440 | The position argument (defaults to 0) is the index in the completers |
|
1441 | 1441 | list where you want the completer to be inserted.""" |
|
1442 | 1442 | |
|
1443 | 1443 | newcomp = new.instancemethod(completer,self.Completer, |
|
1444 | 1444 | self.Completer.__class__) |
|
1445 | 1445 | self.Completer.matchers.insert(pos,newcomp) |
|
1446 | 1446 | |
|
1447 | 1447 | def set_completer(self): |
|
1448 | 1448 | """Reset readline's completer to be our own.""" |
|
1449 | 1449 | self.readline.set_completer(self.Completer.complete) |
|
1450 | 1450 | |
|
1451 | 1451 | def set_completer_frame(self, frame=None): |
|
1452 | 1452 | """Set the frame of the completer.""" |
|
1453 | 1453 | if frame: |
|
1454 | 1454 | self.Completer.namespace = frame.f_locals |
|
1455 | 1455 | self.Completer.global_namespace = frame.f_globals |
|
1456 | 1456 | else: |
|
1457 | 1457 | self.Completer.namespace = self.user_ns |
|
1458 | 1458 | self.Completer.global_namespace = self.user_global_ns |
|
1459 | 1459 | |
|
1460 | 1460 | #------------------------------------------------------------------------- |
|
1461 | 1461 | # Things related to readline |
|
1462 | 1462 | #------------------------------------------------------------------------- |
|
1463 | 1463 | |
|
1464 | 1464 | def init_readline(self): |
|
1465 | 1465 | """Command history completion/saving/reloading.""" |
|
1466 | 1466 | |
|
1467 | 1467 | self.rl_next_input = None |
|
1468 | 1468 | self.rl_do_indent = False |
|
1469 | 1469 | |
|
1470 | 1470 | if not self.readline_use: |
|
1471 | 1471 | return |
|
1472 | 1472 | |
|
1473 | 1473 | import IPython.utils.rlineimpl as readline |
|
1474 | 1474 | |
|
1475 | 1475 | if not readline.have_readline: |
|
1476 | 1476 | self.has_readline = 0 |
|
1477 | 1477 | self.readline = None |
|
1478 | 1478 | # no point in bugging windows users with this every time: |
|
1479 | 1479 | warn('Readline services not available on this platform.') |
|
1480 | 1480 | else: |
|
1481 | 1481 | sys.modules['readline'] = readline |
|
1482 | 1482 | import atexit |
|
1483 | 1483 | from IPython.core.completer import IPCompleter |
|
1484 | 1484 | self.Completer = IPCompleter(self, |
|
1485 | 1485 | self.user_ns, |
|
1486 | 1486 | self.user_global_ns, |
|
1487 | 1487 | self.readline_omit__names, |
|
1488 | 1488 | self.alias_manager.alias_table) |
|
1489 | 1489 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1490 | 1490 | self.strdispatchers['complete_command'] = sdisp |
|
1491 | 1491 | self.Completer.custom_completers = sdisp |
|
1492 | 1492 | # Platform-specific configuration |
|
1493 | 1493 | if os.name == 'nt': |
|
1494 | 1494 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1495 | 1495 | else: |
|
1496 | 1496 | self.readline_startup_hook = readline.set_startup_hook |
|
1497 | 1497 | |
|
1498 | 1498 | # Load user's initrc file (readline config) |
|
1499 | 1499 | # Or if libedit is used, load editrc. |
|
1500 | 1500 | inputrc_name = os.environ.get('INPUTRC') |
|
1501 | 1501 | if inputrc_name is None: |
|
1502 | 1502 | home_dir = get_home_dir() |
|
1503 | 1503 | if home_dir is not None: |
|
1504 | 1504 | inputrc_name = '.inputrc' |
|
1505 | 1505 | if readline.uses_libedit: |
|
1506 | 1506 | inputrc_name = '.editrc' |
|
1507 | 1507 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1508 | 1508 | if os.path.isfile(inputrc_name): |
|
1509 | 1509 | try: |
|
1510 | 1510 | readline.read_init_file(inputrc_name) |
|
1511 | 1511 | except: |
|
1512 | 1512 | warn('Problems reading readline initialization file <%s>' |
|
1513 | 1513 | % inputrc_name) |
|
1514 | 1514 | |
|
1515 | 1515 | self.has_readline = 1 |
|
1516 | 1516 | self.readline = readline |
|
1517 | 1517 | # save this in sys so embedded copies can restore it properly |
|
1518 | 1518 | sys.ipcompleter = self.Completer.complete |
|
1519 | 1519 | self.set_completer() |
|
1520 | 1520 | |
|
1521 | 1521 | # Configure readline according to user's prefs |
|
1522 | 1522 | # This is only done if GNU readline is being used. If libedit |
|
1523 | 1523 | # is being used (as on Leopard) the readline config is |
|
1524 | 1524 | # not run as the syntax for libedit is different. |
|
1525 | 1525 | if not readline.uses_libedit: |
|
1526 | 1526 | for rlcommand in self.readline_parse_and_bind: |
|
1527 | 1527 | #print "loading rl:",rlcommand # dbg |
|
1528 | 1528 | readline.parse_and_bind(rlcommand) |
|
1529 | 1529 | |
|
1530 | 1530 | # Remove some chars from the delimiters list. If we encounter |
|
1531 | 1531 | # unicode chars, discard them. |
|
1532 | 1532 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1533 | 1533 | delims = delims.translate(string._idmap, |
|
1534 | 1534 | self.readline_remove_delims) |
|
1535 | 1535 | readline.set_completer_delims(delims) |
|
1536 | 1536 | # otherwise we end up with a monster history after a while: |
|
1537 | 1537 | readline.set_history_length(1000) |
|
1538 | 1538 | try: |
|
1539 | 1539 | #print '*** Reading readline history' # dbg |
|
1540 | 1540 | readline.read_history_file(self.histfile) |
|
1541 | 1541 | except IOError: |
|
1542 | 1542 | pass # It doesn't exist yet. |
|
1543 | 1543 | |
|
1544 | 1544 | atexit.register(self.atexit_operations) |
|
1545 | 1545 | del atexit |
|
1546 | 1546 | |
|
1547 | 1547 | # Configure auto-indent for all platforms |
|
1548 | 1548 | self.set_autoindent(self.autoindent) |
|
1549 | 1549 | |
|
1550 | 1550 | def set_next_input(self, s): |
|
1551 | 1551 | """ Sets the 'default' input string for the next command line. |
|
1552 | 1552 | |
|
1553 | 1553 | Requires readline. |
|
1554 | 1554 | |
|
1555 | 1555 | Example: |
|
1556 | 1556 | |
|
1557 | 1557 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1558 | 1558 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1559 | 1559 | """ |
|
1560 | 1560 | |
|
1561 | 1561 | self.rl_next_input = s |
|
1562 | 1562 | |
|
1563 | 1563 | def pre_readline(self): |
|
1564 | 1564 | """readline hook to be used at the start of each line. |
|
1565 | 1565 | |
|
1566 | 1566 | Currently it handles auto-indent only.""" |
|
1567 | 1567 | |
|
1568 | 1568 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1569 | 1569 | |
|
1570 | 1570 | if self.rl_do_indent: |
|
1571 | 1571 | self.readline.insert_text(self._indent_current_str()) |
|
1572 | 1572 | if self.rl_next_input is not None: |
|
1573 | 1573 | self.readline.insert_text(self.rl_next_input) |
|
1574 | 1574 | self.rl_next_input = None |
|
1575 | 1575 | |
|
1576 | 1576 | def _indent_current_str(self): |
|
1577 | 1577 | """return the current level of indentation as a string""" |
|
1578 | 1578 | return self.indent_current_nsp * ' ' |
|
1579 | 1579 | |
|
1580 | 1580 | #------------------------------------------------------------------------- |
|
1581 | 1581 | # Things related to magics |
|
1582 | 1582 | #------------------------------------------------------------------------- |
|
1583 | 1583 | |
|
1584 | 1584 | def init_magics(self): |
|
1585 | 1585 | # Set user colors (don't do it in the constructor above so that it |
|
1586 | 1586 | # doesn't crash if colors option is invalid) |
|
1587 | 1587 | self.magic_colors(self.colors) |
|
1588 | 1588 | |
|
1589 | 1589 | def magic(self,arg_s): |
|
1590 | 1590 | """Call a magic function by name. |
|
1591 | 1591 | |
|
1592 | 1592 | Input: a string containing the name of the magic function to call and any |
|
1593 | 1593 | additional arguments to be passed to the magic. |
|
1594 | 1594 | |
|
1595 | 1595 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1596 | 1596 | prompt: |
|
1597 | 1597 | |
|
1598 | 1598 | In[1]: %name -opt foo bar |
|
1599 | 1599 | |
|
1600 | 1600 | To call a magic without arguments, simply use magic('name'). |
|
1601 | 1601 | |
|
1602 | 1602 | This provides a proper Python function to call IPython's magics in any |
|
1603 | 1603 | valid Python code you can type at the interpreter, including loops and |
|
1604 | 1604 | compound statements. |
|
1605 | 1605 | """ |
|
1606 | 1606 | |
|
1607 | 1607 | args = arg_s.split(' ',1) |
|
1608 | 1608 | magic_name = args[0] |
|
1609 | 1609 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1610 | 1610 | |
|
1611 | 1611 | try: |
|
1612 | 1612 | magic_args = args[1] |
|
1613 | 1613 | except IndexError: |
|
1614 | 1614 | magic_args = '' |
|
1615 | 1615 | fn = getattr(self,'magic_'+magic_name,None) |
|
1616 | 1616 | if fn is None: |
|
1617 | 1617 | error("Magic function `%s` not found." % magic_name) |
|
1618 | 1618 | else: |
|
1619 | 1619 | magic_args = self.var_expand(magic_args,1) |
|
1620 | 1620 | with nested(self.builtin_trap,): |
|
1621 | 1621 | result = fn(magic_args) |
|
1622 | 1622 | return result |
|
1623 | 1623 | |
|
1624 | 1624 | def define_magic(self, magicname, func): |
|
1625 | 1625 | """Expose own function as magic function for ipython |
|
1626 | 1626 | |
|
1627 | 1627 | def foo_impl(self,parameter_s=''): |
|
1628 | 1628 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1629 | 1629 | print 'Magic function. Passed parameter is between < >:' |
|
1630 | 1630 | print '<%s>' % parameter_s |
|
1631 | 1631 | print 'The self object is:',self |
|
1632 | 1632 | |
|
1633 | 1633 | self.define_magic('foo',foo_impl) |
|
1634 | 1634 | """ |
|
1635 | 1635 | |
|
1636 | 1636 | import new |
|
1637 | 1637 | im = new.instancemethod(func,self, self.__class__) |
|
1638 | 1638 | old = getattr(self, "magic_" + magicname, None) |
|
1639 | 1639 | setattr(self, "magic_" + magicname, im) |
|
1640 | 1640 | return old |
|
1641 | 1641 | |
|
1642 | 1642 | #------------------------------------------------------------------------- |
|
1643 | 1643 | # Things related to macros |
|
1644 | 1644 | #------------------------------------------------------------------------- |
|
1645 | 1645 | |
|
1646 | 1646 | def define_macro(self, name, themacro): |
|
1647 | 1647 | """Define a new macro |
|
1648 | 1648 | |
|
1649 | 1649 | Parameters |
|
1650 | 1650 | ---------- |
|
1651 | 1651 | name : str |
|
1652 | 1652 | The name of the macro. |
|
1653 | 1653 | themacro : str or Macro |
|
1654 | 1654 | The action to do upon invoking the macro. If a string, a new |
|
1655 | 1655 | Macro object is created by passing the string to it. |
|
1656 | 1656 | """ |
|
1657 | 1657 | |
|
1658 | 1658 | from IPython.core import macro |
|
1659 | 1659 | |
|
1660 | 1660 | if isinstance(themacro, basestring): |
|
1661 | 1661 | themacro = macro.Macro(themacro) |
|
1662 | 1662 | if not isinstance(themacro, macro.Macro): |
|
1663 | 1663 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1664 | 1664 | self.user_ns[name] = themacro |
|
1665 | 1665 | |
|
1666 | 1666 | #------------------------------------------------------------------------- |
|
1667 | 1667 | # Things related to the running of system commands |
|
1668 | 1668 | #------------------------------------------------------------------------- |
|
1669 | 1669 | |
|
1670 | 1670 | def system(self, cmd): |
|
1671 | 1671 | """Make a system call, using IPython.""" |
|
1672 | 1672 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1673 | 1673 | |
|
1674 | 1674 | #------------------------------------------------------------------------- |
|
1675 | 1675 | # Things related to aliases |
|
1676 | 1676 | #------------------------------------------------------------------------- |
|
1677 | 1677 | |
|
1678 | 1678 | def init_alias(self): |
|
1679 | 1679 | self.alias_manager = AliasManager(self, config=self.config) |
|
1680 | 1680 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1681 | 1681 | |
|
1682 | 1682 | #------------------------------------------------------------------------- |
|
1683 | 1683 | # Things related to the running of code |
|
1684 | 1684 | #------------------------------------------------------------------------- |
|
1685 | 1685 | |
|
1686 | 1686 | def ex(self, cmd): |
|
1687 | 1687 | """Execute a normal python statement in user namespace.""" |
|
1688 | 1688 | with nested(self.builtin_trap,): |
|
1689 | 1689 | exec cmd in self.user_global_ns, self.user_ns |
|
1690 | 1690 | |
|
1691 | 1691 | def ev(self, expr): |
|
1692 | 1692 | """Evaluate python expression expr in user namespace. |
|
1693 | 1693 | |
|
1694 | 1694 | Returns the result of evaluation |
|
1695 | 1695 | """ |
|
1696 | 1696 | with nested(self.builtin_trap,): |
|
1697 | 1697 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1698 | 1698 | |
|
1699 | 1699 | def mainloop(self, display_banner=None): |
|
1700 | 1700 | """Start the mainloop. |
|
1701 | 1701 | |
|
1702 | 1702 | If an optional banner argument is given, it will override the |
|
1703 | 1703 | internally created default banner. |
|
1704 | 1704 | """ |
|
1705 | 1705 | |
|
1706 | 1706 | with nested(self.builtin_trap, self.display_trap): |
|
1707 | 1707 | |
|
1708 | 1708 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1709 | 1709 | # ensure that it's in sync |
|
1710 | 1710 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1711 | 1711 | self.input_hist_raw = InputList(self.input_hist) |
|
1712 | 1712 | |
|
1713 | 1713 | while 1: |
|
1714 | 1714 | try: |
|
1715 | 1715 | self.interact(display_banner=display_banner) |
|
1716 | 1716 | #self.interact_with_readline() |
|
1717 | 1717 | # XXX for testing of a readline-decoupled repl loop, call |
|
1718 | 1718 | # interact_with_readline above |
|
1719 | 1719 | break |
|
1720 | 1720 | except KeyboardInterrupt: |
|
1721 | 1721 | # this should not be necessary, but KeyboardInterrupt |
|
1722 | 1722 | # handling seems rather unpredictable... |
|
1723 | 1723 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1724 | 1724 | |
|
1725 | 1725 | def interact_prompt(self): |
|
1726 | 1726 | """ Print the prompt (in read-eval-print loop) |
|
1727 | 1727 | |
|
1728 | 1728 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1729 | 1729 | used in standard IPython flow. |
|
1730 | 1730 | """ |
|
1731 | 1731 | if self.more: |
|
1732 | 1732 | try: |
|
1733 | 1733 | prompt = self.hooks.generate_prompt(True) |
|
1734 | 1734 | except: |
|
1735 | 1735 | self.showtraceback() |
|
1736 | 1736 | if self.autoindent: |
|
1737 | 1737 | self.rl_do_indent = True |
|
1738 | 1738 | |
|
1739 | 1739 | else: |
|
1740 | 1740 | try: |
|
1741 | 1741 | prompt = self.hooks.generate_prompt(False) |
|
1742 | 1742 | except: |
|
1743 | 1743 | self.showtraceback() |
|
1744 | 1744 | self.write(prompt) |
|
1745 | 1745 | |
|
1746 | 1746 | def interact_handle_input(self,line): |
|
1747 | 1747 | """ Handle the input line (in read-eval-print loop) |
|
1748 | 1748 | |
|
1749 | 1749 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1750 | 1750 | used in standard IPython flow. |
|
1751 | 1751 | """ |
|
1752 | 1752 | if line.lstrip() == line: |
|
1753 | 1753 | self.shadowhist.add(line.strip()) |
|
1754 | 1754 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1755 | 1755 | |
|
1756 | 1756 | if line.strip(): |
|
1757 | 1757 | if self.more: |
|
1758 | 1758 | self.input_hist_raw[-1] += '%s\n' % line |
|
1759 | 1759 | else: |
|
1760 | 1760 | self.input_hist_raw.append('%s\n' % line) |
|
1761 | 1761 | |
|
1762 | 1762 | |
|
1763 | 1763 | self.more = self.push_line(lineout) |
|
1764 | 1764 | if (self.SyntaxTB.last_syntax_error and |
|
1765 | 1765 | self.autoedit_syntax): |
|
1766 | 1766 | self.edit_syntax_error() |
|
1767 | 1767 | |
|
1768 | 1768 | def interact_with_readline(self): |
|
1769 | 1769 | """ Demo of using interact_handle_input, interact_prompt |
|
1770 | 1770 | |
|
1771 | 1771 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1772 | 1772 | it should work like this. |
|
1773 | 1773 | """ |
|
1774 | 1774 | self.readline_startup_hook(self.pre_readline) |
|
1775 | 1775 | while not self.exit_now: |
|
1776 | 1776 | self.interact_prompt() |
|
1777 | 1777 | if self.more: |
|
1778 | 1778 | self.rl_do_indent = True |
|
1779 | 1779 | else: |
|
1780 | 1780 | self.rl_do_indent = False |
|
1781 | 1781 | line = raw_input_original().decode(self.stdin_encoding) |
|
1782 | 1782 | self.interact_handle_input(line) |
|
1783 | 1783 | |
|
1784 | 1784 | def interact(self, display_banner=None): |
|
1785 | 1785 | """Closely emulate the interactive Python console.""" |
|
1786 | 1786 | |
|
1787 | 1787 | # batch run -> do not interact |
|
1788 | 1788 | if self.exit_now: |
|
1789 | 1789 | return |
|
1790 | 1790 | |
|
1791 | 1791 | if display_banner is None: |
|
1792 | 1792 | display_banner = self.display_banner |
|
1793 | 1793 | if display_banner: |
|
1794 | 1794 | self.show_banner() |
|
1795 | 1795 | |
|
1796 | 1796 | more = 0 |
|
1797 | 1797 | |
|
1798 | 1798 | # Mark activity in the builtins |
|
1799 | 1799 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1800 | 1800 | |
|
1801 | 1801 | if self.has_readline: |
|
1802 | 1802 | self.readline_startup_hook(self.pre_readline) |
|
1803 | 1803 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1804 | 1804 | # ask_exit callback. |
|
1805 | 1805 | |
|
1806 | 1806 | while not self.exit_now: |
|
1807 | 1807 | self.hooks.pre_prompt_hook() |
|
1808 | 1808 | if more: |
|
1809 | 1809 | try: |
|
1810 | 1810 | prompt = self.hooks.generate_prompt(True) |
|
1811 | 1811 | except: |
|
1812 | 1812 | self.showtraceback() |
|
1813 | 1813 | if self.autoindent: |
|
1814 | 1814 | self.rl_do_indent = True |
|
1815 | 1815 | |
|
1816 | 1816 | else: |
|
1817 | 1817 | try: |
|
1818 | 1818 | prompt = self.hooks.generate_prompt(False) |
|
1819 | 1819 | except: |
|
1820 | 1820 | self.showtraceback() |
|
1821 | 1821 | try: |
|
1822 | 1822 | line = self.raw_input(prompt, more) |
|
1823 | 1823 | if self.exit_now: |
|
1824 | 1824 | # quick exit on sys.std[in|out] close |
|
1825 | 1825 | break |
|
1826 | 1826 | if self.autoindent: |
|
1827 | 1827 | self.rl_do_indent = False |
|
1828 | 1828 | |
|
1829 | 1829 | except KeyboardInterrupt: |
|
1830 | 1830 | #double-guard against keyboardinterrupts during kbdint handling |
|
1831 | 1831 | try: |
|
1832 | 1832 | self.write('\nKeyboardInterrupt\n') |
|
1833 | 1833 | self.resetbuffer() |
|
1834 | 1834 | # keep cache in sync with the prompt counter: |
|
1835 | 1835 | self.outputcache.prompt_count -= 1 |
|
1836 | 1836 | |
|
1837 | 1837 | if self.autoindent: |
|
1838 | 1838 | self.indent_current_nsp = 0 |
|
1839 | 1839 | more = 0 |
|
1840 | 1840 | except KeyboardInterrupt: |
|
1841 | 1841 | pass |
|
1842 | 1842 | except EOFError: |
|
1843 | 1843 | if self.autoindent: |
|
1844 | 1844 | self.rl_do_indent = False |
|
1845 | 1845 | self.readline_startup_hook(None) |
|
1846 | 1846 | self.write('\n') |
|
1847 | 1847 | self.exit() |
|
1848 | 1848 | except bdb.BdbQuit: |
|
1849 | 1849 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1850 | 1850 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1851 | 1851 | 'for IPython to properly format this particular exception.\n' |
|
1852 | 1852 | 'IPython will resume normal operation.') |
|
1853 | 1853 | except: |
|
1854 | 1854 | # exceptions here are VERY RARE, but they can be triggered |
|
1855 | 1855 | # asynchronously by signal handlers, for example. |
|
1856 | 1856 | self.showtraceback() |
|
1857 | 1857 | else: |
|
1858 | 1858 | more = self.push_line(line) |
|
1859 | 1859 | if (self.SyntaxTB.last_syntax_error and |
|
1860 | 1860 | self.autoedit_syntax): |
|
1861 | 1861 | self.edit_syntax_error() |
|
1862 | 1862 | |
|
1863 | 1863 | # We are off again... |
|
1864 | 1864 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1865 | 1865 | |
|
1866 | 1866 | def safe_execfile(self, fname, *where, **kw): |
|
1867 | 1867 | """A safe version of the builtin execfile(). |
|
1868 | 1868 | |
|
1869 | 1869 | This version will never throw an exception, but instead print |
|
1870 | 1870 | helpful error messages to the screen. This only works on pure |
|
1871 | 1871 | Python files with the .py extension. |
|
1872 | 1872 | |
|
1873 | 1873 | Parameters |
|
1874 | 1874 | ---------- |
|
1875 | 1875 | fname : string |
|
1876 | 1876 | The name of the file to be executed. |
|
1877 | 1877 | where : tuple |
|
1878 | 1878 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1879 | 1879 | If only one is given, it is passed as both. |
|
1880 | 1880 | exit_ignore : bool (False) |
|
1881 | 1881 | If True, then don't print errors for non-zero exit statuses. |
|
1882 | 1882 | """ |
|
1883 | 1883 | kw.setdefault('exit_ignore', False) |
|
1884 | 1884 | |
|
1885 | 1885 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1886 | 1886 | |
|
1887 | 1887 | # Make sure we have a .py file |
|
1888 | 1888 | if not fname.endswith('.py'): |
|
1889 | 1889 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1890 | 1890 | |
|
1891 | 1891 | # Make sure we can open the file |
|
1892 | 1892 | try: |
|
1893 | 1893 | with open(fname) as thefile: |
|
1894 | 1894 | pass |
|
1895 | 1895 | except: |
|
1896 | 1896 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1897 | 1897 | return |
|
1898 | 1898 | |
|
1899 | 1899 | # Find things also in current directory. This is needed to mimic the |
|
1900 | 1900 | # behavior of running a script from the system command line, where |
|
1901 | 1901 | # Python inserts the script's directory into sys.path |
|
1902 | 1902 | dname = os.path.dirname(fname) |
|
1903 | 1903 | |
|
1904 | 1904 | with prepended_to_syspath(dname): |
|
1905 | 1905 | try: |
|
1906 | 1906 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
1907 | 1907 | # Work around a bug in Python for Windows. The bug was |
|
1908 | 1908 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
1909 | 1909 | # SVN Python as of March/07. For details, see: |
|
1910 | 1910 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
1911 | 1911 | try: |
|
1912 | 1912 | globs,locs = where[0:2] |
|
1913 | 1913 | except: |
|
1914 | 1914 | try: |
|
1915 | 1915 | globs = locs = where[0] |
|
1916 | 1916 | except: |
|
1917 | 1917 | globs = locs = globals() |
|
1918 | 1918 | exec file(fname) in globs,locs |
|
1919 | 1919 | else: |
|
1920 | 1920 | execfile(fname,*where) |
|
1921 | 1921 | except SyntaxError: |
|
1922 | 1922 | self.showsyntaxerror() |
|
1923 | 1923 | warn('Failure executing file: <%s>' % fname) |
|
1924 | 1924 | except SystemExit, status: |
|
1925 | 1925 | # Code that correctly sets the exit status flag to success (0) |
|
1926 | 1926 | # shouldn't be bothered with a traceback. Note that a plain |
|
1927 | 1927 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
1928 | 1928 | # will still get a traceback. Note that the structure of the |
|
1929 | 1929 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
1930 | 1930 | # the checks must be done in a version-dependent way. |
|
1931 | 1931 | show = False |
|
1932 | 1932 | if status.args[0]==0 and not kw['exit_ignore']: |
|
1933 | 1933 | show = True |
|
1934 | 1934 | if show: |
|
1935 | 1935 | self.showtraceback() |
|
1936 | 1936 | warn('Failure executing file: <%s>' % fname) |
|
1937 | 1937 | except: |
|
1938 | 1938 | self.showtraceback() |
|
1939 | 1939 | warn('Failure executing file: <%s>' % fname) |
|
1940 | 1940 | |
|
1941 | 1941 | def safe_execfile_ipy(self, fname): |
|
1942 | 1942 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1943 | 1943 | |
|
1944 | 1944 | Parameters |
|
1945 | 1945 | ---------- |
|
1946 | 1946 | fname : str |
|
1947 | 1947 | The name of the file to execute. The filename must have a |
|
1948 | 1948 | .ipy extension. |
|
1949 | 1949 | """ |
|
1950 | 1950 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1951 | 1951 | |
|
1952 | 1952 | # Make sure we have a .py file |
|
1953 | 1953 | if not fname.endswith('.ipy'): |
|
1954 | 1954 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1955 | 1955 | |
|
1956 | 1956 | # Make sure we can open the file |
|
1957 | 1957 | try: |
|
1958 | 1958 | with open(fname) as thefile: |
|
1959 | 1959 | pass |
|
1960 | 1960 | except: |
|
1961 | 1961 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1962 | 1962 | return |
|
1963 | 1963 | |
|
1964 | 1964 | # Find things also in current directory. This is needed to mimic the |
|
1965 | 1965 | # behavior of running a script from the system command line, where |
|
1966 | 1966 | # Python inserts the script's directory into sys.path |
|
1967 | 1967 | dname = os.path.dirname(fname) |
|
1968 | 1968 | |
|
1969 | 1969 | with prepended_to_syspath(dname): |
|
1970 | 1970 | try: |
|
1971 | 1971 | with open(fname) as thefile: |
|
1972 | 1972 | script = thefile.read() |
|
1973 | 1973 | # self.runlines currently captures all exceptions |
|
1974 | 1974 | # raise in user code. It would be nice if there were |
|
1975 | 1975 | # versions of runlines, execfile that did raise, so |
|
1976 | 1976 | # we could catch the errors. |
|
1977 | 1977 | self.runlines(script, clean=True) |
|
1978 | 1978 | except: |
|
1979 | 1979 | self.showtraceback() |
|
1980 | 1980 | warn('Unknown failure executing file: <%s>' % fname) |
|
1981 | 1981 | |
|
1982 | 1982 | def _is_secondary_block_start(self, s): |
|
1983 | 1983 | if not s.endswith(':'): |
|
1984 | 1984 | return False |
|
1985 | 1985 | if (s.startswith('elif') or |
|
1986 | 1986 | s.startswith('else') or |
|
1987 | 1987 | s.startswith('except') or |
|
1988 | 1988 | s.startswith('finally')): |
|
1989 | 1989 | return True |
|
1990 | 1990 | |
|
1991 | 1991 | def cleanup_ipy_script(self, script): |
|
1992 | 1992 | """Make a script safe for self.runlines() |
|
1993 | 1993 | |
|
1994 | 1994 | Currently, IPython is lines based, with blocks being detected by |
|
1995 | 1995 | empty lines. This is a problem for block based scripts that may |
|
1996 | 1996 | not have empty lines after blocks. This script adds those empty |
|
1997 | 1997 | lines to make scripts safe for running in the current line based |
|
1998 | 1998 | IPython. |
|
1999 | 1999 | """ |
|
2000 | 2000 | res = [] |
|
2001 | 2001 | lines = script.splitlines() |
|
2002 | 2002 | level = 0 |
|
2003 | 2003 | |
|
2004 | 2004 | for l in lines: |
|
2005 | 2005 | lstripped = l.lstrip() |
|
2006 | 2006 | stripped = l.strip() |
|
2007 | 2007 | if not stripped: |
|
2008 | 2008 | continue |
|
2009 | 2009 | newlevel = len(l) - len(lstripped) |
|
2010 | 2010 | if level > 0 and newlevel == 0 and \ |
|
2011 | 2011 | not self._is_secondary_block_start(stripped): |
|
2012 | 2012 | # add empty line |
|
2013 | 2013 | res.append('') |
|
2014 | 2014 | res.append(l) |
|
2015 | 2015 | level = newlevel |
|
2016 | 2016 | |
|
2017 | 2017 | return '\n'.join(res) + '\n' |
|
2018 | 2018 | |
|
2019 | 2019 | def runlines(self, lines, clean=False): |
|
2020 | 2020 | """Run a string of one or more lines of source. |
|
2021 | 2021 | |
|
2022 | 2022 | This method is capable of running a string containing multiple source |
|
2023 | 2023 | lines, as if they had been entered at the IPython prompt. Since it |
|
2024 | 2024 | exposes IPython's processing machinery, the given strings can contain |
|
2025 | 2025 | magic calls (%magic), special shell access (!cmd), etc. |
|
2026 | 2026 | """ |
|
2027 | 2027 | |
|
2028 | 2028 | if isinstance(lines, (list, tuple)): |
|
2029 | 2029 | lines = '\n'.join(lines) |
|
2030 | 2030 | |
|
2031 | 2031 | if clean: |
|
2032 | 2032 | lines = self.cleanup_ipy_script(lines) |
|
2033 | 2033 | |
|
2034 | 2034 | # We must start with a clean buffer, in case this is run from an |
|
2035 | 2035 | # interactive IPython session (via a magic, for example). |
|
2036 | 2036 | self.resetbuffer() |
|
2037 | 2037 | lines = lines.splitlines() |
|
2038 | 2038 | more = 0 |
|
2039 | 2039 | |
|
2040 | 2040 | with nested(self.builtin_trap, self.display_trap): |
|
2041 | 2041 | for line in lines: |
|
2042 | 2042 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2043 | 2043 | # NOT skip even a blank line if we are in a code block (more is |
|
2044 | 2044 | # true) |
|
2045 | 2045 | |
|
2046 | 2046 | if line or more: |
|
2047 | 2047 | # push to raw history, so hist line numbers stay in sync |
|
2048 | 2048 | self.input_hist_raw.append("# " + line + "\n") |
|
2049 | 2049 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2050 | 2050 | more = self.push_line(prefiltered) |
|
2051 | 2051 | # IPython's runsource returns None if there was an error |
|
2052 | 2052 | # compiling the code. This allows us to stop processing right |
|
2053 | 2053 | # away, so the user gets the error message at the right place. |
|
2054 | 2054 | if more is None: |
|
2055 | 2055 | break |
|
2056 | 2056 | else: |
|
2057 | 2057 | self.input_hist_raw.append("\n") |
|
2058 | 2058 | # final newline in case the input didn't have it, so that the code |
|
2059 | 2059 | # actually does get executed |
|
2060 | 2060 | if more: |
|
2061 | 2061 | self.push_line('\n') |
|
2062 | 2062 | |
|
2063 | 2063 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2064 | 2064 | """Compile and run some source in the interpreter. |
|
2065 | 2065 | |
|
2066 | 2066 | Arguments are as for compile_command(). |
|
2067 | 2067 | |
|
2068 | 2068 | One several things can happen: |
|
2069 | 2069 | |
|
2070 | 2070 | 1) The input is incorrect; compile_command() raised an |
|
2071 | 2071 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2072 | 2072 | will be printed by calling the showsyntaxerror() method. |
|
2073 | 2073 | |
|
2074 | 2074 | 2) The input is incomplete, and more input is required; |
|
2075 | 2075 | compile_command() returned None. Nothing happens. |
|
2076 | 2076 | |
|
2077 | 2077 | 3) The input is complete; compile_command() returned a code |
|
2078 | 2078 | object. The code is executed by calling self.runcode() (which |
|
2079 | 2079 | also handles run-time exceptions, except for SystemExit). |
|
2080 | 2080 | |
|
2081 | 2081 | The return value is: |
|
2082 | 2082 | |
|
2083 | 2083 | - True in case 2 |
|
2084 | 2084 | |
|
2085 | 2085 | - False in the other cases, unless an exception is raised, where |
|
2086 | 2086 | None is returned instead. This can be used by external callers to |
|
2087 | 2087 | know whether to continue feeding input or not. |
|
2088 | 2088 | |
|
2089 | 2089 | The return value can be used to decide whether to use sys.ps1 or |
|
2090 | 2090 | sys.ps2 to prompt the next line.""" |
|
2091 | 2091 | |
|
2092 | 2092 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2093 | 2093 | # this allows execution of indented pasted code. It is tempting |
|
2094 | 2094 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2095 | 2095 | # directly, but this fails for more complicated scenarios |
|
2096 | 2096 | source=source.encode(self.stdin_encoding) |
|
2097 | 2097 | if source[:1] in [' ', '\t']: |
|
2098 | 2098 | source = 'if 1:\n%s' % source |
|
2099 | 2099 | |
|
2100 | 2100 | try: |
|
2101 | 2101 | code = self.compile(source,filename,symbol) |
|
2102 | 2102 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2103 | 2103 | # Case 1 |
|
2104 | 2104 | self.showsyntaxerror(filename) |
|
2105 | 2105 | return None |
|
2106 | 2106 | |
|
2107 | 2107 | if code is None: |
|
2108 | 2108 | # Case 2 |
|
2109 | 2109 | return True |
|
2110 | 2110 | |
|
2111 | 2111 | # Case 3 |
|
2112 | 2112 | # We store the code object so that threaded shells and |
|
2113 | 2113 | # custom exception handlers can access all this info if needed. |
|
2114 | 2114 | # The source corresponding to this can be obtained from the |
|
2115 | 2115 | # buffer attribute as '\n'.join(self.buffer). |
|
2116 | 2116 | self.code_to_run = code |
|
2117 | 2117 | # now actually execute the code object |
|
2118 | 2118 | if self.runcode(code) == 0: |
|
2119 | 2119 | return False |
|
2120 | 2120 | else: |
|
2121 | 2121 | return None |
|
2122 | 2122 | |
|
2123 | 2123 | def runcode(self,code_obj): |
|
2124 | 2124 | """Execute a code object. |
|
2125 | 2125 | |
|
2126 | 2126 | When an exception occurs, self.showtraceback() is called to display a |
|
2127 | 2127 | traceback. |
|
2128 | 2128 | |
|
2129 | 2129 | Return value: a flag indicating whether the code to be run completed |
|
2130 | 2130 | successfully: |
|
2131 | 2131 | |
|
2132 | 2132 | - 0: successful execution. |
|
2133 | 2133 | - 1: an error occurred. |
|
2134 | 2134 | """ |
|
2135 | 2135 | |
|
2136 | 2136 | # Set our own excepthook in case the user code tries to call it |
|
2137 | 2137 | # directly, so that the IPython crash handler doesn't get triggered |
|
2138 | 2138 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2139 | 2139 | |
|
2140 | 2140 | # we save the original sys.excepthook in the instance, in case config |
|
2141 | 2141 | # code (such as magics) needs access to it. |
|
2142 | 2142 | self.sys_excepthook = old_excepthook |
|
2143 | 2143 | outflag = 1 # happens in more places, so it's easier as default |
|
2144 | 2144 | try: |
|
2145 | 2145 | try: |
|
2146 | 2146 | self.hooks.pre_runcode_hook() |
|
2147 | 2147 | exec code_obj in self.user_global_ns, self.user_ns |
|
2148 | 2148 | finally: |
|
2149 | 2149 | # Reset our crash handler in place |
|
2150 | 2150 | sys.excepthook = old_excepthook |
|
2151 | 2151 | except SystemExit: |
|
2152 | 2152 | self.resetbuffer() |
|
2153 | 2153 | self.showtraceback() |
|
2154 | 2154 | warn("Type %exit or %quit to exit IPython " |
|
2155 | 2155 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2156 | 2156 | except self.custom_exceptions: |
|
2157 | 2157 | etype,value,tb = sys.exc_info() |
|
2158 | 2158 | self.CustomTB(etype,value,tb) |
|
2159 | 2159 | except: |
|
2160 | 2160 | self.showtraceback() |
|
2161 | 2161 | else: |
|
2162 | 2162 | outflag = 0 |
|
2163 | 2163 | if softspace(sys.stdout, 0): |
|
2164 | 2164 | |
|
2165 | 2165 | # Flush out code object which has been run (and source) |
|
2166 | 2166 | self.code_to_run = None |
|
2167 | 2167 | return outflag |
|
2168 | 2168 | |
|
2169 | 2169 | def push_line(self, line): |
|
2170 | 2170 | """Push a line to the interpreter. |
|
2171 | 2171 | |
|
2172 | 2172 | The line should not have a trailing newline; it may have |
|
2173 | 2173 | internal newlines. The line is appended to a buffer and the |
|
2174 | 2174 | interpreter's runsource() method is called with the |
|
2175 | 2175 | concatenated contents of the buffer as source. If this |
|
2176 | 2176 | indicates that the command was executed or invalid, the buffer |
|
2177 | 2177 | is reset; otherwise, the command is incomplete, and the buffer |
|
2178 | 2178 | is left as it was after the line was appended. The return |
|
2179 | 2179 | value is 1 if more input is required, 0 if the line was dealt |
|
2180 | 2180 | with in some way (this is the same as runsource()). |
|
2181 | 2181 | """ |
|
2182 | 2182 | |
|
2183 | 2183 | # autoindent management should be done here, and not in the |
|
2184 | 2184 | # interactive loop, since that one is only seen by keyboard input. We |
|
2185 | 2185 | # need this done correctly even for code run via runlines (which uses |
|
2186 | 2186 | # push). |
|
2187 | 2187 | |
|
2188 | 2188 | #print 'push line: <%s>' % line # dbg |
|
2189 | 2189 | for subline in line.splitlines(): |
|
2190 | 2190 | self._autoindent_update(subline) |
|
2191 | 2191 | self.buffer.append(line) |
|
2192 | 2192 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2193 | 2193 | if not more: |
|
2194 | 2194 | self.resetbuffer() |
|
2195 | 2195 | return more |
|
2196 | 2196 | |
|
2197 | 2197 | def _autoindent_update(self,line): |
|
2198 | 2198 | """Keep track of the indent level.""" |
|
2199 | 2199 | |
|
2200 | 2200 | #debugx('line') |
|
2201 | 2201 | #debugx('self.indent_current_nsp') |
|
2202 | 2202 | if self.autoindent: |
|
2203 | 2203 | if line: |
|
2204 | 2204 | inisp = num_ini_spaces(line) |
|
2205 | 2205 | if inisp < self.indent_current_nsp: |
|
2206 | 2206 | self.indent_current_nsp = inisp |
|
2207 | 2207 | |
|
2208 | 2208 | if line[-1] == ':': |
|
2209 | 2209 | self.indent_current_nsp += 4 |
|
2210 | 2210 | elif dedent_re.match(line): |
|
2211 | 2211 | self.indent_current_nsp -= 4 |
|
2212 | 2212 | else: |
|
2213 | 2213 | self.indent_current_nsp = 0 |
|
2214 | 2214 | |
|
2215 | 2215 | def resetbuffer(self): |
|
2216 | 2216 | """Reset the input buffer.""" |
|
2217 | 2217 | self.buffer[:] = [] |
|
2218 | 2218 | |
|
2219 | 2219 | def raw_input(self,prompt='',continue_prompt=False): |
|
2220 | 2220 | """Write a prompt and read a line. |
|
2221 | 2221 | |
|
2222 | 2222 | The returned line does not include the trailing newline. |
|
2223 | 2223 | When the user enters the EOF key sequence, EOFError is raised. |
|
2224 | 2224 | |
|
2225 | 2225 | Optional inputs: |
|
2226 | 2226 | |
|
2227 | 2227 | - prompt(''): a string to be printed to prompt the user. |
|
2228 | 2228 | |
|
2229 | 2229 | - continue_prompt(False): whether this line is the first one or a |
|
2230 | 2230 | continuation in a sequence of inputs. |
|
2231 | 2231 | """ |
|
2232 | 2232 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2233 | 2233 | |
|
2234 | 2234 | # Code run by the user may have modified the readline completer state. |
|
2235 | 2235 | # We must ensure that our completer is back in place. |
|
2236 | 2236 | |
|
2237 | 2237 | if self.has_readline: |
|
2238 | 2238 | self.set_completer() |
|
2239 | 2239 | |
|
2240 | 2240 | try: |
|
2241 | 2241 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2242 | 2242 | except ValueError: |
|
2243 | 2243 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2244 | 2244 | " or sys.stdout.close()!\nExiting IPython!") |
|
2245 | 2245 | self.ask_exit() |
|
2246 | 2246 | return "" |
|
2247 | 2247 | |
|
2248 | 2248 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2249 | 2249 | # than necessary. We do this by trimming out the auto-indent initial |
|
2250 | 2250 | # spaces, if the user's actual input started itself with whitespace. |
|
2251 | 2251 | #debugx('self.buffer[-1]') |
|
2252 | 2252 | |
|
2253 | 2253 | if self.autoindent: |
|
2254 | 2254 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2255 | 2255 | line = line[self.indent_current_nsp:] |
|
2256 | 2256 | self.indent_current_nsp = 0 |
|
2257 | 2257 | |
|
2258 | 2258 | # store the unfiltered input before the user has any chance to modify |
|
2259 | 2259 | # it. |
|
2260 | 2260 | if line.strip(): |
|
2261 | 2261 | if continue_prompt: |
|
2262 | 2262 | self.input_hist_raw[-1] += '%s\n' % line |
|
2263 | 2263 | if self.has_readline and self.readline_use: |
|
2264 | 2264 | try: |
|
2265 | 2265 | histlen = self.readline.get_current_history_length() |
|
2266 | 2266 | if histlen > 1: |
|
2267 | 2267 | newhist = self.input_hist_raw[-1].rstrip() |
|
2268 | 2268 | self.readline.remove_history_item(histlen-1) |
|
2269 | 2269 | self.readline.replace_history_item(histlen-2, |
|
2270 | 2270 | newhist.encode(self.stdin_encoding)) |
|
2271 | 2271 | except AttributeError: |
|
2272 | 2272 | pass # re{move,place}_history_item are new in 2.4. |
|
2273 | 2273 | else: |
|
2274 | 2274 | self.input_hist_raw.append('%s\n' % line) |
|
2275 | 2275 | # only entries starting at first column go to shadow history |
|
2276 | 2276 | if line.lstrip() == line: |
|
2277 | 2277 | self.shadowhist.add(line.strip()) |
|
2278 | 2278 | elif not continue_prompt: |
|
2279 | 2279 | self.input_hist_raw.append('\n') |
|
2280 | 2280 | try: |
|
2281 | 2281 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2282 | 2282 | except: |
|
2283 | 2283 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2284 | 2284 | # can't take all of ipython with it. |
|
2285 | 2285 | self.showtraceback() |
|
2286 | 2286 | return '' |
|
2287 | 2287 | else: |
|
2288 | 2288 | return lineout |
|
2289 | 2289 | |
|
2290 | 2290 | #------------------------------------------------------------------------- |
|
2291 | 2291 | # Working with components |
|
2292 | 2292 | #------------------------------------------------------------------------- |
|
2293 | 2293 | |
|
2294 | 2294 | def get_component(self, name=None, klass=None): |
|
2295 | 2295 | """Fetch a component by name and klass in my tree.""" |
|
2296 | 2296 | c = Component.get_instances(root=self, name=name, klass=klass) |
|
2297 | 2297 | if len(c) == 0: |
|
2298 | 2298 | return None |
|
2299 | 2299 | if len(c) == 1: |
|
2300 | 2300 | return c[0] |
|
2301 | 2301 | else: |
|
2302 | 2302 | return c |
|
2303 | 2303 | |
|
2304 | 2304 | #------------------------------------------------------------------------- |
|
2305 | 2305 | # IPython extensions |
|
2306 | 2306 | #------------------------------------------------------------------------- |
|
2307 | 2307 | |
|
2308 | 2308 | def load_extension(self, module_str): |
|
2309 | 2309 | """Load an IPython extension by its module name. |
|
2310 | 2310 | |
|
2311 | 2311 | An IPython extension is an importable Python module that has |
|
2312 | 2312 | a function with the signature:: |
|
2313 | 2313 | |
|
2314 | 2314 | def load_ipython_extension(ipython): |
|
2315 | 2315 | # Do things with ipython |
|
2316 | 2316 | |
|
2317 | 2317 | This function is called after your extension is imported and the |
|
2318 | 2318 | currently active :class:`InteractiveShell` instance is passed as |
|
2319 | 2319 | the only argument. You can do anything you want with IPython at |
|
2320 | 2320 | that point, including defining new magic and aliases, adding new |
|
2321 | 2321 | components, etc. |
|
2322 | 2322 | |
|
2323 | 2323 | The :func:`load_ipython_extension` will be called again is you |
|
2324 | 2324 | load or reload the extension again. It is up to the extension |
|
2325 | 2325 | author to add code to manage that. |
|
2326 | 2326 | |
|
2327 | 2327 | You can put your extension modules anywhere you want, as long as |
|
2328 | 2328 | they can be imported by Python's standard import mechanism. However, |
|
2329 | 2329 | to make it easy to write extensions, you can also put your extensions |
|
2330 | in ``os.path.join(self.ipythondir, 'extensions')``. This directory | |
|
2330 | in ``os.path.join(self.ipython_dir, 'extensions')``. This directory | |
|
2331 | 2331 | is added to ``sys.path`` automatically. |
|
2332 | 2332 | """ |
|
2333 | 2333 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2334 | 2334 | |
|
2335 | 2335 | if module_str not in sys.modules: |
|
2336 | 2336 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2337 | 2337 | __import__(module_str) |
|
2338 | 2338 | mod = sys.modules[module_str] |
|
2339 | 2339 | self._call_load_ipython_extension(mod) |
|
2340 | 2340 | |
|
2341 | 2341 | def unload_extension(self, module_str): |
|
2342 | 2342 | """Unload an IPython extension by its module name. |
|
2343 | 2343 | |
|
2344 | 2344 | This function looks up the extension's name in ``sys.modules`` and |
|
2345 | 2345 | simply calls ``mod.unload_ipython_extension(self)``. |
|
2346 | 2346 | """ |
|
2347 | 2347 | if module_str in sys.modules: |
|
2348 | 2348 | mod = sys.modules[module_str] |
|
2349 | 2349 | self._call_unload_ipython_extension(mod) |
|
2350 | 2350 | |
|
2351 | 2351 | def reload_extension(self, module_str): |
|
2352 | 2352 | """Reload an IPython extension by calling reload. |
|
2353 | 2353 | |
|
2354 | 2354 | If the module has not been loaded before, |
|
2355 | 2355 | :meth:`InteractiveShell.load_extension` is called. Otherwise |
|
2356 | 2356 | :func:`reload` is called and then the :func:`load_ipython_extension` |
|
2357 | 2357 | function of the module, if it exists is called. |
|
2358 | 2358 | """ |
|
2359 | 2359 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2360 | 2360 | |
|
2361 | 2361 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2362 | 2362 | if module_str in sys.modules: |
|
2363 | 2363 | mod = sys.modules[module_str] |
|
2364 | 2364 | reload(mod) |
|
2365 | 2365 | self._call_load_ipython_extension(mod) |
|
2366 | 2366 | else: |
|
2367 | 2367 | self.load_extension(module_str) |
|
2368 | 2368 | |
|
2369 | 2369 | def _call_load_ipython_extension(self, mod): |
|
2370 | 2370 | if hasattr(mod, 'load_ipython_extension'): |
|
2371 | 2371 | mod.load_ipython_extension(self) |
|
2372 | 2372 | |
|
2373 | 2373 | def _call_unload_ipython_extension(self, mod): |
|
2374 | 2374 | if hasattr(mod, 'unload_ipython_extension'): |
|
2375 | 2375 | mod.unload_ipython_extension(self) |
|
2376 | 2376 | |
|
2377 | 2377 | #------------------------------------------------------------------------- |
|
2378 | 2378 | # Things related to the prefilter |
|
2379 | 2379 | #------------------------------------------------------------------------- |
|
2380 | 2380 | |
|
2381 | 2381 | def init_prefilter(self): |
|
2382 | 2382 | self.prefilter_manager = PrefilterManager(self, config=self.config) |
|
2383 | 2383 | |
|
2384 | 2384 | #------------------------------------------------------------------------- |
|
2385 | 2385 | # Utilities |
|
2386 | 2386 | #------------------------------------------------------------------------- |
|
2387 | 2387 | |
|
2388 | 2388 | def getoutput(self, cmd): |
|
2389 | 2389 | return getoutput(self.var_expand(cmd,depth=2), |
|
2390 | 2390 | header=self.system_header, |
|
2391 | 2391 | verbose=self.system_verbose) |
|
2392 | 2392 | |
|
2393 | 2393 | def getoutputerror(self, cmd): |
|
2394 | 2394 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2395 | 2395 | header=self.system_header, |
|
2396 | 2396 | verbose=self.system_verbose) |
|
2397 | 2397 | |
|
2398 | 2398 | def var_expand(self,cmd,depth=0): |
|
2399 | 2399 | """Expand python variables in a string. |
|
2400 | 2400 | |
|
2401 | 2401 | The depth argument indicates how many frames above the caller should |
|
2402 | 2402 | be walked to look for the local namespace where to expand variables. |
|
2403 | 2403 | |
|
2404 | 2404 | The global namespace for expansion is always the user's interactive |
|
2405 | 2405 | namespace. |
|
2406 | 2406 | """ |
|
2407 | 2407 | |
|
2408 | 2408 | return str(ItplNS(cmd, |
|
2409 | 2409 | self.user_ns, # globals |
|
2410 | 2410 | # Skip our own frame in searching for locals: |
|
2411 | 2411 | sys._getframe(depth+1).f_locals # locals |
|
2412 | 2412 | )) |
|
2413 | 2413 | |
|
2414 | 2414 | def mktempfile(self,data=None): |
|
2415 | 2415 | """Make a new tempfile and return its filename. |
|
2416 | 2416 | |
|
2417 | 2417 | This makes a call to tempfile.mktemp, but it registers the created |
|
2418 | 2418 | filename internally so ipython cleans it up at exit time. |
|
2419 | 2419 | |
|
2420 | 2420 | Optional inputs: |
|
2421 | 2421 | |
|
2422 | 2422 | - data(None): if data is given, it gets written out to the temp file |
|
2423 | 2423 | immediately, and the file is closed again.""" |
|
2424 | 2424 | |
|
2425 | 2425 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2426 | 2426 | self.tempfiles.append(filename) |
|
2427 | 2427 | |
|
2428 | 2428 | if data: |
|
2429 | 2429 | tmp_file = open(filename,'w') |
|
2430 | 2430 | tmp_file.write(data) |
|
2431 | 2431 | tmp_file.close() |
|
2432 | 2432 | return filename |
|
2433 | 2433 | |
|
2434 | 2434 | def write(self,data): |
|
2435 | 2435 | """Write a string to the default output""" |
|
2436 | 2436 | Term.cout.write(data) |
|
2437 | 2437 | |
|
2438 | 2438 | def write_err(self,data): |
|
2439 | 2439 | """Write a string to the default error output""" |
|
2440 | 2440 | Term.cerr.write(data) |
|
2441 | 2441 | |
|
2442 | 2442 | def ask_yes_no(self,prompt,default=True): |
|
2443 | 2443 | if self.quiet: |
|
2444 | 2444 | return True |
|
2445 | 2445 | return ask_yes_no(prompt,default) |
|
2446 | 2446 | |
|
2447 | 2447 | #------------------------------------------------------------------------- |
|
2448 | 2448 | # Things related to IPython exiting |
|
2449 | 2449 | #------------------------------------------------------------------------- |
|
2450 | 2450 | |
|
2451 | 2451 | def ask_exit(self): |
|
2452 | 2452 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2453 | 2453 | self.exit_now = True |
|
2454 | 2454 | |
|
2455 | 2455 | def exit(self): |
|
2456 | 2456 | """Handle interactive exit. |
|
2457 | 2457 | |
|
2458 | 2458 | This method calls the ask_exit callback.""" |
|
2459 | 2459 | if self.confirm_exit: |
|
2460 | 2460 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2461 | 2461 | self.ask_exit() |
|
2462 | 2462 | else: |
|
2463 | 2463 | self.ask_exit() |
|
2464 | 2464 | |
|
2465 | 2465 | def atexit_operations(self): |
|
2466 | 2466 | """This will be executed at the time of exit. |
|
2467 | 2467 | |
|
2468 | 2468 | Saving of persistent data should be performed here. |
|
2469 | 2469 | """ |
|
2470 | 2470 | self.savehist() |
|
2471 | 2471 | |
|
2472 | 2472 | # Cleanup all tempfiles left around |
|
2473 | 2473 | for tfile in self.tempfiles: |
|
2474 | 2474 | try: |
|
2475 | 2475 | os.unlink(tfile) |
|
2476 | 2476 | except OSError: |
|
2477 | 2477 | pass |
|
2478 | 2478 | |
|
2479 | 2479 | # Clear all user namespaces to release all references cleanly. |
|
2480 | 2480 | self.reset() |
|
2481 | 2481 | |
|
2482 | 2482 | # Run user hooks |
|
2483 | 2483 | self.hooks.shutdown_hook() |
|
2484 | 2484 | |
|
2485 | 2485 | def cleanup(self): |
|
2486 | 2486 | self.restore_sys_module_state() |
|
2487 | 2487 | |
|
2488 | 2488 |
@@ -1,3608 +1,3580 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #***************************************************************************** |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
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 | # Modules and globals |
|
15 | 15 | |
|
16 | 16 | # Python standard modules |
|
17 | 17 | import __builtin__ |
|
18 | 18 | import bdb |
|
19 | 19 | import inspect |
|
20 | 20 | import os |
|
21 | 21 | import pdb |
|
22 | 22 | import pydoc |
|
23 | 23 | import sys |
|
24 | 24 | import shutil |
|
25 | 25 | import re |
|
26 | 26 | import tempfile |
|
27 | 27 | import time |
|
28 | 28 | import cPickle as pickle |
|
29 | 29 | import textwrap |
|
30 | 30 | from cStringIO import StringIO |
|
31 | 31 | from getopt import getopt,GetoptError |
|
32 | 32 | from pprint import pprint, pformat |
|
33 | 33 | |
|
34 | 34 | # cProfile was added in Python2.5 |
|
35 | 35 | try: |
|
36 | 36 | import cProfile as profile |
|
37 | 37 | import pstats |
|
38 | 38 | except ImportError: |
|
39 | 39 | # profile isn't bundled by default in Debian for license reasons |
|
40 | 40 | try: |
|
41 | 41 | import profile,pstats |
|
42 | 42 | except ImportError: |
|
43 | 43 | profile = pstats = None |
|
44 | 44 | |
|
45 | 45 | # Homebrewed |
|
46 | 46 | import IPython |
|
47 | 47 | from IPython.utils import wildcard |
|
48 | 48 | from IPython.core import debugger, oinspect |
|
49 | 49 | from IPython.core.error import TryNext |
|
50 | 50 | from IPython.core.fakemodule import FakeModule |
|
51 | 51 | from IPython.core.prefilter import ESC_MAGIC |
|
52 | 52 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
53 | 53 | from IPython.utils.PyColorize import Parser |
|
54 | 54 | from IPython.utils.ipstruct import Struct |
|
55 | 55 | from IPython.core.macro import Macro |
|
56 | 56 | from IPython.utils.genutils import * |
|
57 | 57 | from IPython.core.page import page |
|
58 | 58 | from IPython.utils import platutils |
|
59 | 59 | import IPython.utils.generics |
|
60 | 60 | from IPython.core.error import UsageError |
|
61 | 61 | from IPython.testing import decorators as testdec |
|
62 | 62 | |
|
63 | 63 | #*************************************************************************** |
|
64 | 64 | # Utility functions |
|
65 | 65 | def on_off(tag): |
|
66 | 66 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
67 | 67 | return ['OFF','ON'][tag] |
|
68 | 68 | |
|
69 | 69 | class Bunch: pass |
|
70 | 70 | |
|
71 | 71 | def compress_dhist(dh): |
|
72 | 72 | head, tail = dh[:-10], dh[-10:] |
|
73 | 73 | |
|
74 | 74 | newhead = [] |
|
75 | 75 | done = set() |
|
76 | 76 | for h in head: |
|
77 | 77 | if h in done: |
|
78 | 78 | continue |
|
79 | 79 | newhead.append(h) |
|
80 | 80 | done.add(h) |
|
81 | 81 | |
|
82 | 82 | return newhead + tail |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | #*************************************************************************** |
|
86 | 86 | # Main class implementing Magic functionality |
|
87 | 87 | class Magic: |
|
88 | 88 | """Magic functions for InteractiveShell. |
|
89 | 89 | |
|
90 | 90 | Shell functions which can be reached as %function_name. All magic |
|
91 | 91 | functions should accept a string, which they can parse for their own |
|
92 | 92 | needs. This can make some functions easier to type, eg `%cd ../` |
|
93 | 93 | vs. `%cd("../")` |
|
94 | 94 | |
|
95 | 95 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
96 | 96 | at the command line, but it is is needed in the definition. """ |
|
97 | 97 | |
|
98 | 98 | # class globals |
|
99 | 99 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
100 | 100 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
101 | 101 | |
|
102 | 102 | #...................................................................... |
|
103 | 103 | # some utility functions |
|
104 | 104 | |
|
105 | 105 | def __init__(self,shell): |
|
106 | 106 | |
|
107 | 107 | self.options_table = {} |
|
108 | 108 | if profile is None: |
|
109 | 109 | self.magic_prun = self.profile_missing_notice |
|
110 | 110 | self.shell = shell |
|
111 | 111 | |
|
112 | 112 | # namespace for holding state we may need |
|
113 | 113 | self._magic_state = Bunch() |
|
114 | 114 | |
|
115 | 115 | def profile_missing_notice(self, *args, **kwargs): |
|
116 | 116 | error("""\ |
|
117 | 117 | The profile module could not be found. It has been removed from the standard |
|
118 | 118 | python packages because of its non-free license. To use profiling, install the |
|
119 | 119 | python-profiler package from non-free.""") |
|
120 | 120 | |
|
121 | 121 | def default_option(self,fn,optstr): |
|
122 | 122 | """Make an entry in the options_table for fn, with value optstr""" |
|
123 | 123 | |
|
124 | 124 | if fn not in self.lsmagic(): |
|
125 | 125 | error("%s is not a magic function" % fn) |
|
126 | 126 | self.options_table[fn] = optstr |
|
127 | 127 | |
|
128 | 128 | def lsmagic(self): |
|
129 | 129 | """Return a list of currently available magic functions. |
|
130 | 130 | |
|
131 | 131 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
132 | 132 | ['magic_ls','magic_cd',...]""" |
|
133 | 133 | |
|
134 | 134 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
135 | 135 | |
|
136 | 136 | # magics in class definition |
|
137 | 137 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
138 | 138 | callable(Magic.__dict__[fn]) |
|
139 | 139 | # in instance namespace (run-time user additions) |
|
140 | 140 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | 141 | callable(self.__dict__[fn]) |
|
142 | 142 | # and bound magics by user (so they can access self): |
|
143 | 143 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
144 | 144 | callable(self.__class__.__dict__[fn]) |
|
145 | 145 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
146 | 146 | filter(inst_magic,self.__dict__.keys()) + \ |
|
147 | 147 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
148 | 148 | out = [] |
|
149 | 149 | for fn in set(magics): |
|
150 | 150 | out.append(fn.replace('magic_','',1)) |
|
151 | 151 | out.sort() |
|
152 | 152 | return out |
|
153 | 153 | |
|
154 | 154 | def extract_input_slices(self,slices,raw=False): |
|
155 | 155 | """Return as a string a set of input history slices. |
|
156 | 156 | |
|
157 | 157 | Inputs: |
|
158 | 158 | |
|
159 | 159 | - slices: the set of slices is given as a list of strings (like |
|
160 | 160 | ['1','4:8','9'], since this function is for use by magic functions |
|
161 | 161 | which get their arguments as strings. |
|
162 | 162 | |
|
163 | 163 | Optional inputs: |
|
164 | 164 | |
|
165 | 165 | - raw(False): by default, the processed input is used. If this is |
|
166 | 166 | true, the raw input history is used instead. |
|
167 | 167 | |
|
168 | 168 | Note that slices can be called with two notations: |
|
169 | 169 | |
|
170 | 170 | N:M -> standard python form, means including items N...(M-1). |
|
171 | 171 | |
|
172 | 172 | N-M -> include items N..M (closed endpoint).""" |
|
173 | 173 | |
|
174 | 174 | if raw: |
|
175 | 175 | hist = self.shell.input_hist_raw |
|
176 | 176 | else: |
|
177 | 177 | hist = self.shell.input_hist |
|
178 | 178 | |
|
179 | 179 | cmds = [] |
|
180 | 180 | for chunk in slices: |
|
181 | 181 | if ':' in chunk: |
|
182 | 182 | ini,fin = map(int,chunk.split(':')) |
|
183 | 183 | elif '-' in chunk: |
|
184 | 184 | ini,fin = map(int,chunk.split('-')) |
|
185 | 185 | fin += 1 |
|
186 | 186 | else: |
|
187 | 187 | ini = int(chunk) |
|
188 | 188 | fin = ini+1 |
|
189 | 189 | cmds.append(hist[ini:fin]) |
|
190 | 190 | return cmds |
|
191 | 191 | |
|
192 | 192 | def _ofind(self, oname, namespaces=None): |
|
193 | 193 | """Find an object in the available namespaces. |
|
194 | 194 | |
|
195 | 195 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
196 | 196 | |
|
197 | 197 | Has special code to detect magic functions. |
|
198 | 198 | """ |
|
199 | 199 | |
|
200 | 200 | oname = oname.strip() |
|
201 | 201 | |
|
202 | 202 | alias_ns = None |
|
203 | 203 | if namespaces is None: |
|
204 | 204 | # Namespaces to search in: |
|
205 | 205 | # Put them in a list. The order is important so that we |
|
206 | 206 | # find things in the same order that Python finds them. |
|
207 | 207 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
208 | 208 | ('IPython internal', self.shell.internal_ns), |
|
209 | 209 | ('Python builtin', __builtin__.__dict__), |
|
210 | 210 | ('Alias', self.shell.alias_manager.alias_table), |
|
211 | 211 | ] |
|
212 | 212 | alias_ns = self.shell.alias_manager.alias_table |
|
213 | 213 | |
|
214 | 214 | # initialize results to 'null' |
|
215 | 215 | found = 0; obj = None; ospace = None; ds = None; |
|
216 | 216 | ismagic = 0; isalias = 0; parent = None |
|
217 | 217 | |
|
218 | 218 | # Look for the given name by splitting it in parts. If the head is |
|
219 | 219 | # found, then we look for all the remaining parts as members, and only |
|
220 | 220 | # declare success if we can find them all. |
|
221 | 221 | oname_parts = oname.split('.') |
|
222 | 222 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
223 | 223 | for nsname,ns in namespaces: |
|
224 | 224 | try: |
|
225 | 225 | obj = ns[oname_head] |
|
226 | 226 | except KeyError: |
|
227 | 227 | continue |
|
228 | 228 | else: |
|
229 | 229 | #print 'oname_rest:', oname_rest # dbg |
|
230 | 230 | for part in oname_rest: |
|
231 | 231 | try: |
|
232 | 232 | parent = obj |
|
233 | 233 | obj = getattr(obj,part) |
|
234 | 234 | except: |
|
235 | 235 | # Blanket except b/c some badly implemented objects |
|
236 | 236 | # allow __getattr__ to raise exceptions other than |
|
237 | 237 | # AttributeError, which then crashes IPython. |
|
238 | 238 | break |
|
239 | 239 | else: |
|
240 | 240 | # If we finish the for loop (no break), we got all members |
|
241 | 241 | found = 1 |
|
242 | 242 | ospace = nsname |
|
243 | 243 | if ns == alias_ns: |
|
244 | 244 | isalias = 1 |
|
245 | 245 | break # namespace loop |
|
246 | 246 | |
|
247 | 247 | # Try to see if it's magic |
|
248 | 248 | if not found: |
|
249 | 249 | if oname.startswith(ESC_MAGIC): |
|
250 | 250 | oname = oname[1:] |
|
251 | 251 | obj = getattr(self,'magic_'+oname,None) |
|
252 | 252 | if obj is not None: |
|
253 | 253 | found = 1 |
|
254 | 254 | ospace = 'IPython internal' |
|
255 | 255 | ismagic = 1 |
|
256 | 256 | |
|
257 | 257 | # Last try: special-case some literals like '', [], {}, etc: |
|
258 | 258 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
259 | 259 | obj = eval(oname_head) |
|
260 | 260 | found = 1 |
|
261 | 261 | ospace = 'Interactive' |
|
262 | 262 | |
|
263 | 263 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
264 | 264 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
265 | 265 | |
|
266 | 266 | def arg_err(self,func): |
|
267 | 267 | """Print docstring if incorrect arguments were passed""" |
|
268 | 268 | print 'Error in arguments:' |
|
269 | 269 | print OInspect.getdoc(func) |
|
270 | 270 | |
|
271 | 271 | def format_latex(self,strng): |
|
272 | 272 | """Format a string for latex inclusion.""" |
|
273 | 273 | |
|
274 | 274 | # Characters that need to be escaped for latex: |
|
275 | 275 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
276 | 276 | # Magic command names as headers: |
|
277 | 277 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
278 | 278 | re.MULTILINE) |
|
279 | 279 | # Magic commands |
|
280 | 280 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
281 | 281 | re.MULTILINE) |
|
282 | 282 | # Paragraph continue |
|
283 | 283 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
284 | 284 | |
|
285 | 285 | # The "\n" symbol |
|
286 | 286 | newline_re = re.compile(r'\\n') |
|
287 | 287 | |
|
288 | 288 | # Now build the string for output: |
|
289 | 289 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
290 | 290 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
291 | 291 | strng) |
|
292 | 292 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
293 | 293 | strng = par_re.sub(r'\\\\',strng) |
|
294 | 294 | strng = escape_re.sub(r'\\\1',strng) |
|
295 | 295 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
296 | 296 | return strng |
|
297 | 297 | |
|
298 | 298 | def format_screen(self,strng): |
|
299 | 299 | """Format a string for screen printing. |
|
300 | 300 | |
|
301 | 301 | This removes some latex-type format codes.""" |
|
302 | 302 | # Paragraph continue |
|
303 | 303 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
304 | 304 | strng = par_re.sub('',strng) |
|
305 | 305 | return strng |
|
306 | 306 | |
|
307 | 307 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
308 | 308 | """Parse options passed to an argument string. |
|
309 | 309 | |
|
310 | 310 | The interface is similar to that of getopt(), but it returns back a |
|
311 | 311 | Struct with the options as keys and the stripped argument string still |
|
312 | 312 | as a string. |
|
313 | 313 | |
|
314 | 314 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
315 | 315 | This allows us to easily expand variables, glob files, quote |
|
316 | 316 | arguments, etc. |
|
317 | 317 | |
|
318 | 318 | Options: |
|
319 | 319 | -mode: default 'string'. If given as 'list', the argument string is |
|
320 | 320 | returned as a list (split on whitespace) instead of a string. |
|
321 | 321 | |
|
322 | 322 | -list_all: put all option values in lists. Normally only options |
|
323 | 323 | appearing more than once are put in a list. |
|
324 | 324 | |
|
325 | 325 | -posix (True): whether to split the input line in POSIX mode or not, |
|
326 | 326 | as per the conventions outlined in the shlex module from the |
|
327 | 327 | standard library.""" |
|
328 | 328 | |
|
329 | 329 | # inject default options at the beginning of the input line |
|
330 | 330 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
331 | 331 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
332 | 332 | |
|
333 | 333 | mode = kw.get('mode','string') |
|
334 | 334 | if mode not in ['string','list']: |
|
335 | 335 | raise ValueError,'incorrect mode given: %s' % mode |
|
336 | 336 | # Get options |
|
337 | 337 | list_all = kw.get('list_all',0) |
|
338 | 338 | posix = kw.get('posix',True) |
|
339 | 339 | |
|
340 | 340 | # Check if we have more than one argument to warrant extra processing: |
|
341 | 341 | odict = {} # Dictionary with options |
|
342 | 342 | args = arg_str.split() |
|
343 | 343 | if len(args) >= 1: |
|
344 | 344 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
345 | 345 | # need to look for options |
|
346 | 346 | argv = arg_split(arg_str,posix) |
|
347 | 347 | # Do regular option processing |
|
348 | 348 | try: |
|
349 | 349 | opts,args = getopt(argv,opt_str,*long_opts) |
|
350 | 350 | except GetoptError,e: |
|
351 | 351 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
352 | 352 | " ".join(long_opts))) |
|
353 | 353 | for o,a in opts: |
|
354 | 354 | if o.startswith('--'): |
|
355 | 355 | o = o[2:] |
|
356 | 356 | else: |
|
357 | 357 | o = o[1:] |
|
358 | 358 | try: |
|
359 | 359 | odict[o].append(a) |
|
360 | 360 | except AttributeError: |
|
361 | 361 | odict[o] = [odict[o],a] |
|
362 | 362 | except KeyError: |
|
363 | 363 | if list_all: |
|
364 | 364 | odict[o] = [a] |
|
365 | 365 | else: |
|
366 | 366 | odict[o] = a |
|
367 | 367 | |
|
368 | 368 | # Prepare opts,args for return |
|
369 | 369 | opts = Struct(odict) |
|
370 | 370 | if mode == 'string': |
|
371 | 371 | args = ' '.join(args) |
|
372 | 372 | |
|
373 | 373 | return opts,args |
|
374 | 374 | |
|
375 | 375 | #...................................................................... |
|
376 | 376 | # And now the actual magic functions |
|
377 | 377 | |
|
378 | 378 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
379 | 379 | def magic_lsmagic(self, parameter_s = ''): |
|
380 | 380 | """List currently available magic functions.""" |
|
381 | 381 | mesc = ESC_MAGIC |
|
382 | 382 | print 'Available magic functions:\n'+mesc+\ |
|
383 | 383 | (' '+mesc).join(self.lsmagic()) |
|
384 | 384 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
385 | 385 | return None |
|
386 | 386 | |
|
387 | 387 | def magic_magic(self, parameter_s = ''): |
|
388 | 388 | """Print information about the magic function system. |
|
389 | 389 | |
|
390 | 390 | Supported formats: -latex, -brief, -rest |
|
391 | 391 | """ |
|
392 | 392 | |
|
393 | 393 | mode = '' |
|
394 | 394 | try: |
|
395 | 395 | if parameter_s.split()[0] == '-latex': |
|
396 | 396 | mode = 'latex' |
|
397 | 397 | if parameter_s.split()[0] == '-brief': |
|
398 | 398 | mode = 'brief' |
|
399 | 399 | if parameter_s.split()[0] == '-rest': |
|
400 | 400 | mode = 'rest' |
|
401 | 401 | rest_docs = [] |
|
402 | 402 | except: |
|
403 | 403 | pass |
|
404 | 404 | |
|
405 | 405 | magic_docs = [] |
|
406 | 406 | for fname in self.lsmagic(): |
|
407 | 407 | mname = 'magic_' + fname |
|
408 | 408 | for space in (Magic,self,self.__class__): |
|
409 | 409 | try: |
|
410 | 410 | fn = space.__dict__[mname] |
|
411 | 411 | except KeyError: |
|
412 | 412 | pass |
|
413 | 413 | else: |
|
414 | 414 | break |
|
415 | 415 | if mode == 'brief': |
|
416 | 416 | # only first line |
|
417 | 417 | if fn.__doc__: |
|
418 | 418 | fndoc = fn.__doc__.split('\n',1)[0] |
|
419 | 419 | else: |
|
420 | 420 | fndoc = 'No documentation' |
|
421 | 421 | else: |
|
422 | 422 | if fn.__doc__: |
|
423 | 423 | fndoc = fn.__doc__.rstrip() |
|
424 | 424 | else: |
|
425 | 425 | fndoc = 'No documentation' |
|
426 | 426 | |
|
427 | 427 | |
|
428 | 428 | if mode == 'rest': |
|
429 | 429 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
430 | 430 | fname,fndoc)) |
|
431 | 431 | |
|
432 | 432 | else: |
|
433 | 433 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
434 | 434 | fname,fndoc)) |
|
435 | 435 | |
|
436 | 436 | magic_docs = ''.join(magic_docs) |
|
437 | 437 | |
|
438 | 438 | if mode == 'rest': |
|
439 | 439 | return "".join(rest_docs) |
|
440 | 440 | |
|
441 | 441 | if mode == 'latex': |
|
442 | 442 | print self.format_latex(magic_docs) |
|
443 | 443 | return |
|
444 | 444 | else: |
|
445 | 445 | magic_docs = self.format_screen(magic_docs) |
|
446 | 446 | if mode == 'brief': |
|
447 | 447 | return magic_docs |
|
448 | 448 | |
|
449 | 449 | outmsg = """ |
|
450 | 450 | IPython's 'magic' functions |
|
451 | 451 | =========================== |
|
452 | 452 | |
|
453 | 453 | The magic function system provides a series of functions which allow you to |
|
454 | 454 | control the behavior of IPython itself, plus a lot of system-type |
|
455 | 455 | features. All these functions are prefixed with a % character, but parameters |
|
456 | 456 | are given without parentheses or quotes. |
|
457 | 457 | |
|
458 | 458 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
459 | 459 | %automagic function), you don't need to type in the % explicitly. By default, |
|
460 | 460 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
461 | 461 | |
|
462 | 462 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
463 | 463 | to 'mydir', if it exists. |
|
464 | 464 | |
|
465 | 465 | You can define your own magic functions to extend the system. See the supplied |
|
466 | 466 | ipythonrc and example-magic.py files for details (in your ipython |
|
467 | 467 | configuration directory, typically $HOME/.ipython/). |
|
468 | 468 | |
|
469 | 469 | You can also define your own aliased names for magic functions. In your |
|
470 | 470 | ipythonrc file, placing a line like: |
|
471 | 471 | |
|
472 | 472 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
473 | 473 | |
|
474 | 474 | will define %pf as a new name for %profile. |
|
475 | 475 | |
|
476 | 476 | You can also call magics in code using the magic() function, which IPython |
|
477 | 477 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
478 | 478 | |
|
479 | 479 | For a list of the available magic functions, use %lsmagic. For a description |
|
480 | 480 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
481 | 481 | |
|
482 | 482 | Currently the magic system has the following functions:\n""" |
|
483 | 483 | |
|
484 | 484 | mesc = ESC_MAGIC |
|
485 | 485 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
486 | 486 | "\n\n%s%s\n\n%s" % (outmsg, |
|
487 | 487 | magic_docs,mesc,mesc, |
|
488 | 488 | (' '+mesc).join(self.lsmagic()), |
|
489 | 489 | Magic.auto_status[self.shell.automagic] ) ) |
|
490 | 490 | |
|
491 | 491 | page(outmsg,screen_lines=self.shell.usable_screen_length) |
|
492 | 492 | |
|
493 | 493 | |
|
494 | 494 | def magic_autoindent(self, parameter_s = ''): |
|
495 | 495 | """Toggle autoindent on/off (if available).""" |
|
496 | 496 | |
|
497 | 497 | self.shell.set_autoindent() |
|
498 | 498 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
499 | 499 | |
|
500 | 500 | |
|
501 | 501 | def magic_automagic(self, parameter_s = ''): |
|
502 | 502 | """Make magic functions callable without having to type the initial %. |
|
503 | 503 | |
|
504 | 504 | Without argumentsl toggles on/off (when off, you must call it as |
|
505 | 505 | %automagic, of course). With arguments it sets the value, and you can |
|
506 | 506 | use any of (case insensitive): |
|
507 | 507 | |
|
508 | 508 | - on,1,True: to activate |
|
509 | 509 | |
|
510 | 510 | - off,0,False: to deactivate. |
|
511 | 511 | |
|
512 | 512 | Note that magic functions have lowest priority, so if there's a |
|
513 | 513 | variable whose name collides with that of a magic fn, automagic won't |
|
514 | 514 | work for that function (you get the variable instead). However, if you |
|
515 | 515 | delete the variable (del var), the previously shadowed magic function |
|
516 | 516 | becomes visible to automagic again.""" |
|
517 | 517 | |
|
518 | 518 | arg = parameter_s.lower() |
|
519 | 519 | if parameter_s in ('on','1','true'): |
|
520 | 520 | self.shell.automagic = True |
|
521 | 521 | elif parameter_s in ('off','0','false'): |
|
522 | 522 | self.shell.automagic = False |
|
523 | 523 | else: |
|
524 | 524 | self.shell.automagic = not self.shell.automagic |
|
525 | 525 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
526 | 526 | |
|
527 | 527 | @testdec.skip_doctest |
|
528 | 528 | def magic_autocall(self, parameter_s = ''): |
|
529 | 529 | """Make functions callable without having to type parentheses. |
|
530 | 530 | |
|
531 | 531 | Usage: |
|
532 | 532 | |
|
533 | 533 | %autocall [mode] |
|
534 | 534 | |
|
535 | 535 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
536 | 536 | value is toggled on and off (remembering the previous state). |
|
537 | 537 | |
|
538 | 538 | In more detail, these values mean: |
|
539 | 539 | |
|
540 | 540 | 0 -> fully disabled |
|
541 | 541 | |
|
542 | 542 | 1 -> active, but do not apply if there are no arguments on the line. |
|
543 | 543 | |
|
544 | 544 | In this mode, you get: |
|
545 | 545 | |
|
546 | 546 | In [1]: callable |
|
547 | 547 | Out[1]: <built-in function callable> |
|
548 | 548 | |
|
549 | 549 | In [2]: callable 'hello' |
|
550 | 550 | ------> callable('hello') |
|
551 | 551 | Out[2]: False |
|
552 | 552 | |
|
553 | 553 | 2 -> Active always. Even if no arguments are present, the callable |
|
554 | 554 | object is called: |
|
555 | 555 | |
|
556 | 556 | In [2]: float |
|
557 | 557 | ------> float() |
|
558 | 558 | Out[2]: 0.0 |
|
559 | 559 | |
|
560 | 560 | Note that even with autocall off, you can still use '/' at the start of |
|
561 | 561 | a line to treat the first argument on the command line as a function |
|
562 | 562 | and add parentheses to it: |
|
563 | 563 | |
|
564 | 564 | In [8]: /str 43 |
|
565 | 565 | ------> str(43) |
|
566 | 566 | Out[8]: '43' |
|
567 | 567 | |
|
568 | 568 | # all-random (note for auto-testing) |
|
569 | 569 | """ |
|
570 | 570 | |
|
571 | 571 | if parameter_s: |
|
572 | 572 | arg = int(parameter_s) |
|
573 | 573 | else: |
|
574 | 574 | arg = 'toggle' |
|
575 | 575 | |
|
576 | 576 | if not arg in (0,1,2,'toggle'): |
|
577 | 577 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
578 | 578 | return |
|
579 | 579 | |
|
580 | 580 | if arg in (0,1,2): |
|
581 | 581 | self.shell.autocall = arg |
|
582 | 582 | else: # toggle |
|
583 | 583 | if self.shell.autocall: |
|
584 | 584 | self._magic_state.autocall_save = self.shell.autocall |
|
585 | 585 | self.shell.autocall = 0 |
|
586 | 586 | else: |
|
587 | 587 | try: |
|
588 | 588 | self.shell.autocall = self._magic_state.autocall_save |
|
589 | 589 | except AttributeError: |
|
590 | 590 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
591 | 591 | |
|
592 | 592 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
593 | 593 | |
|
594 | 594 | def magic_system_verbose(self, parameter_s = ''): |
|
595 | 595 | """Set verbose printing of system calls. |
|
596 | 596 | |
|
597 | 597 | If called without an argument, act as a toggle""" |
|
598 | 598 | |
|
599 | 599 | if parameter_s: |
|
600 | 600 | val = bool(eval(parameter_s)) |
|
601 | 601 | else: |
|
602 | 602 | val = None |
|
603 | 603 | |
|
604 | 604 | if self.shell.system_verbose: |
|
605 | 605 | self.shell.system_verbose = False |
|
606 | 606 | else: |
|
607 | 607 | self.shell.system_verbose = True |
|
608 | 608 | print "System verbose printing is:",\ |
|
609 | 609 | ['OFF','ON'][self.shell.system_verbose] |
|
610 | 610 | |
|
611 | 611 | |
|
612 | 612 | def magic_page(self, parameter_s=''): |
|
613 | 613 | """Pretty print the object and display it through a pager. |
|
614 | 614 | |
|
615 | 615 | %page [options] OBJECT |
|
616 | 616 | |
|
617 | 617 | If no object is given, use _ (last output). |
|
618 | 618 | |
|
619 | 619 | Options: |
|
620 | 620 | |
|
621 | 621 | -r: page str(object), don't pretty-print it.""" |
|
622 | 622 | |
|
623 | 623 | # After a function contributed by Olivier Aubert, slightly modified. |
|
624 | 624 | |
|
625 | 625 | # Process options/args |
|
626 | 626 | opts,args = self.parse_options(parameter_s,'r') |
|
627 | 627 | raw = 'r' in opts |
|
628 | 628 | |
|
629 | 629 | oname = args and args or '_' |
|
630 | 630 | info = self._ofind(oname) |
|
631 | 631 | if info['found']: |
|
632 | 632 | txt = (raw and str or pformat)( info['obj'] ) |
|
633 | 633 | page(txt) |
|
634 | 634 | else: |
|
635 | 635 | print 'Object `%s` not found' % oname |
|
636 | 636 | |
|
637 | 637 | def magic_profile(self, parameter_s=''): |
|
638 | 638 | """Print your currently active IPyhton profile.""" |
|
639 | 639 | if self.shell.profile: |
|
640 | 640 | printpl('Current IPython profile: $self.shell.profile.') |
|
641 | 641 | else: |
|
642 | 642 | print 'No profile active.' |
|
643 | 643 | |
|
644 | 644 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
645 | 645 | """Provide detailed information about an object. |
|
646 | 646 | |
|
647 | 647 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
648 | 648 | |
|
649 | 649 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
650 | 650 | |
|
651 | 651 | |
|
652 | 652 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
653 | 653 | detail_level = 0 |
|
654 | 654 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
655 | 655 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
656 | 656 | pinfo,qmark1,oname,qmark2 = \ |
|
657 | 657 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
658 | 658 | if pinfo or qmark1 or qmark2: |
|
659 | 659 | detail_level = 1 |
|
660 | 660 | if "*" in oname: |
|
661 | 661 | self.magic_psearch(oname) |
|
662 | 662 | else: |
|
663 | 663 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
664 | 664 | namespaces=namespaces) |
|
665 | 665 | |
|
666 | 666 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
667 | 667 | """Print the definition header for any callable object. |
|
668 | 668 | |
|
669 | 669 | If the object is a class, print the constructor information.""" |
|
670 | 670 | self._inspect('pdef',parameter_s, namespaces) |
|
671 | 671 | |
|
672 | 672 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
673 | 673 | """Print the docstring for an object. |
|
674 | 674 | |
|
675 | 675 | If the given object is a class, it will print both the class and the |
|
676 | 676 | constructor docstrings.""" |
|
677 | 677 | self._inspect('pdoc',parameter_s, namespaces) |
|
678 | 678 | |
|
679 | 679 | def magic_psource(self, parameter_s='', namespaces=None): |
|
680 | 680 | """Print (or run through pager) the source code for an object.""" |
|
681 | 681 | self._inspect('psource',parameter_s, namespaces) |
|
682 | 682 | |
|
683 | 683 | def magic_pfile(self, parameter_s=''): |
|
684 | 684 | """Print (or run through pager) the file where an object is defined. |
|
685 | 685 | |
|
686 | 686 | The file opens at the line where the object definition begins. IPython |
|
687 | 687 | will honor the environment variable PAGER if set, and otherwise will |
|
688 | 688 | do its best to print the file in a convenient form. |
|
689 | 689 | |
|
690 | 690 | If the given argument is not an object currently defined, IPython will |
|
691 | 691 | try to interpret it as a filename (automatically adding a .py extension |
|
692 | 692 | if needed). You can thus use %pfile as a syntax highlighting code |
|
693 | 693 | viewer.""" |
|
694 | 694 | |
|
695 | 695 | # first interpret argument as an object name |
|
696 | 696 | out = self._inspect('pfile',parameter_s) |
|
697 | 697 | # if not, try the input as a filename |
|
698 | 698 | if out == 'not found': |
|
699 | 699 | try: |
|
700 | 700 | filename = get_py_filename(parameter_s) |
|
701 | 701 | except IOError,msg: |
|
702 | 702 | print msg |
|
703 | 703 | return |
|
704 | 704 | page(self.shell.inspector.format(file(filename).read())) |
|
705 | 705 | |
|
706 | 706 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
707 | 707 | """Generic interface to the inspector system. |
|
708 | 708 | |
|
709 | 709 | This function is meant to be called by pdef, pdoc & friends.""" |
|
710 | 710 | |
|
711 | 711 | #oname = oname.strip() |
|
712 | 712 | #print '1- oname: <%r>' % oname # dbg |
|
713 | 713 | try: |
|
714 | 714 | oname = oname.strip().encode('ascii') |
|
715 | 715 | #print '2- oname: <%r>' % oname # dbg |
|
716 | 716 | except UnicodeEncodeError: |
|
717 | 717 | print 'Python identifiers can only contain ascii characters.' |
|
718 | 718 | return 'not found' |
|
719 | 719 | |
|
720 | 720 | info = Struct(self._ofind(oname, namespaces)) |
|
721 | 721 | |
|
722 | 722 | if info.found: |
|
723 | 723 | try: |
|
724 | 724 | IPython.utils.generics.inspect_object(info.obj) |
|
725 | 725 | return |
|
726 | 726 | except TryNext: |
|
727 | 727 | pass |
|
728 | 728 | # Get the docstring of the class property if it exists. |
|
729 | 729 | path = oname.split('.') |
|
730 | 730 | root = '.'.join(path[:-1]) |
|
731 | 731 | if info.parent is not None: |
|
732 | 732 | try: |
|
733 | 733 | target = getattr(info.parent, '__class__') |
|
734 | 734 | # The object belongs to a class instance. |
|
735 | 735 | try: |
|
736 | 736 | target = getattr(target, path[-1]) |
|
737 | 737 | # The class defines the object. |
|
738 | 738 | if isinstance(target, property): |
|
739 | 739 | oname = root + '.__class__.' + path[-1] |
|
740 | 740 | info = Struct(self._ofind(oname)) |
|
741 | 741 | except AttributeError: pass |
|
742 | 742 | except AttributeError: pass |
|
743 | 743 | |
|
744 | 744 | pmethod = getattr(self.shell.inspector,meth) |
|
745 | 745 | formatter = info.ismagic and self.format_screen or None |
|
746 | 746 | if meth == 'pdoc': |
|
747 | 747 | pmethod(info.obj,oname,formatter) |
|
748 | 748 | elif meth == 'pinfo': |
|
749 | 749 | pmethod(info.obj,oname,formatter,info,**kw) |
|
750 | 750 | else: |
|
751 | 751 | pmethod(info.obj,oname) |
|
752 | 752 | else: |
|
753 | 753 | print 'Object `%s` not found.' % oname |
|
754 | 754 | return 'not found' # so callers can take other action |
|
755 | 755 | |
|
756 | 756 | def magic_psearch(self, parameter_s=''): |
|
757 | 757 | """Search for object in namespaces by wildcard. |
|
758 | 758 | |
|
759 | 759 | %psearch [options] PATTERN [OBJECT TYPE] |
|
760 | 760 | |
|
761 | 761 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
762 | 762 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
763 | 763 | rest of the command line must be unchanged (options come first), so |
|
764 | 764 | for example the following forms are equivalent |
|
765 | 765 | |
|
766 | 766 | %psearch -i a* function |
|
767 | 767 | -i a* function? |
|
768 | 768 | ?-i a* function |
|
769 | 769 | |
|
770 | 770 | Arguments: |
|
771 | 771 | |
|
772 | 772 | PATTERN |
|
773 | 773 | |
|
774 | 774 | where PATTERN is a string containing * as a wildcard similar to its |
|
775 | 775 | use in a shell. The pattern is matched in all namespaces on the |
|
776 | 776 | search path. By default objects starting with a single _ are not |
|
777 | 777 | matched, many IPython generated objects have a single |
|
778 | 778 | underscore. The default is case insensitive matching. Matching is |
|
779 | 779 | also done on the attributes of objects and not only on the objects |
|
780 | 780 | in a module. |
|
781 | 781 | |
|
782 | 782 | [OBJECT TYPE] |
|
783 | 783 | |
|
784 | 784 | Is the name of a python type from the types module. The name is |
|
785 | 785 | given in lowercase without the ending type, ex. StringType is |
|
786 | 786 | written string. By adding a type here only objects matching the |
|
787 | 787 | given type are matched. Using all here makes the pattern match all |
|
788 | 788 | types (this is the default). |
|
789 | 789 | |
|
790 | 790 | Options: |
|
791 | 791 | |
|
792 | 792 | -a: makes the pattern match even objects whose names start with a |
|
793 | 793 | single underscore. These names are normally ommitted from the |
|
794 | 794 | search. |
|
795 | 795 | |
|
796 | 796 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
797 | 797 | these options is given, the default is read from your ipythonrc |
|
798 | 798 | file. The option name which sets this value is |
|
799 | 799 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
800 | 800 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
801 | 801 | search. |
|
802 | 802 | |
|
803 | 803 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
804 | 804 | specifiy can be searched in any of the following namespaces: |
|
805 | 805 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
806 | 806 | 'builtin' and 'user' are the search defaults. Note that you should |
|
807 | 807 | not use quotes when specifying namespaces. |
|
808 | 808 | |
|
809 | 809 | 'Builtin' contains the python module builtin, 'user' contains all |
|
810 | 810 | user data, 'alias' only contain the shell aliases and no python |
|
811 | 811 | objects, 'internal' contains objects used by IPython. The |
|
812 | 812 | 'user_global' namespace is only used by embedded IPython instances, |
|
813 | 813 | and it contains module-level globals. You can add namespaces to the |
|
814 | 814 | search with -s or exclude them with -e (these options can be given |
|
815 | 815 | more than once). |
|
816 | 816 | |
|
817 | 817 | Examples: |
|
818 | 818 | |
|
819 | 819 | %psearch a* -> objects beginning with an a |
|
820 | 820 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
821 | 821 | %psearch a* function -> all functions beginning with an a |
|
822 | 822 | %psearch re.e* -> objects beginning with an e in module re |
|
823 | 823 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
824 | 824 | %psearch r*.* string -> all strings in modules beginning with r |
|
825 | 825 | |
|
826 | 826 | Case sensitve search: |
|
827 | 827 | |
|
828 | 828 | %psearch -c a* list all object beginning with lower case a |
|
829 | 829 | |
|
830 | 830 | Show objects beginning with a single _: |
|
831 | 831 | |
|
832 | 832 | %psearch -a _* list objects beginning with a single underscore""" |
|
833 | 833 | try: |
|
834 | 834 | parameter_s = parameter_s.encode('ascii') |
|
835 | 835 | except UnicodeEncodeError: |
|
836 | 836 | print 'Python identifiers can only contain ascii characters.' |
|
837 | 837 | return |
|
838 | 838 | |
|
839 | 839 | # default namespaces to be searched |
|
840 | 840 | def_search = ['user','builtin'] |
|
841 | 841 | |
|
842 | 842 | # Process options/args |
|
843 | 843 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
844 | 844 | opt = opts.get |
|
845 | 845 | shell = self.shell |
|
846 | 846 | psearch = shell.inspector.psearch |
|
847 | 847 | |
|
848 | 848 | # select case options |
|
849 | 849 | if opts.has_key('i'): |
|
850 | 850 | ignore_case = True |
|
851 | 851 | elif opts.has_key('c'): |
|
852 | 852 | ignore_case = False |
|
853 | 853 | else: |
|
854 | 854 | ignore_case = not shell.wildcards_case_sensitive |
|
855 | 855 | |
|
856 | 856 | # Build list of namespaces to search from user options |
|
857 | 857 | def_search.extend(opt('s',[])) |
|
858 | 858 | ns_exclude = ns_exclude=opt('e',[]) |
|
859 | 859 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
860 | 860 | |
|
861 | 861 | # Call the actual search |
|
862 | 862 | try: |
|
863 | 863 | psearch(args,shell.ns_table,ns_search, |
|
864 | 864 | show_all=opt('a'),ignore_case=ignore_case) |
|
865 | 865 | except: |
|
866 | 866 | shell.showtraceback() |
|
867 | 867 | |
|
868 | 868 | def magic_who_ls(self, parameter_s=''): |
|
869 | 869 | """Return a sorted list of all interactive variables. |
|
870 | 870 | |
|
871 | 871 | If arguments are given, only variables of types matching these |
|
872 | 872 | arguments are returned.""" |
|
873 | 873 | |
|
874 | 874 | user_ns = self.shell.user_ns |
|
875 | 875 | internal_ns = self.shell.internal_ns |
|
876 | 876 | user_config_ns = self.shell.user_config_ns |
|
877 | 877 | out = [] |
|
878 | 878 | typelist = parameter_s.split() |
|
879 | 879 | |
|
880 | 880 | for i in user_ns: |
|
881 | 881 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
882 | 882 | and not (i in internal_ns or i in user_config_ns): |
|
883 | 883 | if typelist: |
|
884 | 884 | if type(user_ns[i]).__name__ in typelist: |
|
885 | 885 | out.append(i) |
|
886 | 886 | else: |
|
887 | 887 | out.append(i) |
|
888 | 888 | out.sort() |
|
889 | 889 | return out |
|
890 | 890 | |
|
891 | 891 | def magic_who(self, parameter_s=''): |
|
892 | 892 | """Print all interactive variables, with some minimal formatting. |
|
893 | 893 | |
|
894 | 894 | If any arguments are given, only variables whose type matches one of |
|
895 | 895 | these are printed. For example: |
|
896 | 896 | |
|
897 | 897 | %who function str |
|
898 | 898 | |
|
899 | 899 | will only list functions and strings, excluding all other types of |
|
900 | 900 | variables. To find the proper type names, simply use type(var) at a |
|
901 | 901 | command line to see how python prints type names. For example: |
|
902 | 902 | |
|
903 | 903 | In [1]: type('hello')\\ |
|
904 | 904 | Out[1]: <type 'str'> |
|
905 | 905 | |
|
906 | 906 | indicates that the type name for strings is 'str'. |
|
907 | 907 | |
|
908 | 908 | %who always excludes executed names loaded through your configuration |
|
909 | 909 | file and things which are internal to IPython. |
|
910 | 910 | |
|
911 | 911 | This is deliberate, as typically you may load many modules and the |
|
912 | 912 | purpose of %who is to show you only what you've manually defined.""" |
|
913 | 913 | |
|
914 | 914 | varlist = self.magic_who_ls(parameter_s) |
|
915 | 915 | if not varlist: |
|
916 | 916 | if parameter_s: |
|
917 | 917 | print 'No variables match your requested type.' |
|
918 | 918 | else: |
|
919 | 919 | print 'Interactive namespace is empty.' |
|
920 | 920 | return |
|
921 | 921 | |
|
922 | 922 | # if we have variables, move on... |
|
923 | 923 | count = 0 |
|
924 | 924 | for i in varlist: |
|
925 | 925 | print i+'\t', |
|
926 | 926 | count += 1 |
|
927 | 927 | if count > 8: |
|
928 | 928 | count = 0 |
|
929 | 929 | |
|
930 | 930 | |
|
931 | 931 | |
|
932 | 932 | def magic_whos(self, parameter_s=''): |
|
933 | 933 | """Like %who, but gives some extra information about each variable. |
|
934 | 934 | |
|
935 | 935 | The same type filtering of %who can be applied here. |
|
936 | 936 | |
|
937 | 937 | For all variables, the type is printed. Additionally it prints: |
|
938 | 938 | |
|
939 | 939 | - For {},[],(): their length. |
|
940 | 940 | |
|
941 | 941 | - For numpy and Numeric arrays, a summary with shape, number of |
|
942 | 942 | elements, typecode and size in memory. |
|
943 | 943 | |
|
944 | 944 | - Everything else: a string representation, snipping their middle if |
|
945 | 945 | too long.""" |
|
946 | 946 | |
|
947 | 947 | varnames = self.magic_who_ls(parameter_s) |
|
948 | 948 | if not varnames: |
|
949 | 949 | if parameter_s: |
|
950 | 950 | print 'No variables match your requested type.' |
|
951 | 951 | else: |
|
952 | 952 | print 'Interactive namespace is empty.' |
|
953 | 953 | return |
|
954 | 954 | |
|
955 | 955 | # if we have variables, move on... |
|
956 | 956 | |
|
957 | 957 | # for these types, show len() instead of data: |
|
958 | 958 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
959 | 959 | |
|
960 | 960 | # for numpy/Numeric arrays, display summary info |
|
961 | 961 | try: |
|
962 | 962 | import numpy |
|
963 | 963 | except ImportError: |
|
964 | 964 | ndarray_type = None |
|
965 | 965 | else: |
|
966 | 966 | ndarray_type = numpy.ndarray.__name__ |
|
967 | 967 | try: |
|
968 | 968 | import Numeric |
|
969 | 969 | except ImportError: |
|
970 | 970 | array_type = None |
|
971 | 971 | else: |
|
972 | 972 | array_type = Numeric.ArrayType.__name__ |
|
973 | 973 | |
|
974 | 974 | # Find all variable names and types so we can figure out column sizes |
|
975 | 975 | def get_vars(i): |
|
976 | 976 | return self.shell.user_ns[i] |
|
977 | 977 | |
|
978 | 978 | # some types are well known and can be shorter |
|
979 | 979 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
980 | 980 | def type_name(v): |
|
981 | 981 | tn = type(v).__name__ |
|
982 | 982 | return abbrevs.get(tn,tn) |
|
983 | 983 | |
|
984 | 984 | varlist = map(get_vars,varnames) |
|
985 | 985 | |
|
986 | 986 | typelist = [] |
|
987 | 987 | for vv in varlist: |
|
988 | 988 | tt = type_name(vv) |
|
989 | 989 | |
|
990 | 990 | if tt=='instance': |
|
991 | 991 | typelist.append( abbrevs.get(str(vv.__class__), |
|
992 | 992 | str(vv.__class__))) |
|
993 | 993 | else: |
|
994 | 994 | typelist.append(tt) |
|
995 | 995 | |
|
996 | 996 | # column labels and # of spaces as separator |
|
997 | 997 | varlabel = 'Variable' |
|
998 | 998 | typelabel = 'Type' |
|
999 | 999 | datalabel = 'Data/Info' |
|
1000 | 1000 | colsep = 3 |
|
1001 | 1001 | # variable format strings |
|
1002 | 1002 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1003 | 1003 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1004 | 1004 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1005 | 1005 | # find the size of the columns to format the output nicely |
|
1006 | 1006 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1007 | 1007 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1008 | 1008 | # table header |
|
1009 | 1009 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1010 | 1010 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1011 | 1011 | # and the table itself |
|
1012 | 1012 | kb = 1024 |
|
1013 | 1013 | Mb = 1048576 # kb**2 |
|
1014 | 1014 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1015 | 1015 | print itpl(vformat), |
|
1016 | 1016 | if vtype in seq_types: |
|
1017 | 1017 | print len(var) |
|
1018 | 1018 | elif vtype in [array_type,ndarray_type]: |
|
1019 | 1019 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1020 | 1020 | if vtype==ndarray_type: |
|
1021 | 1021 | # numpy |
|
1022 | 1022 | vsize = var.size |
|
1023 | 1023 | vbytes = vsize*var.itemsize |
|
1024 | 1024 | vdtype = var.dtype |
|
1025 | 1025 | else: |
|
1026 | 1026 | # Numeric |
|
1027 | 1027 | vsize = Numeric.size(var) |
|
1028 | 1028 | vbytes = vsize*var.itemsize() |
|
1029 | 1029 | vdtype = var.typecode() |
|
1030 | 1030 | |
|
1031 | 1031 | if vbytes < 100000: |
|
1032 | 1032 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1033 | 1033 | else: |
|
1034 | 1034 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1035 | 1035 | if vbytes < Mb: |
|
1036 | 1036 | print '(%s kb)' % (vbytes/kb,) |
|
1037 | 1037 | else: |
|
1038 | 1038 | print '(%s Mb)' % (vbytes/Mb,) |
|
1039 | 1039 | else: |
|
1040 | 1040 | try: |
|
1041 | 1041 | vstr = str(var) |
|
1042 | 1042 | except UnicodeEncodeError: |
|
1043 | 1043 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1044 | 1044 | 'backslashreplace') |
|
1045 | 1045 | vstr = vstr.replace('\n','\\n') |
|
1046 | 1046 | if len(vstr) < 50: |
|
1047 | 1047 | print vstr |
|
1048 | 1048 | else: |
|
1049 | 1049 | printpl(vfmt_short) |
|
1050 | 1050 | |
|
1051 | 1051 | def magic_reset(self, parameter_s=''): |
|
1052 | 1052 | """Resets the namespace by removing all names defined by the user. |
|
1053 | 1053 | |
|
1054 | 1054 | Input/Output history are left around in case you need them. |
|
1055 | 1055 | |
|
1056 | 1056 | Parameters |
|
1057 | 1057 | ---------- |
|
1058 | 1058 | -y : force reset without asking for confirmation. |
|
1059 | 1059 | |
|
1060 | 1060 | Examples |
|
1061 | 1061 | -------- |
|
1062 | 1062 | In [6]: a = 1 |
|
1063 | 1063 | |
|
1064 | 1064 | In [7]: a |
|
1065 | 1065 | Out[7]: 1 |
|
1066 | 1066 | |
|
1067 | 1067 | In [8]: 'a' in _ip.user_ns |
|
1068 | 1068 | Out[8]: True |
|
1069 | 1069 | |
|
1070 | 1070 | In [9]: %reset -f |
|
1071 | 1071 | |
|
1072 | 1072 | In [10]: 'a' in _ip.user_ns |
|
1073 | 1073 | Out[10]: False |
|
1074 | 1074 | """ |
|
1075 | 1075 | |
|
1076 | 1076 | if parameter_s == '-f': |
|
1077 | 1077 | ans = True |
|
1078 | 1078 | else: |
|
1079 | 1079 | ans = self.shell.ask_yes_no( |
|
1080 | 1080 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1081 | 1081 | if not ans: |
|
1082 | 1082 | print 'Nothing done.' |
|
1083 | 1083 | return |
|
1084 | 1084 | user_ns = self.shell.user_ns |
|
1085 | 1085 | for i in self.magic_who_ls(): |
|
1086 | 1086 | del(user_ns[i]) |
|
1087 | 1087 | |
|
1088 | 1088 | # Also flush the private list of module references kept for script |
|
1089 | 1089 | # execution protection |
|
1090 | 1090 | self.shell.clear_main_mod_cache() |
|
1091 | 1091 | |
|
1092 | 1092 | def magic_logstart(self,parameter_s=''): |
|
1093 | 1093 | """Start logging anywhere in a session. |
|
1094 | 1094 | |
|
1095 | 1095 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1096 | 1096 | |
|
1097 | 1097 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1098 | 1098 | current directory, in 'rotate' mode (see below). |
|
1099 | 1099 | |
|
1100 | 1100 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1101 | 1101 | history up to that point and then continues logging. |
|
1102 | 1102 | |
|
1103 | 1103 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1104 | 1104 | of (note that the modes are given unquoted):\\ |
|
1105 | 1105 | append: well, that says it.\\ |
|
1106 | 1106 | backup: rename (if exists) to name~ and start name.\\ |
|
1107 | 1107 | global: single logfile in your home dir, appended to.\\ |
|
1108 | 1108 | over : overwrite existing log.\\ |
|
1109 | 1109 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1110 | 1110 | |
|
1111 | 1111 | Options: |
|
1112 | 1112 | |
|
1113 | 1113 | -o: log also IPython's output. In this mode, all commands which |
|
1114 | 1114 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1115 | 1115 | their corresponding input line. The output lines are always |
|
1116 | 1116 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1117 | 1117 | Python code. |
|
1118 | 1118 | |
|
1119 | 1119 | Since this marker is always the same, filtering only the output from |
|
1120 | 1120 | a log is very easy, using for example a simple awk call: |
|
1121 | 1121 | |
|
1122 | 1122 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1123 | 1123 | |
|
1124 | 1124 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1125 | 1125 | input, so that user lines are logged in their final form, converted |
|
1126 | 1126 | into valid Python. For example, %Exit is logged as |
|
1127 | 1127 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1128 | 1128 | exactly as typed, with no transformations applied. |
|
1129 | 1129 | |
|
1130 | 1130 | -t: put timestamps before each input line logged (these are put in |
|
1131 | 1131 | comments).""" |
|
1132 | 1132 | |
|
1133 | 1133 | opts,par = self.parse_options(parameter_s,'ort') |
|
1134 | 1134 | log_output = 'o' in opts |
|
1135 | 1135 | log_raw_input = 'r' in opts |
|
1136 | 1136 | timestamp = 't' in opts |
|
1137 | 1137 | |
|
1138 | 1138 | logger = self.shell.logger |
|
1139 | 1139 | |
|
1140 | 1140 | # if no args are given, the defaults set in the logger constructor by |
|
1141 | 1141 | # ipytohn remain valid |
|
1142 | 1142 | if par: |
|
1143 | 1143 | try: |
|
1144 | 1144 | logfname,logmode = par.split() |
|
1145 | 1145 | except: |
|
1146 | 1146 | logfname = par |
|
1147 | 1147 | logmode = 'backup' |
|
1148 | 1148 | else: |
|
1149 | 1149 | logfname = logger.logfname |
|
1150 | 1150 | logmode = logger.logmode |
|
1151 | 1151 | # put logfname into rc struct as if it had been called on the command |
|
1152 | 1152 | # line, so it ends up saved in the log header Save it in case we need |
|
1153 | 1153 | # to restore it... |
|
1154 | 1154 | old_logfile = self.shell.logfile |
|
1155 | 1155 | if logfname: |
|
1156 | 1156 | logfname = os.path.expanduser(logfname) |
|
1157 | 1157 | self.shell.logfile = logfname |
|
1158 | 1158 | |
|
1159 | 1159 | loghead = '# IPython log file\n\n' |
|
1160 | 1160 | try: |
|
1161 | 1161 | started = logger.logstart(logfname,loghead,logmode, |
|
1162 | 1162 | log_output,timestamp,log_raw_input) |
|
1163 | 1163 | except: |
|
1164 | 1164 | rc.opts.logfile = old_logfile |
|
1165 | 1165 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1166 | 1166 | else: |
|
1167 | 1167 | # log input history up to this point, optionally interleaving |
|
1168 | 1168 | # output if requested |
|
1169 | 1169 | |
|
1170 | 1170 | if timestamp: |
|
1171 | 1171 | # disable timestamping for the previous history, since we've |
|
1172 | 1172 | # lost those already (no time machine here). |
|
1173 | 1173 | logger.timestamp = False |
|
1174 | 1174 | |
|
1175 | 1175 | if log_raw_input: |
|
1176 | 1176 | input_hist = self.shell.input_hist_raw |
|
1177 | 1177 | else: |
|
1178 | 1178 | input_hist = self.shell.input_hist |
|
1179 | 1179 | |
|
1180 | 1180 | if log_output: |
|
1181 | 1181 | log_write = logger.log_write |
|
1182 | 1182 | output_hist = self.shell.output_hist |
|
1183 | 1183 | for n in range(1,len(input_hist)-1): |
|
1184 | 1184 | log_write(input_hist[n].rstrip()) |
|
1185 | 1185 | if n in output_hist: |
|
1186 | 1186 | log_write(repr(output_hist[n]),'output') |
|
1187 | 1187 | else: |
|
1188 | 1188 | logger.log_write(input_hist[1:]) |
|
1189 | 1189 | if timestamp: |
|
1190 | 1190 | # re-enable timestamping |
|
1191 | 1191 | logger.timestamp = True |
|
1192 | 1192 | |
|
1193 | 1193 | print ('Activating auto-logging. ' |
|
1194 | 1194 | 'Current session state plus future input saved.') |
|
1195 | 1195 | logger.logstate() |
|
1196 | 1196 | |
|
1197 | 1197 | def magic_logstop(self,parameter_s=''): |
|
1198 | 1198 | """Fully stop logging and close log file. |
|
1199 | 1199 | |
|
1200 | 1200 | In order to start logging again, a new %logstart call needs to be made, |
|
1201 | 1201 | possibly (though not necessarily) with a new filename, mode and other |
|
1202 | 1202 | options.""" |
|
1203 | 1203 | self.logger.logstop() |
|
1204 | 1204 | |
|
1205 | 1205 | def magic_logoff(self,parameter_s=''): |
|
1206 | 1206 | """Temporarily stop logging. |
|
1207 | 1207 | |
|
1208 | 1208 | You must have previously started logging.""" |
|
1209 | 1209 | self.shell.logger.switch_log(0) |
|
1210 | 1210 | |
|
1211 | 1211 | def magic_logon(self,parameter_s=''): |
|
1212 | 1212 | """Restart logging. |
|
1213 | 1213 | |
|
1214 | 1214 | This function is for restarting logging which you've temporarily |
|
1215 | 1215 | stopped with %logoff. For starting logging for the first time, you |
|
1216 | 1216 | must use the %logstart function, which allows you to specify an |
|
1217 | 1217 | optional log filename.""" |
|
1218 | 1218 | |
|
1219 | 1219 | self.shell.logger.switch_log(1) |
|
1220 | 1220 | |
|
1221 | 1221 | def magic_logstate(self,parameter_s=''): |
|
1222 | 1222 | """Print the status of the logging system.""" |
|
1223 | 1223 | |
|
1224 | 1224 | self.shell.logger.logstate() |
|
1225 | 1225 | |
|
1226 | 1226 | def magic_pdb(self, parameter_s=''): |
|
1227 | 1227 | """Control the automatic calling of the pdb interactive debugger. |
|
1228 | 1228 | |
|
1229 | 1229 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1230 | 1230 | argument it works as a toggle. |
|
1231 | 1231 | |
|
1232 | 1232 | When an exception is triggered, IPython can optionally call the |
|
1233 | 1233 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1234 | 1234 | this feature on and off. |
|
1235 | 1235 | |
|
1236 | 1236 | The initial state of this feature is set in your ipythonrc |
|
1237 | 1237 | configuration file (the variable is called 'pdb'). |
|
1238 | 1238 | |
|
1239 | 1239 | If you want to just activate the debugger AFTER an exception has fired, |
|
1240 | 1240 | without having to type '%pdb on' and rerunning your code, you can use |
|
1241 | 1241 | the %debug magic.""" |
|
1242 | 1242 | |
|
1243 | 1243 | par = parameter_s.strip().lower() |
|
1244 | 1244 | |
|
1245 | 1245 | if par: |
|
1246 | 1246 | try: |
|
1247 | 1247 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1248 | 1248 | except KeyError: |
|
1249 | 1249 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1250 | 1250 | 'or nothing for a toggle.') |
|
1251 | 1251 | return |
|
1252 | 1252 | else: |
|
1253 | 1253 | # toggle |
|
1254 | 1254 | new_pdb = not self.shell.call_pdb |
|
1255 | 1255 | |
|
1256 | 1256 | # set on the shell |
|
1257 | 1257 | self.shell.call_pdb = new_pdb |
|
1258 | 1258 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1259 | 1259 | |
|
1260 | 1260 | def magic_debug(self, parameter_s=''): |
|
1261 | 1261 | """Activate the interactive debugger in post-mortem mode. |
|
1262 | 1262 | |
|
1263 | 1263 | If an exception has just occurred, this lets you inspect its stack |
|
1264 | 1264 | frames interactively. Note that this will always work only on the last |
|
1265 | 1265 | traceback that occurred, so you must call this quickly after an |
|
1266 | 1266 | exception that you wish to inspect has fired, because if another one |
|
1267 | 1267 | occurs, it clobbers the previous one. |
|
1268 | 1268 | |
|
1269 | 1269 | If you want IPython to automatically do this on every exception, see |
|
1270 | 1270 | the %pdb magic for more details. |
|
1271 | 1271 | """ |
|
1272 | 1272 | self.shell.debugger(force=True) |
|
1273 | 1273 | |
|
1274 | 1274 | @testdec.skip_doctest |
|
1275 | 1275 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1276 | 1276 | opts=None,arg_lst=None,prog_ns=None): |
|
1277 | 1277 | |
|
1278 | 1278 | """Run a statement through the python code profiler. |
|
1279 | 1279 | |
|
1280 | 1280 | Usage: |
|
1281 | 1281 | %prun [options] statement |
|
1282 | 1282 | |
|
1283 | 1283 | The given statement (which doesn't require quote marks) is run via the |
|
1284 | 1284 | python profiler in a manner similar to the profile.run() function. |
|
1285 | 1285 | Namespaces are internally managed to work correctly; profile.run |
|
1286 | 1286 | cannot be used in IPython because it makes certain assumptions about |
|
1287 | 1287 | namespaces which do not hold under IPython. |
|
1288 | 1288 | |
|
1289 | 1289 | Options: |
|
1290 | 1290 | |
|
1291 | 1291 | -l <limit>: you can place restrictions on what or how much of the |
|
1292 | 1292 | profile gets printed. The limit value can be: |
|
1293 | 1293 | |
|
1294 | 1294 | * A string: only information for function names containing this string |
|
1295 | 1295 | is printed. |
|
1296 | 1296 | |
|
1297 | 1297 | * An integer: only these many lines are printed. |
|
1298 | 1298 | |
|
1299 | 1299 | * A float (between 0 and 1): this fraction of the report is printed |
|
1300 | 1300 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1301 | 1301 | |
|
1302 | 1302 | You can combine several limits with repeated use of the option. For |
|
1303 | 1303 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1304 | 1304 | information about class constructors. |
|
1305 | 1305 | |
|
1306 | 1306 | -r: return the pstats.Stats object generated by the profiling. This |
|
1307 | 1307 | object has all the information about the profile in it, and you can |
|
1308 | 1308 | later use it for further analysis or in other functions. |
|
1309 | 1309 | |
|
1310 | 1310 | -s <key>: sort profile by given key. You can provide more than one key |
|
1311 | 1311 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1312 | 1312 | default sorting key is 'time'. |
|
1313 | 1313 | |
|
1314 | 1314 | The following is copied verbatim from the profile documentation |
|
1315 | 1315 | referenced below: |
|
1316 | 1316 | |
|
1317 | 1317 | When more than one key is provided, additional keys are used as |
|
1318 | 1318 | secondary criteria when the there is equality in all keys selected |
|
1319 | 1319 | before them. |
|
1320 | 1320 | |
|
1321 | 1321 | Abbreviations can be used for any key names, as long as the |
|
1322 | 1322 | abbreviation is unambiguous. The following are the keys currently |
|
1323 | 1323 | defined: |
|
1324 | 1324 | |
|
1325 | 1325 | Valid Arg Meaning |
|
1326 | 1326 | "calls" call count |
|
1327 | 1327 | "cumulative" cumulative time |
|
1328 | 1328 | "file" file name |
|
1329 | 1329 | "module" file name |
|
1330 | 1330 | "pcalls" primitive call count |
|
1331 | 1331 | "line" line number |
|
1332 | 1332 | "name" function name |
|
1333 | 1333 | "nfl" name/file/line |
|
1334 | 1334 | "stdname" standard name |
|
1335 | 1335 | "time" internal time |
|
1336 | 1336 | |
|
1337 | 1337 | Note that all sorts on statistics are in descending order (placing |
|
1338 | 1338 | most time consuming items first), where as name, file, and line number |
|
1339 | 1339 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1340 | 1340 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1341 | 1341 | sort of the name as printed, which means that the embedded line |
|
1342 | 1342 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1343 | 1343 | would (if the file names were the same) appear in the string order |
|
1344 | 1344 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1345 | 1345 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1346 | 1346 | sort_stats("name", "file", "line"). |
|
1347 | 1347 | |
|
1348 | 1348 | -T <filename>: save profile results as shown on screen to a text |
|
1349 | 1349 | file. The profile is still shown on screen. |
|
1350 | 1350 | |
|
1351 | 1351 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1352 | 1352 | filename. This data is in a format understod by the pstats module, and |
|
1353 | 1353 | is generated by a call to the dump_stats() method of profile |
|
1354 | 1354 | objects. The profile is still shown on screen. |
|
1355 | 1355 | |
|
1356 | 1356 | If you want to run complete programs under the profiler's control, use |
|
1357 | 1357 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1358 | 1358 | contains profiler specific options as described here. |
|
1359 | 1359 | |
|
1360 | 1360 | You can read the complete documentation for the profile module with:: |
|
1361 | 1361 | |
|
1362 | 1362 | In [1]: import profile; profile.help() |
|
1363 | 1363 | """ |
|
1364 | 1364 | |
|
1365 | 1365 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1366 | 1366 | # protect user quote marks |
|
1367 | 1367 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1368 | 1368 | |
|
1369 | 1369 | if user_mode: # regular user call |
|
1370 | 1370 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1371 | 1371 | list_all=1) |
|
1372 | 1372 | namespace = self.shell.user_ns |
|
1373 | 1373 | else: # called to run a program by %run -p |
|
1374 | 1374 | try: |
|
1375 | 1375 | filename = get_py_filename(arg_lst[0]) |
|
1376 | 1376 | except IOError,msg: |
|
1377 | 1377 | error(msg) |
|
1378 | 1378 | return |
|
1379 | 1379 | |
|
1380 | 1380 | arg_str = 'execfile(filename,prog_ns)' |
|
1381 | 1381 | namespace = locals() |
|
1382 | 1382 | |
|
1383 | 1383 | opts.merge(opts_def) |
|
1384 | 1384 | |
|
1385 | 1385 | prof = profile.Profile() |
|
1386 | 1386 | try: |
|
1387 | 1387 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1388 | 1388 | sys_exit = '' |
|
1389 | 1389 | except SystemExit: |
|
1390 | 1390 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1391 | 1391 | |
|
1392 | 1392 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1393 | 1393 | |
|
1394 | 1394 | lims = opts.l |
|
1395 | 1395 | if lims: |
|
1396 | 1396 | lims = [] # rebuild lims with ints/floats/strings |
|
1397 | 1397 | for lim in opts.l: |
|
1398 | 1398 | try: |
|
1399 | 1399 | lims.append(int(lim)) |
|
1400 | 1400 | except ValueError: |
|
1401 | 1401 | try: |
|
1402 | 1402 | lims.append(float(lim)) |
|
1403 | 1403 | except ValueError: |
|
1404 | 1404 | lims.append(lim) |
|
1405 | 1405 | |
|
1406 | 1406 | # Trap output. |
|
1407 | 1407 | stdout_trap = StringIO() |
|
1408 | 1408 | |
|
1409 | 1409 | if hasattr(stats,'stream'): |
|
1410 | 1410 | # In newer versions of python, the stats object has a 'stream' |
|
1411 | 1411 | # attribute to write into. |
|
1412 | 1412 | stats.stream = stdout_trap |
|
1413 | 1413 | stats.print_stats(*lims) |
|
1414 | 1414 | else: |
|
1415 | 1415 | # For older versions, we manually redirect stdout during printing |
|
1416 | 1416 | sys_stdout = sys.stdout |
|
1417 | 1417 | try: |
|
1418 | 1418 | sys.stdout = stdout_trap |
|
1419 | 1419 | stats.print_stats(*lims) |
|
1420 | 1420 | finally: |
|
1421 | 1421 | sys.stdout = sys_stdout |
|
1422 | 1422 | |
|
1423 | 1423 | output = stdout_trap.getvalue() |
|
1424 | 1424 | output = output.rstrip() |
|
1425 | 1425 | |
|
1426 | 1426 | page(output,screen_lines=self.shell.usable_screen_length) |
|
1427 | 1427 | print sys_exit, |
|
1428 | 1428 | |
|
1429 | 1429 | dump_file = opts.D[0] |
|
1430 | 1430 | text_file = opts.T[0] |
|
1431 | 1431 | if dump_file: |
|
1432 | 1432 | prof.dump_stats(dump_file) |
|
1433 | 1433 | print '\n*** Profile stats marshalled to file',\ |
|
1434 | 1434 | `dump_file`+'.',sys_exit |
|
1435 | 1435 | if text_file: |
|
1436 | 1436 | pfile = file(text_file,'w') |
|
1437 | 1437 | pfile.write(output) |
|
1438 | 1438 | pfile.close() |
|
1439 | 1439 | print '\n*** Profile printout saved to text file',\ |
|
1440 | 1440 | `text_file`+'.',sys_exit |
|
1441 | 1441 | |
|
1442 | 1442 | if opts.has_key('r'): |
|
1443 | 1443 | return stats |
|
1444 | 1444 | else: |
|
1445 | 1445 | return None |
|
1446 | 1446 | |
|
1447 | 1447 | @testdec.skip_doctest |
|
1448 | 1448 | def magic_run(self, parameter_s ='',runner=None, |
|
1449 | 1449 | file_finder=get_py_filename): |
|
1450 | 1450 | """Run the named file inside IPython as a program. |
|
1451 | 1451 | |
|
1452 | 1452 | Usage:\\ |
|
1453 | 1453 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1454 | 1454 | |
|
1455 | 1455 | Parameters after the filename are passed as command-line arguments to |
|
1456 | 1456 | the program (put in sys.argv). Then, control returns to IPython's |
|
1457 | 1457 | prompt. |
|
1458 | 1458 | |
|
1459 | 1459 | This is similar to running at a system prompt:\\ |
|
1460 | 1460 | $ python file args\\ |
|
1461 | 1461 | but with the advantage of giving you IPython's tracebacks, and of |
|
1462 | 1462 | loading all variables into your interactive namespace for further use |
|
1463 | 1463 | (unless -p is used, see below). |
|
1464 | 1464 | |
|
1465 | 1465 | The file is executed in a namespace initially consisting only of |
|
1466 | 1466 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1467 | 1467 | sees its environment as if it were being run as a stand-alone program |
|
1468 | 1468 | (except for sharing global objects such as previously imported |
|
1469 | 1469 | modules). But after execution, the IPython interactive namespace gets |
|
1470 | 1470 | updated with all variables defined in the program (except for __name__ |
|
1471 | 1471 | and sys.argv). This allows for very convenient loading of code for |
|
1472 | 1472 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1473 | 1473 | |
|
1474 | 1474 | Options: |
|
1475 | 1475 | |
|
1476 | 1476 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1477 | 1477 | without extension (as python does under import). This allows running |
|
1478 | 1478 | scripts and reloading the definitions in them without calling code |
|
1479 | 1479 | protected by an ' if __name__ == "__main__" ' clause. |
|
1480 | 1480 | |
|
1481 | 1481 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1482 | 1482 | is useful if you are experimenting with code written in a text editor |
|
1483 | 1483 | which depends on variables defined interactively. |
|
1484 | 1484 | |
|
1485 | 1485 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1486 | 1486 | being run. This is particularly useful if IPython is being used to |
|
1487 | 1487 | run unittests, which always exit with a sys.exit() call. In such |
|
1488 | 1488 | cases you are interested in the output of the test results, not in |
|
1489 | 1489 | seeing a traceback of the unittest module. |
|
1490 | 1490 | |
|
1491 | 1491 | -t: print timing information at the end of the run. IPython will give |
|
1492 | 1492 | you an estimated CPU time consumption for your script, which under |
|
1493 | 1493 | Unix uses the resource module to avoid the wraparound problems of |
|
1494 | 1494 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1495 | 1495 | is also given (for Windows platforms this is reported as 0.0). |
|
1496 | 1496 | |
|
1497 | 1497 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1498 | 1498 | must be an integer indicating how many times you want the script to |
|
1499 | 1499 | run. The final timing report will include total and per run results. |
|
1500 | 1500 | |
|
1501 | 1501 | For example (testing the script uniq_stable.py): |
|
1502 | 1502 | |
|
1503 | 1503 | In [1]: run -t uniq_stable |
|
1504 | 1504 | |
|
1505 | 1505 | IPython CPU timings (estimated):\\ |
|
1506 | 1506 | User : 0.19597 s.\\ |
|
1507 | 1507 | System: 0.0 s.\\ |
|
1508 | 1508 | |
|
1509 | 1509 | In [2]: run -t -N5 uniq_stable |
|
1510 | 1510 | |
|
1511 | 1511 | IPython CPU timings (estimated):\\ |
|
1512 | 1512 | Total runs performed: 5\\ |
|
1513 | 1513 | Times : Total Per run\\ |
|
1514 | 1514 | User : 0.910862 s, 0.1821724 s.\\ |
|
1515 | 1515 | System: 0.0 s, 0.0 s. |
|
1516 | 1516 | |
|
1517 | 1517 | -d: run your program under the control of pdb, the Python debugger. |
|
1518 | 1518 | This allows you to execute your program step by step, watch variables, |
|
1519 | 1519 | etc. Internally, what IPython does is similar to calling: |
|
1520 | 1520 | |
|
1521 | 1521 | pdb.run('execfile("YOURFILENAME")') |
|
1522 | 1522 | |
|
1523 | 1523 | with a breakpoint set on line 1 of your file. You can change the line |
|
1524 | 1524 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1525 | 1525 | (where N must be an integer). For example: |
|
1526 | 1526 | |
|
1527 | 1527 | %run -d -b40 myscript |
|
1528 | 1528 | |
|
1529 | 1529 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1530 | 1530 | the first breakpoint must be set on a line which actually does |
|
1531 | 1531 | something (not a comment or docstring) for it to stop execution. |
|
1532 | 1532 | |
|
1533 | 1533 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1534 | 1534 | first enter 'c' (without qoutes) to start execution up to the first |
|
1535 | 1535 | breakpoint. |
|
1536 | 1536 | |
|
1537 | 1537 | Entering 'help' gives information about the use of the debugger. You |
|
1538 | 1538 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1539 | 1539 | at a prompt. |
|
1540 | 1540 | |
|
1541 | 1541 | -p: run program under the control of the Python profiler module (which |
|
1542 | 1542 | prints a detailed report of execution times, function calls, etc). |
|
1543 | 1543 | |
|
1544 | 1544 | You can pass other options after -p which affect the behavior of the |
|
1545 | 1545 | profiler itself. See the docs for %prun for details. |
|
1546 | 1546 | |
|
1547 | 1547 | In this mode, the program's variables do NOT propagate back to the |
|
1548 | 1548 | IPython interactive namespace (because they remain in the namespace |
|
1549 | 1549 | where the profiler executes them). |
|
1550 | 1550 | |
|
1551 | 1551 | Internally this triggers a call to %prun, see its documentation for |
|
1552 | 1552 | details on the options available specifically for profiling. |
|
1553 | 1553 | |
|
1554 | 1554 | There is one special usage for which the text above doesn't apply: |
|
1555 | 1555 | if the filename ends with .ipy, the file is run as ipython script, |
|
1556 | 1556 | just as if the commands were written on IPython prompt. |
|
1557 | 1557 | """ |
|
1558 | 1558 | |
|
1559 | 1559 | # get arguments and set sys.argv for program to be run. |
|
1560 | 1560 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1561 | 1561 | mode='list',list_all=1) |
|
1562 | 1562 | |
|
1563 | 1563 | try: |
|
1564 | 1564 | filename = file_finder(arg_lst[0]) |
|
1565 | 1565 | except IndexError: |
|
1566 | 1566 | warn('you must provide at least a filename.') |
|
1567 | 1567 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1568 | 1568 | return |
|
1569 | 1569 | except IOError,msg: |
|
1570 | 1570 | error(msg) |
|
1571 | 1571 | return |
|
1572 | 1572 | |
|
1573 | 1573 | if filename.lower().endswith('.ipy'): |
|
1574 | 1574 | self.safe_execfile_ipy(filename) |
|
1575 | 1575 | return |
|
1576 | 1576 | |
|
1577 | 1577 | # Control the response to exit() calls made by the script being run |
|
1578 | 1578 | exit_ignore = opts.has_key('e') |
|
1579 | 1579 | |
|
1580 | 1580 | # Make sure that the running script gets a proper sys.argv as if it |
|
1581 | 1581 | # were run from a system shell. |
|
1582 | 1582 | save_argv = sys.argv # save it for later restoring |
|
1583 | 1583 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1584 | 1584 | |
|
1585 | 1585 | if opts.has_key('i'): |
|
1586 | 1586 | # Run in user's interactive namespace |
|
1587 | 1587 | prog_ns = self.shell.user_ns |
|
1588 | 1588 | __name__save = self.shell.user_ns['__name__'] |
|
1589 | 1589 | prog_ns['__name__'] = '__main__' |
|
1590 | 1590 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1591 | 1591 | else: |
|
1592 | 1592 | # Run in a fresh, empty namespace |
|
1593 | 1593 | if opts.has_key('n'): |
|
1594 | 1594 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1595 | 1595 | else: |
|
1596 | 1596 | name = '__main__' |
|
1597 | 1597 | |
|
1598 | 1598 | main_mod = self.shell.new_main_mod() |
|
1599 | 1599 | prog_ns = main_mod.__dict__ |
|
1600 | 1600 | prog_ns['__name__'] = name |
|
1601 | 1601 | |
|
1602 | 1602 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1603 | 1603 | # set the __file__ global in the script's namespace |
|
1604 | 1604 | prog_ns['__file__'] = filename |
|
1605 | 1605 | |
|
1606 | 1606 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1607 | 1607 | # that, if we overwrite __main__, we replace it at the end |
|
1608 | 1608 | main_mod_name = prog_ns['__name__'] |
|
1609 | 1609 | |
|
1610 | 1610 | if main_mod_name == '__main__': |
|
1611 | 1611 | restore_main = sys.modules['__main__'] |
|
1612 | 1612 | else: |
|
1613 | 1613 | restore_main = False |
|
1614 | 1614 | |
|
1615 | 1615 | # This needs to be undone at the end to prevent holding references to |
|
1616 | 1616 | # every single object ever created. |
|
1617 | 1617 | sys.modules[main_mod_name] = main_mod |
|
1618 | 1618 | |
|
1619 | 1619 | stats = None |
|
1620 | 1620 | try: |
|
1621 | 1621 | self.shell.savehist() |
|
1622 | 1622 | |
|
1623 | 1623 | if opts.has_key('p'): |
|
1624 | 1624 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1625 | 1625 | else: |
|
1626 | 1626 | if opts.has_key('d'): |
|
1627 | 1627 | deb = debugger.Pdb(self.shell.colors) |
|
1628 | 1628 | # reset Breakpoint state, which is moronically kept |
|
1629 | 1629 | # in a class |
|
1630 | 1630 | bdb.Breakpoint.next = 1 |
|
1631 | 1631 | bdb.Breakpoint.bplist = {} |
|
1632 | 1632 | bdb.Breakpoint.bpbynumber = [None] |
|
1633 | 1633 | # Set an initial breakpoint to stop execution |
|
1634 | 1634 | maxtries = 10 |
|
1635 | 1635 | bp = int(opts.get('b',[1])[0]) |
|
1636 | 1636 | checkline = deb.checkline(filename,bp) |
|
1637 | 1637 | if not checkline: |
|
1638 | 1638 | for bp in range(bp+1,bp+maxtries+1): |
|
1639 | 1639 | if deb.checkline(filename,bp): |
|
1640 | 1640 | break |
|
1641 | 1641 | else: |
|
1642 | 1642 | msg = ("\nI failed to find a valid line to set " |
|
1643 | 1643 | "a breakpoint\n" |
|
1644 | 1644 | "after trying up to line: %s.\n" |
|
1645 | 1645 | "Please set a valid breakpoint manually " |
|
1646 | 1646 | "with the -b option." % bp) |
|
1647 | 1647 | error(msg) |
|
1648 | 1648 | return |
|
1649 | 1649 | # if we find a good linenumber, set the breakpoint |
|
1650 | 1650 | deb.do_break('%s:%s' % (filename,bp)) |
|
1651 | 1651 | # Start file run |
|
1652 | 1652 | print "NOTE: Enter 'c' at the", |
|
1653 | 1653 | print "%s prompt to start your script." % deb.prompt |
|
1654 | 1654 | try: |
|
1655 | 1655 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1656 | 1656 | |
|
1657 | 1657 | except: |
|
1658 | 1658 | etype, value, tb = sys.exc_info() |
|
1659 | 1659 | # Skip three frames in the traceback: the %run one, |
|
1660 | 1660 | # one inside bdb.py, and the command-line typed by the |
|
1661 | 1661 | # user (run by exec in pdb itself). |
|
1662 | 1662 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1663 | 1663 | else: |
|
1664 | 1664 | if runner is None: |
|
1665 | 1665 | runner = self.shell.safe_execfile |
|
1666 | 1666 | if opts.has_key('t'): |
|
1667 | 1667 | # timed execution |
|
1668 | 1668 | try: |
|
1669 | 1669 | nruns = int(opts['N'][0]) |
|
1670 | 1670 | if nruns < 1: |
|
1671 | 1671 | error('Number of runs must be >=1') |
|
1672 | 1672 | return |
|
1673 | 1673 | except (KeyError): |
|
1674 | 1674 | nruns = 1 |
|
1675 | 1675 | if nruns == 1: |
|
1676 | 1676 | t0 = clock2() |
|
1677 | 1677 | runner(filename,prog_ns,prog_ns, |
|
1678 | 1678 | exit_ignore=exit_ignore) |
|
1679 | 1679 | t1 = clock2() |
|
1680 | 1680 | t_usr = t1[0]-t0[0] |
|
1681 | 1681 | t_sys = t1[1]-t0[1] |
|
1682 | 1682 | print "\nIPython CPU timings (estimated):" |
|
1683 | 1683 | print " User : %10s s." % t_usr |
|
1684 | 1684 | print " System: %10s s." % t_sys |
|
1685 | 1685 | else: |
|
1686 | 1686 | runs = range(nruns) |
|
1687 | 1687 | t0 = clock2() |
|
1688 | 1688 | for nr in runs: |
|
1689 | 1689 | runner(filename,prog_ns,prog_ns, |
|
1690 | 1690 | exit_ignore=exit_ignore) |
|
1691 | 1691 | t1 = clock2() |
|
1692 | 1692 | t_usr = t1[0]-t0[0] |
|
1693 | 1693 | t_sys = t1[1]-t0[1] |
|
1694 | 1694 | print "\nIPython CPU timings (estimated):" |
|
1695 | 1695 | print "Total runs performed:",nruns |
|
1696 | 1696 | print " Times : %10s %10s" % ('Total','Per run') |
|
1697 | 1697 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1698 | 1698 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1699 | 1699 | |
|
1700 | 1700 | else: |
|
1701 | 1701 | # regular execution |
|
1702 | 1702 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1703 | 1703 | |
|
1704 | 1704 | if opts.has_key('i'): |
|
1705 | 1705 | self.shell.user_ns['__name__'] = __name__save |
|
1706 | 1706 | else: |
|
1707 | 1707 | # The shell MUST hold a reference to prog_ns so after %run |
|
1708 | 1708 | # exits, the python deletion mechanism doesn't zero it out |
|
1709 | 1709 | # (leaving dangling references). |
|
1710 | 1710 | self.shell.cache_main_mod(prog_ns,filename) |
|
1711 | 1711 | # update IPython interactive namespace |
|
1712 | 1712 | |
|
1713 | 1713 | # Some forms of read errors on the file may mean the |
|
1714 | 1714 | # __name__ key was never set; using pop we don't have to |
|
1715 | 1715 | # worry about a possible KeyError. |
|
1716 | 1716 | prog_ns.pop('__name__', None) |
|
1717 | 1717 | |
|
1718 | 1718 | self.shell.user_ns.update(prog_ns) |
|
1719 | 1719 | finally: |
|
1720 | 1720 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1721 | 1721 | # being a module to becoming a dict missing some key data after |
|
1722 | 1722 | # %run. As best I can see, this is NOT something IPython is doing |
|
1723 | 1723 | # at all, and similar problems have been reported before: |
|
1724 | 1724 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1725 | 1725 | # Since this seems to be done by the interpreter itself, the best |
|
1726 | 1726 | # we can do is to at least restore __builtins__ for the user on |
|
1727 | 1727 | # exit. |
|
1728 | 1728 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1729 | 1729 | |
|
1730 | 1730 | # Ensure key global structures are restored |
|
1731 | 1731 | sys.argv = save_argv |
|
1732 | 1732 | if restore_main: |
|
1733 | 1733 | sys.modules['__main__'] = restore_main |
|
1734 | 1734 | else: |
|
1735 | 1735 | # Remove from sys.modules the reference to main_mod we'd |
|
1736 | 1736 | # added. Otherwise it will trap references to objects |
|
1737 | 1737 | # contained therein. |
|
1738 | 1738 | del sys.modules[main_mod_name] |
|
1739 | 1739 | |
|
1740 | 1740 | self.shell.reloadhist() |
|
1741 | 1741 | |
|
1742 | 1742 | return stats |
|
1743 | 1743 | |
|
1744 | 1744 | @testdec.skip_doctest |
|
1745 | 1745 | def magic_timeit(self, parameter_s =''): |
|
1746 | 1746 | """Time execution of a Python statement or expression |
|
1747 | 1747 | |
|
1748 | 1748 | Usage:\\ |
|
1749 | 1749 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1750 | 1750 | |
|
1751 | 1751 | Time execution of a Python statement or expression using the timeit |
|
1752 | 1752 | module. |
|
1753 | 1753 | |
|
1754 | 1754 | Options: |
|
1755 | 1755 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1756 | 1756 | is not given, a fitting value is chosen. |
|
1757 | 1757 | |
|
1758 | 1758 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1759 | 1759 | Default: 3 |
|
1760 | 1760 | |
|
1761 | 1761 | -t: use time.time to measure the time, which is the default on Unix. |
|
1762 | 1762 | This function measures wall time. |
|
1763 | 1763 | |
|
1764 | 1764 | -c: use time.clock to measure the time, which is the default on |
|
1765 | 1765 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1766 | 1766 | instead and returns the CPU user time. |
|
1767 | 1767 | |
|
1768 | 1768 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1769 | 1769 | Default: 3 |
|
1770 | 1770 | |
|
1771 | 1771 | |
|
1772 | 1772 | Examples: |
|
1773 | 1773 | |
|
1774 | 1774 | In [1]: %timeit pass |
|
1775 | 1775 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1776 | 1776 | |
|
1777 | 1777 | In [2]: u = None |
|
1778 | 1778 | |
|
1779 | 1779 | In [3]: %timeit u is None |
|
1780 | 1780 | 10000000 loops, best of 3: 184 ns per loop |
|
1781 | 1781 | |
|
1782 | 1782 | In [4]: %timeit -r 4 u == None |
|
1783 | 1783 | 1000000 loops, best of 4: 242 ns per loop |
|
1784 | 1784 | |
|
1785 | 1785 | In [5]: import time |
|
1786 | 1786 | |
|
1787 | 1787 | In [6]: %timeit -n1 time.sleep(2) |
|
1788 | 1788 | 1 loops, best of 3: 2 s per loop |
|
1789 | 1789 | |
|
1790 | 1790 | |
|
1791 | 1791 | The times reported by %timeit will be slightly higher than those |
|
1792 | 1792 | reported by the timeit.py script when variables are accessed. This is |
|
1793 | 1793 | due to the fact that %timeit executes the statement in the namespace |
|
1794 | 1794 | of the shell, compared with timeit.py, which uses a single setup |
|
1795 | 1795 | statement to import function or create variables. Generally, the bias |
|
1796 | 1796 | does not matter as long as results from timeit.py are not mixed with |
|
1797 | 1797 | those from %timeit.""" |
|
1798 | 1798 | |
|
1799 | 1799 | import timeit |
|
1800 | 1800 | import math |
|
1801 | 1801 | |
|
1802 | 1802 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1803 | 1803 | # certain terminals. Until we figure out a robust way of |
|
1804 | 1804 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1805 | 1805 | # microseconds. I am really NOT happy about disabling the proper |
|
1806 | 1806 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1807 | 1807 | # right solution for this is, I'm all ears... |
|
1808 | 1808 | # |
|
1809 | 1809 | # Note: using |
|
1810 | 1810 | # |
|
1811 | 1811 | # s = u'\xb5' |
|
1812 | 1812 | # s.encode(sys.getdefaultencoding()) |
|
1813 | 1813 | # |
|
1814 | 1814 | # is not sufficient, as I've seen terminals where that fails but |
|
1815 | 1815 | # print s |
|
1816 | 1816 | # |
|
1817 | 1817 | # succeeds |
|
1818 | 1818 | # |
|
1819 | 1819 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1820 | 1820 | |
|
1821 | 1821 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1822 | 1822 | units = [u"s", u"ms",u'us',"ns"] |
|
1823 | 1823 | |
|
1824 | 1824 | scaling = [1, 1e3, 1e6, 1e9] |
|
1825 | 1825 | |
|
1826 | 1826 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1827 | 1827 | posix=False) |
|
1828 | 1828 | if stmt == "": |
|
1829 | 1829 | return |
|
1830 | 1830 | timefunc = timeit.default_timer |
|
1831 | 1831 | number = int(getattr(opts, "n", 0)) |
|
1832 | 1832 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1833 | 1833 | precision = int(getattr(opts, "p", 3)) |
|
1834 | 1834 | if hasattr(opts, "t"): |
|
1835 | 1835 | timefunc = time.time |
|
1836 | 1836 | if hasattr(opts, "c"): |
|
1837 | 1837 | timefunc = clock |
|
1838 | 1838 | |
|
1839 | 1839 | timer = timeit.Timer(timer=timefunc) |
|
1840 | 1840 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1841 | 1841 | # but is there a better way to achieve that the code stmt has access |
|
1842 | 1842 | # to the shell namespace? |
|
1843 | 1843 | |
|
1844 | 1844 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1845 | 1845 | 'setup': "pass"} |
|
1846 | 1846 | # Track compilation time so it can be reported if too long |
|
1847 | 1847 | # Minimum time above which compilation time will be reported |
|
1848 | 1848 | tc_min = 0.1 |
|
1849 | 1849 | |
|
1850 | 1850 | t0 = clock() |
|
1851 | 1851 | code = compile(src, "<magic-timeit>", "exec") |
|
1852 | 1852 | tc = clock()-t0 |
|
1853 | 1853 | |
|
1854 | 1854 | ns = {} |
|
1855 | 1855 | exec code in self.shell.user_ns, ns |
|
1856 | 1856 | timer.inner = ns["inner"] |
|
1857 | 1857 | |
|
1858 | 1858 | if number == 0: |
|
1859 | 1859 | # determine number so that 0.2 <= total time < 2.0 |
|
1860 | 1860 | number = 1 |
|
1861 | 1861 | for i in range(1, 10): |
|
1862 | 1862 | if timer.timeit(number) >= 0.2: |
|
1863 | 1863 | break |
|
1864 | 1864 | number *= 10 |
|
1865 | 1865 | |
|
1866 | 1866 | best = min(timer.repeat(repeat, number)) / number |
|
1867 | 1867 | |
|
1868 | 1868 | if best > 0.0: |
|
1869 | 1869 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1870 | 1870 | else: |
|
1871 | 1871 | order = 3 |
|
1872 | 1872 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1873 | 1873 | precision, |
|
1874 | 1874 | best * scaling[order], |
|
1875 | 1875 | units[order]) |
|
1876 | 1876 | if tc > tc_min: |
|
1877 | 1877 | print "Compiler time: %.2f s" % tc |
|
1878 | 1878 | |
|
1879 | 1879 | @testdec.skip_doctest |
|
1880 | 1880 | def magic_time(self,parameter_s = ''): |
|
1881 | 1881 | """Time execution of a Python statement or expression. |
|
1882 | 1882 | |
|
1883 | 1883 | The CPU and wall clock times are printed, and the value of the |
|
1884 | 1884 | expression (if any) is returned. Note that under Win32, system time |
|
1885 | 1885 | is always reported as 0, since it can not be measured. |
|
1886 | 1886 | |
|
1887 | 1887 | This function provides very basic timing functionality. In Python |
|
1888 | 1888 | 2.3, the timeit module offers more control and sophistication, so this |
|
1889 | 1889 | could be rewritten to use it (patches welcome). |
|
1890 | 1890 | |
|
1891 | 1891 | Some examples: |
|
1892 | 1892 | |
|
1893 | 1893 | In [1]: time 2**128 |
|
1894 | 1894 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1895 | 1895 | Wall time: 0.00 |
|
1896 | 1896 | Out[1]: 340282366920938463463374607431768211456L |
|
1897 | 1897 | |
|
1898 | 1898 | In [2]: n = 1000000 |
|
1899 | 1899 | |
|
1900 | 1900 | In [3]: time sum(range(n)) |
|
1901 | 1901 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1902 | 1902 | Wall time: 1.37 |
|
1903 | 1903 | Out[3]: 499999500000L |
|
1904 | 1904 | |
|
1905 | 1905 | In [4]: time print 'hello world' |
|
1906 | 1906 | hello world |
|
1907 | 1907 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1908 | 1908 | Wall time: 0.00 |
|
1909 | 1909 | |
|
1910 | 1910 | Note that the time needed by Python to compile the given expression |
|
1911 | 1911 | will be reported if it is more than 0.1s. In this example, the |
|
1912 | 1912 | actual exponentiation is done by Python at compilation time, so while |
|
1913 | 1913 | the expression can take a noticeable amount of time to compute, that |
|
1914 | 1914 | time is purely due to the compilation: |
|
1915 | 1915 | |
|
1916 | 1916 | In [5]: time 3**9999; |
|
1917 | 1917 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1918 | 1918 | Wall time: 0.00 s |
|
1919 | 1919 | |
|
1920 | 1920 | In [6]: time 3**999999; |
|
1921 | 1921 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1922 | 1922 | Wall time: 0.00 s |
|
1923 | 1923 | Compiler : 0.78 s |
|
1924 | 1924 | """ |
|
1925 | 1925 | |
|
1926 | 1926 | # fail immediately if the given expression can't be compiled |
|
1927 | 1927 | |
|
1928 | 1928 | expr = self.shell.prefilter(parameter_s,False) |
|
1929 | 1929 | |
|
1930 | 1930 | # Minimum time above which compilation time will be reported |
|
1931 | 1931 | tc_min = 0.1 |
|
1932 | 1932 | |
|
1933 | 1933 | try: |
|
1934 | 1934 | mode = 'eval' |
|
1935 | 1935 | t0 = clock() |
|
1936 | 1936 | code = compile(expr,'<timed eval>',mode) |
|
1937 | 1937 | tc = clock()-t0 |
|
1938 | 1938 | except SyntaxError: |
|
1939 | 1939 | mode = 'exec' |
|
1940 | 1940 | t0 = clock() |
|
1941 | 1941 | code = compile(expr,'<timed exec>',mode) |
|
1942 | 1942 | tc = clock()-t0 |
|
1943 | 1943 | # skew measurement as little as possible |
|
1944 | 1944 | glob = self.shell.user_ns |
|
1945 | 1945 | clk = clock2 |
|
1946 | 1946 | wtime = time.time |
|
1947 | 1947 | # time execution |
|
1948 | 1948 | wall_st = wtime() |
|
1949 | 1949 | if mode=='eval': |
|
1950 | 1950 | st = clk() |
|
1951 | 1951 | out = eval(code,glob) |
|
1952 | 1952 | end = clk() |
|
1953 | 1953 | else: |
|
1954 | 1954 | st = clk() |
|
1955 | 1955 | exec code in glob |
|
1956 | 1956 | end = clk() |
|
1957 | 1957 | out = None |
|
1958 | 1958 | wall_end = wtime() |
|
1959 | 1959 | # Compute actual times and report |
|
1960 | 1960 | wall_time = wall_end-wall_st |
|
1961 | 1961 | cpu_user = end[0]-st[0] |
|
1962 | 1962 | cpu_sys = end[1]-st[1] |
|
1963 | 1963 | cpu_tot = cpu_user+cpu_sys |
|
1964 | 1964 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1965 | 1965 | (cpu_user,cpu_sys,cpu_tot) |
|
1966 | 1966 | print "Wall time: %.2f s" % wall_time |
|
1967 | 1967 | if tc > tc_min: |
|
1968 | 1968 | print "Compiler : %.2f s" % tc |
|
1969 | 1969 | return out |
|
1970 | 1970 | |
|
1971 | 1971 | @testdec.skip_doctest |
|
1972 | 1972 | def magic_macro(self,parameter_s = ''): |
|
1973 | 1973 | """Define a set of input lines as a macro for future re-execution. |
|
1974 | 1974 | |
|
1975 | 1975 | Usage:\\ |
|
1976 | 1976 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1977 | 1977 | |
|
1978 | 1978 | Options: |
|
1979 | 1979 | |
|
1980 | 1980 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1981 | 1981 | so that magics are loaded in their transformed version to valid |
|
1982 | 1982 | Python. If this option is given, the raw input as typed as the |
|
1983 | 1983 | command line is used instead. |
|
1984 | 1984 | |
|
1985 | 1985 | This will define a global variable called `name` which is a string |
|
1986 | 1986 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1987 | 1987 | above) from your input history into a single string. This variable |
|
1988 | 1988 | acts like an automatic function which re-executes those lines as if |
|
1989 | 1989 | you had typed them. You just type 'name' at the prompt and the code |
|
1990 | 1990 | executes. |
|
1991 | 1991 | |
|
1992 | 1992 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1993 | 1993 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1994 | 1994 | using the lines numbered 5,6 and 7. |
|
1995 | 1995 | |
|
1996 | 1996 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1997 | 1997 | notation, where N:M means numbers N through M-1. |
|
1998 | 1998 | |
|
1999 | 1999 | For example, if your history contains (%hist prints it): |
|
2000 | 2000 | |
|
2001 | 2001 | 44: x=1 |
|
2002 | 2002 | 45: y=3 |
|
2003 | 2003 | 46: z=x+y |
|
2004 | 2004 | 47: print x |
|
2005 | 2005 | 48: a=5 |
|
2006 | 2006 | 49: print 'x',x,'y',y |
|
2007 | 2007 | |
|
2008 | 2008 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2009 | 2009 | called my_macro with: |
|
2010 | 2010 | |
|
2011 | 2011 | In [55]: %macro my_macro 44-47 49 |
|
2012 | 2012 | |
|
2013 | 2013 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2014 | 2014 | in one pass. |
|
2015 | 2015 | |
|
2016 | 2016 | You don't need to give the line-numbers in order, and any given line |
|
2017 | 2017 | number can appear multiple times. You can assemble macros with any |
|
2018 | 2018 | lines from your input history in any order. |
|
2019 | 2019 | |
|
2020 | 2020 | The macro is a simple object which holds its value in an attribute, |
|
2021 | 2021 | but IPython's display system checks for macros and executes them as |
|
2022 | 2022 | code instead of printing them when you type their name. |
|
2023 | 2023 | |
|
2024 | 2024 | You can view a macro's contents by explicitly printing it with: |
|
2025 | 2025 | |
|
2026 | 2026 | 'print macro_name'. |
|
2027 | 2027 | |
|
2028 | 2028 | For one-off cases which DON'T contain magic function calls in them you |
|
2029 | 2029 | can obtain similar results by explicitly executing slices from your |
|
2030 | 2030 | input history with: |
|
2031 | 2031 | |
|
2032 | 2032 | In [60]: exec In[44:48]+In[49]""" |
|
2033 | 2033 | |
|
2034 | 2034 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2035 | 2035 | if not args: |
|
2036 | 2036 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2037 | 2037 | macs.sort() |
|
2038 | 2038 | return macs |
|
2039 | 2039 | if len(args) == 1: |
|
2040 | 2040 | raise UsageError( |
|
2041 | 2041 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2042 | 2042 | name,ranges = args[0], args[1:] |
|
2043 | 2043 | |
|
2044 | 2044 | #print 'rng',ranges # dbg |
|
2045 | 2045 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2046 | 2046 | macro = Macro(lines) |
|
2047 | 2047 | self.shell.define_macro(name, macro) |
|
2048 | 2048 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2049 | 2049 | print 'Macro contents:' |
|
2050 | 2050 | print macro, |
|
2051 | 2051 | |
|
2052 | 2052 | def magic_save(self,parameter_s = ''): |
|
2053 | 2053 | """Save a set of lines to a given filename. |
|
2054 | 2054 | |
|
2055 | 2055 | Usage:\\ |
|
2056 | 2056 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2057 | 2057 | |
|
2058 | 2058 | Options: |
|
2059 | 2059 | |
|
2060 | 2060 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2061 | 2061 | so that magics are loaded in their transformed version to valid |
|
2062 | 2062 | Python. If this option is given, the raw input as typed as the |
|
2063 | 2063 | command line is used instead. |
|
2064 | 2064 | |
|
2065 | 2065 | This function uses the same syntax as %macro for line extraction, but |
|
2066 | 2066 | instead of creating a macro it saves the resulting string to the |
|
2067 | 2067 | filename you specify. |
|
2068 | 2068 | |
|
2069 | 2069 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2070 | 2070 | it asks for confirmation before overwriting existing files.""" |
|
2071 | 2071 | |
|
2072 | 2072 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2073 | 2073 | fname,ranges = args[0], args[1:] |
|
2074 | 2074 | if not fname.endswith('.py'): |
|
2075 | 2075 | fname += '.py' |
|
2076 | 2076 | if os.path.isfile(fname): |
|
2077 | 2077 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2078 | 2078 | if ans.lower() not in ['y','yes']: |
|
2079 | 2079 | print 'Operation cancelled.' |
|
2080 | 2080 | return |
|
2081 | 2081 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2082 | 2082 | f = file(fname,'w') |
|
2083 | 2083 | f.write(cmds) |
|
2084 | 2084 | f.close() |
|
2085 | 2085 | print 'The following commands were written to file `%s`:' % fname |
|
2086 | 2086 | print cmds |
|
2087 | 2087 | |
|
2088 | 2088 | def _edit_macro(self,mname,macro): |
|
2089 | 2089 | """open an editor with the macro data in a file""" |
|
2090 | 2090 | filename = self.shell.mktempfile(macro.value) |
|
2091 | 2091 | self.shell.hooks.editor(filename) |
|
2092 | 2092 | |
|
2093 | 2093 | # and make a new macro object, to replace the old one |
|
2094 | 2094 | mfile = open(filename) |
|
2095 | 2095 | mvalue = mfile.read() |
|
2096 | 2096 | mfile.close() |
|
2097 | 2097 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2098 | 2098 | |
|
2099 | 2099 | def magic_ed(self,parameter_s=''): |
|
2100 | 2100 | """Alias to %edit.""" |
|
2101 | 2101 | return self.magic_edit(parameter_s) |
|
2102 | 2102 | |
|
2103 | 2103 | @testdec.skip_doctest |
|
2104 | 2104 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2105 | 2105 | """Bring up an editor and execute the resulting code. |
|
2106 | 2106 | |
|
2107 | 2107 | Usage: |
|
2108 | 2108 | %edit [options] [args] |
|
2109 | 2109 | |
|
2110 | 2110 | %edit runs IPython's editor hook. The default version of this hook is |
|
2111 | 2111 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2112 | 2112 | environment variable $EDITOR. If this isn't found, it will default to |
|
2113 | 2113 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2114 | 2114 | docstring for how to change the editor hook. |
|
2115 | 2115 | |
|
2116 | 2116 | You can also set the value of this editor via the command line option |
|
2117 | 2117 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2118 | 2118 | specifically for IPython an editor different from your typical default |
|
2119 | 2119 | (and for Windows users who typically don't set environment variables). |
|
2120 | 2120 | |
|
2121 | 2121 | This command allows you to conveniently edit multi-line code right in |
|
2122 | 2122 | your IPython session. |
|
2123 | 2123 | |
|
2124 | 2124 | If called without arguments, %edit opens up an empty editor with a |
|
2125 | 2125 | temporary file and will execute the contents of this file when you |
|
2126 | 2126 | close it (don't forget to save it!). |
|
2127 | 2127 | |
|
2128 | 2128 | |
|
2129 | 2129 | Options: |
|
2130 | 2130 | |
|
2131 | 2131 | -n <number>: open the editor at a specified line number. By default, |
|
2132 | 2132 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2133 | 2133 | you can configure this by providing your own modified hook if your |
|
2134 | 2134 | favorite editor supports line-number specifications with a different |
|
2135 | 2135 | syntax. |
|
2136 | 2136 | |
|
2137 | 2137 | -p: this will call the editor with the same data as the previous time |
|
2138 | 2138 | it was used, regardless of how long ago (in your current session) it |
|
2139 | 2139 | was. |
|
2140 | 2140 | |
|
2141 | 2141 | -r: use 'raw' input. This option only applies to input taken from the |
|
2142 | 2142 | user's history. By default, the 'processed' history is used, so that |
|
2143 | 2143 | magics are loaded in their transformed version to valid Python. If |
|
2144 | 2144 | this option is given, the raw input as typed as the command line is |
|
2145 | 2145 | used instead. When you exit the editor, it will be executed by |
|
2146 | 2146 | IPython's own processor. |
|
2147 | 2147 | |
|
2148 | 2148 | -x: do not execute the edited code immediately upon exit. This is |
|
2149 | 2149 | mainly useful if you are editing programs which need to be called with |
|
2150 | 2150 | command line arguments, which you can then do using %run. |
|
2151 | 2151 | |
|
2152 | 2152 | |
|
2153 | 2153 | Arguments: |
|
2154 | 2154 | |
|
2155 | 2155 | If arguments are given, the following possibilites exist: |
|
2156 | 2156 | |
|
2157 | 2157 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2158 | 2158 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2159 | 2159 | loaded into the editor. The syntax is the same of the %macro command. |
|
2160 | 2160 | |
|
2161 | 2161 | - If the argument doesn't start with a number, it is evaluated as a |
|
2162 | 2162 | variable and its contents loaded into the editor. You can thus edit |
|
2163 | 2163 | any string which contains python code (including the result of |
|
2164 | 2164 | previous edits). |
|
2165 | 2165 | |
|
2166 | 2166 | - If the argument is the name of an object (other than a string), |
|
2167 | 2167 | IPython will try to locate the file where it was defined and open the |
|
2168 | 2168 | editor at the point where it is defined. You can use `%edit function` |
|
2169 | 2169 | to load an editor exactly at the point where 'function' is defined, |
|
2170 | 2170 | edit it and have the file be executed automatically. |
|
2171 | 2171 | |
|
2172 | 2172 | If the object is a macro (see %macro for details), this opens up your |
|
2173 | 2173 | specified editor with a temporary file containing the macro's data. |
|
2174 | 2174 | Upon exit, the macro is reloaded with the contents of the file. |
|
2175 | 2175 | |
|
2176 | 2176 | Note: opening at an exact line is only supported under Unix, and some |
|
2177 | 2177 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2178 | 2178 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2179 | 2179 | (X)Emacs, vi, jed, pico and joe all do. |
|
2180 | 2180 | |
|
2181 | 2181 | - If the argument is not found as a variable, IPython will look for a |
|
2182 | 2182 | file with that name (adding .py if necessary) and load it into the |
|
2183 | 2183 | editor. It will execute its contents with execfile() when you exit, |
|
2184 | 2184 | loading any code in the file into your interactive namespace. |
|
2185 | 2185 | |
|
2186 | 2186 | After executing your code, %edit will return as output the code you |
|
2187 | 2187 | typed in the editor (except when it was an existing file). This way |
|
2188 | 2188 | you can reload the code in further invocations of %edit as a variable, |
|
2189 | 2189 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2190 | 2190 | the output. |
|
2191 | 2191 | |
|
2192 | 2192 | Note that %edit is also available through the alias %ed. |
|
2193 | 2193 | |
|
2194 | 2194 | This is an example of creating a simple function inside the editor and |
|
2195 | 2195 | then modifying it. First, start up the editor: |
|
2196 | 2196 | |
|
2197 | 2197 | In [1]: ed |
|
2198 | 2198 | Editing... done. Executing edited code... |
|
2199 | 2199 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2200 | 2200 | |
|
2201 | 2201 | We can then call the function foo(): |
|
2202 | 2202 | |
|
2203 | 2203 | In [2]: foo() |
|
2204 | 2204 | foo() was defined in an editing session |
|
2205 | 2205 | |
|
2206 | 2206 | Now we edit foo. IPython automatically loads the editor with the |
|
2207 | 2207 | (temporary) file where foo() was previously defined: |
|
2208 | 2208 | |
|
2209 | 2209 | In [3]: ed foo |
|
2210 | 2210 | Editing... done. Executing edited code... |
|
2211 | 2211 | |
|
2212 | 2212 | And if we call foo() again we get the modified version: |
|
2213 | 2213 | |
|
2214 | 2214 | In [4]: foo() |
|
2215 | 2215 | foo() has now been changed! |
|
2216 | 2216 | |
|
2217 | 2217 | Here is an example of how to edit a code snippet successive |
|
2218 | 2218 | times. First we call the editor: |
|
2219 | 2219 | |
|
2220 | 2220 | In [5]: ed |
|
2221 | 2221 | Editing... done. Executing edited code... |
|
2222 | 2222 | hello |
|
2223 | 2223 | Out[5]: "print 'hello'n" |
|
2224 | 2224 | |
|
2225 | 2225 | Now we call it again with the previous output (stored in _): |
|
2226 | 2226 | |
|
2227 | 2227 | In [6]: ed _ |
|
2228 | 2228 | Editing... done. Executing edited code... |
|
2229 | 2229 | hello world |
|
2230 | 2230 | Out[6]: "print 'hello world'n" |
|
2231 | 2231 | |
|
2232 | 2232 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2233 | 2233 | |
|
2234 | 2234 | In [7]: ed _8 |
|
2235 | 2235 | Editing... done. Executing edited code... |
|
2236 | 2236 | hello again |
|
2237 | 2237 | Out[7]: "print 'hello again'n" |
|
2238 | 2238 | |
|
2239 | 2239 | |
|
2240 | 2240 | Changing the default editor hook: |
|
2241 | 2241 | |
|
2242 | 2242 | If you wish to write your own editor hook, you can put it in a |
|
2243 | 2243 | configuration file which you load at startup time. The default hook |
|
2244 | 2244 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2245 | 2245 | starting example for further modifications. That file also has |
|
2246 | 2246 | general instructions on how to set a new hook for use once you've |
|
2247 | 2247 | defined it.""" |
|
2248 | 2248 | |
|
2249 | 2249 | # FIXME: This function has become a convoluted mess. It needs a |
|
2250 | 2250 | # ground-up rewrite with clean, simple logic. |
|
2251 | 2251 | |
|
2252 | 2252 | def make_filename(arg): |
|
2253 | 2253 | "Make a filename from the given args" |
|
2254 | 2254 | try: |
|
2255 | 2255 | filename = get_py_filename(arg) |
|
2256 | 2256 | except IOError: |
|
2257 | 2257 | if args.endswith('.py'): |
|
2258 | 2258 | filename = arg |
|
2259 | 2259 | else: |
|
2260 | 2260 | filename = None |
|
2261 | 2261 | return filename |
|
2262 | 2262 | |
|
2263 | 2263 | # custom exceptions |
|
2264 | 2264 | class DataIsObject(Exception): pass |
|
2265 | 2265 | |
|
2266 | 2266 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2267 | 2267 | # Set a few locals from the options for convenience: |
|
2268 | 2268 | opts_p = opts.has_key('p') |
|
2269 | 2269 | opts_r = opts.has_key('r') |
|
2270 | 2270 | |
|
2271 | 2271 | # Default line number value |
|
2272 | 2272 | lineno = opts.get('n',None) |
|
2273 | 2273 | |
|
2274 | 2274 | if opts_p: |
|
2275 | 2275 | args = '_%s' % last_call[0] |
|
2276 | 2276 | if not self.shell.user_ns.has_key(args): |
|
2277 | 2277 | args = last_call[1] |
|
2278 | 2278 | |
|
2279 | 2279 | # use last_call to remember the state of the previous call, but don't |
|
2280 | 2280 | # let it be clobbered by successive '-p' calls. |
|
2281 | 2281 | try: |
|
2282 | 2282 | last_call[0] = self.shell.outputcache.prompt_count |
|
2283 | 2283 | if not opts_p: |
|
2284 | 2284 | last_call[1] = parameter_s |
|
2285 | 2285 | except: |
|
2286 | 2286 | pass |
|
2287 | 2287 | |
|
2288 | 2288 | # by default this is done with temp files, except when the given |
|
2289 | 2289 | # arg is a filename |
|
2290 | 2290 | use_temp = 1 |
|
2291 | 2291 | |
|
2292 | 2292 | if re.match(r'\d',args): |
|
2293 | 2293 | # Mode where user specifies ranges of lines, like in %macro. |
|
2294 | 2294 | # This means that you can't edit files whose names begin with |
|
2295 | 2295 | # numbers this way. Tough. |
|
2296 | 2296 | ranges = args.split() |
|
2297 | 2297 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2298 | 2298 | elif args.endswith('.py'): |
|
2299 | 2299 | filename = make_filename(args) |
|
2300 | 2300 | data = '' |
|
2301 | 2301 | use_temp = 0 |
|
2302 | 2302 | elif args: |
|
2303 | 2303 | try: |
|
2304 | 2304 | # Load the parameter given as a variable. If not a string, |
|
2305 | 2305 | # process it as an object instead (below) |
|
2306 | 2306 | |
|
2307 | 2307 | #print '*** args',args,'type',type(args) # dbg |
|
2308 | 2308 | data = eval(args,self.shell.user_ns) |
|
2309 | 2309 | if not type(data) in StringTypes: |
|
2310 | 2310 | raise DataIsObject |
|
2311 | 2311 | |
|
2312 | 2312 | except (NameError,SyntaxError): |
|
2313 | 2313 | # given argument is not a variable, try as a filename |
|
2314 | 2314 | filename = make_filename(args) |
|
2315 | 2315 | if filename is None: |
|
2316 | 2316 | warn("Argument given (%s) can't be found as a variable " |
|
2317 | 2317 | "or as a filename." % args) |
|
2318 | 2318 | return |
|
2319 | 2319 | |
|
2320 | 2320 | data = '' |
|
2321 | 2321 | use_temp = 0 |
|
2322 | 2322 | except DataIsObject: |
|
2323 | 2323 | |
|
2324 | 2324 | # macros have a special edit function |
|
2325 | 2325 | if isinstance(data,Macro): |
|
2326 | 2326 | self._edit_macro(args,data) |
|
2327 | 2327 | return |
|
2328 | 2328 | |
|
2329 | 2329 | # For objects, try to edit the file where they are defined |
|
2330 | 2330 | try: |
|
2331 | 2331 | filename = inspect.getabsfile(data) |
|
2332 | 2332 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2333 | 2333 | # class created by %edit? Try to find source |
|
2334 | 2334 | # by looking for method definitions instead, the |
|
2335 | 2335 | # __module__ in those classes is FakeModule. |
|
2336 | 2336 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2337 | 2337 | for attr in attrs: |
|
2338 | 2338 | if not inspect.ismethod(attr): |
|
2339 | 2339 | continue |
|
2340 | 2340 | filename = inspect.getabsfile(attr) |
|
2341 | 2341 | if filename and 'fakemodule' not in filename.lower(): |
|
2342 | 2342 | # change the attribute to be the edit target instead |
|
2343 | 2343 | data = attr |
|
2344 | 2344 | break |
|
2345 | 2345 | |
|
2346 | 2346 | datafile = 1 |
|
2347 | 2347 | except TypeError: |
|
2348 | 2348 | filename = make_filename(args) |
|
2349 | 2349 | datafile = 1 |
|
2350 | 2350 | warn('Could not find file where `%s` is defined.\n' |
|
2351 | 2351 | 'Opening a file named `%s`' % (args,filename)) |
|
2352 | 2352 | # Now, make sure we can actually read the source (if it was in |
|
2353 | 2353 | # a temp file it's gone by now). |
|
2354 | 2354 | if datafile: |
|
2355 | 2355 | try: |
|
2356 | 2356 | if lineno is None: |
|
2357 | 2357 | lineno = inspect.getsourcelines(data)[1] |
|
2358 | 2358 | except IOError: |
|
2359 | 2359 | filename = make_filename(args) |
|
2360 | 2360 | if filename is None: |
|
2361 | 2361 | warn('The file `%s` where `%s` was defined cannot ' |
|
2362 | 2362 | 'be read.' % (filename,data)) |
|
2363 | 2363 | return |
|
2364 | 2364 | use_temp = 0 |
|
2365 | 2365 | else: |
|
2366 | 2366 | data = '' |
|
2367 | 2367 | |
|
2368 | 2368 | if use_temp: |
|
2369 | 2369 | filename = self.shell.mktempfile(data) |
|
2370 | 2370 | print 'IPython will make a temporary file named:',filename |
|
2371 | 2371 | |
|
2372 | 2372 | # do actual editing here |
|
2373 | 2373 | print 'Editing...', |
|
2374 | 2374 | sys.stdout.flush() |
|
2375 | 2375 | try: |
|
2376 | 2376 | self.shell.hooks.editor(filename,lineno) |
|
2377 | 2377 | except TryNext: |
|
2378 | 2378 | warn('Could not open editor') |
|
2379 | 2379 | return |
|
2380 | 2380 | |
|
2381 | 2381 | # XXX TODO: should this be generalized for all string vars? |
|
2382 | 2382 | # For now, this is special-cased to blocks created by cpaste |
|
2383 | 2383 | if args.strip() == 'pasted_block': |
|
2384 | 2384 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2385 | 2385 | |
|
2386 | 2386 | if opts.has_key('x'): # -x prevents actual execution |
|
2387 | 2387 | |
|
2388 | 2388 | else: |
|
2389 | 2389 | print 'done. Executing edited code...' |
|
2390 | 2390 | if opts_r: |
|
2391 | 2391 | self.shell.runlines(file_read(filename)) |
|
2392 | 2392 | else: |
|
2393 | 2393 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2394 | 2394 | self.shell.user_ns) |
|
2395 | 2395 | |
|
2396 | 2396 | |
|
2397 | 2397 | if use_temp: |
|
2398 | 2398 | try: |
|
2399 | 2399 | return open(filename).read() |
|
2400 | 2400 | except IOError,msg: |
|
2401 | 2401 | if msg.filename == filename: |
|
2402 | 2402 | warn('File not found. Did you forget to save?') |
|
2403 | 2403 | return |
|
2404 | 2404 | else: |
|
2405 | 2405 | self.shell.showtraceback() |
|
2406 | 2406 | |
|
2407 | 2407 | def magic_xmode(self,parameter_s = ''): |
|
2408 | 2408 | """Switch modes for the exception handlers. |
|
2409 | 2409 | |
|
2410 | 2410 | Valid modes: Plain, Context and Verbose. |
|
2411 | 2411 | |
|
2412 | 2412 | If called without arguments, acts as a toggle.""" |
|
2413 | 2413 | |
|
2414 | 2414 | def xmode_switch_err(name): |
|
2415 | 2415 | warn('Error changing %s exception modes.\n%s' % |
|
2416 | 2416 | (name,sys.exc_info()[1])) |
|
2417 | 2417 | |
|
2418 | 2418 | shell = self.shell |
|
2419 | 2419 | new_mode = parameter_s.strip().capitalize() |
|
2420 | 2420 | try: |
|
2421 | 2421 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2422 | 2422 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2423 | 2423 | except: |
|
2424 | 2424 | xmode_switch_err('user') |
|
2425 | 2425 | |
|
2426 | 2426 | # threaded shells use a special handler in sys.excepthook |
|
2427 | 2427 | if shell.isthreaded: |
|
2428 | 2428 | try: |
|
2429 | 2429 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2430 | 2430 | except: |
|
2431 | 2431 | xmode_switch_err('threaded') |
|
2432 | 2432 | |
|
2433 | 2433 | def magic_colors(self,parameter_s = ''): |
|
2434 | 2434 | """Switch color scheme for prompts, info system and exception handlers. |
|
2435 | 2435 | |
|
2436 | 2436 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2437 | 2437 | |
|
2438 | 2438 | Color scheme names are not case-sensitive.""" |
|
2439 | 2439 | |
|
2440 | 2440 | def color_switch_err(name): |
|
2441 | 2441 | warn('Error changing %s color schemes.\n%s' % |
|
2442 | 2442 | (name,sys.exc_info()[1])) |
|
2443 | 2443 | |
|
2444 | 2444 | |
|
2445 | 2445 | new_scheme = parameter_s.strip() |
|
2446 | 2446 | if not new_scheme: |
|
2447 | 2447 | raise UsageError( |
|
2448 | 2448 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2449 | 2449 | return |
|
2450 | 2450 | # local shortcut |
|
2451 | 2451 | shell = self.shell |
|
2452 | 2452 | |
|
2453 | 2453 | import IPython.utils.rlineimpl as readline |
|
2454 | 2454 | |
|
2455 | 2455 | if not readline.have_readline and sys.platform == "win32": |
|
2456 | 2456 | msg = """\ |
|
2457 | 2457 | Proper color support under MS Windows requires the pyreadline library. |
|
2458 | 2458 | You can find it at: |
|
2459 | 2459 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2460 | 2460 | Gary's readline needs the ctypes module, from: |
|
2461 | 2461 | http://starship.python.net/crew/theller/ctypes |
|
2462 | 2462 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2463 | 2463 | |
|
2464 | 2464 | Defaulting color scheme to 'NoColor'""" |
|
2465 | 2465 | new_scheme = 'NoColor' |
|
2466 | 2466 | warn(msg) |
|
2467 | 2467 | |
|
2468 | 2468 | # readline option is 0 |
|
2469 | 2469 | if not shell.has_readline: |
|
2470 | 2470 | new_scheme = 'NoColor' |
|
2471 | 2471 | |
|
2472 | 2472 | # Set prompt colors |
|
2473 | 2473 | try: |
|
2474 | 2474 | shell.outputcache.set_colors(new_scheme) |
|
2475 | 2475 | except: |
|
2476 | 2476 | color_switch_err('prompt') |
|
2477 | 2477 | else: |
|
2478 | 2478 | shell.colors = \ |
|
2479 | 2479 | shell.outputcache.color_table.active_scheme_name |
|
2480 | 2480 | # Set exception colors |
|
2481 | 2481 | try: |
|
2482 | 2482 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2483 | 2483 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2484 | 2484 | except: |
|
2485 | 2485 | color_switch_err('exception') |
|
2486 | 2486 | |
|
2487 | 2487 | # threaded shells use a verbose traceback in sys.excepthook |
|
2488 | 2488 | if shell.isthreaded: |
|
2489 | 2489 | try: |
|
2490 | 2490 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2491 | 2491 | except: |
|
2492 | 2492 | color_switch_err('system exception handler') |
|
2493 | 2493 | |
|
2494 | 2494 | # Set info (for 'object?') colors |
|
2495 | 2495 | if shell.color_info: |
|
2496 | 2496 | try: |
|
2497 | 2497 | shell.inspector.set_active_scheme(new_scheme) |
|
2498 | 2498 | except: |
|
2499 | 2499 | color_switch_err('object inspector') |
|
2500 | 2500 | else: |
|
2501 | 2501 | shell.inspector.set_active_scheme('NoColor') |
|
2502 | 2502 | |
|
2503 | 2503 | def magic_color_info(self,parameter_s = ''): |
|
2504 | 2504 | """Toggle color_info. |
|
2505 | 2505 | |
|
2506 | 2506 | The color_info configuration parameter controls whether colors are |
|
2507 | 2507 | used for displaying object details (by things like %psource, %pfile or |
|
2508 | 2508 | the '?' system). This function toggles this value with each call. |
|
2509 | 2509 | |
|
2510 | 2510 | Note that unless you have a fairly recent pager (less works better |
|
2511 | 2511 | than more) in your system, using colored object information displays |
|
2512 | 2512 | will not work properly. Test it and see.""" |
|
2513 | 2513 | |
|
2514 | 2514 | self.shell.color_info = not self.shell.color_info |
|
2515 | 2515 | self.magic_colors(self.shell.colors) |
|
2516 | 2516 | print 'Object introspection functions have now coloring:', |
|
2517 | 2517 | print ['OFF','ON'][int(self.shell.color_info)] |
|
2518 | 2518 | |
|
2519 | 2519 | def magic_Pprint(self, parameter_s=''): |
|
2520 | 2520 | """Toggle pretty printing on/off.""" |
|
2521 | 2521 | |
|
2522 | 2522 | self.shell.pprint = 1 - self.shell.pprint |
|
2523 | 2523 | print 'Pretty printing has been turned', \ |
|
2524 | 2524 | ['OFF','ON'][self.shell.pprint] |
|
2525 | 2525 | |
|
2526 | 2526 | def magic_exit(self, parameter_s=''): |
|
2527 | 2527 | """Exit IPython, confirming if configured to do so. |
|
2528 | 2528 | |
|
2529 | 2529 | You can configure whether IPython asks for confirmation upon exit by |
|
2530 | 2530 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2531 | 2531 | |
|
2532 | 2532 | self.shell.exit() |
|
2533 | 2533 | |
|
2534 | 2534 | def magic_quit(self, parameter_s=''): |
|
2535 | 2535 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2536 | 2536 | |
|
2537 | 2537 | self.shell.exit() |
|
2538 | 2538 | |
|
2539 | 2539 | def magic_Exit(self, parameter_s=''): |
|
2540 | 2540 | """Exit IPython without confirmation.""" |
|
2541 | 2541 | |
|
2542 | 2542 | self.shell.ask_exit() |
|
2543 | 2543 | |
|
2544 | 2544 | #...................................................................... |
|
2545 | 2545 | # Functions to implement unix shell-type things |
|
2546 | 2546 | |
|
2547 | 2547 | @testdec.skip_doctest |
|
2548 | 2548 | def magic_alias(self, parameter_s = ''): |
|
2549 | 2549 | """Define an alias for a system command. |
|
2550 | 2550 | |
|
2551 | 2551 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2552 | 2552 | |
|
2553 | 2553 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2554 | 2554 | params' (from your underlying operating system). |
|
2555 | 2555 | |
|
2556 | 2556 | Aliases have lower precedence than magic functions and Python normal |
|
2557 | 2557 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2558 | 2558 | alias can not be executed until 'del foo' removes the Python variable. |
|
2559 | 2559 | |
|
2560 | 2560 | You can use the %l specifier in an alias definition to represent the |
|
2561 | 2561 | whole line when the alias is called. For example: |
|
2562 | 2562 | |
|
2563 | 2563 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2564 | 2564 | In [3]: all hello world |
|
2565 | 2565 | Input in brackets: <hello world> |
|
2566 | 2566 | |
|
2567 | 2567 | You can also define aliases with parameters using %s specifiers (one |
|
2568 | 2568 | per parameter): |
|
2569 | 2569 | |
|
2570 | 2570 | In [1]: alias parts echo first %s second %s |
|
2571 | 2571 | In [2]: %parts A B |
|
2572 | 2572 | first A second B |
|
2573 | 2573 | In [3]: %parts A |
|
2574 | 2574 | Incorrect number of arguments: 2 expected. |
|
2575 | 2575 | parts is an alias to: 'echo first %s second %s' |
|
2576 | 2576 | |
|
2577 | 2577 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2578 | 2578 | the other in your aliases. |
|
2579 | 2579 | |
|
2580 | 2580 | Aliases expand Python variables just like system calls using ! or !! |
|
2581 | 2581 | do: all expressions prefixed with '$' get expanded. For details of |
|
2582 | 2582 | the semantic rules, see PEP-215: |
|
2583 | 2583 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2584 | 2584 | IPython for variable expansion. If you want to access a true shell |
|
2585 | 2585 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2586 | 2586 | |
|
2587 | 2587 | In [6]: alias show echo |
|
2588 | 2588 | In [7]: PATH='A Python string' |
|
2589 | 2589 | In [8]: show $PATH |
|
2590 | 2590 | A Python string |
|
2591 | 2591 | In [9]: show $$PATH |
|
2592 | 2592 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2593 | 2593 | |
|
2594 | 2594 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2595 | 2595 | and %rehashx functions, which automatically create aliases for the |
|
2596 | 2596 | contents of your $PATH. |
|
2597 | 2597 | |
|
2598 | 2598 | If called with no parameters, %alias prints the current alias table.""" |
|
2599 | 2599 | |
|
2600 | 2600 | par = parameter_s.strip() |
|
2601 | 2601 | if not par: |
|
2602 | 2602 | stored = self.db.get('stored_aliases', {} ) |
|
2603 | 2603 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2604 | 2604 | # for k, v in stored: |
|
2605 | 2605 | # atab.append(k, v[0]) |
|
2606 | 2606 | |
|
2607 | 2607 | print "Total number of aliases:", len(aliases) |
|
2608 | 2608 | return aliases |
|
2609 | 2609 | |
|
2610 | 2610 | # Now try to define a new one |
|
2611 | 2611 | try: |
|
2612 | 2612 | alias,cmd = par.split(None, 1) |
|
2613 | 2613 | except: |
|
2614 | 2614 | print oinspect.getdoc(self.magic_alias) |
|
2615 | 2615 | else: |
|
2616 | 2616 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2617 | 2617 | # end magic_alias |
|
2618 | 2618 | |
|
2619 | 2619 | def magic_unalias(self, parameter_s = ''): |
|
2620 | 2620 | """Remove an alias""" |
|
2621 | 2621 | |
|
2622 | 2622 | aname = parameter_s.strip() |
|
2623 | 2623 | self.shell.alias_manager.undefine_alias(aname) |
|
2624 | 2624 | stored = self.db.get('stored_aliases', {} ) |
|
2625 | 2625 | if aname in stored: |
|
2626 | 2626 | print "Removing %stored alias",aname |
|
2627 | 2627 | del stored[aname] |
|
2628 | 2628 | self.db['stored_aliases'] = stored |
|
2629 | 2629 | |
|
2630 | 2630 | |
|
2631 | 2631 | def magic_rehashx(self, parameter_s = ''): |
|
2632 | 2632 | """Update the alias table with all executable files in $PATH. |
|
2633 | 2633 | |
|
2634 | 2634 | This version explicitly checks that every entry in $PATH is a file |
|
2635 | 2635 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2636 | 2636 | |
|
2637 | 2637 | Under Windows, it checks executability as a match agains a |
|
2638 | 2638 | '|'-separated string of extensions, stored in the IPython config |
|
2639 | 2639 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2640 | 2640 | |
|
2641 | 2641 | This function also resets the root module cache of module completer, |
|
2642 | 2642 | used on slow filesystems. |
|
2643 | 2643 | """ |
|
2644 | 2644 | from IPython.core.alias import InvalidAliasError |
|
2645 | 2645 | |
|
2646 | 2646 | # for the benefit of module completer in ipy_completers.py |
|
2647 | 2647 | del self.db['rootmodules'] |
|
2648 | 2648 | |
|
2649 | 2649 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2650 | 2650 | os.environ.get('PATH','').split(os.pathsep)] |
|
2651 | 2651 | path = filter(os.path.isdir,path) |
|
2652 | 2652 | |
|
2653 | 2653 | syscmdlist = [] |
|
2654 | 2654 | # Now define isexec in a cross platform manner. |
|
2655 | 2655 | if os.name == 'posix': |
|
2656 | 2656 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2657 | 2657 | os.access(fname,os.X_OK) |
|
2658 | 2658 | else: |
|
2659 | 2659 | try: |
|
2660 | 2660 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2661 | 2661 | except KeyError: |
|
2662 | 2662 | winext = 'exe|com|bat|py' |
|
2663 | 2663 | if 'py' not in winext: |
|
2664 | 2664 | winext += '|py' |
|
2665 | 2665 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2666 | 2666 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2667 | 2667 | savedir = os.getcwd() |
|
2668 | 2668 | |
|
2669 | 2669 | # Now walk the paths looking for executables to alias. |
|
2670 | 2670 | try: |
|
2671 | 2671 | # write the whole loop for posix/Windows so we don't have an if in |
|
2672 | 2672 | # the innermost part |
|
2673 | 2673 | if os.name == 'posix': |
|
2674 | 2674 | for pdir in path: |
|
2675 | 2675 | os.chdir(pdir) |
|
2676 | 2676 | for ff in os.listdir(pdir): |
|
2677 | 2677 | if isexec(ff): |
|
2678 | 2678 | try: |
|
2679 | 2679 | # Removes dots from the name since ipython |
|
2680 | 2680 | # will assume names with dots to be python. |
|
2681 | 2681 | self.shell.alias_manager.define_alias( |
|
2682 | 2682 | ff.replace('.',''), ff) |
|
2683 | 2683 | except InvalidAliasError: |
|
2684 | 2684 | pass |
|
2685 | 2685 | else: |
|
2686 | 2686 | syscmdlist.append(ff) |
|
2687 | 2687 | else: |
|
2688 | 2688 | for pdir in path: |
|
2689 | 2689 | os.chdir(pdir) |
|
2690 | 2690 | for ff in os.listdir(pdir): |
|
2691 | 2691 | base, ext = os.path.splitext(ff) |
|
2692 | 2692 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2693 | 2693 | if ext.lower() == '.exe': |
|
2694 | 2694 | ff = base |
|
2695 | 2695 | try: |
|
2696 | 2696 | # Removes dots from the name since ipython |
|
2697 | 2697 | # will assume names with dots to be python. |
|
2698 | 2698 | self.shell.alias_manager.define_alias( |
|
2699 | 2699 | base.lower().replace('.',''), ff) |
|
2700 | 2700 | except InvalidAliasError: |
|
2701 | 2701 | pass |
|
2702 | 2702 | syscmdlist.append(ff) |
|
2703 | 2703 | db = self.db |
|
2704 | 2704 | db['syscmdlist'] = syscmdlist |
|
2705 | 2705 | finally: |
|
2706 | 2706 | os.chdir(savedir) |
|
2707 | 2707 | |
|
2708 | 2708 | def magic_pwd(self, parameter_s = ''): |
|
2709 | 2709 | """Return the current working directory path.""" |
|
2710 | 2710 | return os.getcwd() |
|
2711 | 2711 | |
|
2712 | 2712 | def magic_cd(self, parameter_s=''): |
|
2713 | 2713 | """Change the current working directory. |
|
2714 | 2714 | |
|
2715 | 2715 | This command automatically maintains an internal list of directories |
|
2716 | 2716 | you visit during your IPython session, in the variable _dh. The |
|
2717 | 2717 | command %dhist shows this history nicely formatted. You can also |
|
2718 | 2718 | do 'cd -<tab>' to see directory history conveniently. |
|
2719 | 2719 | |
|
2720 | 2720 | Usage: |
|
2721 | 2721 | |
|
2722 | 2722 | cd 'dir': changes to directory 'dir'. |
|
2723 | 2723 | |
|
2724 | 2724 | cd -: changes to the last visited directory. |
|
2725 | 2725 | |
|
2726 | 2726 | cd -<n>: changes to the n-th directory in the directory history. |
|
2727 | 2727 | |
|
2728 | 2728 | cd --foo: change to directory that matches 'foo' in history |
|
2729 | 2729 | |
|
2730 | 2730 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2731 | 2731 | (note: cd <bookmark_name> is enough if there is no |
|
2732 | 2732 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2733 | 2733 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2734 | 2734 | |
|
2735 | 2735 | Options: |
|
2736 | 2736 | |
|
2737 | 2737 | -q: quiet. Do not print the working directory after the cd command is |
|
2738 | 2738 | executed. By default IPython's cd command does print this directory, |
|
2739 | 2739 | since the default prompts do not display path information. |
|
2740 | 2740 | |
|
2741 | 2741 | Note that !cd doesn't work for this purpose because the shell where |
|
2742 | 2742 | !command runs is immediately discarded after executing 'command'.""" |
|
2743 | 2743 | |
|
2744 | 2744 | parameter_s = parameter_s.strip() |
|
2745 | 2745 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2746 | 2746 | |
|
2747 | 2747 | oldcwd = os.getcwd() |
|
2748 | 2748 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2749 | 2749 | # jump in directory history by number |
|
2750 | 2750 | if numcd: |
|
2751 | 2751 | nn = int(numcd.group(2)) |
|
2752 | 2752 | try: |
|
2753 | 2753 | ps = self.shell.user_ns['_dh'][nn] |
|
2754 | 2754 | except IndexError: |
|
2755 | 2755 | print 'The requested directory does not exist in history.' |
|
2756 | 2756 | return |
|
2757 | 2757 | else: |
|
2758 | 2758 | opts = {} |
|
2759 | 2759 | elif parameter_s.startswith('--'): |
|
2760 | 2760 | ps = None |
|
2761 | 2761 | fallback = None |
|
2762 | 2762 | pat = parameter_s[2:] |
|
2763 | 2763 | dh = self.shell.user_ns['_dh'] |
|
2764 | 2764 | # first search only by basename (last component) |
|
2765 | 2765 | for ent in reversed(dh): |
|
2766 | 2766 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2767 | 2767 | ps = ent |
|
2768 | 2768 | break |
|
2769 | 2769 | |
|
2770 | 2770 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2771 | 2771 | fallback = ent |
|
2772 | 2772 | |
|
2773 | 2773 | # if we have no last part match, pick the first full path match |
|
2774 | 2774 | if ps is None: |
|
2775 | 2775 | ps = fallback |
|
2776 | 2776 | |
|
2777 | 2777 | if ps is None: |
|
2778 | 2778 | print "No matching entry in directory history" |
|
2779 | 2779 | return |
|
2780 | 2780 | else: |
|
2781 | 2781 | opts = {} |
|
2782 | 2782 | |
|
2783 | 2783 | |
|
2784 | 2784 | else: |
|
2785 | 2785 | #turn all non-space-escaping backslashes to slashes, |
|
2786 | 2786 | # for c:\windows\directory\names\ |
|
2787 | 2787 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2788 | 2788 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2789 | 2789 | # jump to previous |
|
2790 | 2790 | if ps == '-': |
|
2791 | 2791 | try: |
|
2792 | 2792 | ps = self.shell.user_ns['_dh'][-2] |
|
2793 | 2793 | except IndexError: |
|
2794 | 2794 | raise UsageError('%cd -: No previous directory to change to.') |
|
2795 | 2795 | # jump to bookmark if needed |
|
2796 | 2796 | else: |
|
2797 | 2797 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2798 | 2798 | bkms = self.db.get('bookmarks', {}) |
|
2799 | 2799 | |
|
2800 | 2800 | if bkms.has_key(ps): |
|
2801 | 2801 | target = bkms[ps] |
|
2802 | 2802 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2803 | 2803 | ps = target |
|
2804 | 2804 | else: |
|
2805 | 2805 | if opts.has_key('b'): |
|
2806 | 2806 | raise UsageError("Bookmark '%s' not found. " |
|
2807 | 2807 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2808 | 2808 | |
|
2809 | 2809 | # at this point ps should point to the target dir |
|
2810 | 2810 | if ps: |
|
2811 | 2811 | try: |
|
2812 | 2812 | os.chdir(os.path.expanduser(ps)) |
|
2813 | 2813 | if self.shell.term_title: |
|
2814 | 2814 | platutils.set_term_title('IPython: ' + abbrev_cwd()) |
|
2815 | 2815 | except OSError: |
|
2816 | 2816 | print sys.exc_info()[1] |
|
2817 | 2817 | else: |
|
2818 | 2818 | cwd = os.getcwd() |
|
2819 | 2819 | dhist = self.shell.user_ns['_dh'] |
|
2820 | 2820 | if oldcwd != cwd: |
|
2821 | 2821 | dhist.append(cwd) |
|
2822 | 2822 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2823 | 2823 | |
|
2824 | 2824 | else: |
|
2825 | 2825 | os.chdir(self.shell.home_dir) |
|
2826 | 2826 | if self.shell.term_title: |
|
2827 | 2827 | platutils.set_term_title('IPython: ' + '~') |
|
2828 | 2828 | cwd = os.getcwd() |
|
2829 | 2829 | dhist = self.shell.user_ns['_dh'] |
|
2830 | 2830 | |
|
2831 | 2831 | if oldcwd != cwd: |
|
2832 | 2832 | dhist.append(cwd) |
|
2833 | 2833 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2834 | 2834 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2835 | 2835 | print self.shell.user_ns['_dh'][-1] |
|
2836 | 2836 | |
|
2837 | 2837 | |
|
2838 | 2838 | def magic_env(self, parameter_s=''): |
|
2839 | 2839 | """List environment variables.""" |
|
2840 | 2840 | |
|
2841 | 2841 | return os.environ.data |
|
2842 | 2842 | |
|
2843 | 2843 | def magic_pushd(self, parameter_s=''): |
|
2844 | 2844 | """Place the current dir on stack and change directory. |
|
2845 | 2845 | |
|
2846 | 2846 | Usage:\\ |
|
2847 | 2847 | %pushd ['dirname'] |
|
2848 | 2848 | """ |
|
2849 | 2849 | |
|
2850 | 2850 | dir_s = self.shell.dir_stack |
|
2851 | 2851 | tgt = os.path.expanduser(parameter_s) |
|
2852 | 2852 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2853 | 2853 | if tgt: |
|
2854 | 2854 | self.magic_cd(parameter_s) |
|
2855 | 2855 | dir_s.insert(0,cwd) |
|
2856 | 2856 | return self.magic_dirs() |
|
2857 | 2857 | |
|
2858 | 2858 | def magic_popd(self, parameter_s=''): |
|
2859 | 2859 | """Change to directory popped off the top of the stack. |
|
2860 | 2860 | """ |
|
2861 | 2861 | if not self.shell.dir_stack: |
|
2862 | 2862 | raise UsageError("%popd on empty stack") |
|
2863 | 2863 | top = self.shell.dir_stack.pop(0) |
|
2864 | 2864 | self.magic_cd(top) |
|
2865 | 2865 | print "popd ->",top |
|
2866 | 2866 | |
|
2867 | 2867 | def magic_dirs(self, parameter_s=''): |
|
2868 | 2868 | """Return the current directory stack.""" |
|
2869 | 2869 | |
|
2870 | 2870 | return self.shell.dir_stack |
|
2871 | 2871 | |
|
2872 | 2872 | def magic_dhist(self, parameter_s=''): |
|
2873 | 2873 | """Print your history of visited directories. |
|
2874 | 2874 | |
|
2875 | 2875 | %dhist -> print full history\\ |
|
2876 | 2876 | %dhist n -> print last n entries only\\ |
|
2877 | 2877 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2878 | 2878 | |
|
2879 | 2879 | This history is automatically maintained by the %cd command, and |
|
2880 | 2880 | always available as the global list variable _dh. You can use %cd -<n> |
|
2881 | 2881 | to go to directory number <n>. |
|
2882 | 2882 | |
|
2883 | 2883 | Note that most of time, you should view directory history by entering |
|
2884 | 2884 | cd -<TAB>. |
|
2885 | 2885 | |
|
2886 | 2886 | """ |
|
2887 | 2887 | |
|
2888 | 2888 | dh = self.shell.user_ns['_dh'] |
|
2889 | 2889 | if parameter_s: |
|
2890 | 2890 | try: |
|
2891 | 2891 | args = map(int,parameter_s.split()) |
|
2892 | 2892 | except: |
|
2893 | 2893 | self.arg_err(Magic.magic_dhist) |
|
2894 | 2894 | return |
|
2895 | 2895 | if len(args) == 1: |
|
2896 | 2896 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2897 | 2897 | elif len(args) == 2: |
|
2898 | 2898 | ini,fin = args |
|
2899 | 2899 | else: |
|
2900 | 2900 | self.arg_err(Magic.magic_dhist) |
|
2901 | 2901 | return |
|
2902 | 2902 | else: |
|
2903 | 2903 | ini,fin = 0,len(dh) |
|
2904 | 2904 | nlprint(dh, |
|
2905 | 2905 | header = 'Directory history (kept in _dh)', |
|
2906 | 2906 | start=ini,stop=fin) |
|
2907 | 2907 | |
|
2908 | 2908 | @testdec.skip_doctest |
|
2909 | 2909 | def magic_sc(self, parameter_s=''): |
|
2910 | 2910 | """Shell capture - execute a shell command and capture its output. |
|
2911 | 2911 | |
|
2912 | 2912 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2913 | 2913 | |
|
2914 | 2914 | You should use the form 'var = !command' instead. Example: |
|
2915 | 2915 | |
|
2916 | 2916 | "%sc -l myfiles = ls ~" should now be written as |
|
2917 | 2917 | |
|
2918 | 2918 | "myfiles = !ls ~" |
|
2919 | 2919 | |
|
2920 | 2920 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2921 | 2921 | below. |
|
2922 | 2922 | |
|
2923 | 2923 | -- |
|
2924 | 2924 | %sc [options] varname=command |
|
2925 | 2925 | |
|
2926 | 2926 | IPython will run the given command using commands.getoutput(), and |
|
2927 | 2927 | will then update the user's interactive namespace with a variable |
|
2928 | 2928 | called varname, containing the value of the call. Your command can |
|
2929 | 2929 | contain shell wildcards, pipes, etc. |
|
2930 | 2930 | |
|
2931 | 2931 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2932 | 2932 | supply must follow Python's standard conventions for valid names. |
|
2933 | 2933 | |
|
2934 | 2934 | (A special format without variable name exists for internal use) |
|
2935 | 2935 | |
|
2936 | 2936 | Options: |
|
2937 | 2937 | |
|
2938 | 2938 | -l: list output. Split the output on newlines into a list before |
|
2939 | 2939 | assigning it to the given variable. By default the output is stored |
|
2940 | 2940 | as a single string. |
|
2941 | 2941 | |
|
2942 | 2942 | -v: verbose. Print the contents of the variable. |
|
2943 | 2943 | |
|
2944 | 2944 | In most cases you should not need to split as a list, because the |
|
2945 | 2945 | returned value is a special type of string which can automatically |
|
2946 | 2946 | provide its contents either as a list (split on newlines) or as a |
|
2947 | 2947 | space-separated string. These are convenient, respectively, either |
|
2948 | 2948 | for sequential processing or to be passed to a shell command. |
|
2949 | 2949 | |
|
2950 | 2950 | For example: |
|
2951 | 2951 | |
|
2952 | 2952 | # all-random |
|
2953 | 2953 | |
|
2954 | 2954 | # Capture into variable a |
|
2955 | 2955 | In [1]: sc a=ls *py |
|
2956 | 2956 | |
|
2957 | 2957 | # a is a string with embedded newlines |
|
2958 | 2958 | In [2]: a |
|
2959 | 2959 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2960 | 2960 | |
|
2961 | 2961 | # which can be seen as a list: |
|
2962 | 2962 | In [3]: a.l |
|
2963 | 2963 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2964 | 2964 | |
|
2965 | 2965 | # or as a whitespace-separated string: |
|
2966 | 2966 | In [4]: a.s |
|
2967 | 2967 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2968 | 2968 | |
|
2969 | 2969 | # a.s is useful to pass as a single command line: |
|
2970 | 2970 | In [5]: !wc -l $a.s |
|
2971 | 2971 | 146 setup.py |
|
2972 | 2972 | 130 win32_manual_post_install.py |
|
2973 | 2973 | 276 total |
|
2974 | 2974 | |
|
2975 | 2975 | # while the list form is useful to loop over: |
|
2976 | 2976 | In [6]: for f in a.l: |
|
2977 | 2977 | ...: !wc -l $f |
|
2978 | 2978 | ...: |
|
2979 | 2979 | 146 setup.py |
|
2980 | 2980 | 130 win32_manual_post_install.py |
|
2981 | 2981 | |
|
2982 | 2982 | Similiarly, the lists returned by the -l option are also special, in |
|
2983 | 2983 | the sense that you can equally invoke the .s attribute on them to |
|
2984 | 2984 | automatically get a whitespace-separated string from their contents: |
|
2985 | 2985 | |
|
2986 | 2986 | In [7]: sc -l b=ls *py |
|
2987 | 2987 | |
|
2988 | 2988 | In [8]: b |
|
2989 | 2989 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2990 | 2990 | |
|
2991 | 2991 | In [9]: b.s |
|
2992 | 2992 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2993 | 2993 | |
|
2994 | 2994 | In summary, both the lists and strings used for ouptut capture have |
|
2995 | 2995 | the following special attributes: |
|
2996 | 2996 | |
|
2997 | 2997 | .l (or .list) : value as list. |
|
2998 | 2998 | .n (or .nlstr): value as newline-separated string. |
|
2999 | 2999 | .s (or .spstr): value as space-separated string. |
|
3000 | 3000 | """ |
|
3001 | 3001 | |
|
3002 | 3002 | opts,args = self.parse_options(parameter_s,'lv') |
|
3003 | 3003 | # Try to get a variable name and command to run |
|
3004 | 3004 | try: |
|
3005 | 3005 | # the variable name must be obtained from the parse_options |
|
3006 | 3006 | # output, which uses shlex.split to strip options out. |
|
3007 | 3007 | var,_ = args.split('=',1) |
|
3008 | 3008 | var = var.strip() |
|
3009 | 3009 | # But the the command has to be extracted from the original input |
|
3010 | 3010 | # parameter_s, not on what parse_options returns, to avoid the |
|
3011 | 3011 | # quote stripping which shlex.split performs on it. |
|
3012 | 3012 | _,cmd = parameter_s.split('=',1) |
|
3013 | 3013 | except ValueError: |
|
3014 | 3014 | var,cmd = '','' |
|
3015 | 3015 | # If all looks ok, proceed |
|
3016 | 3016 | out,err = self.shell.getoutputerror(cmd) |
|
3017 | 3017 | if err: |
|
3018 | 3018 | print >> Term.cerr,err |
|
3019 | 3019 | if opts.has_key('l'): |
|
3020 | 3020 | out = SList(out.split('\n')) |
|
3021 | 3021 | else: |
|
3022 | 3022 | out = LSString(out) |
|
3023 | 3023 | if opts.has_key('v'): |
|
3024 | 3024 | print '%s ==\n%s' % (var,pformat(out)) |
|
3025 | 3025 | if var: |
|
3026 | 3026 | self.shell.user_ns.update({var:out}) |
|
3027 | 3027 | else: |
|
3028 | 3028 | return out |
|
3029 | 3029 | |
|
3030 | 3030 | def magic_sx(self, parameter_s=''): |
|
3031 | 3031 | """Shell execute - run a shell command and capture its output. |
|
3032 | 3032 | |
|
3033 | 3033 | %sx command |
|
3034 | 3034 | |
|
3035 | 3035 | IPython will run the given command using commands.getoutput(), and |
|
3036 | 3036 | return the result formatted as a list (split on '\\n'). Since the |
|
3037 | 3037 | output is _returned_, it will be stored in ipython's regular output |
|
3038 | 3038 | cache Out[N] and in the '_N' automatic variables. |
|
3039 | 3039 | |
|
3040 | 3040 | Notes: |
|
3041 | 3041 | |
|
3042 | 3042 | 1) If an input line begins with '!!', then %sx is automatically |
|
3043 | 3043 | invoked. That is, while: |
|
3044 | 3044 | !ls |
|
3045 | 3045 | causes ipython to simply issue system('ls'), typing |
|
3046 | 3046 | !!ls |
|
3047 | 3047 | is a shorthand equivalent to: |
|
3048 | 3048 | %sx ls |
|
3049 | 3049 | |
|
3050 | 3050 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3051 | 3051 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3052 | 3052 | to process line-oriented shell output via further python commands. |
|
3053 | 3053 | %sc is meant to provide much finer control, but requires more |
|
3054 | 3054 | typing. |
|
3055 | 3055 | |
|
3056 | 3056 | 3) Just like %sc -l, this is a list with special attributes: |
|
3057 | 3057 | |
|
3058 | 3058 | .l (or .list) : value as list. |
|
3059 | 3059 | .n (or .nlstr): value as newline-separated string. |
|
3060 | 3060 | .s (or .spstr): value as whitespace-separated string. |
|
3061 | 3061 | |
|
3062 | 3062 | This is very useful when trying to use such lists as arguments to |
|
3063 | 3063 | system commands.""" |
|
3064 | 3064 | |
|
3065 | 3065 | if parameter_s: |
|
3066 | 3066 | out,err = self.shell.getoutputerror(parameter_s) |
|
3067 | 3067 | if err: |
|
3068 | 3068 | print >> Term.cerr,err |
|
3069 | 3069 | return SList(out.split('\n')) |
|
3070 | 3070 | |
|
3071 | 3071 | def magic_bg(self, parameter_s=''): |
|
3072 | 3072 | """Run a job in the background, in a separate thread. |
|
3073 | 3073 | |
|
3074 | 3074 | For example, |
|
3075 | 3075 | |
|
3076 | 3076 | %bg myfunc(x,y,z=1) |
|
3077 | 3077 | |
|
3078 | 3078 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3079 | 3079 | execution starts, a message will be printed indicating the job |
|
3080 | 3080 | number. If your job number is 5, you can use |
|
3081 | 3081 | |
|
3082 | 3082 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3083 | 3083 | |
|
3084 | 3084 | to assign this result to variable 'myvar'. |
|
3085 | 3085 | |
|
3086 | 3086 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3087 | 3087 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3088 | 3088 | its attributes. All attributes not starting with an underscore are |
|
3089 | 3089 | meant for public use. |
|
3090 | 3090 | |
|
3091 | 3091 | In particular, look at the jobs.new() method, which is used to create |
|
3092 | 3092 | new jobs. This magic %bg function is just a convenience wrapper |
|
3093 | 3093 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3094 | 3094 | new job with an explicit function object and arguments, you must call |
|
3095 | 3095 | jobs.new() directly. |
|
3096 | 3096 | |
|
3097 | 3097 | The jobs.new docstring also describes in detail several important |
|
3098 | 3098 | caveats associated with a thread-based model for background job |
|
3099 | 3099 | execution. Type jobs.new? for details. |
|
3100 | 3100 | |
|
3101 | 3101 | You can check the status of all jobs with jobs.status(). |
|
3102 | 3102 | |
|
3103 | 3103 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3104 | 3104 | If you ever declare a variable named 'jobs', you will shadow this |
|
3105 | 3105 | name. You can either delete your global jobs variable to regain |
|
3106 | 3106 | access to the job manager, or make a new name and assign it manually |
|
3107 | 3107 | to the manager (stored in IPython's namespace). For example, to |
|
3108 | 3108 | assign the job manager to the Jobs name, use: |
|
3109 | 3109 | |
|
3110 | 3110 | Jobs = __builtins__.jobs""" |
|
3111 | 3111 | |
|
3112 | 3112 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3113 | 3113 | |
|
3114 | 3114 | def magic_r(self, parameter_s=''): |
|
3115 | 3115 | """Repeat previous input. |
|
3116 | 3116 | |
|
3117 | 3117 | Note: Consider using the more powerfull %rep instead! |
|
3118 | 3118 | |
|
3119 | 3119 | If given an argument, repeats the previous command which starts with |
|
3120 | 3120 | the same string, otherwise it just repeats the previous input. |
|
3121 | 3121 | |
|
3122 | 3122 | Shell escaped commands (with ! as first character) are not recognized |
|
3123 | 3123 | by this system, only pure python code and magic commands. |
|
3124 | 3124 | """ |
|
3125 | 3125 | |
|
3126 | 3126 | start = parameter_s.strip() |
|
3127 | 3127 | esc_magic = ESC_MAGIC |
|
3128 | 3128 | # Identify magic commands even if automagic is on (which means |
|
3129 | 3129 | # the in-memory version is different from that typed by the user). |
|
3130 | 3130 | if self.shell.automagic: |
|
3131 | 3131 | start_magic = esc_magic+start |
|
3132 | 3132 | else: |
|
3133 | 3133 | start_magic = start |
|
3134 | 3134 | # Look through the input history in reverse |
|
3135 | 3135 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3136 | 3136 | input = self.shell.input_hist[n] |
|
3137 | 3137 | # skip plain 'r' lines so we don't recurse to infinity |
|
3138 | 3138 | if input != '_ip.magic("r")\n' and \ |
|
3139 | 3139 | (input.startswith(start) or input.startswith(start_magic)): |
|
3140 | 3140 | #print 'match',`input` # dbg |
|
3141 | 3141 | print 'Executing:',input, |
|
3142 | 3142 | self.shell.runlines(input) |
|
3143 | 3143 | return |
|
3144 | 3144 | print 'No previous input matching `%s` found.' % start |
|
3145 | 3145 | |
|
3146 | 3146 | |
|
3147 | 3147 | def magic_bookmark(self, parameter_s=''): |
|
3148 | 3148 | """Manage IPython's bookmark system. |
|
3149 | 3149 | |
|
3150 | 3150 | %bookmark <name> - set bookmark to current dir |
|
3151 | 3151 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3152 | 3152 | %bookmark -l - list all bookmarks |
|
3153 | 3153 | %bookmark -d <name> - remove bookmark |
|
3154 | 3154 | %bookmark -r - remove all bookmarks |
|
3155 | 3155 | |
|
3156 | 3156 | You can later on access a bookmarked folder with: |
|
3157 | 3157 | %cd -b <name> |
|
3158 | 3158 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3159 | 3159 | there is such a bookmark defined. |
|
3160 | 3160 | |
|
3161 | 3161 | Your bookmarks persist through IPython sessions, but they are |
|
3162 | 3162 | associated with each profile.""" |
|
3163 | 3163 | |
|
3164 | 3164 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3165 | 3165 | if len(args) > 2: |
|
3166 | 3166 | raise UsageError("%bookmark: too many arguments") |
|
3167 | 3167 | |
|
3168 | 3168 | bkms = self.db.get('bookmarks',{}) |
|
3169 | 3169 | |
|
3170 | 3170 | if opts.has_key('d'): |
|
3171 | 3171 | try: |
|
3172 | 3172 | todel = args[0] |
|
3173 | 3173 | except IndexError: |
|
3174 | 3174 | raise UsageError( |
|
3175 | 3175 | "%bookmark -d: must provide a bookmark to delete") |
|
3176 | 3176 | else: |
|
3177 | 3177 | try: |
|
3178 | 3178 | del bkms[todel] |
|
3179 | 3179 | except KeyError: |
|
3180 | 3180 | raise UsageError( |
|
3181 | 3181 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3182 | 3182 | |
|
3183 | 3183 | elif opts.has_key('r'): |
|
3184 | 3184 | bkms = {} |
|
3185 | 3185 | elif opts.has_key('l'): |
|
3186 | 3186 | bks = bkms.keys() |
|
3187 | 3187 | bks.sort() |
|
3188 | 3188 | if bks: |
|
3189 | 3189 | size = max(map(len,bks)) |
|
3190 | 3190 | else: |
|
3191 | 3191 | size = 0 |
|
3192 | 3192 | fmt = '%-'+str(size)+'s -> %s' |
|
3193 | 3193 | print 'Current bookmarks:' |
|
3194 | 3194 | for bk in bks: |
|
3195 | 3195 | print fmt % (bk,bkms[bk]) |
|
3196 | 3196 | else: |
|
3197 | 3197 | if not args: |
|
3198 | 3198 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3199 | 3199 | elif len(args)==1: |
|
3200 | 3200 | bkms[args[0]] = os.getcwd() |
|
3201 | 3201 | elif len(args)==2: |
|
3202 | 3202 | bkms[args[0]] = args[1] |
|
3203 | 3203 | self.db['bookmarks'] = bkms |
|
3204 | 3204 | |
|
3205 | 3205 | def magic_pycat(self, parameter_s=''): |
|
3206 | 3206 | """Show a syntax-highlighted file through a pager. |
|
3207 | 3207 | |
|
3208 | 3208 | This magic is similar to the cat utility, but it will assume the file |
|
3209 | 3209 | to be Python source and will show it with syntax highlighting. """ |
|
3210 | 3210 | |
|
3211 | 3211 | try: |
|
3212 | 3212 | filename = get_py_filename(parameter_s) |
|
3213 | 3213 | cont = file_read(filename) |
|
3214 | 3214 | except IOError: |
|
3215 | 3215 | try: |
|
3216 | 3216 | cont = eval(parameter_s,self.user_ns) |
|
3217 | 3217 | except NameError: |
|
3218 | 3218 | cont = None |
|
3219 | 3219 | if cont is None: |
|
3220 | 3220 | print "Error: no such file or variable" |
|
3221 | 3221 | return |
|
3222 | 3222 | |
|
3223 | 3223 | page(self.shell.pycolorize(cont), |
|
3224 | 3224 | screen_lines=self.shell.usable_screen_length) |
|
3225 | 3225 | |
|
3226 | 3226 | def _rerun_pasted(self): |
|
3227 | 3227 | """ Rerun a previously pasted command. |
|
3228 | 3228 | """ |
|
3229 | 3229 | b = self.user_ns.get('pasted_block', None) |
|
3230 | 3230 | if b is None: |
|
3231 | 3231 | raise UsageError('No previous pasted block available') |
|
3232 | 3232 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3233 | 3233 | exec b in self.user_ns |
|
3234 | 3234 | |
|
3235 | 3235 | def _get_pasted_lines(self, sentinel): |
|
3236 | 3236 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3237 | 3237 | """ |
|
3238 | 3238 | from IPython.core import iplib |
|
3239 | 3239 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3240 | 3240 | while True: |
|
3241 | 3241 | l = iplib.raw_input_original(':') |
|
3242 | 3242 | if l == sentinel: |
|
3243 | 3243 | return |
|
3244 | 3244 | else: |
|
3245 | 3245 | yield l |
|
3246 | 3246 | |
|
3247 | 3247 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3248 | 3248 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3249 | 3249 | code. |
|
3250 | 3250 | """ |
|
3251 | 3251 | # Regular expressions that declare text we strip from the input: |
|
3252 | 3252 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3253 | 3253 | r'^\s*(\s?>)+', # Python input prompt |
|
3254 | 3254 | r'^\s*\.{3,}', # Continuation prompts |
|
3255 | 3255 | r'^\++', |
|
3256 | 3256 | ] |
|
3257 | 3257 | |
|
3258 | 3258 | strip_from_start = map(re.compile,strip_re) |
|
3259 | 3259 | |
|
3260 | 3260 | lines = [] |
|
3261 | 3261 | for l in raw_lines: |
|
3262 | 3262 | for pat in strip_from_start: |
|
3263 | 3263 | l = pat.sub('',l) |
|
3264 | 3264 | lines.append(l) |
|
3265 | 3265 | |
|
3266 | 3266 | block = "\n".join(lines) + '\n' |
|
3267 | 3267 | #print "block:\n",block |
|
3268 | 3268 | return block |
|
3269 | 3269 | |
|
3270 | 3270 | def _execute_block(self, block, par): |
|
3271 | 3271 | """ Execute a block, or store it in a variable, per the user's request. |
|
3272 | 3272 | """ |
|
3273 | 3273 | if not par: |
|
3274 | 3274 | b = textwrap.dedent(block) |
|
3275 | 3275 | self.user_ns['pasted_block'] = b |
|
3276 | 3276 | exec b in self.user_ns |
|
3277 | 3277 | else: |
|
3278 | 3278 | self.user_ns[par] = SList(block.splitlines()) |
|
3279 | 3279 | print "Block assigned to '%s'" % par |
|
3280 | 3280 | |
|
3281 | 3281 | def magic_cpaste(self, parameter_s=''): |
|
3282 | 3282 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3283 | 3283 | |
|
3284 | 3284 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3285 | 3285 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3286 | 3286 | is the new sentinel for this operation) |
|
3287 | 3287 | |
|
3288 | 3288 | The block is dedented prior to execution to enable execution of method |
|
3289 | 3289 | definitions. '>' and '+' characters at the beginning of a line are |
|
3290 | 3290 | ignored, to allow pasting directly from e-mails, diff files and |
|
3291 | 3291 | doctests (the '...' continuation prompt is also stripped). The |
|
3292 | 3292 | executed block is also assigned to variable named 'pasted_block' for |
|
3293 | 3293 | later editing with '%edit pasted_block'. |
|
3294 | 3294 | |
|
3295 | 3295 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3296 | 3296 | This assigns the pasted block to variable 'foo' as string, without |
|
3297 | 3297 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3298 | 3298 | |
|
3299 | 3299 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3300 | 3300 | |
|
3301 | 3301 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3302 | 3302 | Just press enter and type -- (and press enter again) and the block |
|
3303 | 3303 | will be what was just pasted. |
|
3304 | 3304 | |
|
3305 | 3305 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3306 | 3306 | |
|
3307 | 3307 | See also |
|
3308 | 3308 | -------- |
|
3309 | 3309 | paste: automatically pull code from clipboard. |
|
3310 | 3310 | """ |
|
3311 | 3311 | |
|
3312 | 3312 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3313 | 3313 | par = args.strip() |
|
3314 | 3314 | if opts.has_key('r'): |
|
3315 | 3315 | self._rerun_pasted() |
|
3316 | 3316 | return |
|
3317 | 3317 | |
|
3318 | 3318 | sentinel = opts.get('s','--') |
|
3319 | 3319 | |
|
3320 | 3320 | block = self._strip_pasted_lines_for_code( |
|
3321 | 3321 | self._get_pasted_lines(sentinel)) |
|
3322 | 3322 | |
|
3323 | 3323 | self._execute_block(block, par) |
|
3324 | 3324 | |
|
3325 | 3325 | def magic_paste(self, parameter_s=''): |
|
3326 | 3326 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3327 | 3327 | |
|
3328 | 3328 | The text is pulled directly from the clipboard without user |
|
3329 | 3329 | intervention and printed back on the screen before execution (unless |
|
3330 | 3330 | the -q flag is given to force quiet mode). |
|
3331 | 3331 | |
|
3332 | 3332 | The block is dedented prior to execution to enable execution of method |
|
3333 | 3333 | definitions. '>' and '+' characters at the beginning of a line are |
|
3334 | 3334 | ignored, to allow pasting directly from e-mails, diff files and |
|
3335 | 3335 | doctests (the '...' continuation prompt is also stripped). The |
|
3336 | 3336 | executed block is also assigned to variable named 'pasted_block' for |
|
3337 | 3337 | later editing with '%edit pasted_block'. |
|
3338 | 3338 | |
|
3339 | 3339 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3340 | 3340 | This assigns the pasted block to variable 'foo' as string, without |
|
3341 | 3341 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3342 | 3342 | |
|
3343 | 3343 | Options |
|
3344 | 3344 | ------- |
|
3345 | 3345 | |
|
3346 | 3346 | -r: re-executes the block previously entered by cpaste. |
|
3347 | 3347 | |
|
3348 | 3348 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3349 | 3349 | |
|
3350 | 3350 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3351 | 3351 | |
|
3352 | 3352 | See also |
|
3353 | 3353 | -------- |
|
3354 | 3354 | cpaste: manually paste code into terminal until you mark its end. |
|
3355 | 3355 | """ |
|
3356 | 3356 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3357 | 3357 | par = args.strip() |
|
3358 | 3358 | if opts.has_key('r'): |
|
3359 | 3359 | self._rerun_pasted() |
|
3360 | 3360 | return |
|
3361 | 3361 | |
|
3362 | 3362 | text = self.shell.hooks.clipboard_get() |
|
3363 | 3363 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3364 | 3364 | |
|
3365 | 3365 | # By default, echo back to terminal unless quiet mode is requested |
|
3366 | 3366 | if not opts.has_key('q'): |
|
3367 | 3367 | write = self.shell.write |
|
3368 | 3368 | write(block) |
|
3369 | 3369 | if not block.endswith('\n'): |
|
3370 | 3370 | write('\n') |
|
3371 | 3371 | write("## -- End pasted text --\n") |
|
3372 | 3372 | |
|
3373 | 3373 | self._execute_block(block, par) |
|
3374 | 3374 | |
|
3375 | 3375 | def magic_quickref(self,arg): |
|
3376 | 3376 | """ Show a quick reference sheet """ |
|
3377 | 3377 | import IPython.core.usage |
|
3378 | 3378 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3379 | 3379 | |
|
3380 | 3380 | page(qr) |
|
3381 | 3381 | |
|
3382 | def magic_upgrade(self,arg): | |
|
3383 | """ Upgrade your IPython installation | |
|
3384 | ||
|
3385 | This will copy the config files that don't yet exist in your | |
|
3386 | ipython dir from the system config dir. Use this after upgrading | |
|
3387 | IPython if you don't wish to delete your .ipython dir. | |
|
3388 | ||
|
3389 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
|
3390 | new users) | |
|
3391 | ||
|
3392 | """ | |
|
3393 | ip = self.getapi() | |
|
3394 | ipinstallation = path(IPython.__file__).dirname() | |
|
3395 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') | |
|
3396 | src_config = ipinstallation / 'config' / 'userconfig' | |
|
3397 | userdir = path(ip.config.IPYTHONDIR) | |
|
3398 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
|
3399 | print ">",cmd | |
|
3400 | shell(cmd) | |
|
3401 | if arg == '-nolegacy': | |
|
3402 | legacy = userdir.files('ipythonrc*') | |
|
3403 | print "Nuking legacy files:",legacy | |
|
3404 | ||
|
3405 | [p.remove() for p in legacy] | |
|
3406 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
|
3407 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
|
3408 | ||
|
3409 | ||
|
3410 | 3382 | def magic_doctest_mode(self,parameter_s=''): |
|
3411 | 3383 | """Toggle doctest mode on and off. |
|
3412 | 3384 | |
|
3413 | 3385 | This mode allows you to toggle the prompt behavior between normal |
|
3414 | 3386 | IPython prompts and ones that are as similar to the default IPython |
|
3415 | 3387 | interpreter as possible. |
|
3416 | 3388 | |
|
3417 | 3389 | It also supports the pasting of code snippets that have leading '>>>' |
|
3418 | 3390 | and '...' prompts in them. This means that you can paste doctests from |
|
3419 | 3391 | files or docstrings (even if they have leading whitespace), and the |
|
3420 | 3392 | code will execute correctly. You can then use '%history -tn' to see |
|
3421 | 3393 | the translated history without line numbers; this will give you the |
|
3422 | 3394 | input after removal of all the leading prompts and whitespace, which |
|
3423 | 3395 | can be pasted back into an editor. |
|
3424 | 3396 | |
|
3425 | 3397 | With these features, you can switch into this mode easily whenever you |
|
3426 | 3398 | need to do testing and changes to doctests, without having to leave |
|
3427 | 3399 | your existing IPython session. |
|
3428 | 3400 | """ |
|
3429 | 3401 | |
|
3430 | 3402 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3431 | 3403 | from IPython.extensions import InterpreterPasteInput as ipaste |
|
3432 | 3404 | from IPython.utils.ipstruct import Struct |
|
3433 | 3405 | |
|
3434 | 3406 | # Shorthands |
|
3435 | 3407 | shell = self.shell |
|
3436 | 3408 | oc = shell.outputcache |
|
3437 | 3409 | meta = shell.meta |
|
3438 | 3410 | # dstore is a data store kept in the instance metadata bag to track any |
|
3439 | 3411 | # changes we make, so we can undo them later. |
|
3440 | 3412 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3441 | 3413 | save_dstore = dstore.setdefault |
|
3442 | 3414 | |
|
3443 | 3415 | # save a few values we'll need to recover later |
|
3444 | 3416 | mode = save_dstore('mode',False) |
|
3445 | 3417 | save_dstore('rc_pprint',shell.pprint) |
|
3446 | 3418 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3447 | 3419 | save_dstore('rc_separate_out',shell.separate_out) |
|
3448 | 3420 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3449 | 3421 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3450 | 3422 | save_dstore('rc_separate_in',shell.separate_in) |
|
3451 | 3423 | |
|
3452 | 3424 | if mode == False: |
|
3453 | 3425 | # turn on |
|
3454 | 3426 | ipaste.activate_prefilter() |
|
3455 | 3427 | |
|
3456 | 3428 | oc.prompt1.p_template = '>>> ' |
|
3457 | 3429 | oc.prompt2.p_template = '... ' |
|
3458 | 3430 | oc.prompt_out.p_template = '' |
|
3459 | 3431 | |
|
3460 | 3432 | # Prompt separators like plain python |
|
3461 | 3433 | oc.input_sep = oc.prompt1.sep = '' |
|
3462 | 3434 | oc.output_sep = '' |
|
3463 | 3435 | oc.output_sep2 = '' |
|
3464 | 3436 | |
|
3465 | 3437 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3466 | 3438 | oc.prompt_out.pad_left = False |
|
3467 | 3439 | |
|
3468 | 3440 | shell.pprint = False |
|
3469 | 3441 | |
|
3470 | 3442 | shell.magic_xmode('Plain') |
|
3471 | 3443 | |
|
3472 | 3444 | else: |
|
3473 | 3445 | # turn off |
|
3474 | 3446 | ipaste.deactivate_prefilter() |
|
3475 | 3447 | |
|
3476 | 3448 | oc.prompt1.p_template = shell.prompt_in1 |
|
3477 | 3449 | oc.prompt2.p_template = shell.prompt_in2 |
|
3478 | 3450 | oc.prompt_out.p_template = shell.prompt_out |
|
3479 | 3451 | |
|
3480 | 3452 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3481 | 3453 | |
|
3482 | 3454 | oc.output_sep = dstore.rc_separate_out |
|
3483 | 3455 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3484 | 3456 | |
|
3485 | 3457 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3486 | 3458 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3487 | 3459 | |
|
3488 | 3460 | rc.pprint = dstore.rc_pprint |
|
3489 | 3461 | |
|
3490 | 3462 | shell.magic_xmode(dstore.xmode) |
|
3491 | 3463 | |
|
3492 | 3464 | # Store new mode and inform |
|
3493 | 3465 | dstore.mode = bool(1-int(mode)) |
|
3494 | 3466 | print 'Doctest mode is:', |
|
3495 | 3467 | print ['OFF','ON'][dstore.mode] |
|
3496 | 3468 | |
|
3497 | 3469 | def magic_gui(self, parameter_s=''): |
|
3498 | 3470 | """Enable or disable IPython GUI event loop integration. |
|
3499 | 3471 | |
|
3500 | 3472 | %gui [-a] [GUINAME] |
|
3501 | 3473 | |
|
3502 | 3474 | This magic replaces IPython's threaded shells that were activated |
|
3503 | 3475 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3504 | 3476 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3505 | 3477 | interrupts should work without any problems. The following toolkits |
|
3506 | 3478 | are supports: wxPython, PyQt4, PyGTK, and Tk:: |
|
3507 | 3479 | |
|
3508 | 3480 | %gui wx # enable wxPython event loop integration |
|
3509 | 3481 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3510 | 3482 | %gui gtk # enable PyGTK event loop integration |
|
3511 | 3483 | %gui tk # enable Tk event loop integration |
|
3512 | 3484 | %gui # disable all event loop integration |
|
3513 | 3485 | |
|
3514 | 3486 | WARNING: after any of these has been called you can simply create |
|
3515 | 3487 | an application object, but DO NOT start the event loop yourself, as |
|
3516 | 3488 | we have already handled that. |
|
3517 | 3489 | |
|
3518 | 3490 | If you want us to create an appropriate application object add the |
|
3519 | 3491 | "-a" flag to your command:: |
|
3520 | 3492 | |
|
3521 | 3493 | %gui -a wx |
|
3522 | 3494 | |
|
3523 | 3495 | This is highly recommended for most users. |
|
3524 | 3496 | """ |
|
3525 | 3497 | from IPython.lib import inputhook |
|
3526 | 3498 | if "-a" in parameter_s: |
|
3527 | 3499 | app = True |
|
3528 | 3500 | else: |
|
3529 | 3501 | app = False |
|
3530 | 3502 | if not parameter_s: |
|
3531 | 3503 | inputhook.clear_inputhook() |
|
3532 | 3504 | elif 'wx' in parameter_s: |
|
3533 | 3505 | return inputhook.enable_wx(app) |
|
3534 | 3506 | elif ('qt4' in parameter_s) or ('qt' in parameter_s): |
|
3535 | 3507 | return inputhook.enable_qt4(app) |
|
3536 | 3508 | elif 'gtk' in parameter_s: |
|
3537 | 3509 | return inputhook.enable_gtk(app) |
|
3538 | 3510 | elif 'tk' in parameter_s: |
|
3539 | 3511 | return inputhook.enable_tk(app) |
|
3540 | 3512 | |
|
3541 | 3513 | def magic_load_ext(self, module_str): |
|
3542 | 3514 | """Load an IPython extension by its module name.""" |
|
3543 | 3515 | self.load_extension(module_str) |
|
3544 | 3516 | |
|
3545 | 3517 | def magic_unload_ext(self, module_str): |
|
3546 | 3518 | """Unload an IPython extension by its module name.""" |
|
3547 | 3519 | self.unload_extension(module_str) |
|
3548 | 3520 | |
|
3549 | 3521 | def magic_reload_ext(self, module_str): |
|
3550 | 3522 | """Reload an IPython extension by its module name.""" |
|
3551 | 3523 | self.reload_extension(module_str) |
|
3552 | 3524 | |
|
3553 | 3525 | def magic_install_profiles(self, s): |
|
3554 | 3526 | """Install the default IPython profiles into the .ipython dir. |
|
3555 | 3527 | |
|
3556 | 3528 | If the default profiles have already been installed, they will not |
|
3557 | 3529 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3558 | 3530 | option:: |
|
3559 | 3531 | |
|
3560 | 3532 | In [1]: %install_profiles -o |
|
3561 | 3533 | """ |
|
3562 | 3534 | if '-o' in s: |
|
3563 | 3535 | overwrite = True |
|
3564 | 3536 | else: |
|
3565 | 3537 | overwrite = False |
|
3566 | 3538 | from IPython.config import profile |
|
3567 | 3539 | profile_dir = os.path.split(profile.__file__)[0] |
|
3568 | ipythondir = self.ipythondir | |
|
3540 | ipython_dir = self.ipython_dir | |
|
3569 | 3541 | files = os.listdir(profile_dir) |
|
3570 | 3542 | |
|
3571 | 3543 | to_install = [] |
|
3572 | 3544 | for f in files: |
|
3573 | 3545 | if f.startswith('ipython_config'): |
|
3574 | 3546 | src = os.path.join(profile_dir, f) |
|
3575 | dst = os.path.join(ipythondir, f) | |
|
3547 | dst = os.path.join(ipython_dir, f) | |
|
3576 | 3548 | if (not os.path.isfile(dst)) or overwrite: |
|
3577 | 3549 | to_install.append((f, src, dst)) |
|
3578 | 3550 | if len(to_install)>0: |
|
3579 | print "Installing profiles to: ", ipythondir | |
|
3551 | print "Installing profiles to: ", ipython_dir | |
|
3580 | 3552 | for (f, src, dst) in to_install: |
|
3581 | 3553 | shutil.copy(src, dst) |
|
3582 | 3554 | print " %s" % f |
|
3583 | 3555 | |
|
3584 | 3556 | def magic_install_default_config(self, s): |
|
3585 | 3557 | """Install IPython's default config file into the .ipython dir. |
|
3586 | 3558 | |
|
3587 | 3559 | If the default config file (:file:`ipython_config.py`) is already |
|
3588 | 3560 | installed, it will not be overwritten. You can force overwriting |
|
3589 | 3561 | by using the ``-o`` option:: |
|
3590 | 3562 | |
|
3591 | 3563 | In [1]: %install_default_config |
|
3592 | 3564 | """ |
|
3593 | 3565 | if '-o' in s: |
|
3594 | 3566 | overwrite = True |
|
3595 | 3567 | else: |
|
3596 | 3568 | overwrite = False |
|
3597 | 3569 | from IPython.config import default |
|
3598 | 3570 | config_dir = os.path.split(default.__file__)[0] |
|
3599 | ipythondir = self.ipythondir | |
|
3571 | ipython_dir = self.ipython_dir | |
|
3600 | 3572 | default_config_file_name = 'ipython_config.py' |
|
3601 | 3573 | src = os.path.join(config_dir, default_config_file_name) |
|
3602 | dst = os.path.join(ipythondir, default_config_file_name) | |
|
3574 | dst = os.path.join(ipython_dir, default_config_file_name) | |
|
3603 | 3575 | if (not os.path.isfile(dst)) or overwrite: |
|
3604 | 3576 | shutil.copy(src, dst) |
|
3605 | 3577 | print "Installing default config file: %s" % dst |
|
3606 | 3578 | |
|
3607 | 3579 | |
|
3608 | 3580 | # end Magic |
@@ -1,80 +1,57 b'' | |||
|
1 | 1 | """Tests for the key iplib module, where the main ipython class is defined. |
|
2 | 2 | """ |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Module imports |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | |
|
7 | 7 | # stdlib |
|
8 | 8 | import os |
|
9 | 9 | import shutil |
|
10 | 10 | import tempfile |
|
11 | 11 | |
|
12 | 12 | # third party |
|
13 | 13 | import nose.tools as nt |
|
14 | 14 | |
|
15 | 15 | # our own packages |
|
16 | 16 | from IPython.core import iplib |
|
17 | 17 | from IPython.core import ipapi |
|
18 | from IPython.core.oldusersetup import user_setup | |
|
18 | ||
|
19 | 19 | |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | # Globals |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | |
|
24 | 24 | # Useful global ipapi object and main IPython one. Unfortunately we have a |
|
25 | 25 | # long precedent of carrying the 'ipapi' global object which is injected into |
|
26 | 26 | # the system namespace as _ip, but that keeps a pointer to the actual IPython |
|
27 | 27 | # InteractiveShell instance, which is named IP. Since in testing we do need |
|
28 | 28 | # access to the real thing (we want to probe beyond what ipapi exposes), make |
|
29 | 29 | # here a global reference to each. In general, things that are exposed by the |
|
30 | 30 | # ipapi instance should be read from there, but we also will often need to use |
|
31 | 31 | # the actual IPython one. |
|
32 | 32 | |
|
33 | 33 | # Get the public instance of IPython, and if it's None, make one so we can use |
|
34 | 34 | # it for testing |
|
35 | 35 | ip = ipapi.get() |
|
36 | 36 | if ip is None: |
|
37 | 37 | # IPython not running yet, make one from the testing machinery for |
|
38 | 38 | # consistency when the test suite is being run via iptest |
|
39 | 39 | from IPython.testing.plugin import ipdoctest |
|
40 | 40 | ip = ipapi.get() |
|
41 | 41 | |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # Test functions |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | |
|
46 | 46 | def test_reset(): |
|
47 | 47 | """reset must clear most namespaces.""" |
|
48 | 48 | ip.reset() # first, it should run without error |
|
49 | 49 | # Then, check that most namespaces end up empty |
|
50 | 50 | for ns in ip.ns_refs_table: |
|
51 | 51 | if ns is ip.user_ns: |
|
52 | 52 | # The user namespace is reset with some data, so we can't check for |
|
53 | 53 | # it being empty |
|
54 | 54 | continue |
|
55 | 55 | nt.assert_equals(len(ns),0) |
|
56 | 56 | |
|
57 | 57 | |
|
No newline at end of file | ||
|
58 | # make sure that user_setup can be run re-entrantly in 'install' mode. | |
|
59 | def test_user_setup(): | |
|
60 | # use a lambda to pass kwargs to the generator | |
|
61 | user_setup = lambda a,k: user_setup(*a,**k) | |
|
62 | kw = dict(mode='install', interactive=False) | |
|
63 | ||
|
64 | # Call the user setup and verify that the directory exists | |
|
65 | yield user_setup, (ip.config.IPYTHONDIR,''), kw | |
|
66 | yield os.path.isdir, ip.config.IPYTHONDIR | |
|
67 | ||
|
68 | # Now repeat the operation with a non-existent directory. Check both that | |
|
69 | # the call succeeds and that the directory is created. | |
|
70 | tmpdir = tempfile.mktemp(prefix='ipython-test-') | |
|
71 | # Use a try with an empty except because try/finally doesn't work with a | |
|
72 | # yield in Python 2.4. | |
|
73 | try: | |
|
74 | yield user_setup, (tmpdir,''), kw | |
|
75 | yield os.path.isdir, tmpdir | |
|
76 | except: | |
|
77 | pass | |
|
78 | # Clean up the temp dir once done | |
|
79 | shutil.rmtree(tmpdir) | |
|
80 | No newline at end of file |
@@ -1,588 +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 | IPYTHONDIR. | |
|
43 | IPYTHON_DIR. | |
|
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 | The name of your IPython configuration directory IPYTHONDIR. | |
|
153 | The name of your IPython configuration directory IPYTHON_DIR. | |
|
154 | 154 | This can also be specified through the environment variable |
|
155 | IPYTHONDIR. | |
|
155 | IPYTHON_DIR. | |
|
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 | rent dir first, then in IPYTHONDIR). This is a quick way to keep | |
|
204 | rent dir first, then in IPYTHON_DIR). 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 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' | |
|
207 | basic IPYTHON_DIR/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 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, | |
|
248 | IPYTHON_DIR/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 | Allows you to upgrade your IPYTHONDIR configuration when you | |
|
287 | Allows you to upgrade your IPYTHON_DIR 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 | 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 | 587 | |
|
588 | 588 | default_banner = '\n'.join(default_banner_parts) |
@@ -1,266 +1,266 b'' | |||
|
1 | 1 | #!/usr/bin/python |
|
2 | 2 | # -*- coding: iso-8859-15 -*- |
|
3 | 3 | |
|
4 | 4 | import wx.aui |
|
5 | 5 | import sys |
|
6 | 6 | #used for about dialog |
|
7 | 7 | from wx.lib.wordwrap import wordwrap |
|
8 | 8 | |
|
9 | 9 | #used for ipython GUI objects |
|
10 | 10 | from IPython.gui.wx.ipython_view import IPShellWidget |
|
11 | 11 | from IPython.gui.wx.ipython_history import IPythonHistoryPanel |
|
12 | 12 | |
|
13 | 13 | #used to invoke ipython1 wx implementation |
|
14 | 14 | ### FIXME ### temporary disabled due to interference with 'show_in_pager' hook |
|
15 | 15 | is_sync_frontend_ok = False |
|
16 | 16 | try: |
|
17 | 17 | from IPython.frontend.wx.ipythonx import IPythonXController |
|
18 | 18 | except ImportError: |
|
19 | 19 | is_sync_frontend_ok = False |
|
20 | 20 | |
|
21 | 21 | #used to create options.conf file in user directory |
|
22 | 22 | from IPython.core.ipapi import get |
|
23 | 23 | |
|
24 | 24 | __version__ = 0.91 |
|
25 | 25 | __author__ = "Laurent Dufrechou" |
|
26 | 26 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
27 | 27 | __license__ = "BSD" |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------- |
|
30 | 30 | # Creating one main frame for our |
|
31 | 31 | # application with movables windows |
|
32 | 32 | #----------------------------------------- |
|
33 | 33 | class MyFrame(wx.Frame): |
|
34 | 34 | """Creating one main frame for our |
|
35 | 35 | application with movables windows""" |
|
36 | 36 | def __init__(self, parent=None, id=-1, title="WxIPython", |
|
37 | 37 | pos=wx.DefaultPosition, |
|
38 | 38 | size=(800, 600), style=wx.DEFAULT_FRAME_STYLE, sync_ok=False): |
|
39 | 39 | wx.Frame.__init__(self, parent, id, title, pos, size, style) |
|
40 | 40 | self._mgr = wx.aui.AuiManager() |
|
41 | 41 | |
|
42 | 42 | # notify PyAUI which frame to use |
|
43 | 43 | self._mgr.SetManagedWindow(self) |
|
44 | 44 | |
|
45 | 45 | #create differents panels and make them persistant |
|
46 | 46 | self.history_panel = IPythonHistoryPanel(self) |
|
47 | 47 | |
|
48 | 48 | self.history_panel.setOptionTrackerHook(self.optionSave) |
|
49 | 49 | |
|
50 | 50 | self.ipython_panel = IPShellWidget(self,background_color = "BLACK") |
|
51 | 51 | #self.ipython_panel = IPShellWidget(self,background_color = "WHITE") |
|
52 | 52 | if(sync_ok): |
|
53 | 53 | self.ipython_panel2 = IPythonXController(self) |
|
54 | 54 | else: |
|
55 | 55 | self.ipython_panel2 = None |
|
56 | 56 | self.ipython_panel.setHistoryTrackerHook(self.history_panel.write) |
|
57 | 57 | self.ipython_panel.setStatusTrackerHook(self.updateStatus) |
|
58 | 58 | self.ipython_panel.setAskExitHandler(self.OnExitDlg) |
|
59 | 59 | self.ipython_panel.setOptionTrackerHook(self.optionSave) |
|
60 | 60 | |
|
61 | 61 | #Create a notebook to display different IPython shell implementations |
|
62 | 62 | self.nb = wx.aui.AuiNotebook(self) |
|
63 | 63 | |
|
64 | 64 | self.optionLoad() |
|
65 | 65 | |
|
66 | 66 | self.statusbar = self.createStatus() |
|
67 | 67 | self.createMenu() |
|
68 | 68 | |
|
69 | 69 | ######################################################################## |
|
70 | 70 | ### add the panes to the manager |
|
71 | 71 | # main panels |
|
72 | 72 | self._mgr.AddPane(self.nb , wx.CENTER, "IPython Shells") |
|
73 | 73 | self.nb.AddPage(self.ipython_panel , "IPython0 Shell") |
|
74 | 74 | if(sync_ok): |
|
75 | 75 | self.nb.AddPage(self.ipython_panel2, "IPython1 Synchroneous Shell") |
|
76 | 76 | |
|
77 | 77 | self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history") |
|
78 | 78 | |
|
79 | 79 | # now we specify some panel characteristics |
|
80 | 80 | self._mgr.GetPane(self.ipython_panel).CaptionVisible(True); |
|
81 | 81 | self._mgr.GetPane(self.history_panel).CaptionVisible(True); |
|
82 | 82 | self._mgr.GetPane(self.history_panel).MinSize((200,400)); |
|
83 | 83 | |
|
84 | 84 | # tell the manager to "commit" all the changes just made |
|
85 | 85 | self._mgr.Update() |
|
86 | 86 | |
|
87 | 87 | #global event handling |
|
88 | 88 | self.Bind(wx.EVT_CLOSE, self.OnClose) |
|
89 | 89 | self.Bind(wx.EVT_MENU, self.OnClose,id=wx.ID_EXIT) |
|
90 | 90 | self.Bind(wx.EVT_MENU, self.OnShowIPythonPanel,id=wx.ID_HIGHEST+1) |
|
91 | 91 | self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2) |
|
92 | 92 | self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3) |
|
93 | 93 | self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6) |
|
94 | 94 | |
|
95 | 95 | warn_text = 'Hello from IPython and wxPython.\n' |
|
96 | 96 | warn_text +='Please Note that this work is still EXPERIMENTAL\n' |
|
97 | 97 | warn_text +='It does NOT emulate currently all the IPython functions.\n' |
|
98 | 98 | warn_text +="\nIf you use MATPLOTLIB with show() you'll need to deactivate the THREADING option.\n" |
|
99 | 99 | if(not sync_ok): |
|
100 | 100 | warn_text +="\n->No twisted package detected, IPython1 example deactivated." |
|
101 | 101 | |
|
102 | 102 | dlg = wx.MessageDialog(self, |
|
103 | 103 | warn_text, |
|
104 | 104 | 'Warning Box', |
|
105 | 105 | wx.OK | wx.ICON_INFORMATION |
|
106 | 106 | ) |
|
107 | 107 | dlg.ShowModal() |
|
108 | 108 | dlg.Destroy() |
|
109 | 109 | |
|
110 | 110 | def optionSave(self, name, value): |
|
111 | 111 | ip = get() |
|
112 |
path = ip. |
|
|
112 | path = ip.ipython_dir | |
|
113 | 113 | opt = open(path + '/options.conf','w') |
|
114 | 114 | |
|
115 | 115 | try: |
|
116 | 116 | options_ipython_panel = self.ipython_panel.getOptions() |
|
117 | 117 | options_history_panel = self.history_panel.getOptions() |
|
118 | 118 | |
|
119 | 119 | for key in options_ipython_panel.keys(): |
|
120 | 120 | opt.write(key + '=' + options_ipython_panel[key]['value']+'\n') |
|
121 | 121 | for key in options_history_panel.keys(): |
|
122 | 122 | opt.write(key + '=' + options_history_panel[key]['value']+'\n') |
|
123 | 123 | finally: |
|
124 | 124 | opt.close() |
|
125 | 125 | |
|
126 | 126 | def optionLoad(self): |
|
127 | 127 | try: |
|
128 | 128 | ip = get() |
|
129 |
path = ip. |
|
|
129 | path = ip.ipython_dir | |
|
130 | 130 | opt = open(path + '/options.conf','r') |
|
131 | 131 | lines = opt.readlines() |
|
132 | 132 | opt.close() |
|
133 | 133 | |
|
134 | 134 | options_ipython_panel = self.ipython_panel.getOptions() |
|
135 | 135 | options_history_panel = self.history_panel.getOptions() |
|
136 | 136 | |
|
137 | 137 | for line in lines: |
|
138 | 138 | key = line.split('=')[0] |
|
139 | 139 | value = line.split('=')[1].replace('\n','').replace('\r','') |
|
140 | 140 | if key in options_ipython_panel.keys(): |
|
141 | 141 | options_ipython_panel[key]['value'] = value |
|
142 | 142 | elif key in options_history_panel.keys(): |
|
143 | 143 | options_history_panel[key]['value'] = value |
|
144 | 144 | else: |
|
145 | 145 | print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf" |
|
146 | 146 | self.ipython_panel.reloadOptions(options_ipython_panel) |
|
147 | 147 | self.history_panel.reloadOptions(options_history_panel) |
|
148 | 148 | |
|
149 | 149 | except IOError: |
|
150 | 150 | print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values." |
|
151 | 151 | |
|
152 | 152 | |
|
153 | 153 | def createMenu(self): |
|
154 | 154 | """local method used to create one menu bar""" |
|
155 | 155 | |
|
156 | 156 | mb = wx.MenuBar() |
|
157 | 157 | |
|
158 | 158 | file_menu = wx.Menu() |
|
159 | 159 | file_menu.Append(wx.ID_EXIT, "Exit") |
|
160 | 160 | |
|
161 | 161 | view_menu = wx.Menu() |
|
162 | 162 | view_menu.Append(wx.ID_HIGHEST+1, "Show IPython Panel") |
|
163 | 163 | view_menu.Append(wx.ID_HIGHEST+2, "Show History Panel") |
|
164 | 164 | view_menu.AppendSeparator() |
|
165 | 165 | view_menu.Append(wx.ID_HIGHEST+6, "Show All") |
|
166 | 166 | |
|
167 | 167 | about_menu = wx.Menu() |
|
168 | 168 | about_menu.Append(wx.ID_HIGHEST+3, "About") |
|
169 | 169 | |
|
170 | 170 | mb.Append(file_menu, "File") |
|
171 | 171 | mb.Append(view_menu, "View") |
|
172 | 172 | mb.Append(about_menu, "About") |
|
173 | 173 | #mb.Append(options_menu, "Options") |
|
174 | 174 | |
|
175 | 175 | self.SetMenuBar(mb) |
|
176 | 176 | |
|
177 | 177 | def createStatus(self): |
|
178 | 178 | statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP) |
|
179 | 179 | statusbar.SetStatusWidths([-2, -3]) |
|
180 | 180 | statusbar.SetStatusText("Ready", 0) |
|
181 | 181 | statusbar.SetStatusText("WxIPython "+str(__version__), 1) |
|
182 | 182 | return statusbar |
|
183 | 183 | |
|
184 | 184 | def updateStatus(self,text): |
|
185 | 185 | states = {'IDLE':'Idle', |
|
186 | 186 | 'DO_EXECUTE_LINE':'Send command', |
|
187 | 187 | 'WAIT_END_OF_EXECUTION':'Running command', |
|
188 | 188 | 'WAITING_USER_INPUT':'Waiting user input', |
|
189 | 189 | 'SHOW_DOC':'Showing doc', |
|
190 | 190 | 'SHOW_PROMPT':'Showing prompt'} |
|
191 | 191 | self.statusbar.SetStatusText(states[text], 0) |
|
192 | 192 | |
|
193 | 193 | def OnClose(self, event): |
|
194 | 194 | """#event used to close program """ |
|
195 | 195 | # deinitialize the frame manager |
|
196 | 196 | self._mgr.UnInit() |
|
197 | 197 | self.Destroy() |
|
198 | 198 | event.Skip() |
|
199 | 199 | |
|
200 | 200 | def OnExitDlg(self, event): |
|
201 | 201 | dlg = wx.MessageDialog(self, 'Are you sure you want to quit WxIPython', |
|
202 | 202 | 'WxIPython exit', |
|
203 | 203 | wx.ICON_QUESTION | |
|
204 | 204 | wx.YES_NO | wx.NO_DEFAULT |
|
205 | 205 | ) |
|
206 | 206 | if dlg.ShowModal() == wx.ID_YES: |
|
207 | 207 | dlg.Destroy() |
|
208 | 208 | self._mgr.UnInit() |
|
209 | 209 | self.Destroy() |
|
210 | 210 | dlg.Destroy() |
|
211 | 211 | |
|
212 | 212 | #event to display IPython pannel |
|
213 | 213 | def OnShowIPythonPanel(self,event): |
|
214 | 214 | """ #event to display Boxpannel """ |
|
215 | 215 | self._mgr.GetPane(self.ipython_panel).Show(True) |
|
216 | 216 | self._mgr.Update() |
|
217 | 217 | #event to display History pannel |
|
218 | 218 | def OnShowHistoryPanel(self,event): |
|
219 | 219 | self._mgr.GetPane(self.history_panel).Show(True) |
|
220 | 220 | self._mgr.Update() |
|
221 | 221 | |
|
222 | 222 | def OnShowAllPanel(self,event): |
|
223 | 223 | """#event to display all Pannels""" |
|
224 | 224 | self._mgr.GetPane(self.ipython_panel).Show(True) |
|
225 | 225 | self._mgr.GetPane(self.history_panel).Show(True) |
|
226 | 226 | self._mgr.Update() |
|
227 | 227 | |
|
228 | 228 | def OnShowAbout(self, event): |
|
229 | 229 | # First we create and fill the info object |
|
230 | 230 | info = wx.AboutDialogInfo() |
|
231 | 231 | info.Name = "WxIPython" |
|
232 | 232 | info.Version = str(__version__) |
|
233 | 233 | info.Copyright = "(C) 2007 Laurent Dufrechou" |
|
234 | 234 | info.Description = wordwrap( |
|
235 | 235 | "A Gui that embbed a multithreaded IPython Shell", |
|
236 | 236 | 350, wx.ClientDC(self)) |
|
237 | 237 | info.WebSite = ("http://ipython.scipy.org/", "IPython home page") |
|
238 | 238 | info.Developers = [ "Laurent Dufrechou" ] |
|
239 | 239 | licenseText="BSD License.\nAll rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.php" |
|
240 | 240 | info.License = wordwrap(licenseText, 500, wx.ClientDC(self)) |
|
241 | 241 | |
|
242 | 242 | # Then we call wx.AboutBox giving it that info object |
|
243 | 243 | wx.AboutBox(info) |
|
244 | 244 | |
|
245 | 245 | #----------------------------------------- |
|
246 | 246 | #Creating our application |
|
247 | 247 | #----------------------------------------- |
|
248 | 248 | class MyApp(wx.PySimpleApp): |
|
249 | 249 | """Creating our application""" |
|
250 | 250 | def __init__(self, sync_ok=False): |
|
251 | 251 | wx.PySimpleApp.__init__(self) |
|
252 | 252 | |
|
253 | 253 | self.frame = MyFrame(sync_ok=sync_ok) |
|
254 | 254 | self.frame.Show() |
|
255 | 255 | |
|
256 | 256 | #----------------------------------------- |
|
257 | 257 | #Main loop |
|
258 | 258 | #----------------------------------------- |
|
259 | 259 | def main(): |
|
260 | 260 | app = MyApp(is_sync_frontend_ok) |
|
261 | 261 | app.SetTopWindow(app.frame) |
|
262 | 262 | app.MainLoop() |
|
263 | 263 | |
|
264 | 264 | #if launched as main program run this |
|
265 | 265 | if __name__ == '__main__': |
|
266 | 266 | main() |
@@ -1,766 +1,766 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | |
|
4 | 4 | """Facilities for handling client connections to the controller.""" |
|
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 | from __future__ import with_statement |
|
18 | 18 | import os |
|
19 | 19 | |
|
20 | 20 | from IPython.kernel.fcutil import ( |
|
21 | 21 | Tub, |
|
22 | 22 | find_furl, |
|
23 | 23 | is_valid_furl_or_file, |
|
24 | 24 | validate_furl_or_file, |
|
25 | 25 | FURLError |
|
26 | 26 | ) |
|
27 | 27 | from IPython.kernel.clusterdir import ClusterDir, ClusterDirError |
|
28 | 28 | from IPython.kernel.launcher import IPClusterLauncher |
|
29 | 29 | from IPython.kernel.twistedutil import ( |
|
30 | 30 | gatherBoth, |
|
31 | 31 | make_deferred, |
|
32 | 32 | blockingCallFromThread, |
|
33 | 33 | sleep_deferred |
|
34 | 34 | ) |
|
35 | 35 | from IPython.utils.importstring import import_item |
|
36 | 36 | from IPython.utils.genutils import get_ipython_dir |
|
37 | 37 | |
|
38 | 38 | from twisted.internet import defer |
|
39 | 39 | from twisted.internet.defer import inlineCallbacks, returnValue |
|
40 | 40 | from twisted.python import failure, log |
|
41 | 41 | |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # The ClientConnector class |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | |
|
46 | 46 | DELAY = 0.2 |
|
47 | 47 | MAX_TRIES = 9 |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | class ClientConnectorError(Exception): |
|
51 | 51 | pass |
|
52 | 52 | |
|
53 | 53 | |
|
54 | 54 | class AsyncClientConnector(object): |
|
55 | 55 | """A class for getting remote references and clients from furls. |
|
56 | 56 | |
|
57 | 57 | This start a single :class:`Tub` for all remote reference and caches |
|
58 | 58 | references. |
|
59 | 59 | """ |
|
60 | 60 | |
|
61 | 61 | def __init__(self): |
|
62 | 62 | self._remote_refs = {} |
|
63 | 63 | self.tub = Tub() |
|
64 | 64 | self.tub.startService() |
|
65 | 65 | |
|
66 | 66 | def _find_furl(self, profile='default', cluster_dir=None, |
|
67 | 67 | furl_or_file=None, furl_file_name=None, |
|
68 | ipythondir=None): | |
|
69 | """Find a FURL file by profile+ipythondir or cluster dir. | |
|
68 | ipython_dir=None): | |
|
69 | """Find a FURL file by profile+ipython_dir or cluster dir. | |
|
70 | 70 | |
|
71 | 71 | This raises an :exc:`~IPython.kernel.fcutil.FURLError` exception |
|
72 | 72 | if a FURL file can't be found. |
|
73 | 73 | """ |
|
74 | 74 | # Try by furl_or_file |
|
75 | 75 | if furl_or_file is not None: |
|
76 | 76 | validate_furl_or_file(furl_or_file) |
|
77 | 77 | return furl_or_file |
|
78 | 78 | |
|
79 | 79 | if furl_file_name is None: |
|
80 | 80 | raise FURLError('A furl_file_name must be provided') |
|
81 | 81 | |
|
82 | 82 | # Try by cluster_dir |
|
83 | 83 | if cluster_dir is not None: |
|
84 | 84 | cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir) |
|
85 | 85 | sdir = cluster_dir_obj.security_dir |
|
86 | 86 | furl_file = os.path.join(sdir, furl_file_name) |
|
87 | 87 | validate_furl_or_file(furl_file) |
|
88 | 88 | return furl_file |
|
89 | 89 | |
|
90 | 90 | # Try by profile |
|
91 | if ipythondir is None: | |
|
92 | ipythondir = get_ipython_dir() | |
|
91 | if ipython_dir is None: | |
|
92 | ipython_dir = get_ipython_dir() | |
|
93 | 93 | if profile is not None: |
|
94 | 94 | cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile( |
|
95 | ipythondir, profile) | |
|
95 | ipython_dir, profile) | |
|
96 | 96 | sdir = cluster_dir_obj.security_dir |
|
97 | 97 | furl_file = os.path.join(sdir, furl_file_name) |
|
98 | 98 | validate_furl_or_file(furl_file) |
|
99 | 99 | return furl_file |
|
100 | 100 | |
|
101 | 101 | raise FURLError('Could not find a valid FURL file.') |
|
102 | 102 | |
|
103 | 103 | def get_reference(self, furl_or_file): |
|
104 | 104 | """Get a remote reference using a furl or a file containing a furl. |
|
105 | 105 | |
|
106 | 106 | Remote references are cached locally so once a remote reference |
|
107 | 107 | has been retrieved for a given furl, the cached version is |
|
108 | 108 | returned. |
|
109 | 109 | |
|
110 | 110 | Parameters |
|
111 | 111 | ---------- |
|
112 | 112 | furl_or_file : str |
|
113 | 113 | A furl or a filename containing a furl. This should already be |
|
114 | 114 | validated, but might not yet exist. |
|
115 | 115 | |
|
116 | 116 | Returns |
|
117 | 117 | ------- |
|
118 | 118 | A deferred to a remote reference |
|
119 | 119 | """ |
|
120 | 120 | furl = furl_or_file |
|
121 | 121 | if furl in self._remote_refs: |
|
122 | 122 | d = defer.succeed(self._remote_refs[furl]) |
|
123 | 123 | else: |
|
124 | 124 | d = self.tub.getReference(furl) |
|
125 | 125 | d.addCallback(self._save_ref, furl) |
|
126 | 126 | return d |
|
127 | 127 | |
|
128 | 128 | def _save_ref(self, ref, furl): |
|
129 | 129 | """Cache a remote reference by its furl.""" |
|
130 | 130 | self._remote_refs[furl] = ref |
|
131 | 131 | return ref |
|
132 | 132 | |
|
133 | 133 | def get_task_client(self, profile='default', cluster_dir=None, |
|
134 | furl_or_file=None, ipythondir=None, | |
|
134 | furl_or_file=None, ipython_dir=None, | |
|
135 | 135 | delay=DELAY, max_tries=MAX_TRIES): |
|
136 | 136 | """Get the task controller client. |
|
137 | 137 | |
|
138 | 138 | This method is a simple wrapper around `get_client` that passes in |
|
139 | 139 | the default name of the task client FURL file. Usually only |
|
140 | 140 | the ``profile`` option will be needed. If a FURL file can't be |
|
141 | 141 | found by its profile, use ``cluster_dir`` or ``furl_or_file``. |
|
142 | 142 | |
|
143 | 143 | Parameters |
|
144 | 144 | ---------- |
|
145 | 145 | profile : str |
|
146 | 146 | The name of a cluster directory profile (default="default"). The |
|
147 | 147 | cluster directory "cluster_<profile>" will be searched for |
|
148 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
149 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
148 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
149 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
150 | 150 | cluster_dir : str |
|
151 | 151 | The full path to a cluster directory. This is useful if profiles |
|
152 | 152 | are not being used. |
|
153 | 153 | furl_or_file : str |
|
154 | 154 | A furl or a filename containing a FURLK. This is useful if you |
|
155 | 155 | simply know the location of the FURL file. |
|
156 | ipythondir : str | |
|
157 | The location of the ipythondir if different from the default. | |
|
156 | ipython_dir : str | |
|
157 | The location of the ipython_dir if different from the default. | |
|
158 | 158 | This is used if the cluster directory is being found by profile. |
|
159 | 159 | delay : float |
|
160 | 160 | The initial delay between re-connection attempts. Susequent delays |
|
161 | 161 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
162 | 162 | max_tries : int |
|
163 | 163 | The max number of re-connection attempts. |
|
164 | 164 | |
|
165 | 165 | Returns |
|
166 | 166 | ------- |
|
167 | 167 | A deferred to the actual client class. |
|
168 | 168 | """ |
|
169 | 169 | return self.get_client( |
|
170 | 170 | profile, cluster_dir, furl_or_file, |
|
171 | 'ipcontroller-tc.furl', ipythondir, | |
|
171 | 'ipcontroller-tc.furl', ipython_dir, | |
|
172 | 172 | delay, max_tries |
|
173 | 173 | ) |
|
174 | 174 | |
|
175 | 175 | def get_multiengine_client(self, profile='default', cluster_dir=None, |
|
176 | furl_or_file=None, ipythondir=None, | |
|
176 | furl_or_file=None, ipython_dir=None, | |
|
177 | 177 | delay=DELAY, max_tries=MAX_TRIES): |
|
178 | 178 | """Get the multiengine controller client. |
|
179 | 179 | |
|
180 | 180 | This method is a simple wrapper around `get_client` that passes in |
|
181 | 181 | the default name of the task client FURL file. Usually only |
|
182 | 182 | the ``profile`` option will be needed. If a FURL file can't be |
|
183 | 183 | found by its profile, use ``cluster_dir`` or ``furl_or_file``. |
|
184 | 184 | |
|
185 | 185 | Parameters |
|
186 | 186 | ---------- |
|
187 | 187 | profile : str |
|
188 | 188 | The name of a cluster directory profile (default="default"). The |
|
189 | 189 | cluster directory "cluster_<profile>" will be searched for |
|
190 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
191 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
190 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
191 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
192 | 192 | cluster_dir : str |
|
193 | 193 | The full path to a cluster directory. This is useful if profiles |
|
194 | 194 | are not being used. |
|
195 | 195 | furl_or_file : str |
|
196 | 196 | A furl or a filename containing a FURLK. This is useful if you |
|
197 | 197 | simply know the location of the FURL file. |
|
198 | ipythondir : str | |
|
199 | The location of the ipythondir if different from the default. | |
|
198 | ipython_dir : str | |
|
199 | The location of the ipython_dir if different from the default. | |
|
200 | 200 | This is used if the cluster directory is being found by profile. |
|
201 | 201 | delay : float |
|
202 | 202 | The initial delay between re-connection attempts. Susequent delays |
|
203 | 203 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
204 | 204 | max_tries : int |
|
205 | 205 | The max number of re-connection attempts. |
|
206 | 206 | |
|
207 | 207 | Returns |
|
208 | 208 | ------- |
|
209 | 209 | A deferred to the actual client class. |
|
210 | 210 | """ |
|
211 | 211 | return self.get_client( |
|
212 | 212 | profile, cluster_dir, furl_or_file, |
|
213 | 'ipcontroller-mec.furl', ipythondir, | |
|
213 | 'ipcontroller-mec.furl', ipython_dir, | |
|
214 | 214 | delay, max_tries |
|
215 | 215 | ) |
|
216 | 216 | |
|
217 | 217 | def get_client(self, profile='default', cluster_dir=None, |
|
218 | furl_or_file=None, furl_file_name=None, ipythondir=None, | |
|
218 | furl_or_file=None, furl_file_name=None, ipython_dir=None, | |
|
219 | 219 | delay=DELAY, max_tries=MAX_TRIES): |
|
220 | 220 | """Get a remote reference and wrap it in a client by furl. |
|
221 | 221 | |
|
222 | 222 | This method is a simple wrapper around `get_client` that passes in |
|
223 | 223 | the default name of the task client FURL file. Usually only |
|
224 | 224 | the ``profile`` option will be needed. If a FURL file can't be |
|
225 | 225 | found by its profile, use ``cluster_dir`` or ``furl_or_file``. |
|
226 | 226 | |
|
227 | 227 | Parameters |
|
228 | 228 | ---------- |
|
229 | 229 | profile : str |
|
230 | 230 | The name of a cluster directory profile (default="default"). The |
|
231 | 231 | cluster directory "cluster_<profile>" will be searched for |
|
232 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
233 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
232 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
233 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
234 | 234 | cluster_dir : str |
|
235 | 235 | The full path to a cluster directory. This is useful if profiles |
|
236 | 236 | are not being used. |
|
237 | 237 | furl_or_file : str |
|
238 | 238 | A furl or a filename containing a FURL. This is useful if you |
|
239 | 239 | simply know the location of the FURL file. |
|
240 | 240 | furl_file_name : str |
|
241 | 241 | The filename (not the full path) of the FURL. This must be |
|
242 | 242 | provided if ``furl_or_file`` is not. |
|
243 | ipythondir : str | |
|
244 | The location of the ipythondir if different from the default. | |
|
243 | ipython_dir : str | |
|
244 | The location of the ipython_dir if different from the default. | |
|
245 | 245 | This is used if the cluster directory is being found by profile. |
|
246 | 246 | delay : float |
|
247 | 247 | The initial delay between re-connection attempts. Susequent delays |
|
248 | 248 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
249 | 249 | max_tries : int |
|
250 | 250 | The max number of re-connection attempts. |
|
251 | 251 | |
|
252 | 252 | Returns |
|
253 | 253 | ------- |
|
254 | 254 | A deferred to the actual client class. Or a failure to a |
|
255 | 255 | :exc:`FURLError`. |
|
256 | 256 | """ |
|
257 | 257 | try: |
|
258 | 258 | furl_file = self._find_furl( |
|
259 | 259 | profile, cluster_dir, furl_or_file, |
|
260 | furl_file_name, ipythondir | |
|
260 | furl_file_name, ipython_dir | |
|
261 | 261 | ) |
|
262 | 262 | except FURLError: |
|
263 | 263 | return defer.fail(failure.Failure()) |
|
264 | 264 | |
|
265 | 265 | def _wrap_remote_reference(rr): |
|
266 | 266 | d = rr.callRemote('get_client_name') |
|
267 | 267 | d.addCallback(lambda name: import_item(name)) |
|
268 | 268 | def adapt(client_interface): |
|
269 | 269 | client = client_interface(rr) |
|
270 | 270 | client.tub = self.tub |
|
271 | 271 | return client |
|
272 | 272 | d.addCallback(adapt) |
|
273 | 273 | |
|
274 | 274 | return d |
|
275 | 275 | |
|
276 | 276 | d = self._try_to_connect(furl_file, delay, max_tries, attempt=0) |
|
277 | 277 | d.addCallback(_wrap_remote_reference) |
|
278 | 278 | return d |
|
279 | 279 | |
|
280 | 280 | @inlineCallbacks |
|
281 | 281 | def _try_to_connect(self, furl_or_file, delay, max_tries, attempt): |
|
282 | 282 | """Try to connect to the controller with retry logic.""" |
|
283 | 283 | if attempt < max_tries: |
|
284 | 284 | log.msg("Connecting to controller [%r]: %s" % \ |
|
285 | 285 | (attempt, furl_or_file)) |
|
286 | 286 | try: |
|
287 | 287 | self.furl = find_furl(furl_or_file) |
|
288 | 288 | # Uncomment this to see the FURL being tried. |
|
289 | 289 | # log.msg("FURL: %s" % self.furl) |
|
290 | 290 | rr = yield self.get_reference(self.furl) |
|
291 | 291 | except: |
|
292 | 292 | if attempt==max_tries-1: |
|
293 | 293 | # This will propagate the exception all the way to the top |
|
294 | 294 | # where it can be handled. |
|
295 | 295 | raise |
|
296 | 296 | else: |
|
297 | 297 | yield sleep_deferred(delay) |
|
298 | 298 | rr = yield self._try_to_connect( |
|
299 | 299 | furl_or_file, 1.5*delay, max_tries, attempt+1 |
|
300 | 300 | ) |
|
301 | 301 | returnValue(rr) |
|
302 | 302 | else: |
|
303 | 303 | returnValue(rr) |
|
304 | 304 | else: |
|
305 | 305 | raise ClientConnectorError( |
|
306 | 306 | 'Could not connect to controller, max_tries (%r) exceeded. ' |
|
307 | 307 | 'This usually means that i) the controller was not started, ' |
|
308 | 308 | 'or ii) a firewall was blocking the client from connecting ' |
|
309 | 309 | 'to the controller.' % max_tries |
|
310 | 310 | ) |
|
311 | 311 | |
|
312 | 312 | |
|
313 | 313 | class ClientConnector(object): |
|
314 | 314 | """A blocking version of a client connector. |
|
315 | 315 | |
|
316 | 316 | This class creates a single :class:`Tub` instance and allows remote |
|
317 | 317 | references and client to be retrieved by their FURLs. Remote references |
|
318 | 318 | are cached locally and FURL files can be found using profiles and cluster |
|
319 | 319 | directories. |
|
320 | 320 | """ |
|
321 | 321 | |
|
322 | 322 | def __init__(self): |
|
323 | 323 | self.async_cc = AsyncClientConnector() |
|
324 | 324 | |
|
325 | 325 | def get_task_client(self, profile='default', cluster_dir=None, |
|
326 | furl_or_file=None, ipythondir=None, | |
|
326 | furl_or_file=None, ipython_dir=None, | |
|
327 | 327 | delay=DELAY, max_tries=MAX_TRIES): |
|
328 | 328 | """Get the task client. |
|
329 | 329 | |
|
330 | 330 | Usually only the ``profile`` option will be needed. If a FURL file |
|
331 | 331 | can't be found by its profile, use ``cluster_dir`` or |
|
332 | 332 | ``furl_or_file``. |
|
333 | 333 | |
|
334 | 334 | Parameters |
|
335 | 335 | ---------- |
|
336 | 336 | profile : str |
|
337 | 337 | The name of a cluster directory profile (default="default"). The |
|
338 | 338 | cluster directory "cluster_<profile>" will be searched for |
|
339 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
340 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
339 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
340 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
341 | 341 | cluster_dir : str |
|
342 | 342 | The full path to a cluster directory. This is useful if profiles |
|
343 | 343 | are not being used. |
|
344 | 344 | furl_or_file : str |
|
345 | 345 | A furl or a filename containing a FURLK. This is useful if you |
|
346 | 346 | simply know the location of the FURL file. |
|
347 | ipythondir : str | |
|
348 | The location of the ipythondir if different from the default. | |
|
347 | ipython_dir : str | |
|
348 | The location of the ipython_dir if different from the default. | |
|
349 | 349 | This is used if the cluster directory is being found by profile. |
|
350 | 350 | delay : float |
|
351 | 351 | The initial delay between re-connection attempts. Susequent delays |
|
352 | 352 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
353 | 353 | max_tries : int |
|
354 | 354 | The max number of re-connection attempts. |
|
355 | 355 | |
|
356 | 356 | Returns |
|
357 | 357 | ------- |
|
358 | 358 | The task client instance. |
|
359 | 359 | """ |
|
360 | 360 | client = blockingCallFromThread( |
|
361 | 361 | self.async_cc.get_task_client, profile, cluster_dir, |
|
362 | furl_or_file, ipythondir, delay, max_tries | |
|
362 | furl_or_file, ipython_dir, delay, max_tries | |
|
363 | 363 | ) |
|
364 | 364 | return client.adapt_to_blocking_client() |
|
365 | 365 | |
|
366 | 366 | def get_multiengine_client(self, profile='default', cluster_dir=None, |
|
367 | furl_or_file=None, ipythondir=None, | |
|
367 | furl_or_file=None, ipython_dir=None, | |
|
368 | 368 | delay=DELAY, max_tries=MAX_TRIES): |
|
369 | 369 | """Get the multiengine client. |
|
370 | 370 | |
|
371 | 371 | Usually only the ``profile`` option will be needed. If a FURL file |
|
372 | 372 | can't be found by its profile, use ``cluster_dir`` or |
|
373 | 373 | ``furl_or_file``. |
|
374 | 374 | |
|
375 | 375 | Parameters |
|
376 | 376 | ---------- |
|
377 | 377 | profile : str |
|
378 | 378 | The name of a cluster directory profile (default="default"). The |
|
379 | 379 | cluster directory "cluster_<profile>" will be searched for |
|
380 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
381 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
380 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
381 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
382 | 382 | cluster_dir : str |
|
383 | 383 | The full path to a cluster directory. This is useful if profiles |
|
384 | 384 | are not being used. |
|
385 | 385 | furl_or_file : str |
|
386 | 386 | A furl or a filename containing a FURLK. This is useful if you |
|
387 | 387 | simply know the location of the FURL file. |
|
388 | ipythondir : str | |
|
389 | The location of the ipythondir if different from the default. | |
|
388 | ipython_dir : str | |
|
389 | The location of the ipython_dir if different from the default. | |
|
390 | 390 | This is used if the cluster directory is being found by profile. |
|
391 | 391 | delay : float |
|
392 | 392 | The initial delay between re-connection attempts. Susequent delays |
|
393 | 393 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
394 | 394 | max_tries : int |
|
395 | 395 | The max number of re-connection attempts. |
|
396 | 396 | |
|
397 | 397 | Returns |
|
398 | 398 | ------- |
|
399 | 399 | The multiengine client instance. |
|
400 | 400 | """ |
|
401 | 401 | client = blockingCallFromThread( |
|
402 | 402 | self.async_cc.get_multiengine_client, profile, cluster_dir, |
|
403 | furl_or_file, ipythondir, delay, max_tries | |
|
403 | furl_or_file, ipython_dir, delay, max_tries | |
|
404 | 404 | ) |
|
405 | 405 | return client.adapt_to_blocking_client() |
|
406 | 406 | |
|
407 | 407 | def get_client(self, profile='default', cluster_dir=None, |
|
408 | furl_or_file=None, ipythondir=None, | |
|
408 | furl_or_file=None, ipython_dir=None, | |
|
409 | 409 | delay=DELAY, max_tries=MAX_TRIES): |
|
410 | 410 | client = blockingCallFromThread( |
|
411 | 411 | self.async_cc.get_client, profile, cluster_dir, |
|
412 | furl_or_file, ipythondir, | |
|
412 | furl_or_file, ipython_dir, | |
|
413 | 413 | delay, max_tries |
|
414 | 414 | ) |
|
415 | 415 | return client.adapt_to_blocking_client() |
|
416 | 416 | |
|
417 | 417 | |
|
418 | 418 | class ClusterStateError(Exception): |
|
419 | 419 | pass |
|
420 | 420 | |
|
421 | 421 | |
|
422 | 422 | class AsyncCluster(object): |
|
423 | 423 | """An class that wraps the :command:`ipcluster` script.""" |
|
424 | 424 | |
|
425 | def __init__(self, profile='default', cluster_dir=None, ipythondir=None, | |
|
425 | def __init__(self, profile='default', cluster_dir=None, ipython_dir=None, | |
|
426 | 426 | auto_create=False, auto_stop=True): |
|
427 | 427 | """Create a class to manage an IPython cluster. |
|
428 | 428 | |
|
429 | 429 | This class calls the :command:`ipcluster` command with the right |
|
430 | 430 | options to start an IPython cluster. Typically a cluster directory |
|
431 | 431 | must be created (:command:`ipcluster create`) and configured before |
|
432 | 432 | using this class. Configuration is done by editing the |
|
433 | 433 | configuration files in the top level of the cluster directory. |
|
434 | 434 | |
|
435 | 435 | Parameters |
|
436 | 436 | ---------- |
|
437 | 437 | profile : str |
|
438 | 438 | The name of a cluster directory profile (default="default"). The |
|
439 | 439 | cluster directory "cluster_<profile>" will be searched for |
|
440 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
441 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
440 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
441 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
442 | 442 | cluster_dir : str |
|
443 | 443 | The full path to a cluster directory. This is useful if profiles |
|
444 | 444 | are not being used. |
|
445 | ipythondir : str | |
|
446 | The location of the ipythondir if different from the default. | |
|
445 | ipython_dir : str | |
|
446 | The location of the ipython_dir if different from the default. | |
|
447 | 447 | This is used if the cluster directory is being found by profile. |
|
448 | 448 | auto_create : bool |
|
449 | 449 | Automatically create the cluster directory it is dones't exist. |
|
450 | 450 | This will usually only make sense if using a local cluster |
|
451 | 451 | (default=False). |
|
452 | 452 | auto_stop : bool |
|
453 | 453 | Automatically stop the cluster when this instance is garbage |
|
454 | 454 | collected (default=True). This is useful if you want the cluster |
|
455 | 455 | to live beyond your current process. There is also an instance |
|
456 | 456 | attribute ``auto_stop`` to change this behavior. |
|
457 | 457 | """ |
|
458 | self._setup_cluster_dir(profile, cluster_dir, ipythondir, auto_create) | |
|
458 | self._setup_cluster_dir(profile, cluster_dir, ipython_dir, auto_create) | |
|
459 | 459 | self.state = 'before' |
|
460 | 460 | self.launcher = None |
|
461 | 461 | self.client_connector = None |
|
462 | 462 | self.auto_stop = auto_stop |
|
463 | 463 | |
|
464 | 464 | def __del__(self): |
|
465 | 465 | if self.auto_stop and self.state=='running': |
|
466 | 466 | print "Auto stopping the cluster..." |
|
467 | 467 | self.stop() |
|
468 | 468 | |
|
469 | 469 | @property |
|
470 | 470 | def location(self): |
|
471 | 471 | if hasattr(self, 'cluster_dir_obj'): |
|
472 | 472 | return self.cluster_dir_obj.location |
|
473 | 473 | else: |
|
474 | 474 | return '' |
|
475 | 475 | |
|
476 | 476 | @property |
|
477 | 477 | def running(self): |
|
478 | 478 | if self.state=='running': |
|
479 | 479 | return True |
|
480 | 480 | else: |
|
481 | 481 | return False |
|
482 | 482 | |
|
483 | def _setup_cluster_dir(self, profile, cluster_dir, ipythondir, auto_create): | |
|
484 | if ipythondir is None: | |
|
485 | ipythondir = get_ipython_dir() | |
|
483 | def _setup_cluster_dir(self, profile, cluster_dir, ipython_dir, auto_create): | |
|
484 | if ipython_dir is None: | |
|
485 | ipython_dir = get_ipython_dir() | |
|
486 | 486 | if cluster_dir is not None: |
|
487 | 487 | try: |
|
488 | 488 | self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir) |
|
489 | 489 | except ClusterDirError: |
|
490 | 490 | pass |
|
491 | 491 | if profile is not None: |
|
492 | 492 | try: |
|
493 | 493 | self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile( |
|
494 | ipythondir, profile) | |
|
494 | ipython_dir, profile) | |
|
495 | 495 | except ClusterDirError: |
|
496 | 496 | pass |
|
497 | 497 | if auto_create or profile=='default': |
|
498 | 498 | # This should call 'ipcluster create --profile default |
|
499 | 499 | self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile( |
|
500 | ipythondir, profile) | |
|
500 | ipython_dir, profile) | |
|
501 | 501 | else: |
|
502 | 502 | raise ClusterDirError('Cluster dir not found.') |
|
503 | 503 | |
|
504 | 504 | @make_deferred |
|
505 | 505 | def start(self, n=2): |
|
506 | 506 | """Start the IPython cluster with n engines. |
|
507 | 507 | |
|
508 | 508 | Parameters |
|
509 | 509 | ---------- |
|
510 | 510 | n : int |
|
511 | 511 | The number of engine to start. |
|
512 | 512 | """ |
|
513 | 513 | # We might want to add logic to test if the cluster has started |
|
514 | 514 | # by another process.... |
|
515 | 515 | if not self.state=='running': |
|
516 | 516 | self.launcher = IPClusterLauncher(os.getcwd()) |
|
517 | 517 | self.launcher.ipcluster_n = n |
|
518 | 518 | self.launcher.ipcluster_subcommand = 'start' |
|
519 | 519 | d = self.launcher.start() |
|
520 | 520 | d.addCallback(self._handle_start) |
|
521 | 521 | return d |
|
522 | 522 | else: |
|
523 | 523 | raise ClusterStateError('Cluster is already running') |
|
524 | 524 | |
|
525 | 525 | @make_deferred |
|
526 | 526 | def stop(self): |
|
527 | 527 | """Stop the IPython cluster if it is running.""" |
|
528 | 528 | if self.state=='running': |
|
529 | 529 | d1 = self.launcher.observe_stop() |
|
530 | 530 | d1.addCallback(self._handle_stop) |
|
531 | 531 | d2 = self.launcher.stop() |
|
532 | 532 | return gatherBoth([d1, d2], consumeErrors=True) |
|
533 | 533 | else: |
|
534 | 534 | raise ClusterStateError("Cluster not running") |
|
535 | 535 | |
|
536 | 536 | def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES): |
|
537 | 537 | """Get the multiengine client for the running cluster. |
|
538 | 538 | |
|
539 | 539 | If this fails, it means that the cluster has not finished starting. |
|
540 | 540 | Usually waiting a few seconds are re-trying will solve this. |
|
541 | 541 | """ |
|
542 | 542 | if self.client_connector is None: |
|
543 | 543 | self.client_connector = AsyncClientConnector() |
|
544 | 544 | return self.client_connector.get_multiengine_client( |
|
545 | 545 | cluster_dir=self.cluster_dir_obj.location, |
|
546 | 546 | delay=delay, max_tries=max_tries |
|
547 | 547 | ) |
|
548 | 548 | |
|
549 | 549 | def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES): |
|
550 | 550 | """Get the task client for the running cluster. |
|
551 | 551 | |
|
552 | 552 | If this fails, it means that the cluster has not finished starting. |
|
553 | 553 | Usually waiting a few seconds are re-trying will solve this. |
|
554 | 554 | """ |
|
555 | 555 | if self.client_connector is None: |
|
556 | 556 | self.client_connector = AsyncClientConnector() |
|
557 | 557 | return self.client_connector.get_task_client( |
|
558 | 558 | cluster_dir=self.cluster_dir_obj.location, |
|
559 | 559 | delay=delay, max_tries=max_tries |
|
560 | 560 | ) |
|
561 | 561 | |
|
562 | 562 | def get_ipengine_logs(self): |
|
563 | 563 | return self.get_logs_by_name('ipengine') |
|
564 | 564 | |
|
565 | 565 | def get_ipcontroller_logs(self): |
|
566 | 566 | return self.get_logs_by_name('ipcontroller') |
|
567 | 567 | |
|
568 | 568 | def get_ipcluster_logs(self): |
|
569 | 569 | return self.get_logs_by_name('ipcluster') |
|
570 | 570 | |
|
571 | 571 | def get_logs_by_name(self, name='ipcluster'): |
|
572 | 572 | log_dir = self.cluster_dir_obj.log_dir |
|
573 | 573 | logs = {} |
|
574 | 574 | for log in os.listdir(log_dir): |
|
575 | 575 | if log.startswith(name + '-') and log.endswith('.log'): |
|
576 | 576 | with open(os.path.join(log_dir, log), 'r') as f: |
|
577 | 577 | logs[log] = f.read() |
|
578 | 578 | return logs |
|
579 | 579 | |
|
580 | 580 | def get_logs(self): |
|
581 | 581 | d = self.get_ipcluster_logs() |
|
582 | 582 | d.update(self.get_ipengine_logs()) |
|
583 | 583 | d.update(self.get_ipcontroller_logs()) |
|
584 | 584 | return d |
|
585 | 585 | |
|
586 | 586 | def _handle_start(self, r): |
|
587 | 587 | self.state = 'running' |
|
588 | 588 | |
|
589 | 589 | def _handle_stop(self, r): |
|
590 | 590 | self.state = 'after' |
|
591 | 591 | |
|
592 | 592 | |
|
593 | 593 | class Cluster(object): |
|
594 | 594 | |
|
595 | 595 | |
|
596 | def __init__(self, profile='default', cluster_dir=None, ipythondir=None, | |
|
596 | def __init__(self, profile='default', cluster_dir=None, ipython_dir=None, | |
|
597 | 597 | auto_create=False, auto_stop=True): |
|
598 | 598 | """Create a class to manage an IPython cluster. |
|
599 | 599 | |
|
600 | 600 | This class calls the :command:`ipcluster` command with the right |
|
601 | 601 | options to start an IPython cluster. Typically a cluster directory |
|
602 | 602 | must be created (:command:`ipcluster create`) and configured before |
|
603 | 603 | using this class. Configuration is done by editing the |
|
604 | 604 | configuration files in the top level of the cluster directory. |
|
605 | 605 | |
|
606 | 606 | Parameters |
|
607 | 607 | ---------- |
|
608 | 608 | profile : str |
|
609 | 609 | The name of a cluster directory profile (default="default"). The |
|
610 | 610 | cluster directory "cluster_<profile>" will be searched for |
|
611 | in ``os.getcwd()``, the ipythondir and then in the directories | |
|
612 | listed in the :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
611 | in ``os.getcwd()``, the ipython_dir and then in the directories | |
|
612 | listed in the :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
613 | 613 | cluster_dir : str |
|
614 | 614 | The full path to a cluster directory. This is useful if profiles |
|
615 | 615 | are not being used. |
|
616 | ipythondir : str | |
|
617 | The location of the ipythondir if different from the default. | |
|
616 | ipython_dir : str | |
|
617 | The location of the ipython_dir if different from the default. | |
|
618 | 618 | This is used if the cluster directory is being found by profile. |
|
619 | 619 | auto_create : bool |
|
620 | 620 | Automatically create the cluster directory it is dones't exist. |
|
621 | 621 | This will usually only make sense if using a local cluster |
|
622 | 622 | (default=False). |
|
623 | 623 | auto_stop : bool |
|
624 | 624 | Automatically stop the cluster when this instance is garbage |
|
625 | 625 | collected (default=True). This is useful if you want the cluster |
|
626 | 626 | to live beyond your current process. There is also an instance |
|
627 | 627 | attribute ``auto_stop`` to change this behavior. |
|
628 | 628 | """ |
|
629 | 629 | self.async_cluster = AsyncCluster( |
|
630 | profile, cluster_dir, ipythondir, auto_create, auto_stop | |
|
630 | profile, cluster_dir, ipython_dir, auto_create, auto_stop | |
|
631 | 631 | ) |
|
632 | 632 | self.cluster_dir_obj = self.async_cluster.cluster_dir_obj |
|
633 | 633 | self.client_connector = None |
|
634 | 634 | |
|
635 | 635 | def _set_auto_stop(self, value): |
|
636 | 636 | self.async_cluster.auto_stop = value |
|
637 | 637 | |
|
638 | 638 | def _get_auto_stop(self): |
|
639 | 639 | return self.async_cluster.auto_stop |
|
640 | 640 | |
|
641 | 641 | auto_stop = property(_get_auto_stop, _set_auto_stop) |
|
642 | 642 | |
|
643 | 643 | @property |
|
644 | 644 | def location(self): |
|
645 | 645 | return self.async_cluster.location |
|
646 | 646 | |
|
647 | 647 | @property |
|
648 | 648 | def running(self): |
|
649 | 649 | return self.async_cluster.running |
|
650 | 650 | |
|
651 | 651 | def start(self, n=2): |
|
652 | 652 | """Start the IPython cluster with n engines. |
|
653 | 653 | |
|
654 | 654 | Parameters |
|
655 | 655 | ---------- |
|
656 | 656 | n : int |
|
657 | 657 | The number of engine to start. |
|
658 | 658 | """ |
|
659 | 659 | return blockingCallFromThread(self.async_cluster.start, n) |
|
660 | 660 | |
|
661 | 661 | def stop(self): |
|
662 | 662 | """Stop the IPython cluster if it is running.""" |
|
663 | 663 | return blockingCallFromThread(self.async_cluster.stop) |
|
664 | 664 | |
|
665 | 665 | def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES): |
|
666 | 666 | """Get the multiengine client for the running cluster. |
|
667 | 667 | |
|
668 | 668 | This will try to attempt to the controller multiple times. If this |
|
669 | 669 | fails altogether, try looking at the following: |
|
670 | 670 | * Make sure the controller is starting properly by looking at its |
|
671 | 671 | log files. |
|
672 | 672 | * Make sure the controller is writing its FURL file in the location |
|
673 | 673 | expected by the client. |
|
674 | 674 | * Make sure a firewall on the controller's host is not blocking the |
|
675 | 675 | client from connecting. |
|
676 | 676 | |
|
677 | 677 | Parameters |
|
678 | 678 | ---------- |
|
679 | 679 | delay : float |
|
680 | 680 | The initial delay between re-connection attempts. Susequent delays |
|
681 | 681 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
682 | 682 | max_tries : int |
|
683 | 683 | The max number of re-connection attempts. |
|
684 | 684 | """ |
|
685 | 685 | if self.client_connector is None: |
|
686 | 686 | self.client_connector = ClientConnector() |
|
687 | 687 | return self.client_connector.get_multiengine_client( |
|
688 | 688 | cluster_dir=self.cluster_dir_obj.location, |
|
689 | 689 | delay=delay, max_tries=max_tries |
|
690 | 690 | ) |
|
691 | 691 | |
|
692 | 692 | def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES): |
|
693 | 693 | """Get the task client for the running cluster. |
|
694 | 694 | |
|
695 | 695 | This will try to attempt to the controller multiple times. If this |
|
696 | 696 | fails altogether, try looking at the following: |
|
697 | 697 | * Make sure the controller is starting properly by looking at its |
|
698 | 698 | log files. |
|
699 | 699 | * Make sure the controller is writing its FURL file in the location |
|
700 | 700 | expected by the client. |
|
701 | 701 | * Make sure a firewall on the controller's host is not blocking the |
|
702 | 702 | client from connecting. |
|
703 | 703 | |
|
704 | 704 | Parameters |
|
705 | 705 | ---------- |
|
706 | 706 | delay : float |
|
707 | 707 | The initial delay between re-connection attempts. Susequent delays |
|
708 | 708 | get longer according to ``delay[i] = 1.5*delay[i-1]``. |
|
709 | 709 | max_tries : int |
|
710 | 710 | The max number of re-connection attempts. |
|
711 | 711 | """ |
|
712 | 712 | if self.client_connector is None: |
|
713 | 713 | self.client_connector = ClientConnector() |
|
714 | 714 | return self.client_connector.get_task_client( |
|
715 | 715 | cluster_dir=self.cluster_dir_obj.location, |
|
716 | 716 | delay=delay, max_tries=max_tries |
|
717 | 717 | ) |
|
718 | 718 | |
|
719 | 719 | def __repr__(self): |
|
720 | 720 | s = "<Cluster(running=%r, location=%s)" % (self.running, self.location) |
|
721 | 721 | return s |
|
722 | 722 | |
|
723 | 723 | def get_logs_by_name(self, name='ipcluter'): |
|
724 | 724 | """Get a dict of logs by process name (ipcluster, ipengine, etc.)""" |
|
725 | 725 | return self.async_cluster.get_logs_by_name(name) |
|
726 | 726 | |
|
727 | 727 | def get_ipengine_logs(self): |
|
728 | 728 | """Get a dict of logs for all engines in this cluster.""" |
|
729 | 729 | return self.async_cluster.get_ipengine_logs() |
|
730 | 730 | |
|
731 | 731 | def get_ipcontroller_logs(self): |
|
732 | 732 | """Get a dict of logs for the controller in this cluster.""" |
|
733 | 733 | return self.async_cluster.get_ipcontroller_logs() |
|
734 | 734 | |
|
735 | 735 | def get_ipcluster_logs(self): |
|
736 | 736 | """Get a dict of the ipcluster logs for this cluster.""" |
|
737 | 737 | return self.async_cluster.get_ipcluster_logs() |
|
738 | 738 | |
|
739 | 739 | def get_logs(self): |
|
740 | 740 | """Get a dict of all logs for this cluster.""" |
|
741 | 741 | return self.async_cluster.get_logs() |
|
742 | 742 | |
|
743 | 743 | def _print_logs(self, logs): |
|
744 | 744 | for k, v in logs.iteritems(): |
|
745 | 745 | print "===================================" |
|
746 | 746 | print "Logfile: %s" % k |
|
747 | 747 | print "===================================" |
|
748 | 748 | print v |
|
749 | 749 | |
|
750 | 750 | |
|
751 | 751 | def print_ipengine_logs(self): |
|
752 | 752 | """Print the ipengine logs for this cluster to stdout.""" |
|
753 | 753 | self._print_logs(self.get_ipengine_logs()) |
|
754 | 754 | |
|
755 | 755 | def print_ipcontroller_logs(self): |
|
756 | 756 | """Print the ipcontroller logs for this cluster to stdout.""" |
|
757 | 757 | self._print_logs(self.get_ipcontroller_logs()) |
|
758 | 758 | |
|
759 | 759 | def print_ipcluster_logs(self): |
|
760 | 760 | """Print the ipcluster logs for this cluster to stdout.""" |
|
761 | 761 | self._print_logs(self.get_ipcluster_logs()) |
|
762 | 762 | |
|
763 | 763 | def print_logs(self): |
|
764 | 764 | """Print all the logs for this cluster to stdout.""" |
|
765 | 765 | self._print_logs(self.get_logs()) |
|
766 | 766 |
@@ -1,461 +1,461 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The IPython cluster directory |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | from __future__ import with_statement |
|
19 | 19 | |
|
20 | 20 | import os |
|
21 | 21 | import shutil |
|
22 | 22 | import sys |
|
23 | 23 | |
|
24 | 24 | from twisted.python import log |
|
25 | 25 | |
|
26 | 26 | from IPython.core import release |
|
27 | 27 | from IPython.config.loader import PyFileConfigLoader |
|
28 | 28 | from IPython.core.application import Application |
|
29 | 29 | from IPython.core.component import Component |
|
30 | 30 | from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault |
|
31 | 31 | from IPython.utils.traitlets import Unicode, Bool |
|
32 | 32 | |
|
33 | 33 | #----------------------------------------------------------------------------- |
|
34 | 34 | # Imports |
|
35 | 35 | #----------------------------------------------------------------------------- |
|
36 | 36 | |
|
37 | 37 | |
|
38 | 38 | class ClusterDirError(Exception): |
|
39 | 39 | pass |
|
40 | 40 | |
|
41 | 41 | |
|
42 | 42 | class PIDFileError(Exception): |
|
43 | 43 | pass |
|
44 | 44 | |
|
45 | 45 | |
|
46 | 46 | class ClusterDir(Component): |
|
47 | 47 | """An object to manage the cluster directory and its resources. |
|
48 | 48 | |
|
49 | 49 | The cluster directory is used by :command:`ipcontroller`, |
|
50 | 50 | :command:`ipcontroller` and :command:`ipcontroller` to manage the |
|
51 | 51 | configuration, logging and security of these applications. |
|
52 | 52 | |
|
53 | 53 | This object knows how to find, create and manage these directories. This |
|
54 | 54 | should be used by any code that want's to handle cluster directories. |
|
55 | 55 | """ |
|
56 | 56 | |
|
57 | 57 | security_dir_name = Unicode('security') |
|
58 | 58 | log_dir_name = Unicode('log') |
|
59 | 59 | pid_dir_name = Unicode('pid') |
|
60 | 60 | security_dir = Unicode(u'') |
|
61 | 61 | log_dir = Unicode(u'') |
|
62 | 62 | pid_dir = Unicode(u'') |
|
63 | 63 | location = Unicode(u'') |
|
64 | 64 | |
|
65 | 65 | def __init__(self, location): |
|
66 | 66 | super(ClusterDir, self).__init__(None) |
|
67 | 67 | self.location = location |
|
68 | 68 | |
|
69 | 69 | def _location_changed(self, name, old, new): |
|
70 | 70 | if not os.path.isdir(new): |
|
71 | 71 | os.makedirs(new, mode=0777) |
|
72 | 72 | else: |
|
73 | 73 | os.chmod(new, 0777) |
|
74 | 74 | self.security_dir = os.path.join(new, self.security_dir_name) |
|
75 | 75 | self.log_dir = os.path.join(new, self.log_dir_name) |
|
76 | 76 | self.pid_dir = os.path.join(new, self.pid_dir_name) |
|
77 | 77 | self.check_dirs() |
|
78 | 78 | |
|
79 | 79 | def _log_dir_changed(self, name, old, new): |
|
80 | 80 | self.check_log_dir() |
|
81 | 81 | |
|
82 | 82 | def check_log_dir(self): |
|
83 | 83 | if not os.path.isdir(self.log_dir): |
|
84 | 84 | os.mkdir(self.log_dir, 0777) |
|
85 | 85 | else: |
|
86 | 86 | os.chmod(self.log_dir, 0777) |
|
87 | 87 | |
|
88 | 88 | def _security_dir_changed(self, name, old, new): |
|
89 | 89 | self.check_security_dir() |
|
90 | 90 | |
|
91 | 91 | def check_security_dir(self): |
|
92 | 92 | if not os.path.isdir(self.security_dir): |
|
93 | 93 | os.mkdir(self.security_dir, 0700) |
|
94 | 94 | else: |
|
95 | 95 | os.chmod(self.security_dir, 0700) |
|
96 | 96 | |
|
97 | 97 | def _pid_dir_changed(self, name, old, new): |
|
98 | 98 | self.check_pid_dir() |
|
99 | 99 | |
|
100 | 100 | def check_pid_dir(self): |
|
101 | 101 | if not os.path.isdir(self.pid_dir): |
|
102 | 102 | os.mkdir(self.pid_dir, 0700) |
|
103 | 103 | else: |
|
104 | 104 | os.chmod(self.pid_dir, 0700) |
|
105 | 105 | |
|
106 | 106 | def check_dirs(self): |
|
107 | 107 | self.check_security_dir() |
|
108 | 108 | self.check_log_dir() |
|
109 | 109 | self.check_pid_dir() |
|
110 | 110 | |
|
111 | 111 | def load_config_file(self, filename): |
|
112 | 112 | """Load a config file from the top level of the cluster dir. |
|
113 | 113 | |
|
114 | 114 | Parameters |
|
115 | 115 | ---------- |
|
116 | 116 | filename : unicode or str |
|
117 | 117 | The filename only of the config file that must be located in |
|
118 | 118 | the top-level of the cluster directory. |
|
119 | 119 | """ |
|
120 | 120 | loader = PyFileConfigLoader(filename, self.location) |
|
121 | 121 | return loader.load_config() |
|
122 | 122 | |
|
123 | 123 | def copy_config_file(self, config_file, path=None, overwrite=False): |
|
124 | 124 | """Copy a default config file into the active cluster directory. |
|
125 | 125 | |
|
126 | 126 | Default configuration files are kept in :mod:`IPython.config.default`. |
|
127 | 127 | This function moves these from that location to the working cluster |
|
128 | 128 | directory. |
|
129 | 129 | """ |
|
130 | 130 | if path is None: |
|
131 | 131 | import IPython.config.default |
|
132 | 132 | path = IPython.config.default.__file__.split(os.path.sep)[:-1] |
|
133 | 133 | path = os.path.sep.join(path) |
|
134 | 134 | src = os.path.join(path, config_file) |
|
135 | 135 | dst = os.path.join(self.location, config_file) |
|
136 | 136 | if not os.path.isfile(dst) or overwrite: |
|
137 | 137 | shutil.copy(src, dst) |
|
138 | 138 | |
|
139 | 139 | def copy_all_config_files(self, path=None, overwrite=False): |
|
140 | 140 | """Copy all config files into the active cluster directory.""" |
|
141 | 141 | for f in ['ipcontroller_config.py', 'ipengine_config.py', |
|
142 | 142 | 'ipcluster_config.py']: |
|
143 | 143 | self.copy_config_file(f, path=path, overwrite=overwrite) |
|
144 | 144 | |
|
145 | 145 | @classmethod |
|
146 | 146 | def create_cluster_dir(csl, cluster_dir): |
|
147 | 147 | """Create a new cluster directory given a full path. |
|
148 | 148 | |
|
149 | 149 | Parameters |
|
150 | 150 | ---------- |
|
151 | 151 | cluster_dir : str |
|
152 | 152 | The full path to the cluster directory. If it does exist, it will |
|
153 | 153 | be used. If not, it will be created. |
|
154 | 154 | """ |
|
155 | 155 | return ClusterDir(cluster_dir) |
|
156 | 156 | |
|
157 | 157 | @classmethod |
|
158 | 158 | def create_cluster_dir_by_profile(cls, path, profile='default'): |
|
159 | 159 | """Create a cluster dir by profile name and path. |
|
160 | 160 | |
|
161 | 161 | Parameters |
|
162 | 162 | ---------- |
|
163 | 163 | path : str |
|
164 | 164 | The path (directory) to put the cluster directory in. |
|
165 | 165 | profile : str |
|
166 | 166 | The name of the profile. The name of the cluster directory will |
|
167 | 167 | be "cluster_<profile>". |
|
168 | 168 | """ |
|
169 | 169 | if not os.path.isdir(path): |
|
170 | 170 | raise ClusterDirError('Directory not found: %s' % path) |
|
171 | 171 | cluster_dir = os.path.join(path, 'cluster_' + profile) |
|
172 | 172 | return ClusterDir(cluster_dir) |
|
173 | 173 | |
|
174 | 174 | @classmethod |
|
175 | def find_cluster_dir_by_profile(cls, ipythondir, profile='default'): | |
|
175 | def find_cluster_dir_by_profile(cls, ipython_dir, profile='default'): | |
|
176 | 176 | """Find an existing cluster dir by profile name, return its ClusterDir. |
|
177 | 177 | |
|
178 | 178 | This searches through a sequence of paths for a cluster dir. If it |
|
179 | 179 | is not found, a :class:`ClusterDirError` exception will be raised. |
|
180 | 180 | |
|
181 | 181 | The search path algorithm is: |
|
182 | 182 | 1. ``os.getcwd()`` |
|
183 | 2. ``ipythondir`` | |
|
183 | 2. ``ipython_dir`` | |
|
184 | 184 | 3. The directories found in the ":" separated |
|
185 | :env:`IPCLUSTERDIR_PATH` environment variable. | |
|
185 | :env:`IPCLUSTER_DIR_PATH` environment variable. | |
|
186 | 186 | |
|
187 | 187 | Parameters |
|
188 | 188 | ---------- |
|
189 | ipythondir : unicode or str | |
|
189 | ipython_dir : unicode or str | |
|
190 | 190 | The IPython directory to use. |
|
191 | 191 | profile : unicode or str |
|
192 | 192 | The name of the profile. The name of the cluster directory |
|
193 | 193 | will be "cluster_<profile>". |
|
194 | 194 | """ |
|
195 | 195 | dirname = 'cluster_' + profile |
|
196 | cluster_dir_paths = os.environ.get('IPCLUSTERDIR_PATH','') | |
|
196 | cluster_dir_paths = os.environ.get('IPCLUSTER_DIR_PATH','') | |
|
197 | 197 | if cluster_dir_paths: |
|
198 | 198 | cluster_dir_paths = cluster_dir_paths.split(':') |
|
199 | 199 | else: |
|
200 | 200 | cluster_dir_paths = [] |
|
201 | paths = [os.getcwd(), ipythondir] + cluster_dir_paths | |
|
201 | paths = [os.getcwd(), ipython_dir] + cluster_dir_paths | |
|
202 | 202 | for p in paths: |
|
203 | 203 | cluster_dir = os.path.join(p, dirname) |
|
204 | 204 | if os.path.isdir(cluster_dir): |
|
205 | 205 | return ClusterDir(cluster_dir) |
|
206 | 206 | else: |
|
207 | 207 | raise ClusterDirError('Cluster directory not found in paths: %s' % dirname) |
|
208 | 208 | |
|
209 | 209 | @classmethod |
|
210 | 210 | def find_cluster_dir(cls, cluster_dir): |
|
211 | 211 | """Find/create a cluster dir and return its ClusterDir. |
|
212 | 212 | |
|
213 | 213 | This will create the cluster directory if it doesn't exist. |
|
214 | 214 | |
|
215 | 215 | Parameters |
|
216 | 216 | ---------- |
|
217 | 217 | cluster_dir : unicode or str |
|
218 | 218 | The path of the cluster directory. This is expanded using |
|
219 | 219 | :func:`os.path.expandvars` and :func:`os.path.expanduser`. |
|
220 | 220 | """ |
|
221 | 221 | cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir)) |
|
222 | 222 | if not os.path.isdir(cluster_dir): |
|
223 | 223 | raise ClusterDirError('Cluster directory not found: %s' % cluster_dir) |
|
224 | 224 | return ClusterDir(cluster_dir) |
|
225 | 225 | |
|
226 | 226 | |
|
227 | 227 | class AppWithClusterDirArgParseConfigLoader(ArgParseConfigLoader): |
|
228 | 228 | """Default command line options for IPython cluster applications.""" |
|
229 | 229 | |
|
230 | 230 | def _add_other_arguments(self): |
|
231 | 231 | self.parser.add_argument('--ipython-dir', |
|
232 | dest='Global.ipythondir',type=str, | |
|
233 | help='Set to override default location of Global.ipythondir.', | |
|
232 | dest='Global.ipython_dir',type=str, | |
|
233 | help='Set to override default location of Global.ipython_dir.', | |
|
234 | 234 | default=NoConfigDefault, |
|
235 | metavar='Global.ipythondir' | |
|
235 | metavar='Global.ipython_dir' | |
|
236 | 236 | ) |
|
237 | 237 | self.parser.add_argument('-p', '--profile', |
|
238 | 238 | dest='Global.profile',type=str, |
|
239 | 239 | help='The string name of the profile to be used. This determines ' |
|
240 | 240 | 'the name of the cluster dir as: cluster_<profile>. The default profile ' |
|
241 | 241 | 'is named "default". The cluster directory is resolve this way ' |
|
242 | 242 | 'if the --cluster-dir option is not used.', |
|
243 | 243 | default=NoConfigDefault, |
|
244 | 244 | metavar='Global.profile' |
|
245 | 245 | ) |
|
246 | 246 | self.parser.add_argument('--log-level', |
|
247 | 247 | dest="Global.log_level",type=int, |
|
248 | 248 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
249 | 249 | default=NoConfigDefault, |
|
250 | 250 | metavar="Global.log_level" |
|
251 | 251 | ) |
|
252 | 252 | self.parser.add_argument('--cluster-dir', |
|
253 | 253 | dest='Global.cluster_dir',type=str, |
|
254 | 254 | help='Set the cluster dir. This overrides the logic used by the ' |
|
255 | 255 | '--profile option.', |
|
256 | 256 | default=NoConfigDefault, |
|
257 | 257 | metavar='Global.cluster_dir' |
|
258 | 258 | ) |
|
259 | 259 | self.parser.add_argument('--clean-logs', |
|
260 | 260 | dest='Global.clean_logs', action='store_true', |
|
261 | 261 | help='Delete old log flies before starting.', |
|
262 | 262 | default=NoConfigDefault |
|
263 | 263 | ) |
|
264 | 264 | self.parser.add_argument('--no-clean-logs', |
|
265 | 265 | dest='Global.clean_logs', action='store_false', |
|
266 | 266 | help="Don't Delete old log flies before starting.", |
|
267 | 267 | default=NoConfigDefault |
|
268 | 268 | ) |
|
269 | 269 | |
|
270 | 270 | class ApplicationWithClusterDir(Application): |
|
271 | 271 | """An application that puts everything into a cluster directory. |
|
272 | 272 | |
|
273 | Instead of looking for things in the ipythondir, this type of application | |
|
273 | Instead of looking for things in the ipython_dir, this type of application | |
|
274 | 274 | will use its own private directory called the "cluster directory" |
|
275 | 275 | for things like config files, log files, etc. |
|
276 | 276 | |
|
277 | 277 | The cluster directory is resolved as follows: |
|
278 | 278 | |
|
279 | 279 | * If the ``--cluster-dir`` option is given, it is used. |
|
280 | 280 | * If ``--cluster-dir`` is not given, the application directory is |
|
281 | 281 | resolve using the profile name as ``cluster_<profile>``. The search |
|
282 | 282 | path for this directory is then i) cwd if it is found there |
|
283 | and ii) in ipythondir otherwise. | |
|
283 | and ii) in ipython_dir otherwise. | |
|
284 | 284 | |
|
285 | 285 | The config file for the application is to be put in the cluster |
|
286 | 286 | dir and named the value of the ``config_file_name`` class attribute. |
|
287 | 287 | """ |
|
288 | 288 | |
|
289 | 289 | auto_create_cluster_dir = True |
|
290 | 290 | |
|
291 | 291 | def create_default_config(self): |
|
292 | 292 | super(ApplicationWithClusterDir, self).create_default_config() |
|
293 | 293 | self.default_config.Global.profile = 'default' |
|
294 | 294 | self.default_config.Global.cluster_dir = '' |
|
295 | 295 | self.default_config.Global.log_to_file = False |
|
296 | 296 | self.default_config.Global.clean_logs = False |
|
297 | 297 | |
|
298 | 298 | def create_command_line_config(self): |
|
299 | 299 | """Create and return a command line config loader.""" |
|
300 | 300 | return AppWithClusterDirArgParseConfigLoader( |
|
301 | 301 | description=self.description, |
|
302 | 302 | version=release.version |
|
303 | 303 | ) |
|
304 | 304 | |
|
305 | 305 | def find_resources(self): |
|
306 | 306 | """This resolves the cluster directory. |
|
307 | 307 | |
|
308 | 308 | This tries to find the cluster directory and if successful, it will |
|
309 | 309 | have done: |
|
310 | 310 | * Sets ``self.cluster_dir_obj`` to the :class:`ClusterDir` object for |
|
311 | 311 | the application. |
|
312 | 312 | * Sets ``self.cluster_dir`` attribute of the application and config |
|
313 | 313 | objects. |
|
314 | 314 | |
|
315 | 315 | The algorithm used for this is as follows: |
|
316 | 316 | 1. Try ``Global.cluster_dir``. |
|
317 | 317 | 2. Try using ``Global.profile``. |
|
318 | 318 | 3. If both of these fail and ``self.auto_create_cluster_dir`` is |
|
319 | 319 | ``True``, then create the new cluster dir in the IPython directory. |
|
320 | 320 | 4. If all fails, then raise :class:`ClusterDirError`. |
|
321 | 321 | """ |
|
322 | 322 | |
|
323 | 323 | try: |
|
324 | 324 | cluster_dir = self.command_line_config.Global.cluster_dir |
|
325 | 325 | except AttributeError: |
|
326 | 326 | cluster_dir = self.default_config.Global.cluster_dir |
|
327 | 327 | cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir)) |
|
328 | 328 | try: |
|
329 | 329 | self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir) |
|
330 | 330 | except ClusterDirError: |
|
331 | 331 | pass |
|
332 | 332 | else: |
|
333 | 333 | self.log.info('Using existing cluster dir: %s' % \ |
|
334 | 334 | self.cluster_dir_obj.location |
|
335 | 335 | ) |
|
336 | 336 | self.finish_cluster_dir() |
|
337 | 337 | return |
|
338 | 338 | |
|
339 | 339 | try: |
|
340 | 340 | self.profile = self.command_line_config.Global.profile |
|
341 | 341 | except AttributeError: |
|
342 | 342 | self.profile = self.default_config.Global.profile |
|
343 | 343 | try: |
|
344 | 344 | self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile( |
|
345 | self.ipythondir, self.profile) | |
|
345 | self.ipython_dir, self.profile) | |
|
346 | 346 | except ClusterDirError: |
|
347 | 347 | pass |
|
348 | 348 | else: |
|
349 | 349 | self.log.info('Using existing cluster dir: %s' % \ |
|
350 | 350 | self.cluster_dir_obj.location |
|
351 | 351 | ) |
|
352 | 352 | self.finish_cluster_dir() |
|
353 | 353 | return |
|
354 | 354 | |
|
355 | 355 | if self.auto_create_cluster_dir: |
|
356 | 356 | self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile( |
|
357 | self.ipythondir, self.profile | |
|
357 | self.ipython_dir, self.profile | |
|
358 | 358 | ) |
|
359 | 359 | self.log.info('Creating new cluster dir: %s' % \ |
|
360 | 360 | self.cluster_dir_obj.location |
|
361 | 361 | ) |
|
362 | 362 | self.finish_cluster_dir() |
|
363 | 363 | else: |
|
364 | 364 | raise ClusterDirError('Could not find a valid cluster directory.') |
|
365 | 365 | |
|
366 | 366 | def finish_cluster_dir(self): |
|
367 | 367 | # Set the cluster directory |
|
368 | 368 | self.cluster_dir = self.cluster_dir_obj.location |
|
369 | 369 | |
|
370 | 370 | # These have to be set because they could be different from the one |
|
371 | 371 | # that we just computed. Because command line has the highest |
|
372 | 372 | # priority, this will always end up in the master_config. |
|
373 | 373 | self.default_config.Global.cluster_dir = self.cluster_dir |
|
374 | 374 | self.command_line_config.Global.cluster_dir = self.cluster_dir |
|
375 | 375 | |
|
376 | 376 | # Set the search path to the cluster directory |
|
377 | 377 | self.config_file_paths = (self.cluster_dir,) |
|
378 | 378 | |
|
379 | 379 | def find_config_file_name(self): |
|
380 | 380 | """Find the config file name for this application.""" |
|
381 | 381 | # For this type of Application it should be set as a class attribute. |
|
382 | 382 | if not hasattr(self, 'config_file_name'): |
|
383 | 383 | self.log.critical("No config filename found") |
|
384 | 384 | |
|
385 | 385 | def find_config_file_paths(self): |
|
386 | 386 | # Set the search path to the cluster directory |
|
387 | 387 | self.config_file_paths = (self.cluster_dir,) |
|
388 | 388 | |
|
389 | 389 | def pre_construct(self): |
|
390 | 390 | # The log and security dirs were set earlier, but here we put them |
|
391 | 391 | # into the config and log them. |
|
392 | 392 | config = self.master_config |
|
393 | 393 | sdir = self.cluster_dir_obj.security_dir |
|
394 | 394 | self.security_dir = config.Global.security_dir = sdir |
|
395 | 395 | ldir = self.cluster_dir_obj.log_dir |
|
396 | 396 | self.log_dir = config.Global.log_dir = ldir |
|
397 | 397 | pdir = self.cluster_dir_obj.pid_dir |
|
398 | 398 | self.pid_dir = config.Global.pid_dir = pdir |
|
399 | 399 | self.log.info("Cluster directory set to: %s" % self.cluster_dir) |
|
400 | 400 | |
|
401 | 401 | def start_logging(self): |
|
402 | 402 | # Remove old log files |
|
403 | 403 | if self.master_config.Global.clean_logs: |
|
404 | 404 | log_dir = self.master_config.Global.log_dir |
|
405 | 405 | for f in os.listdir(log_dir): |
|
406 | 406 | if f.startswith(self.name + '-') and f.endswith('.log'): |
|
407 | 407 | os.remove(os.path.join(log_dir, f)) |
|
408 | 408 | # Start logging to the new log file |
|
409 | 409 | if self.master_config.Global.log_to_file: |
|
410 | 410 | log_filename = self.name + '-' + str(os.getpid()) + '.log' |
|
411 | 411 | logfile = os.path.join(self.log_dir, log_filename) |
|
412 | 412 | open_log_file = open(logfile, 'w') |
|
413 | 413 | else: |
|
414 | 414 | open_log_file = sys.stdout |
|
415 | 415 | log.startLogging(open_log_file) |
|
416 | 416 | |
|
417 | 417 | def write_pid_file(self, overwrite=False): |
|
418 | 418 | """Create a .pid file in the pid_dir with my pid. |
|
419 | 419 | |
|
420 | 420 | This must be called after pre_construct, which sets `self.pid_dir`. |
|
421 | 421 | This raises :exc:`PIDFileError` if the pid file exists already. |
|
422 | 422 | """ |
|
423 | 423 | pid_file = os.path.join(self.pid_dir, self.name + '.pid') |
|
424 | 424 | if os.path.isfile(pid_file): |
|
425 | 425 | pid = self.get_pid_from_file() |
|
426 | 426 | if not overwrite: |
|
427 | 427 | raise PIDFileError( |
|
428 | 428 | 'The pid file [%s] already exists. \nThis could mean that this ' |
|
429 | 429 | 'server is already running with [pid=%s].' % (pid_file, pid) |
|
430 | 430 | ) |
|
431 | 431 | with open(pid_file, 'w') as f: |
|
432 | 432 | self.log.info("Creating pid file: %s" % pid_file) |
|
433 | 433 | f.write(repr(os.getpid())+'\n') |
|
434 | 434 | |
|
435 | 435 | def remove_pid_file(self): |
|
436 | 436 | """Remove the pid file. |
|
437 | 437 | |
|
438 | 438 | This should be called at shutdown by registering a callback with |
|
439 | 439 | :func:`reactor.addSystemEventTrigger`. |
|
440 | 440 | """ |
|
441 | 441 | pid_file = os.path.join(self.pid_dir, self.name + '.pid') |
|
442 | 442 | if os.path.isfile(pid_file): |
|
443 | 443 | try: |
|
444 | 444 | self.log.info("Removing pid file: %s" % pid_file) |
|
445 | 445 | os.remove(pid_file) |
|
446 | 446 | except: |
|
447 | 447 | self.log.warn("Error removing the pid file: %s" % pid_file) |
|
448 | 448 | raise |
|
449 | 449 | |
|
450 | 450 | def get_pid_from_file(self): |
|
451 | 451 | """Get the pid from the pid file. |
|
452 | 452 | |
|
453 | 453 | If the pid file doesn't exist a :exc:`PIDFileError` is raised. |
|
454 | 454 | """ |
|
455 | 455 | pid_file = os.path.join(self.pid_dir, self.name + '.pid') |
|
456 | 456 | if os.path.isfile(pid_file): |
|
457 | 457 | with open(pid_file, 'r') as f: |
|
458 | 458 | pid = int(f.read().strip()) |
|
459 | 459 | return pid |
|
460 | 460 | else: |
|
461 | 461 | raise PIDFileError('pid file not found: %s' % pid_file) No newline at end of file |
@@ -1,384 +1,384 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The ipcluster application. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import logging |
|
19 | 19 | import os |
|
20 | 20 | import signal |
|
21 | 21 | import sys |
|
22 | 22 | |
|
23 | 23 | if os.name=='posix': |
|
24 | 24 | from twisted.scripts._twistd_unix import daemonize |
|
25 | 25 | |
|
26 | 26 | from IPython.core import release |
|
27 | 27 | from IPython.external import argparse |
|
28 | 28 | from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault |
|
29 | 29 | from IPython.utils.importstring import import_item |
|
30 | 30 | |
|
31 | 31 | from IPython.kernel.clusterdir import ( |
|
32 | 32 | ApplicationWithClusterDir, ClusterDirError, PIDFileError |
|
33 | 33 | ) |
|
34 | 34 | |
|
35 | 35 | from twisted.internet import reactor, defer |
|
36 | 36 | from twisted.python import log |
|
37 | 37 | |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | # Code for launchers |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | |
|
42 | 42 | |
|
43 | 43 | |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | # The ipcluster application |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | |
|
48 | 48 | |
|
49 | 49 | class IPClusterCLLoader(ArgParseConfigLoader): |
|
50 | 50 | |
|
51 | 51 | def _add_arguments(self): |
|
52 | 52 | # This has all the common options that all subcommands use |
|
53 | 53 | parent_parser1 = argparse.ArgumentParser(add_help=False) |
|
54 | 54 | parent_parser1.add_argument('--ipython-dir', |
|
55 | dest='Global.ipythondir',type=str, | |
|
56 | help='Set to override default location of Global.ipythondir.', | |
|
55 | dest='Global.ipython_dir',type=str, | |
|
56 | help='Set to override default location of Global.ipython_dir.', | |
|
57 | 57 | default=NoConfigDefault, |
|
58 | metavar='Global.ipythondir') | |
|
58 | metavar='Global.ipython_dir') | |
|
59 | 59 | parent_parser1.add_argument('--log-level', |
|
60 | 60 | dest="Global.log_level",type=int, |
|
61 | 61 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
62 | 62 | default=NoConfigDefault, |
|
63 | 63 | metavar='Global.log_level') |
|
64 | 64 | |
|
65 | 65 | # This has all the common options that other subcommands use |
|
66 | 66 | parent_parser2 = argparse.ArgumentParser(add_help=False) |
|
67 | 67 | parent_parser2.add_argument('-p','--profile', |
|
68 | 68 | dest='Global.profile',type=str, |
|
69 | 69 | default=NoConfigDefault, |
|
70 | 70 | help='The string name of the profile to be used. This determines ' |
|
71 | 71 | 'the name of the cluster dir as: cluster_<profile>. The default profile ' |
|
72 | 72 | 'is named "default". The cluster directory is resolve this way ' |
|
73 | 73 | 'if the --cluster-dir option is not used.', |
|
74 | 74 | default=NoConfigDefault, |
|
75 | 75 | metavar='Global.profile') |
|
76 | 76 | parent_parser2.add_argument('--cluster-dir', |
|
77 | 77 | dest='Global.cluster_dir',type=str, |
|
78 | 78 | default=NoConfigDefault, |
|
79 | 79 | help='Set the cluster dir. This overrides the logic used by the ' |
|
80 | 80 | '--profile option.', |
|
81 | 81 | default=NoConfigDefault, |
|
82 | 82 | metavar='Global.cluster_dir') |
|
83 | 83 | parent_parser2.add_argument('--log-to-file', |
|
84 | 84 | action='store_true', dest='Global.log_to_file', |
|
85 | 85 | default=NoConfigDefault, |
|
86 | 86 | help='Log to a file in the log directory (default is stdout)' |
|
87 | 87 | ) |
|
88 | 88 | |
|
89 | 89 | subparsers = self.parser.add_subparsers( |
|
90 | 90 | dest='Global.subcommand', |
|
91 | 91 | title='ipcluster subcommands', |
|
92 | 92 | description='ipcluster has a variety of subcommands. ' |
|
93 | 93 | 'The general way of running ipcluster is "ipcluster <cmd> ' |
|
94 | 94 | ' [options]""', |
|
95 | 95 | help='For more help, type "ipcluster <cmd> -h"') |
|
96 | 96 | |
|
97 | 97 | parser_list = subparsers.add_parser( |
|
98 | 98 | 'list', |
|
99 | help='List all clusters in cwd and ipythondir.', | |
|
99 | help='List all clusters in cwd and ipython_dir.', | |
|
100 | 100 | parents=[parent_parser1] |
|
101 | 101 | ) |
|
102 | 102 | |
|
103 | 103 | parser_create = subparsers.add_parser( |
|
104 | 104 | 'create', |
|
105 | 105 | help='Create a new cluster directory.', |
|
106 | 106 | parents=[parent_parser1, parent_parser2] |
|
107 | 107 | ) |
|
108 | 108 | parser_create.add_argument( |
|
109 | 109 | '--reset-config', |
|
110 | 110 | dest='Global.reset_config', action='store_true', |
|
111 | 111 | default=NoConfigDefault, |
|
112 | 112 | help='Recopy the default config files to the cluster directory. ' |
|
113 | 113 | 'You will loose any modifications you have made to these files.' |
|
114 | 114 | ) |
|
115 | 115 | |
|
116 | 116 | parser_start = subparsers.add_parser( |
|
117 | 117 | 'start', |
|
118 | 118 | help='Start a cluster.', |
|
119 | 119 | parents=[parent_parser1, parent_parser2] |
|
120 | 120 | ) |
|
121 | 121 | parser_start.add_argument( |
|
122 | 122 | '-n', '--number', |
|
123 | 123 | type=int, dest='Global.n', |
|
124 | 124 | default=NoConfigDefault, |
|
125 | 125 | help='The number of engines to start.', |
|
126 | 126 | metavar='Global.n' |
|
127 | 127 | ) |
|
128 | 128 | parser_start.add_argument('--clean-logs', |
|
129 | 129 | dest='Global.clean_logs', action='store_true', |
|
130 | 130 | help='Delete old log flies before starting.', |
|
131 | 131 | default=NoConfigDefault |
|
132 | 132 | ) |
|
133 | 133 | parser_start.add_argument('--no-clean-logs', |
|
134 | 134 | dest='Global.clean_logs', action='store_false', |
|
135 | 135 | help="Don't delete old log flies before starting.", |
|
136 | 136 | default=NoConfigDefault |
|
137 | 137 | ) |
|
138 | 138 | parser_start.add_argument('--daemon', |
|
139 | 139 | dest='Global.daemonize', action='store_true', |
|
140 | 140 | help='Daemonize the ipcluster program. This implies --log-to-file', |
|
141 | 141 | default=NoConfigDefault |
|
142 | 142 | ) |
|
143 | parser_start.add_argument('--nodaemon', | |
|
143 | parser_start.add_argument('--no-daemon', | |
|
144 | 144 | dest='Global.daemonize', action='store_false', |
|
145 | 145 | help="Dont't daemonize the ipcluster program.", |
|
146 | 146 | default=NoConfigDefault |
|
147 | 147 | ) |
|
148 | 148 | |
|
149 | 149 | parser_start = subparsers.add_parser( |
|
150 | 150 | 'stop', |
|
151 | 151 | help='Stop a cluster.', |
|
152 | 152 | parents=[parent_parser1, parent_parser2] |
|
153 | 153 | ) |
|
154 | 154 | parser_start.add_argument('--signal-number', |
|
155 | 155 | dest='Global.stop_signal', type=int, |
|
156 | 156 | help="The signal number to use in stopping the cluster (default=2).", |
|
157 | 157 | metavar="Global.stop_signal", |
|
158 | 158 | default=NoConfigDefault |
|
159 | 159 | ) |
|
160 | 160 | |
|
161 | 161 | default_config_file_name = 'ipcluster_config.py' |
|
162 | 162 | |
|
163 | 163 | |
|
164 | 164 | class IPClusterApp(ApplicationWithClusterDir): |
|
165 | 165 | |
|
166 | 166 | name = 'ipcluster' |
|
167 | 167 | description = 'Start an IPython cluster (controller and engines).' |
|
168 | 168 | config_file_name = default_config_file_name |
|
169 | 169 | default_log_level = logging.INFO |
|
170 | 170 | auto_create_cluster_dir = False |
|
171 | 171 | |
|
172 | 172 | def create_default_config(self): |
|
173 | 173 | super(IPClusterApp, self).create_default_config() |
|
174 | 174 | self.default_config.Global.controller_launcher = \ |
|
175 | 175 | 'IPython.kernel.launcher.LocalControllerLauncher' |
|
176 | 176 | self.default_config.Global.engine_launcher = \ |
|
177 | 177 | 'IPython.kernel.launcher.LocalEngineSetLauncher' |
|
178 | 178 | self.default_config.Global.n = 2 |
|
179 | 179 | self.default_config.Global.reset_config = False |
|
180 | 180 | self.default_config.Global.clean_logs = True |
|
181 | 181 | self.default_config.Global.stop_signal = 2 |
|
182 | 182 | self.default_config.Global.daemonize = False |
|
183 | 183 | |
|
184 | 184 | def create_command_line_config(self): |
|
185 | 185 | """Create and return a command line config loader.""" |
|
186 | 186 | return IPClusterCLLoader( |
|
187 | 187 | description=self.description, |
|
188 | 188 | version=release.version |
|
189 | 189 | ) |
|
190 | 190 | |
|
191 | 191 | def find_resources(self): |
|
192 | 192 | subcommand = self.command_line_config.Global.subcommand |
|
193 | 193 | if subcommand=='list': |
|
194 | 194 | self.list_cluster_dirs() |
|
195 | 195 | # Exit immediately because there is nothing left to do. |
|
196 | 196 | self.exit() |
|
197 | 197 | elif subcommand=='create': |
|
198 | 198 | self.auto_create_cluster_dir = True |
|
199 | 199 | super(IPClusterApp, self).find_resources() |
|
200 | 200 | elif subcommand=='start' or subcommand=='stop': |
|
201 | 201 | self.auto_create_cluster_dir = False |
|
202 | 202 | try: |
|
203 | 203 | super(IPClusterApp, self).find_resources() |
|
204 | 204 | except ClusterDirError: |
|
205 | 205 | raise ClusterDirError( |
|
206 | 206 | "Could not find a cluster directory. A cluster dir must " |
|
207 | 207 | "be created before running 'ipcluster start'. Do " |
|
208 | 208 | "'ipcluster create -h' or 'ipcluster list -h' for more " |
|
209 | 209 | "information about creating and listing cluster dirs." |
|
210 | 210 | ) |
|
211 | 211 | |
|
212 | 212 | def pre_construct(self): |
|
213 | 213 | super(IPClusterApp, self).pre_construct() |
|
214 | 214 | config = self.master_config |
|
215 | 215 | try: |
|
216 | 216 | daemon = config.Global.daemonize |
|
217 | 217 | if daemon: |
|
218 | 218 | config.Global.log_to_file = True |
|
219 | 219 | except AttributeError: |
|
220 | 220 | pass |
|
221 | 221 | |
|
222 | 222 | def construct(self): |
|
223 | 223 | config = self.master_config |
|
224 | 224 | if config.Global.subcommand=='list': |
|
225 | 225 | pass |
|
226 | 226 | elif config.Global.subcommand=='create': |
|
227 | 227 | self.log.info('Copying default config files to cluster directory ' |
|
228 | 228 | '[overwrite=%r]' % (config.Global.reset_config,)) |
|
229 | 229 | self.cluster_dir_obj.copy_all_config_files(overwrite=config.Global.reset_config) |
|
230 | 230 | elif config.Global.subcommand=='start': |
|
231 | 231 | self.start_logging() |
|
232 | 232 | reactor.callWhenRunning(self.start_launchers) |
|
233 | 233 | |
|
234 | 234 | def list_cluster_dirs(self): |
|
235 | 235 | # Find the search paths |
|
236 | cluster_dir_paths = os.environ.get('IPCLUSTERDIR_PATH','') | |
|
236 | cluster_dir_paths = os.environ.get('IPCLUSTER_DIR_PATH','') | |
|
237 | 237 | if cluster_dir_paths: |
|
238 | 238 | cluster_dir_paths = cluster_dir_paths.split(':') |
|
239 | 239 | else: |
|
240 | 240 | cluster_dir_paths = [] |
|
241 | 241 | try: |
|
242 | ipythondir = self.command_line_config.Global.ipythondir | |
|
242 | ipython_dir = self.command_line_config.Global.ipython_dir | |
|
243 | 243 | except AttributeError: |
|
244 | ipythondir = self.default_config.Global.ipythondir | |
|
245 | paths = [os.getcwd(), ipythondir] + \ | |
|
244 | ipython_dir = self.default_config.Global.ipython_dir | |
|
245 | paths = [os.getcwd(), ipython_dir] + \ | |
|
246 | 246 | cluster_dir_paths |
|
247 | 247 | paths = list(set(paths)) |
|
248 | 248 | |
|
249 | 249 | self.log.info('Searching for cluster dirs in paths: %r' % paths) |
|
250 | 250 | for path in paths: |
|
251 | 251 | files = os.listdir(path) |
|
252 | 252 | for f in files: |
|
253 | 253 | full_path = os.path.join(path, f) |
|
254 | 254 | if os.path.isdir(full_path) and f.startswith('cluster_'): |
|
255 | 255 | profile = full_path.split('_')[-1] |
|
256 | 256 | start_cmd = '"ipcluster start -n 4 -p %s"' % profile |
|
257 | 257 | print start_cmd + " ==> " + full_path |
|
258 | 258 | |
|
259 | 259 | def start_launchers(self): |
|
260 | 260 | config = self.master_config |
|
261 | 261 | |
|
262 | 262 | # Create the launchers |
|
263 | 263 | el_class = import_item(config.Global.engine_launcher) |
|
264 | 264 | self.engine_launcher = el_class( |
|
265 | 265 | self.cluster_dir, config=config |
|
266 | 266 | ) |
|
267 | 267 | cl_class = import_item(config.Global.controller_launcher) |
|
268 | 268 | self.controller_launcher = cl_class( |
|
269 | 269 | self.cluster_dir, config=config |
|
270 | 270 | ) |
|
271 | 271 | |
|
272 | 272 | # Setup signals |
|
273 | 273 | signal.signal(signal.SIGINT, self.stop_launchers) |
|
274 | 274 | # signal.signal(signal.SIGKILL, self.stop_launchers) |
|
275 | 275 | |
|
276 | 276 | # Setup the observing of stopping |
|
277 | 277 | d1 = self.controller_launcher.observe_stop() |
|
278 | 278 | d1.addCallback(self.stop_engines) |
|
279 | 279 | d1.addErrback(self.err_and_stop) |
|
280 | 280 | # If this triggers, just let them die |
|
281 | 281 | # d2 = self.engine_launcher.observe_stop() |
|
282 | 282 | |
|
283 | 283 | # Start the controller and engines |
|
284 | 284 | d = self.controller_launcher.start( |
|
285 | 285 | profile=None, cluster_dir=config.Global.cluster_dir |
|
286 | 286 | ) |
|
287 | 287 | d.addCallback(lambda _: self.start_engines()) |
|
288 | 288 | d.addErrback(self.err_and_stop) |
|
289 | 289 | |
|
290 | 290 | def err_and_stop(self, f): |
|
291 | 291 | log.msg('Unexpected error in ipcluster:') |
|
292 | 292 | log.err(f) |
|
293 | 293 | reactor.stop() |
|
294 | 294 | |
|
295 | 295 | def stop_engines(self, r): |
|
296 | 296 | return self.engine_launcher.stop() |
|
297 | 297 | |
|
298 | 298 | def start_engines(self): |
|
299 | 299 | config = self.master_config |
|
300 | 300 | d = self.engine_launcher.start( |
|
301 | 301 | config.Global.n, |
|
302 | 302 | profile=None, cluster_dir=config.Global.cluster_dir |
|
303 | 303 | ) |
|
304 | 304 | return d |
|
305 | 305 | |
|
306 | 306 | def stop_launchers(self, signum, frame): |
|
307 | 307 | log.msg("Stopping cluster") |
|
308 | 308 | d1 = self.engine_launcher.stop() |
|
309 | 309 | d2 = self.controller_launcher.stop() |
|
310 | 310 | # d1.addCallback(lambda _: self.controller_launcher.stop) |
|
311 | 311 | d1.addErrback(self.err_and_stop) |
|
312 | 312 | d2.addErrback(self.err_and_stop) |
|
313 | 313 | reactor.callLater(2.0, reactor.stop) |
|
314 | 314 | |
|
315 | 315 | def start_logging(self): |
|
316 | 316 | # Remove old log files |
|
317 | 317 | if self.master_config.Global.clean_logs: |
|
318 | 318 | log_dir = self.master_config.Global.log_dir |
|
319 | 319 | for f in os.listdir(log_dir): |
|
320 | 320 | if f.startswith('ipengine' + '-') and f.endswith('.log'): |
|
321 | 321 | os.remove(os.path.join(log_dir, f)) |
|
322 | 322 | for f in os.listdir(log_dir): |
|
323 | 323 | if f.startswith('ipcontroller' + '-') and f.endswith('.log'): |
|
324 | 324 | os.remove(os.path.join(log_dir, f)) |
|
325 | 325 | super(IPClusterApp, self).start_logging() |
|
326 | 326 | |
|
327 | 327 | def start_app(self): |
|
328 | 328 | """Start the application, depending on what subcommand is used.""" |
|
329 | 329 | config = self.master_config |
|
330 | 330 | subcmd = config.Global.subcommand |
|
331 | 331 | if subcmd=='create' or subcmd=='list': |
|
332 | 332 | return |
|
333 | 333 | elif subcmd=='start': |
|
334 | 334 | # First see if the cluster is already running |
|
335 | 335 | try: |
|
336 | 336 | pid = self.get_pid_from_file() |
|
337 | 337 | except: |
|
338 | 338 | pass |
|
339 | 339 | else: |
|
340 | 340 | self.log.critical( |
|
341 | 341 | 'Cluster is already running with [pid=%s]. ' |
|
342 | 342 | 'use "ipcluster stop" to stop the cluster.' % pid |
|
343 | 343 | ) |
|
344 | 344 | # Here I exit with a unusual exit status that other processes |
|
345 | 345 | # can watch for to learn how I existed. |
|
346 | 346 | sys.exit(10) |
|
347 | 347 | # Now log and daemonize |
|
348 | 348 | self.log.info('Starting ipcluster with [daemon=%r]' % config.Global.daemonize) |
|
349 | 349 | if config.Global.daemonize: |
|
350 | 350 | if os.name=='posix': |
|
351 | 351 | os.chdir(config.Global.cluster_dir) |
|
352 | 352 | self.log_level = 40 |
|
353 | 353 | daemonize() |
|
354 | 354 | |
|
355 | 355 | # Now write the new pid file after our new forked pid is active. |
|
356 | 356 | self.write_pid_file() |
|
357 | 357 | reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file) |
|
358 | 358 | reactor.run() |
|
359 | 359 | elif subcmd=='stop': |
|
360 | 360 | try: |
|
361 | 361 | pid = self.get_pid_from_file() |
|
362 | 362 | except PIDFileError: |
|
363 | 363 | self.log.critical( |
|
364 | 364 | 'Problem reading pid file, cluster is probably not running.' |
|
365 | 365 | ) |
|
366 | 366 | # Here I exit with a unusual exit status that other processes |
|
367 | 367 | # can watch for to learn how I existed. |
|
368 | 368 | sys.exit(11) |
|
369 | 369 | sig = config.Global.stop_signal |
|
370 | 370 | self.log.info( |
|
371 | 371 | "Stopping cluster [pid=%r] with [signal=%r]" % (pid, sig) |
|
372 | 372 | ) |
|
373 | 373 | os.kill(pid, sig) |
|
374 | 374 | |
|
375 | 375 | |
|
376 | 376 | def launch_new_instance(): |
|
377 | 377 | """Create and run the IPython cluster.""" |
|
378 | 378 | app = IPClusterApp() |
|
379 | 379 | app.start() |
|
380 | 380 | |
|
381 | 381 | |
|
382 | 382 | if __name__ == '__main__': |
|
383 | 383 | launch_new_instance() |
|
384 | 384 |
@@ -1,441 +1,441 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | """Module for interactively running scripts. |
|
3 | 3 | |
|
4 | 4 | This module implements classes for interactively running scripts written for |
|
5 | 5 | any system with a prompt which can be matched by a regexp suitable for |
|
6 | 6 | pexpect. It can be used to run as if they had been typed up interactively, an |
|
7 | 7 | arbitrary series of commands for the target system. |
|
8 | 8 | |
|
9 | 9 | The module includes classes ready for IPython (with the default prompts), |
|
10 | 10 | plain Python and SAGE, but making a new one is trivial. To see how to use it, |
|
11 | 11 | simply run the module as a script: |
|
12 | 12 | |
|
13 | 13 | ./irunner.py --help |
|
14 | 14 | |
|
15 | 15 | |
|
16 | 16 | This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script |
|
17 | 17 | contributed on the ipython-user list: |
|
18 | 18 | |
|
19 | 19 | http://scipy.net/pipermail/ipython-user/2006-May/001705.html |
|
20 | 20 | |
|
21 | 21 | |
|
22 | 22 | NOTES: |
|
23 | 23 | |
|
24 | 24 | - This module requires pexpect, available in most linux distros, or which can |
|
25 | 25 | be downloaded from |
|
26 | 26 | |
|
27 | 27 | http://pexpect.sourceforge.net |
|
28 | 28 | |
|
29 | 29 | - Because pexpect only works under Unix or Windows-Cygwin, this has the same |
|
30 | 30 | limitations. This means that it will NOT work under native windows Python. |
|
31 | 31 | """ |
|
32 | 32 | |
|
33 | 33 | # Stdlib imports |
|
34 | 34 | import optparse |
|
35 | 35 | import os |
|
36 | 36 | import sys |
|
37 | 37 | |
|
38 | 38 | # Third-party modules. |
|
39 | 39 | import pexpect |
|
40 | 40 | |
|
41 | 41 | # Global usage strings, to avoid indentation issues when typing it below. |
|
42 | 42 | USAGE = """ |
|
43 | 43 | Interactive script runner, type: %s |
|
44 | 44 | |
|
45 | 45 | runner [opts] script_name |
|
46 | 46 | """ |
|
47 | 47 | |
|
48 | 48 | def pexpect_monkeypatch(): |
|
49 | 49 | """Patch pexpect to prevent unhandled exceptions at VM teardown. |
|
50 | 50 | |
|
51 | 51 | Calling this function will monkeypatch the pexpect.spawn class and modify |
|
52 | 52 | its __del__ method to make it more robust in the face of failures that can |
|
53 | 53 | occur if it is called when the Python VM is shutting down. |
|
54 | 54 | |
|
55 | 55 | Since Python may fire __del__ methods arbitrarily late, it's possible for |
|
56 | 56 | them to execute during the teardown of the Python VM itself. At this |
|
57 | 57 | point, various builtin modules have been reset to None. Thus, the call to |
|
58 | 58 | self.close() will trigger an exception because it tries to call os.close(), |
|
59 | 59 | and os is now None. |
|
60 | 60 | """ |
|
61 | 61 | |
|
62 | 62 | if pexpect.__version__[:3] >= '2.2': |
|
63 | 63 | # No need to patch, fix is already the upstream version. |
|
64 | 64 | return |
|
65 | 65 | |
|
66 | 66 | def __del__(self): |
|
67 | 67 | """This makes sure that no system resources are left open. |
|
68 | 68 | Python only garbage collects Python objects. OS file descriptors |
|
69 | 69 | are not Python objects, so they must be handled explicitly. |
|
70 | 70 | If the child file descriptor was opened outside of this class |
|
71 | 71 | (passed to the constructor) then this does not close it. |
|
72 | 72 | """ |
|
73 | 73 | if not self.closed: |
|
74 | 74 | try: |
|
75 | 75 | self.close() |
|
76 | 76 | except AttributeError: |
|
77 | 77 | pass |
|
78 | 78 | |
|
79 | 79 | pexpect.spawn.__del__ = __del__ |
|
80 | 80 | |
|
81 | 81 | pexpect_monkeypatch() |
|
82 | 82 | |
|
83 | 83 | # The generic runner class |
|
84 | 84 | class InteractiveRunner(object): |
|
85 | 85 | """Class to run a sequence of commands through an interactive program.""" |
|
86 | 86 | |
|
87 | 87 | def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True): |
|
88 | 88 | """Construct a runner. |
|
89 | 89 | |
|
90 | 90 | Inputs: |
|
91 | 91 | |
|
92 | 92 | - program: command to execute the given program. |
|
93 | 93 | |
|
94 | 94 | - prompts: a list of patterns to match as valid prompts, in the |
|
95 | 95 | format used by pexpect. This basically means that it can be either |
|
96 | 96 | a string (to be compiled as a regular expression) or a list of such |
|
97 | 97 | (it must be a true list, as pexpect does type checks). |
|
98 | 98 | |
|
99 | 99 | If more than one prompt is given, the first is treated as the main |
|
100 | 100 | program prompt and the others as 'continuation' prompts, like |
|
101 | 101 | python's. This means that blank lines in the input source are |
|
102 | 102 | ommitted when the first prompt is matched, but are NOT ommitted when |
|
103 | 103 | the continuation one matches, since this is how python signals the |
|
104 | 104 | end of multiline input interactively. |
|
105 | 105 | |
|
106 | 106 | Optional inputs: |
|
107 | 107 | |
|
108 | 108 | - args(None): optional list of strings to pass as arguments to the |
|
109 | 109 | child program. |
|
110 | 110 | |
|
111 | 111 | - out(sys.stdout): if given, an output stream to be used when writing |
|
112 | 112 | output. The only requirement is that it must have a .write() method. |
|
113 | 113 | |
|
114 | 114 | Public members not parameterized in the constructor: |
|
115 | 115 | |
|
116 | 116 | - delaybeforesend(0): Newer versions of pexpect have a delay before |
|
117 | 117 | sending each new input. For our purposes here, it's typically best |
|
118 | 118 | to just set this to zero, but if you encounter reliability problems |
|
119 | 119 | or want an interactive run to pause briefly at each prompt, just |
|
120 | 120 | increase this value (it is measured in seconds). Note that this |
|
121 | 121 | variable is not honored at all by older versions of pexpect. |
|
122 | 122 | """ |
|
123 | 123 | |
|
124 | 124 | self.program = program |
|
125 | 125 | self.prompts = prompts |
|
126 | 126 | if args is None: args = [] |
|
127 | 127 | self.args = args |
|
128 | 128 | self.out = out |
|
129 | 129 | self.echo = echo |
|
130 | 130 | # Other public members which we don't make as parameters, but which |
|
131 | 131 | # users may occasionally want to tweak |
|
132 | 132 | self.delaybeforesend = 0 |
|
133 | 133 | |
|
134 | 134 | # Create child process and hold on to it so we don't have to re-create |
|
135 | 135 | # for every single execution call |
|
136 | 136 | c = self.child = pexpect.spawn(self.program,self.args,timeout=None) |
|
137 | 137 | c.delaybeforesend = self.delaybeforesend |
|
138 | 138 | # pexpect hard-codes the terminal size as (24,80) (rows,columns). |
|
139 | 139 | # This causes problems because any line longer than 80 characters gets |
|
140 | 140 | # completely overwrapped on the printed outptut (even though |
|
141 | 141 | # internally the code runs fine). We reset this to 99 rows X 200 |
|
142 | 142 | # columns (arbitrarily chosen), which should avoid problems in all |
|
143 | 143 | # reasonable cases. |
|
144 | 144 | c.setwinsize(99,200) |
|
145 | 145 | |
|
146 | 146 | def close(self): |
|
147 | 147 | """close child process""" |
|
148 | 148 | |
|
149 | 149 | self.child.close() |
|
150 | 150 | |
|
151 | 151 | def run_file(self,fname,interact=False,get_output=False): |
|
152 | 152 | """Run the given file interactively. |
|
153 | 153 | |
|
154 | 154 | Inputs: |
|
155 | 155 | |
|
156 | 156 | -fname: name of the file to execute. |
|
157 | 157 | |
|
158 | 158 | See the run_source docstring for the meaning of the optional |
|
159 | 159 | arguments.""" |
|
160 | 160 | |
|
161 | 161 | fobj = open(fname,'r') |
|
162 | 162 | try: |
|
163 | 163 | out = self.run_source(fobj,interact,get_output) |
|
164 | 164 | finally: |
|
165 | 165 | fobj.close() |
|
166 | 166 | if get_output: |
|
167 | 167 | return out |
|
168 | 168 | |
|
169 | 169 | def run_source(self,source,interact=False,get_output=False): |
|
170 | 170 | """Run the given source code interactively. |
|
171 | 171 | |
|
172 | 172 | Inputs: |
|
173 | 173 | |
|
174 | 174 | - source: a string of code to be executed, or an open file object we |
|
175 | 175 | can iterate over. |
|
176 | 176 | |
|
177 | 177 | Optional inputs: |
|
178 | 178 | |
|
179 | 179 | - interact(False): if true, start to interact with the running |
|
180 | 180 | program at the end of the script. Otherwise, just exit. |
|
181 | 181 | |
|
182 | 182 | - get_output(False): if true, capture the output of the child process |
|
183 | 183 | (filtering the input commands out) and return it as a string. |
|
184 | 184 | |
|
185 | 185 | Returns: |
|
186 | 186 | A string containing the process output, but only if requested. |
|
187 | 187 | """ |
|
188 | 188 | |
|
189 | 189 | # if the source is a string, chop it up in lines so we can iterate |
|
190 | 190 | # over it just as if it were an open file. |
|
191 | 191 | if not isinstance(source,file): |
|
192 | 192 | source = source.splitlines(True) |
|
193 | 193 | |
|
194 | 194 | if self.echo: |
|
195 | 195 | # normalize all strings we write to use the native OS line |
|
196 | 196 | # separators. |
|
197 | 197 | linesep = os.linesep |
|
198 | 198 | stdwrite = self.out.write |
|
199 | 199 | write = lambda s: stdwrite(s.replace('\r\n',linesep)) |
|
200 | 200 | else: |
|
201 | 201 | # Quiet mode, all writes are no-ops |
|
202 | 202 | write = lambda s: None |
|
203 | 203 | |
|
204 | 204 | c = self.child |
|
205 | 205 | prompts = c.compile_pattern_list(self.prompts) |
|
206 | 206 | prompt_idx = c.expect_list(prompts) |
|
207 | 207 | |
|
208 | 208 | # Flag whether the script ends normally or not, to know whether we can |
|
209 | 209 | # do anything further with the underlying process. |
|
210 | 210 | end_normal = True |
|
211 | 211 | |
|
212 | 212 | # If the output was requested, store it in a list for return at the end |
|
213 | 213 | if get_output: |
|
214 | 214 | output = [] |
|
215 | 215 | store_output = output.append |
|
216 | 216 | |
|
217 | 217 | for cmd in source: |
|
218 | 218 | # skip blank lines for all matches to the 'main' prompt, while the |
|
219 | 219 | # secondary prompts do not |
|
220 | 220 | if prompt_idx==0 and \ |
|
221 | 221 | (cmd.isspace() or cmd.lstrip().startswith('#')): |
|
222 | 222 | write(cmd) |
|
223 | 223 | continue |
|
224 | 224 | |
|
225 | 225 | # write('AFTER: '+c.after) # dbg |
|
226 | 226 | write(c.after) |
|
227 | 227 | c.send(cmd) |
|
228 | 228 | try: |
|
229 | 229 | prompt_idx = c.expect_list(prompts) |
|
230 | 230 | except pexpect.EOF: |
|
231 | 231 | # this will happen if the child dies unexpectedly |
|
232 | 232 | write(c.before) |
|
233 | 233 | end_normal = False |
|
234 | 234 | break |
|
235 | 235 | |
|
236 | 236 | write(c.before) |
|
237 | 237 | |
|
238 | 238 | # With an echoing process, the output we get in c.before contains |
|
239 | 239 | # the command sent, a newline, and then the actual process output |
|
240 | 240 | if get_output: |
|
241 | 241 | store_output(c.before[len(cmd+'\n'):]) |
|
242 | 242 | #write('CMD: <<%s>>' % cmd) # dbg |
|
243 | 243 | #write('OUTPUT: <<%s>>' % output[-1]) # dbg |
|
244 | 244 | |
|
245 | 245 | self.out.flush() |
|
246 | 246 | if end_normal: |
|
247 | 247 | if interact: |
|
248 | 248 | c.send('\n') |
|
249 | 249 | print '<< Starting interactive mode >>', |
|
250 | 250 | try: |
|
251 | 251 | c.interact() |
|
252 | 252 | except OSError: |
|
253 | 253 | # This is what fires when the child stops. Simply print a |
|
254 | 254 | # newline so the system prompt is aligned. The extra |
|
255 | 255 | # space is there to make sure it gets printed, otherwise |
|
256 | 256 | # OS buffering sometimes just suppresses it. |
|
257 | 257 | write(' \n') |
|
258 | 258 | self.out.flush() |
|
259 | 259 | else: |
|
260 | 260 | if interact: |
|
261 | 261 | e="Further interaction is not possible: child process is dead." |
|
262 | 262 | print >> sys.stderr, e |
|
263 | 263 | |
|
264 | 264 | # Leave the child ready for more input later on, otherwise select just |
|
265 | 265 | # hangs on the second invocation. |
|
266 | 266 | c.send('\n') |
|
267 | 267 | |
|
268 | 268 | # Return any requested output |
|
269 | 269 | if get_output: |
|
270 | 270 | return ''.join(output) |
|
271 | 271 | |
|
272 | 272 | def main(self,argv=None): |
|
273 | 273 | """Run as a command-line script.""" |
|
274 | 274 | |
|
275 | 275 | parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__) |
|
276 | 276 | newopt = parser.add_option |
|
277 | 277 | newopt('-i','--interact',action='store_true',default=False, |
|
278 | 278 | help='Interact with the program after the script is run.') |
|
279 | 279 | |
|
280 | 280 | opts,args = parser.parse_args(argv) |
|
281 | 281 | |
|
282 | 282 | if len(args) != 1: |
|
283 | 283 | print >> sys.stderr,"You must supply exactly one file to run." |
|
284 | 284 | sys.exit(1) |
|
285 | 285 | |
|
286 | 286 | self.run_file(args[0],opts.interact) |
|
287 | 287 | |
|
288 | 288 | |
|
289 | 289 | # Specific runners for particular programs |
|
290 | 290 | class IPythonRunner(InteractiveRunner): |
|
291 | 291 | """Interactive IPython runner. |
|
292 | 292 | |
|
293 | 293 | This initalizes IPython in 'nocolor' mode for simplicity. This lets us |
|
294 | 294 | avoid having to write a regexp that matches ANSI sequences, though pexpect |
|
295 | 295 | does support them. If anyone contributes patches for ANSI color support, |
|
296 | 296 | they will be welcome. |
|
297 | 297 | |
|
298 | 298 | It also sets the prompts manually, since the prompt regexps for |
|
299 | 299 | pexpect need to be matched to the actual prompts, so user-customized |
|
300 | 300 | prompts would break this. |
|
301 | 301 | """ |
|
302 | 302 | |
|
303 | 303 | def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True): |
|
304 | 304 | """New runner, optionally passing the ipython command to use.""" |
|
305 | 305 | |
|
306 | args0 = ['-colors','NoColor', | |
|
306 | args0 = ['--colors','NoColor', | |
|
307 | 307 | '-pi1','In [\\#]: ', |
|
308 | 308 | '-pi2',' .\\D.: ', |
|
309 |
'-noterm |
|
|
310 | '-noautoindent'] | |
|
309 | '--noterm-title', | |
|
310 | '--no-auto-indent'] | |
|
311 | 311 | if args is None: args = args0 |
|
312 | 312 | else: args = args0 + args |
|
313 | 313 | prompts = [r'In \[\d+\]: ',r' \.*: '] |
|
314 | 314 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
315 | 315 | |
|
316 | 316 | |
|
317 | 317 | class PythonRunner(InteractiveRunner): |
|
318 | 318 | """Interactive Python runner.""" |
|
319 | 319 | |
|
320 | 320 | def __init__(self,program='python',args=None,out=sys.stdout,echo=True): |
|
321 | 321 | """New runner, optionally passing the python command to use.""" |
|
322 | 322 | |
|
323 | 323 | prompts = [r'>>> ',r'\.\.\. '] |
|
324 | 324 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
325 | 325 | |
|
326 | 326 | |
|
327 | 327 | class SAGERunner(InteractiveRunner): |
|
328 | 328 | """Interactive SAGE runner. |
|
329 | 329 | |
|
330 | 330 | WARNING: this runner only works if you manually configure your SAGE copy |
|
331 | 331 | to use 'colors NoColor' in the ipythonrc config file, since currently the |
|
332 | 332 | prompt matching regexp does not identify color sequences.""" |
|
333 | 333 | |
|
334 | 334 | def __init__(self,program='sage',args=None,out=sys.stdout,echo=True): |
|
335 | 335 | """New runner, optionally passing the sage command to use.""" |
|
336 | 336 | |
|
337 | 337 | prompts = ['sage: ',r'\s*\.\.\. '] |
|
338 | 338 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
339 | 339 | |
|
340 | 340 | |
|
341 | 341 | class RunnerFactory(object): |
|
342 | 342 | """Code runner factory. |
|
343 | 343 | |
|
344 | 344 | This class provides an IPython code runner, but enforces that only one |
|
345 | 345 | runner is ever instantiated. The runner is created based on the extension |
|
346 | 346 | of the first file to run, and it raises an exception if a runner is later |
|
347 | 347 | requested for a different extension type. |
|
348 | 348 | |
|
349 | 349 | This ensures that we don't generate example files for doctest with a mix of |
|
350 | 350 | python and ipython syntax. |
|
351 | 351 | """ |
|
352 | 352 | |
|
353 | 353 | def __init__(self,out=sys.stdout): |
|
354 | 354 | """Instantiate a code runner.""" |
|
355 | 355 | |
|
356 | 356 | self.out = out |
|
357 | 357 | self.runner = None |
|
358 | 358 | self.runnerClass = None |
|
359 | 359 | |
|
360 | 360 | def _makeRunner(self,runnerClass): |
|
361 | 361 | self.runnerClass = runnerClass |
|
362 | 362 | self.runner = runnerClass(out=self.out) |
|
363 | 363 | return self.runner |
|
364 | 364 | |
|
365 | 365 | def __call__(self,fname): |
|
366 | 366 | """Return a runner for the given filename.""" |
|
367 | 367 | |
|
368 | 368 | if fname.endswith('.py'): |
|
369 | 369 | runnerClass = PythonRunner |
|
370 | 370 | elif fname.endswith('.ipy'): |
|
371 | 371 | runnerClass = IPythonRunner |
|
372 | 372 | else: |
|
373 | 373 | raise ValueError('Unknown file type for Runner: %r' % fname) |
|
374 | 374 | |
|
375 | 375 | if self.runner is None: |
|
376 | 376 | return self._makeRunner(runnerClass) |
|
377 | 377 | else: |
|
378 | 378 | if runnerClass==self.runnerClass: |
|
379 | 379 | return self.runner |
|
380 | 380 | else: |
|
381 | 381 | e='A runner of type %r can not run file %r' % \ |
|
382 | 382 | (self.runnerClass,fname) |
|
383 | 383 | raise ValueError(e) |
|
384 | 384 | |
|
385 | 385 | |
|
386 | 386 | # Global usage string, to avoid indentation issues if typed in a function def. |
|
387 | 387 | MAIN_USAGE = """ |
|
388 | 388 | %prog [options] file_to_run |
|
389 | 389 | |
|
390 | 390 | This is an interface to the various interactive runners available in this |
|
391 | 391 | module. If you want to pass specific options to one of the runners, you need |
|
392 | 392 | to first terminate the main options with a '--', and then provide the runner's |
|
393 | 393 | options. For example: |
|
394 | 394 | |
|
395 | 395 | irunner.py --python -- --help |
|
396 | 396 | |
|
397 | 397 | will pass --help to the python runner. Similarly, |
|
398 | 398 | |
|
399 | 399 | irunner.py --ipython -- --interact script.ipy |
|
400 | 400 | |
|
401 | 401 | will run the script.ipy file under the IPython runner, and then will start to |
|
402 | 402 | interact with IPython at the end of the script (instead of exiting). |
|
403 | 403 | |
|
404 | 404 | The already implemented runners are listed below; adding one for a new program |
|
405 | 405 | is a trivial task, see the source for examples. |
|
406 | 406 | |
|
407 | 407 | WARNING: the SAGE runner only works if you manually configure your SAGE copy |
|
408 | 408 | to use 'colors NoColor' in the ipythonrc config file, since currently the |
|
409 | 409 | prompt matching regexp does not identify color sequences. |
|
410 | 410 | """ |
|
411 | 411 | |
|
412 | 412 | def main(): |
|
413 | 413 | """Run as a command-line script.""" |
|
414 | 414 | |
|
415 | 415 | parser = optparse.OptionParser(usage=MAIN_USAGE) |
|
416 | 416 | newopt = parser.add_option |
|
417 | 417 | parser.set_defaults(mode='ipython') |
|
418 | 418 | newopt('--ipython',action='store_const',dest='mode',const='ipython', |
|
419 | 419 | help='IPython interactive runner (default).') |
|
420 | 420 | newopt('--python',action='store_const',dest='mode',const='python', |
|
421 | 421 | help='Python interactive runner.') |
|
422 | 422 | newopt('--sage',action='store_const',dest='mode',const='sage', |
|
423 | 423 | help='SAGE interactive runner.') |
|
424 | 424 | |
|
425 | 425 | opts,args = parser.parse_args() |
|
426 | 426 | runners = dict(ipython=IPythonRunner, |
|
427 | 427 | python=PythonRunner, |
|
428 | 428 | sage=SAGERunner) |
|
429 | 429 | |
|
430 | 430 | try: |
|
431 | 431 | ext = os.path.splitext(args[0])[-1] |
|
432 | 432 | except IndexError: |
|
433 | 433 | ext = '' |
|
434 | 434 | modes = {'.ipy':'ipython', |
|
435 | 435 | '.py':'python', |
|
436 | 436 | '.sage':'sage'} |
|
437 | 437 | mode = modes.get(ext,opts.mode) |
|
438 | 438 | runners[mode]().main(args) |
|
439 | 439 | |
|
440 | 440 | if __name__ == '__main__': |
|
441 | 441 | main() |
@@ -1,246 +1,246 b'' | |||
|
1 | 1 | """ File system operations |
|
2 | 2 | |
|
3 | 3 | Contains: Simple variants of normal unix shell commands (icp, imv, irm, |
|
4 | 4 | imkdir, igrep). |
|
5 | 5 | |
|
6 | 6 | Some "otherwise handy" utils ('collect' for gathering files to |
|
7 | 7 | ~/_ipython/collect, 'inote' for collecting single note lines to |
|
8 | 8 | ~/_ipython/note.txt) |
|
9 | 9 | |
|
10 | 10 | Mostly of use for bare windows installations where cygwin/equivalent is not |
|
11 | 11 | installed and you would otherwise need to deal with dos versions of the |
|
12 | 12 | commands (that e.g. don't understand / as path separator). These can |
|
13 | 13 | do some useful tricks on their own, though (like use 'mglob' patterns). |
|
14 | 14 | |
|
15 | 15 | Not to be confused with ipipe commands (ils etc.) that also start with i. |
|
16 | 16 | """ |
|
17 | 17 | |
|
18 | 18 | from IPython.core import ipapi |
|
19 | 19 | from IPython.core.error import TryNext |
|
20 | 20 | ip = ipapi.get() |
|
21 | 21 | |
|
22 | 22 | import shutil,os,shlex |
|
23 | 23 | from IPython.external import mglob |
|
24 | 24 | from IPython.external.path import path |
|
25 | 25 | from IPython.core.error import UsageError |
|
26 | 26 | import IPython.utils.generics |
|
27 | 27 | |
|
28 | 28 | def parse_args(args): |
|
29 | 29 | """ Given arg string 'CMD files... target', return ([files], target) """ |
|
30 | 30 | |
|
31 | 31 | tup = args.split(None, 1) |
|
32 | 32 | if len(tup) == 1: |
|
33 | 33 | raise UsageError("Expected arguments for " + tup[0]) |
|
34 | 34 | |
|
35 | 35 | tup2 = shlex.split(tup[1]) |
|
36 | 36 | |
|
37 | 37 | flist, trg = mglob.expand(tup2[0:-1]), tup2[-1] |
|
38 | 38 | if not flist: |
|
39 | 39 | raise UsageError("No files found:" + str(tup2[0:-1])) |
|
40 | 40 | return flist, trg |
|
41 | 41 | |
|
42 | 42 | def icp(ip,arg): |
|
43 | 43 | """ icp files... targetdir |
|
44 | 44 | |
|
45 | 45 | Copy all files to target, creating dirs for target if necessary |
|
46 | 46 | |
|
47 | 47 | icp srcdir dstdir |
|
48 | 48 | |
|
49 | 49 | Copy srcdir to distdir |
|
50 | 50 | |
|
51 | 51 | """ |
|
52 | 52 | import distutils.dir_util |
|
53 | 53 | |
|
54 | 54 | fs, targetdir = parse_args(arg) |
|
55 | 55 | if not os.path.isdir(targetdir) and len(fs) > 1: |
|
56 | 56 | distutils.dir_util.mkpath(targetdir,verbose =1) |
|
57 | 57 | for f in fs: |
|
58 | 58 | if os.path.isdir(f): |
|
59 | 59 | shutil.copytree(f, targetdir) |
|
60 | 60 | else: |
|
61 | 61 | shutil.copy2(f,targetdir) |
|
62 | 62 | return fs |
|
63 | 63 | ip.define_alias("icp",icp) |
|
64 | 64 | |
|
65 | 65 | def imv(ip,arg): |
|
66 | 66 | """ imv src tgt |
|
67 | 67 | |
|
68 | 68 | Move source to target. |
|
69 | 69 | """ |
|
70 | 70 | |
|
71 | 71 | fs, target = parse_args(arg) |
|
72 | 72 | if len(fs) > 1: |
|
73 | 73 | assert os.path.isdir(target) |
|
74 | 74 | for f in fs: |
|
75 | 75 | shutil.move(f, target) |
|
76 | 76 | return fs |
|
77 | 77 | ip.define_alias("imv",imv) |
|
78 | 78 | |
|
79 | 79 | def irm(ip,arg): |
|
80 | 80 | """ irm path[s]... |
|
81 | 81 | |
|
82 | 82 | Remove file[s] or dir[s] path. Dirs are deleted recursively. |
|
83 | 83 | """ |
|
84 | 84 | try: |
|
85 | 85 | paths = mglob.expand(arg.split(None,1)[1]) |
|
86 | 86 | except IndexError: |
|
87 | 87 | raise UsageError("%irm paths...") |
|
88 | 88 | import distutils.dir_util |
|
89 | 89 | for p in paths: |
|
90 | 90 | print "rm",p |
|
91 | 91 | if os.path.isdir(p): |
|
92 | 92 | distutils.dir_util.remove_tree(p, verbose = 1) |
|
93 | 93 | else: |
|
94 | 94 | os.remove(p) |
|
95 | 95 | |
|
96 | 96 | ip.define_alias("irm",irm) |
|
97 | 97 | |
|
98 | 98 | def imkdir(ip,arg): |
|
99 | 99 | """ imkdir path |
|
100 | 100 | |
|
101 | 101 | Creates dir path, and all dirs on the road |
|
102 | 102 | """ |
|
103 | 103 | import distutils.dir_util |
|
104 | 104 | targetdir = arg.split(None,1)[1] |
|
105 | 105 | distutils.dir_util.mkpath(targetdir,verbose =1) |
|
106 | 106 | |
|
107 | 107 | ip.define_alias("imkdir",imkdir) |
|
108 | 108 | |
|
109 | 109 | def igrep(ip,arg): |
|
110 | 110 | """ igrep PAT files... |
|
111 | 111 | |
|
112 | 112 | Very dumb file scan, case-insensitive. |
|
113 | 113 | |
|
114 | 114 | e.g. |
|
115 | 115 | |
|
116 | 116 | igrep "test this" rec:*.py |
|
117 | 117 | |
|
118 | 118 | """ |
|
119 | 119 | elems = shlex.split(arg) |
|
120 | 120 | dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:]) |
|
121 | 121 | res = [] |
|
122 | 122 | for f in fs: |
|
123 | 123 | found = False |
|
124 | 124 | for l in open(f): |
|
125 | 125 | if pat.lower() in l.lower(): |
|
126 | 126 | if not found: |
|
127 | 127 | print "[[",f,"]]" |
|
128 | 128 | found = True |
|
129 | 129 | res.append(f) |
|
130 | 130 | print l.rstrip() |
|
131 | 131 | return res |
|
132 | 132 | |
|
133 | 133 | ip.define_alias("igrep",igrep) |
|
134 | 134 | |
|
135 | 135 | def collect(ip,arg): |
|
136 | 136 | """ collect foo/a.txt rec:bar=*.py |
|
137 | 137 | |
|
138 | 138 | Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar, |
|
139 | 139 | likewise |
|
140 | 140 | |
|
141 | 141 | Without args, try to open ~/_ipython/collect dir (in win32 at least). |
|
142 | 142 | """ |
|
143 | 143 | from IPython.external.path import path |
|
144 |
basedir = path(ip. |
|
|
144 | basedir = path(ip.ipython_dir + '/collect') | |
|
145 | 145 | try: |
|
146 | 146 | fs = mglob.expand(arg.split(None,1)[1]) |
|
147 | 147 | except IndexError: |
|
148 | 148 | os.startfile(basedir) |
|
149 | 149 | return |
|
150 | 150 | for f in fs: |
|
151 | 151 | f = path(f) |
|
152 | 152 | trg = basedir / f.splitdrive()[1].lstrip('/\\') |
|
153 | 153 | if f.isdir(): |
|
154 | 154 | print "mkdir",trg |
|
155 | 155 | trg.makedirs() |
|
156 | 156 | continue |
|
157 | 157 | dname = trg.dirname() |
|
158 | 158 | if not dname.isdir(): |
|
159 | 159 | dname.makedirs() |
|
160 | 160 | print f,"=>",trg |
|
161 | 161 | shutil.copy2(f,trg) |
|
162 | 162 | |
|
163 | 163 | ip.define_alias("collect",collect) |
|
164 | 164 | |
|
165 | 165 | def inote(ip,arg): |
|
166 | 166 | """ inote Hello world |
|
167 | 167 | |
|
168 | 168 | Adds timestamp and Hello world to ~/_ipython/notes.txt |
|
169 | 169 | |
|
170 | 170 | Without args, opens notes.txt for editing. |
|
171 | 171 | """ |
|
172 | 172 | import time |
|
173 |
fname = ip. |
|
|
173 | fname = ip.ipython_dir + '/notes.txt' | |
|
174 | 174 | |
|
175 | 175 | try: |
|
176 | 176 | entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n' |
|
177 | 177 | f= open(fname, 'a').write(entry) |
|
178 | 178 | except IndexError: |
|
179 | 179 | ip.hooks.editor(fname) |
|
180 | 180 | |
|
181 | 181 | ip.define_alias("inote",inote) |
|
182 | 182 | |
|
183 | 183 | def pathobj_mangle(p): |
|
184 | 184 | return p.replace(' ', '__').replace('.','DOT') |
|
185 | 185 | def pathobj_unmangle(s): |
|
186 | 186 | return s.replace('__',' ').replace('DOT','.') |
|
187 | 187 | |
|
188 | 188 | |
|
189 | 189 | |
|
190 | 190 | class PathObj(path): |
|
191 | 191 | def __init__(self,p): |
|
192 | 192 | self.path = p |
|
193 | 193 | if p != '.': |
|
194 | 194 | self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)] |
|
195 | 195 | else: |
|
196 | 196 | self.ents = None |
|
197 | 197 | def __complete__(self): |
|
198 | 198 | if self.path != '.': |
|
199 | 199 | return self.ents |
|
200 | 200 | self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')] |
|
201 | 201 | return self.ents |
|
202 | 202 | def __getattr__(self,name): |
|
203 | 203 | if name in self.ents: |
|
204 | 204 | if self.path.endswith('/'): |
|
205 | 205 | sep = '' |
|
206 | 206 | else: |
|
207 | 207 | sep = '/' |
|
208 | 208 | |
|
209 | 209 | tgt = self.path + sep + pathobj_unmangle(name) |
|
210 | 210 | #print "tgt",tgt |
|
211 | 211 | if os.path.isdir(tgt): |
|
212 | 212 | return PathObj(tgt) |
|
213 | 213 | if os.path.isfile(tgt): |
|
214 | 214 | return path(tgt) |
|
215 | 215 | |
|
216 | 216 | raise AttributeError, name # <<< DON'T FORGET THIS LINE !! |
|
217 | 217 | def __str__(self): |
|
218 | 218 | return self.path |
|
219 | 219 | |
|
220 | 220 | def __repr__(self): |
|
221 | 221 | return "<PathObj to %s>" % self.path |
|
222 | 222 | |
|
223 | 223 | def __call__(self): |
|
224 | 224 | print "cd:",self.path |
|
225 | 225 | os.chdir(self.path) |
|
226 | 226 | |
|
227 | 227 | def complete_pathobj(obj, prev_completions): |
|
228 | 228 | if hasattr(obj,'__complete__'): |
|
229 | 229 | res = obj.__complete__() |
|
230 | 230 | if res: |
|
231 | 231 | return res |
|
232 | 232 | # just return normal attributes of 'path' object if the dir is empty |
|
233 | 233 | raise TryNext |
|
234 | 234 | |
|
235 | 235 | complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj) |
|
236 | 236 | |
|
237 | 237 | def test_pathobj(): |
|
238 | 238 | #p = PathObj('c:/prj') |
|
239 | 239 | #p2 = p.cgi |
|
240 | 240 | #print p,p2 |
|
241 | 241 | rootdir = PathObj("/") |
|
242 | 242 | startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs") |
|
243 | 243 | cwd = PathObj('.') |
|
244 | 244 | ip.push("rootdir startmenu cwd") |
|
245 | 245 | |
|
246 | 246 | #test_pathobj() No newline at end of file |
@@ -1,1796 +1,1799 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """General purpose utilities. |
|
3 | 3 | |
|
4 | 4 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
5 | 5 | these things are also convenient when working at the command line. |
|
6 | 6 | """ |
|
7 | 7 | |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
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 | # required modules from the Python standard library |
|
17 | 17 | import __main__ |
|
18 | 18 | |
|
19 | 19 | import os |
|
20 | 20 | import platform |
|
21 | 21 | import re |
|
22 | 22 | import shlex |
|
23 | 23 | import shutil |
|
24 | 24 | import subprocess |
|
25 | 25 | import sys |
|
26 | 26 | import time |
|
27 | 27 | import types |
|
28 | 28 | import warnings |
|
29 | 29 | |
|
30 | 30 | # Curses and termios are Unix-only modules |
|
31 | 31 | try: |
|
32 | 32 | import curses |
|
33 | 33 | # We need termios as well, so if its import happens to raise, we bail on |
|
34 | 34 | # using curses altogether. |
|
35 | 35 | import termios |
|
36 | 36 | except ImportError: |
|
37 | 37 | USE_CURSES = False |
|
38 | 38 | else: |
|
39 | 39 | # Curses on Solaris may not be complete, so we can't use it there |
|
40 | 40 | USE_CURSES = hasattr(curses,'initscr') |
|
41 | 41 | |
|
42 | 42 | # Other IPython utilities |
|
43 | 43 | import IPython |
|
44 | 44 | from IPython.external.Itpl import itpl,printpl |
|
45 | 45 | from IPython.utils import platutils |
|
46 | 46 | from IPython.utils.generics import result_display |
|
47 | 47 | from IPython.external.path import path |
|
48 | 48 | |
|
49 | 49 | try: |
|
50 | 50 | set |
|
51 | 51 | except: |
|
52 | 52 | from sets import Set as set |
|
53 | 53 | |
|
54 | 54 | |
|
55 | 55 | #**************************************************************************** |
|
56 | 56 | # Exceptions |
|
57 | 57 | class Error(Exception): |
|
58 | 58 | """Base class for exceptions in this module.""" |
|
59 | 59 | pass |
|
60 | 60 | |
|
61 | 61 | #---------------------------------------------------------------------------- |
|
62 | 62 | class IOStream: |
|
63 | 63 | def __init__(self,stream,fallback): |
|
64 | 64 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
65 | 65 | stream = fallback |
|
66 | 66 | self.stream = stream |
|
67 | 67 | self._swrite = stream.write |
|
68 | 68 | self.flush = stream.flush |
|
69 | 69 | |
|
70 | 70 | def write(self,data): |
|
71 | 71 | try: |
|
72 | 72 | self._swrite(data) |
|
73 | 73 | except: |
|
74 | 74 | try: |
|
75 | 75 | # print handles some unicode issues which may trip a plain |
|
76 | 76 | # write() call. Attempt to emulate write() by using a |
|
77 | 77 | # trailing comma |
|
78 | 78 | print >> self.stream, data, |
|
79 | 79 | except: |
|
80 | 80 | # if we get here, something is seriously broken. |
|
81 | 81 | print >> sys.stderr, \ |
|
82 | 82 | 'ERROR - failed to write data to stream:', self.stream |
|
83 | 83 | |
|
84 | 84 | def close(self): |
|
85 | 85 | pass |
|
86 | 86 | |
|
87 | 87 | |
|
88 | 88 | class IOTerm: |
|
89 | 89 | """ Term holds the file or file-like objects for handling I/O operations. |
|
90 | 90 | |
|
91 | 91 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
92 | 92 | Windows they can can replaced to allow editing the strings before they are |
|
93 | 93 | displayed.""" |
|
94 | 94 | |
|
95 | 95 | # In the future, having IPython channel all its I/O operations through |
|
96 | 96 | # this class will make it easier to embed it into other environments which |
|
97 | 97 | # are not a normal terminal (such as a GUI-based shell) |
|
98 | 98 | def __init__(self,cin=None,cout=None,cerr=None): |
|
99 | 99 | self.cin = IOStream(cin,sys.stdin) |
|
100 | 100 | self.cout = IOStream(cout,sys.stdout) |
|
101 | 101 | self.cerr = IOStream(cerr,sys.stderr) |
|
102 | 102 | |
|
103 | 103 | # Global variable to be used for all I/O |
|
104 | 104 | Term = IOTerm() |
|
105 | 105 | |
|
106 | 106 | import IPython.utils.rlineimpl as readline |
|
107 | 107 | # Remake Term to use the readline i/o facilities |
|
108 | 108 | if sys.platform == 'win32' and readline.have_readline: |
|
109 | 109 | |
|
110 | 110 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | #**************************************************************************** |
|
114 | 114 | # Generic warning/error printer, used by everything else |
|
115 | 115 | def warn(msg,level=2,exit_val=1): |
|
116 | 116 | """Standard warning printer. Gives formatting consistency. |
|
117 | 117 | |
|
118 | 118 | Output is sent to Term.cerr (sys.stderr by default). |
|
119 | 119 | |
|
120 | 120 | Options: |
|
121 | 121 | |
|
122 | 122 | -level(2): allows finer control: |
|
123 | 123 | 0 -> Do nothing, dummy function. |
|
124 | 124 | 1 -> Print message. |
|
125 | 125 | 2 -> Print 'WARNING:' + message. (Default level). |
|
126 | 126 | 3 -> Print 'ERROR:' + message. |
|
127 | 127 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
128 | 128 | |
|
129 | 129 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
130 | 130 | warning. Ignored for all other levels.""" |
|
131 | 131 | |
|
132 | 132 | if level>0: |
|
133 | 133 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
134 | 134 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
135 | 135 | if level == 4: |
|
136 | 136 | print >> Term.cerr,'Exiting.\n' |
|
137 | 137 | sys.exit(exit_val) |
|
138 | 138 | |
|
139 | 139 | def info(msg): |
|
140 | 140 | """Equivalent to warn(msg,level=1).""" |
|
141 | 141 | |
|
142 | 142 | warn(msg,level=1) |
|
143 | 143 | |
|
144 | 144 | def error(msg): |
|
145 | 145 | """Equivalent to warn(msg,level=3).""" |
|
146 | 146 | |
|
147 | 147 | warn(msg,level=3) |
|
148 | 148 | |
|
149 | 149 | def fatal(msg,exit_val=1): |
|
150 | 150 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
151 | 151 | |
|
152 | 152 | warn(msg,exit_val=exit_val,level=4) |
|
153 | 153 | |
|
154 | 154 | #--------------------------------------------------------------------------- |
|
155 | 155 | # Debugging routines |
|
156 | 156 | # |
|
157 | 157 | def debugx(expr,pre_msg=''): |
|
158 | 158 | """Print the value of an expression from the caller's frame. |
|
159 | 159 | |
|
160 | 160 | Takes an expression, evaluates it in the caller's frame and prints both |
|
161 | 161 | the given expression and the resulting value (as well as a debug mark |
|
162 | 162 | indicating the name of the calling function. The input must be of a form |
|
163 | 163 | suitable for eval(). |
|
164 | 164 | |
|
165 | 165 | An optional message can be passed, which will be prepended to the printed |
|
166 | 166 | expr->value pair.""" |
|
167 | 167 | |
|
168 | 168 | cf = sys._getframe(1) |
|
169 | 169 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
170 | 170 | eval(expr,cf.f_globals,cf.f_locals)) |
|
171 | 171 | |
|
172 | 172 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
173 | 173 | #def debugx(expr,pre_msg=''): pass |
|
174 | 174 | |
|
175 | 175 | #---------------------------------------------------------------------------- |
|
176 | 176 | StringTypes = types.StringTypes |
|
177 | 177 | |
|
178 | 178 | # Basic timing functionality |
|
179 | 179 | |
|
180 | 180 | # If possible (Unix), use the resource module instead of time.clock() |
|
181 | 181 | try: |
|
182 | 182 | import resource |
|
183 | 183 | def clocku(): |
|
184 | 184 | """clocku() -> floating point number |
|
185 | 185 | |
|
186 | 186 | Return the *USER* CPU time in seconds since the start of the process. |
|
187 | 187 | This is done via a call to resource.getrusage, so it avoids the |
|
188 | 188 | wraparound problems in time.clock().""" |
|
189 | 189 | |
|
190 | 190 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
191 | 191 | |
|
192 | 192 | def clocks(): |
|
193 | 193 | """clocks() -> floating point number |
|
194 | 194 | |
|
195 | 195 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
196 | 196 | This is done via a call to resource.getrusage, so it avoids the |
|
197 | 197 | wraparound problems in time.clock().""" |
|
198 | 198 | |
|
199 | 199 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
200 | 200 | |
|
201 | 201 | def clock(): |
|
202 | 202 | """clock() -> floating point number |
|
203 | 203 | |
|
204 | 204 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
205 | 205 | the process. This is done via a call to resource.getrusage, so it |
|
206 | 206 | avoids the wraparound problems in time.clock().""" |
|
207 | 207 | |
|
208 | 208 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
209 | 209 | return u+s |
|
210 | 210 | |
|
211 | 211 | def clock2(): |
|
212 | 212 | """clock2() -> (t_user,t_system) |
|
213 | 213 | |
|
214 | 214 | Similar to clock(), but return a tuple of user/system times.""" |
|
215 | 215 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
216 | 216 | |
|
217 | 217 | except ImportError: |
|
218 | 218 | # There is no distinction of user/system time under windows, so we just use |
|
219 | 219 | # time.clock() for everything... |
|
220 | 220 | clocku = clocks = clock = time.clock |
|
221 | 221 | def clock2(): |
|
222 | 222 | """Under windows, system CPU time can't be measured. |
|
223 | 223 | |
|
224 | 224 | This just returns clock() and zero.""" |
|
225 | 225 | return time.clock(),0.0 |
|
226 | 226 | |
|
227 | 227 | def timings_out(reps,func,*args,**kw): |
|
228 | 228 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
229 | 229 | |
|
230 | 230 | Execute a function reps times, return a tuple with the elapsed total |
|
231 | 231 | CPU time in seconds, the time per call and the function's output. |
|
232 | 232 | |
|
233 | 233 | Under Unix, the return value is the sum of user+system time consumed by |
|
234 | 234 | the process, computed via the resource module. This prevents problems |
|
235 | 235 | related to the wraparound effect which the time.clock() function has. |
|
236 | 236 | |
|
237 | 237 | Under Windows the return value is in wall clock seconds. See the |
|
238 | 238 | documentation for the time module for more details.""" |
|
239 | 239 | |
|
240 | 240 | reps = int(reps) |
|
241 | 241 | assert reps >=1, 'reps must be >= 1' |
|
242 | 242 | if reps==1: |
|
243 | 243 | start = clock() |
|
244 | 244 | out = func(*args,**kw) |
|
245 | 245 | tot_time = clock()-start |
|
246 | 246 | else: |
|
247 | 247 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
248 | 248 | start = clock() |
|
249 | 249 | for dummy in rng: func(*args,**kw) |
|
250 | 250 | out = func(*args,**kw) # one last time |
|
251 | 251 | tot_time = clock()-start |
|
252 | 252 | av_time = tot_time / reps |
|
253 | 253 | return tot_time,av_time,out |
|
254 | 254 | |
|
255 | 255 | def timings(reps,func,*args,**kw): |
|
256 | 256 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
257 | 257 | |
|
258 | 258 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
259 | 259 | time in seconds and the time per call. These are just the first two values |
|
260 | 260 | in timings_out().""" |
|
261 | 261 | |
|
262 | 262 | return timings_out(reps,func,*args,**kw)[0:2] |
|
263 | 263 | |
|
264 | 264 | def timing(func,*args,**kw): |
|
265 | 265 | """timing(func,*args,**kw) -> t_total |
|
266 | 266 | |
|
267 | 267 | Execute a function once, return the elapsed total CPU time in |
|
268 | 268 | seconds. This is just the first value in timings_out().""" |
|
269 | 269 | |
|
270 | 270 | return timings_out(1,func,*args,**kw)[0] |
|
271 | 271 | |
|
272 | 272 | #**************************************************************************** |
|
273 | 273 | # file and system |
|
274 | 274 | |
|
275 | 275 | def arg_split(s,posix=False): |
|
276 | 276 | """Split a command line's arguments in a shell-like manner. |
|
277 | 277 | |
|
278 | 278 | This is a modified version of the standard library's shlex.split() |
|
279 | 279 | function, but with a default of posix=False for splitting, so that quotes |
|
280 | 280 | in inputs are respected.""" |
|
281 | 281 | |
|
282 | 282 | # XXX - there may be unicode-related problems here!!! I'm not sure that |
|
283 | 283 | # shlex is truly unicode-safe, so it might be necessary to do |
|
284 | 284 | # |
|
285 | 285 | # s = s.encode(sys.stdin.encoding) |
|
286 | 286 | # |
|
287 | 287 | # first, to ensure that shlex gets a normal string. Input from anyone who |
|
288 | 288 | # knows more about unicode and shlex than I would be good to have here... |
|
289 | 289 | lex = shlex.shlex(s, posix=posix) |
|
290 | 290 | lex.whitespace_split = True |
|
291 | 291 | return list(lex) |
|
292 | 292 | |
|
293 | 293 | def system(cmd,verbose=0,debug=0,header=''): |
|
294 | 294 | """Execute a system command, return its exit status. |
|
295 | 295 | |
|
296 | 296 | Options: |
|
297 | 297 | |
|
298 | 298 | - verbose (0): print the command to be executed. |
|
299 | 299 | |
|
300 | 300 | - debug (0): only print, do not actually execute. |
|
301 | 301 | |
|
302 | 302 | - header (''): Header to print on screen prior to the executed command (it |
|
303 | 303 | is only prepended to the command, no newlines are added). |
|
304 | 304 | |
|
305 | 305 | Note: a stateful version of this function is available through the |
|
306 | 306 | SystemExec class.""" |
|
307 | 307 | |
|
308 | 308 | stat = 0 |
|
309 | 309 | if verbose or debug: print header+cmd |
|
310 | 310 | sys.stdout.flush() |
|
311 | 311 | if not debug: stat = os.system(cmd) |
|
312 | 312 | return stat |
|
313 | 313 | |
|
314 | 314 | def abbrev_cwd(): |
|
315 | 315 | """ Return abbreviated version of cwd, e.g. d:mydir """ |
|
316 | 316 | cwd = os.getcwd().replace('\\','/') |
|
317 | 317 | drivepart = '' |
|
318 | 318 | tail = cwd |
|
319 | 319 | if sys.platform == 'win32': |
|
320 | 320 | if len(cwd) < 4: |
|
321 | 321 | return cwd |
|
322 | 322 | drivepart,tail = os.path.splitdrive(cwd) |
|
323 | 323 | |
|
324 | 324 | |
|
325 | 325 | parts = tail.split('/') |
|
326 | 326 | if len(parts) > 2: |
|
327 | 327 | tail = '/'.join(parts[-2:]) |
|
328 | 328 | |
|
329 | 329 | return (drivepart + ( |
|
330 | 330 | cwd == '/' and '/' or tail)) |
|
331 | 331 | |
|
332 | 332 | |
|
333 | 333 | # This function is used by ipython in a lot of places to make system calls. |
|
334 | 334 | # We need it to be slightly different under win32, due to the vagaries of |
|
335 | 335 | # 'network shares'. A win32 override is below. |
|
336 | 336 | |
|
337 | 337 | def shell(cmd,verbose=0,debug=0,header=''): |
|
338 | 338 | """Execute a command in the system shell, always return None. |
|
339 | 339 | |
|
340 | 340 | Options: |
|
341 | 341 | |
|
342 | 342 | - verbose (0): print the command to be executed. |
|
343 | 343 | |
|
344 | 344 | - debug (0): only print, do not actually execute. |
|
345 | 345 | |
|
346 | 346 | - header (''): Header to print on screen prior to the executed command (it |
|
347 | 347 | is only prepended to the command, no newlines are added). |
|
348 | 348 | |
|
349 | 349 | Note: this is similar to genutils.system(), but it returns None so it can |
|
350 | 350 | be conveniently used in interactive loops without getting the return value |
|
351 | 351 | (typically 0) printed many times.""" |
|
352 | 352 | |
|
353 | 353 | stat = 0 |
|
354 | 354 | if verbose or debug: print header+cmd |
|
355 | 355 | # flush stdout so we don't mangle python's buffering |
|
356 | 356 | sys.stdout.flush() |
|
357 | 357 | |
|
358 | 358 | if not debug: |
|
359 | 359 | platutils.set_term_title("IPy " + cmd) |
|
360 | 360 | os.system(cmd) |
|
361 | 361 | platutils.set_term_title("IPy " + abbrev_cwd()) |
|
362 | 362 | |
|
363 | 363 | # override shell() for win32 to deal with network shares |
|
364 | 364 | if os.name in ('nt','dos'): |
|
365 | 365 | |
|
366 | 366 | shell_ori = shell |
|
367 | 367 | |
|
368 | 368 | def shell(cmd,verbose=0,debug=0,header=''): |
|
369 | 369 | if os.getcwd().startswith(r"\\"): |
|
370 | 370 | path = os.getcwd() |
|
371 | 371 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
372 | 372 | # as cmd.exe cannot handle UNC addresses) |
|
373 | 373 | os.chdir("c:") |
|
374 | 374 | # issue pushd to the UNC-share and then run the command |
|
375 | 375 | try: |
|
376 | 376 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
377 | 377 | finally: |
|
378 | 378 | os.chdir(path) |
|
379 | 379 | else: |
|
380 | 380 | shell_ori(cmd,verbose,debug,header) |
|
381 | 381 | |
|
382 | 382 | shell.__doc__ = shell_ori.__doc__ |
|
383 | 383 | |
|
384 | 384 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
385 | 385 | """Dummy substitute for perl's backquotes. |
|
386 | 386 | |
|
387 | 387 | Executes a command and returns the output. |
|
388 | 388 | |
|
389 | 389 | Accepts the same arguments as system(), plus: |
|
390 | 390 | |
|
391 | 391 | - split(0): if true, the output is returned as a list split on newlines. |
|
392 | 392 | |
|
393 | 393 | Note: a stateful version of this function is available through the |
|
394 | 394 | SystemExec class. |
|
395 | 395 | |
|
396 | 396 | This is pretty much deprecated and rarely used, |
|
397 | 397 | genutils.getoutputerror may be what you need. |
|
398 | 398 | |
|
399 | 399 | """ |
|
400 | 400 | |
|
401 | 401 | if verbose or debug: print header+cmd |
|
402 | 402 | if not debug: |
|
403 | 403 | output = os.popen(cmd).read() |
|
404 | 404 | # stipping last \n is here for backwards compat. |
|
405 | 405 | if output.endswith('\n'): |
|
406 | 406 | output = output[:-1] |
|
407 | 407 | if split: |
|
408 | 408 | return output.split('\n') |
|
409 | 409 | else: |
|
410 | 410 | return output |
|
411 | 411 | |
|
412 | 412 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
413 | 413 | """Return (standard output,standard error) of executing cmd in a shell. |
|
414 | 414 | |
|
415 | 415 | Accepts the same arguments as system(), plus: |
|
416 | 416 | |
|
417 | 417 | - split(0): if true, each of stdout/err is returned as a list split on |
|
418 | 418 | newlines. |
|
419 | 419 | |
|
420 | 420 | Note: a stateful version of this function is available through the |
|
421 | 421 | SystemExec class.""" |
|
422 | 422 | |
|
423 | 423 | if verbose or debug: print header+cmd |
|
424 | 424 | if not cmd: |
|
425 | 425 | if split: |
|
426 | 426 | return [],[] |
|
427 | 427 | else: |
|
428 | 428 | return '','' |
|
429 | 429 | if not debug: |
|
430 | 430 | pin,pout,perr = os.popen3(cmd) |
|
431 | 431 | tout = pout.read().rstrip() |
|
432 | 432 | terr = perr.read().rstrip() |
|
433 | 433 | pin.close() |
|
434 | 434 | pout.close() |
|
435 | 435 | perr.close() |
|
436 | 436 | if split: |
|
437 | 437 | return tout.split('\n'),terr.split('\n') |
|
438 | 438 | else: |
|
439 | 439 | return tout,terr |
|
440 | 440 | |
|
441 | 441 | # for compatibility with older naming conventions |
|
442 | 442 | xsys = system |
|
443 | 443 | bq = getoutput |
|
444 | 444 | |
|
445 | 445 | class SystemExec: |
|
446 | 446 | """Access the system and getoutput functions through a stateful interface. |
|
447 | 447 | |
|
448 | 448 | Note: here we refer to the system and getoutput functions from this |
|
449 | 449 | library, not the ones from the standard python library. |
|
450 | 450 | |
|
451 | 451 | This class offers the system and getoutput functions as methods, but the |
|
452 | 452 | verbose, debug and header parameters can be set for the instance (at |
|
453 | 453 | creation time or later) so that they don't need to be specified on each |
|
454 | 454 | call. |
|
455 | 455 | |
|
456 | 456 | For efficiency reasons, there's no way to override the parameters on a |
|
457 | 457 | per-call basis other than by setting instance attributes. If you need |
|
458 | 458 | local overrides, it's best to directly call system() or getoutput(). |
|
459 | 459 | |
|
460 | 460 | The following names are provided as alternate options: |
|
461 | 461 | - xsys: alias to system |
|
462 | 462 | - bq: alias to getoutput |
|
463 | 463 | |
|
464 | 464 | An instance can then be created as: |
|
465 | 465 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
466 | 466 | """ |
|
467 | 467 | |
|
468 | 468 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
469 | 469 | """Specify the instance's values for verbose, debug and header.""" |
|
470 | 470 | setattr_list(self,'verbose debug header split') |
|
471 | 471 | |
|
472 | 472 | def system(self,cmd): |
|
473 | 473 | """Stateful interface to system(), with the same keyword parameters.""" |
|
474 | 474 | |
|
475 | 475 | system(cmd,self.verbose,self.debug,self.header) |
|
476 | 476 | |
|
477 | 477 | def shell(self,cmd): |
|
478 | 478 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
479 | 479 | |
|
480 | 480 | shell(cmd,self.verbose,self.debug,self.header) |
|
481 | 481 | |
|
482 | 482 | xsys = system # alias |
|
483 | 483 | |
|
484 | 484 | def getoutput(self,cmd): |
|
485 | 485 | """Stateful interface to getoutput().""" |
|
486 | 486 | |
|
487 | 487 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
488 | 488 | |
|
489 | 489 | def getoutputerror(self,cmd): |
|
490 | 490 | """Stateful interface to getoutputerror().""" |
|
491 | 491 | |
|
492 | 492 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
493 | 493 | |
|
494 | 494 | bq = getoutput # alias |
|
495 | 495 | |
|
496 | 496 | #----------------------------------------------------------------------------- |
|
497 | 497 | def mutex_opts(dict,ex_op): |
|
498 | 498 | """Check for presence of mutually exclusive keys in a dict. |
|
499 | 499 | |
|
500 | 500 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
501 | 501 | for op1,op2 in ex_op: |
|
502 | 502 | if op1 in dict and op2 in dict: |
|
503 | 503 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
504 | 504 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
505 | 505 | |
|
506 | 506 | #----------------------------------------------------------------------------- |
|
507 | 507 | def get_py_filename(name): |
|
508 | 508 | """Return a valid python filename in the current directory. |
|
509 | 509 | |
|
510 | 510 | If the given name is not a file, it adds '.py' and searches again. |
|
511 | 511 | Raises IOError with an informative message if the file isn't found.""" |
|
512 | 512 | |
|
513 | 513 | name = os.path.expanduser(name) |
|
514 | 514 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
515 | 515 | name += '.py' |
|
516 | 516 | if os.path.isfile(name): |
|
517 | 517 | return name |
|
518 | 518 | else: |
|
519 | 519 | raise IOError,'File `%s` not found.' % name |
|
520 | 520 | |
|
521 | 521 | #----------------------------------------------------------------------------- |
|
522 | 522 | |
|
523 | 523 | |
|
524 | 524 | def filefind(filename, path_dirs=None): |
|
525 | 525 | """Find a file by looking through a sequence of paths. |
|
526 | 526 | |
|
527 | 527 | This iterates through a sequence of paths looking for a file and returns |
|
528 | 528 | the full, absolute path of the first occurence of the file. If no set of |
|
529 | 529 | path dirs is given, the filename is tested as is, after running through |
|
530 | 530 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
531 | 531 | |
|
532 | 532 | filefind('myfile.txt') |
|
533 | 533 | |
|
534 | 534 | will find the file in the current working dir, but:: |
|
535 | 535 | |
|
536 | 536 | filefind('~/myfile.txt') |
|
537 | 537 | |
|
538 | 538 | Will find the file in the users home directory. This function does not |
|
539 | 539 | automatically try any paths, such as the cwd or the user's home directory. |
|
540 | 540 | |
|
541 | 541 | Parameters |
|
542 | 542 | ---------- |
|
543 | 543 | filename : str |
|
544 | 544 | The filename to look for. |
|
545 | 545 | path_dirs : str, None or sequence of str |
|
546 | 546 | The sequence of paths to look for the file in. If None, the filename |
|
547 | 547 | need to be absolute or be in the cwd. If a string, the string is |
|
548 | 548 | put into a sequence and the searched. If a sequence, walk through |
|
549 | 549 | each element and join with ``filename``, calling :func:`expandvars` |
|
550 | 550 | and :func:`expanduser` before testing for existence. |
|
551 | 551 | |
|
552 | 552 | Returns |
|
553 | 553 | ------- |
|
554 | 554 | Raises :exc:`IOError` or returns absolute path to file. |
|
555 | 555 | """ |
|
556 | 556 | if path_dirs is None: |
|
557 | 557 | path_dirs = ("",) |
|
558 | 558 | elif isinstance(path_dirs, basestring): |
|
559 | 559 | path_dirs = (path_dirs,) |
|
560 | 560 | for path in path_dirs: |
|
561 | 561 | if path == '.': path = os.getcwd() |
|
562 | 562 | testname = os.path.expandvars( |
|
563 | 563 | os.path.expanduser( |
|
564 | 564 | os.path.join(path, filename))) |
|
565 | 565 | if os.path.isfile(testname): |
|
566 | 566 | return os.path.abspath(testname) |
|
567 | 567 | raise IOError("File does not exist in any " |
|
568 | 568 | "of the search paths: %r, %r" % \ |
|
569 | 569 | (filename, path_dirs)) |
|
570 | 570 | |
|
571 | 571 | |
|
572 | 572 | #---------------------------------------------------------------------------- |
|
573 | 573 | def file_read(filename): |
|
574 | 574 | """Read a file and close it. Returns the file source.""" |
|
575 | 575 | fobj = open(filename,'r'); |
|
576 | 576 | source = fobj.read(); |
|
577 | 577 | fobj.close() |
|
578 | 578 | return source |
|
579 | 579 | |
|
580 | 580 | def file_readlines(filename): |
|
581 | 581 | """Read a file and close it. Returns the file source using readlines().""" |
|
582 | 582 | fobj = open(filename,'r'); |
|
583 | 583 | lines = fobj.readlines(); |
|
584 | 584 | fobj.close() |
|
585 | 585 | return lines |
|
586 | 586 | |
|
587 | 587 | #---------------------------------------------------------------------------- |
|
588 | 588 | def target_outdated(target,deps): |
|
589 | 589 | """Determine whether a target is out of date. |
|
590 | 590 | |
|
591 | 591 | target_outdated(target,deps) -> 1/0 |
|
592 | 592 | |
|
593 | 593 | deps: list of filenames which MUST exist. |
|
594 | 594 | target: single filename which may or may not exist. |
|
595 | 595 | |
|
596 | 596 | If target doesn't exist or is older than any file listed in deps, return |
|
597 | 597 | true, otherwise return false. |
|
598 | 598 | """ |
|
599 | 599 | try: |
|
600 | 600 | target_time = os.path.getmtime(target) |
|
601 | 601 | except os.error: |
|
602 | 602 | return 1 |
|
603 | 603 | for dep in deps: |
|
604 | 604 | dep_time = os.path.getmtime(dep) |
|
605 | 605 | if dep_time > target_time: |
|
606 | 606 | #print "For target",target,"Dep failed:",dep # dbg |
|
607 | 607 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
608 | 608 | return 1 |
|
609 | 609 | return 0 |
|
610 | 610 | |
|
611 | 611 | #----------------------------------------------------------------------------- |
|
612 | 612 | def target_update(target,deps,cmd): |
|
613 | 613 | """Update a target with a given command given a list of dependencies. |
|
614 | 614 | |
|
615 | 615 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
616 | 616 | |
|
617 | 617 | This is just a wrapper around target_outdated() which calls the given |
|
618 | 618 | command if target is outdated.""" |
|
619 | 619 | |
|
620 | 620 | if target_outdated(target,deps): |
|
621 | 621 | xsys(cmd) |
|
622 | 622 | |
|
623 | 623 | #---------------------------------------------------------------------------- |
|
624 | 624 | def unquote_ends(istr): |
|
625 | 625 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
626 | 626 | |
|
627 | 627 | if not istr: |
|
628 | 628 | return istr |
|
629 | 629 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
630 | 630 | (istr[0]=='"' and istr[-1]=='"'): |
|
631 | 631 | return istr[1:-1] |
|
632 | 632 | else: |
|
633 | 633 | return istr |
|
634 | 634 | |
|
635 | 635 | #---------------------------------------------------------------------------- |
|
636 | 636 | def flag_calls(func): |
|
637 | 637 | """Wrap a function to detect and flag when it gets called. |
|
638 | 638 | |
|
639 | 639 | This is a decorator which takes a function and wraps it in a function with |
|
640 | 640 | a 'called' attribute. wrapper.called is initialized to False. |
|
641 | 641 | |
|
642 | 642 | The wrapper.called attribute is set to False right before each call to the |
|
643 | 643 | wrapped function, so if the call fails it remains False. After the call |
|
644 | 644 | completes, wrapper.called is set to True and the output is returned. |
|
645 | 645 | |
|
646 | 646 | Testing for truth in wrapper.called allows you to determine if a call to |
|
647 | 647 | func() was attempted and succeeded.""" |
|
648 | 648 | |
|
649 | 649 | def wrapper(*args,**kw): |
|
650 | 650 | wrapper.called = False |
|
651 | 651 | out = func(*args,**kw) |
|
652 | 652 | wrapper.called = True |
|
653 | 653 | return out |
|
654 | 654 | |
|
655 | 655 | wrapper.called = False |
|
656 | 656 | wrapper.__doc__ = func.__doc__ |
|
657 | 657 | return wrapper |
|
658 | 658 | |
|
659 | 659 | #---------------------------------------------------------------------------- |
|
660 | 660 | def dhook_wrap(func,*a,**k): |
|
661 | 661 | """Wrap a function call in a sys.displayhook controller. |
|
662 | 662 | |
|
663 | 663 | Returns a wrapper around func which calls func, with all its arguments and |
|
664 | 664 | keywords unmodified, using the default sys.displayhook. Since IPython |
|
665 | 665 | modifies sys.displayhook, it breaks the behavior of certain systems that |
|
666 | 666 | rely on the default behavior, notably doctest. |
|
667 | 667 | """ |
|
668 | 668 | |
|
669 | 669 | def f(*a,**k): |
|
670 | 670 | |
|
671 | 671 | dhook_s = sys.displayhook |
|
672 | 672 | sys.displayhook = sys.__displayhook__ |
|
673 | 673 | try: |
|
674 | 674 | out = func(*a,**k) |
|
675 | 675 | finally: |
|
676 | 676 | sys.displayhook = dhook_s |
|
677 | 677 | |
|
678 | 678 | return out |
|
679 | 679 | |
|
680 | 680 | f.__doc__ = func.__doc__ |
|
681 | 681 | return f |
|
682 | 682 | |
|
683 | 683 | #---------------------------------------------------------------------------- |
|
684 | 684 | def doctest_reload(): |
|
685 | 685 | """Properly reload doctest to reuse it interactively. |
|
686 | 686 | |
|
687 | 687 | This routine: |
|
688 | 688 | |
|
689 | 689 | - imports doctest but does NOT reload it (see below). |
|
690 | 690 | |
|
691 | 691 | - resets its global 'master' attribute to None, so that multiple uses of |
|
692 | 692 | the module interactively don't produce cumulative reports. |
|
693 | 693 | |
|
694 | 694 | - Monkeypatches its core test runner method to protect it from IPython's |
|
695 | 695 | modified displayhook. Doctest expects the default displayhook behavior |
|
696 | 696 | deep down, so our modification breaks it completely. For this reason, a |
|
697 | 697 | hard monkeypatch seems like a reasonable solution rather than asking |
|
698 | 698 | users to manually use a different doctest runner when under IPython. |
|
699 | 699 | |
|
700 | 700 | Notes |
|
701 | 701 | ----- |
|
702 | 702 | |
|
703 | 703 | This function *used to* reload doctest, but this has been disabled because |
|
704 | 704 | reloading doctest unconditionally can cause massive breakage of other |
|
705 | 705 | doctest-dependent modules already in memory, such as those for IPython's |
|
706 | 706 | own testing system. The name wasn't changed to avoid breaking people's |
|
707 | 707 | code, but the reload call isn't actually made anymore.""" |
|
708 | 708 | |
|
709 | 709 | import doctest |
|
710 | 710 | doctest.master = None |
|
711 | 711 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) |
|
712 | 712 | |
|
713 | 713 | #---------------------------------------------------------------------------- |
|
714 | 714 | class HomeDirError(Error): |
|
715 | 715 | pass |
|
716 | 716 | |
|
717 | 717 | def get_home_dir(): |
|
718 | 718 | """Return the closest possible equivalent to a 'home' directory. |
|
719 | 719 | |
|
720 | 720 | * On POSIX, we try $HOME. |
|
721 | 721 | * On Windows we try: |
|
722 | 722 | - %HOMESHARE% |
|
723 | 723 | - %HOMEDRIVE\%HOMEPATH% |
|
724 | 724 | - %USERPROFILE% |
|
725 | 725 | - Registry hack |
|
726 | 726 | * On Dos C:\ |
|
727 | 727 | |
|
728 | 728 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
729 | 729 | raised for all other OSes. |
|
730 | 730 | """ |
|
731 | 731 | |
|
732 | 732 | isdir = os.path.isdir |
|
733 | 733 | env = os.environ |
|
734 | 734 | |
|
735 | 735 | # first, check py2exe distribution root directory for _ipython. |
|
736 | 736 | # This overrides all. Normally does not exist. |
|
737 | 737 | |
|
738 | 738 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
739 | 739 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
740 | 740 | root, rest = IPython.__file__.lower().split('library.zip') |
|
741 | 741 | else: |
|
742 | 742 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
743 | 743 | root=os.path.abspath(root).rstrip('\\') |
|
744 | 744 | if isdir(os.path.join(root, '_ipython')): |
|
745 | 745 | os.environ["IPYKITROOT"] = root |
|
746 | 746 | return root.decode(sys.getfilesystemencoding()) |
|
747 | 747 | |
|
748 | 748 | if os.name == 'posix': |
|
749 | 749 | # Linux, Unix, AIX, OS X |
|
750 | 750 | try: |
|
751 | 751 | homedir = env['HOME'] |
|
752 | 752 | except KeyError: |
|
753 | 753 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') |
|
754 | 754 | else: |
|
755 | 755 | return homedir.decode(sys.getfilesystemencoding()) |
|
756 | 756 | elif os.name == 'nt': |
|
757 | 757 | # Now for win9x, XP, Vista, 7? |
|
758 | 758 | # For some strange reason all of these return 'nt' for os.name. |
|
759 | 759 | # First look for a network home directory. This will return the UNC |
|
760 | 760 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This |
|
761 | 761 | # is needed when running IPython on cluster where all paths have to |
|
762 | 762 | # be UNC. |
|
763 | 763 | try: |
|
764 | 764 | homedir = env['HOMESHARE'] |
|
765 | 765 | except KeyError: |
|
766 | 766 | pass |
|
767 | 767 | else: |
|
768 | 768 | if isdir(homedir): |
|
769 | 769 | return homedir.decode(sys.getfilesystemencoding()) |
|
770 | 770 | |
|
771 | 771 | # Now look for a local home directory |
|
772 | 772 | try: |
|
773 | 773 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
774 | 774 | except KeyError: |
|
775 | 775 | pass |
|
776 | 776 | else: |
|
777 | 777 | if isdir(homedir): |
|
778 | 778 | return homedir.decode(sys.getfilesystemencoding()) |
|
779 | 779 | |
|
780 | 780 | # Now the users profile directory |
|
781 | 781 | try: |
|
782 | 782 | homedir = os.path.join(env['USERPROFILE']) |
|
783 | 783 | except KeyError: |
|
784 | 784 | pass |
|
785 | 785 | else: |
|
786 | 786 | if isdir(homedir): |
|
787 | 787 | return homedir.decode(sys.getfilesystemencoding()) |
|
788 | 788 | |
|
789 | 789 | # Use the registry to get the 'My Documents' folder. |
|
790 | 790 | try: |
|
791 | 791 | import _winreg as wreg |
|
792 | 792 | key = wreg.OpenKey( |
|
793 | 793 | wreg.HKEY_CURRENT_USER, |
|
794 | 794 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
795 | 795 | ) |
|
796 | 796 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
797 | 797 | key.Close() |
|
798 | 798 | except: |
|
799 | 799 | pass |
|
800 | 800 | else: |
|
801 | 801 | if isdir(homedir): |
|
802 | 802 | return homedir.decode(sys.getfilesystemencoding()) |
|
803 | 803 | |
|
804 | 804 | # If all else fails, raise HomeDirError |
|
805 | 805 | raise HomeDirError('No valid home directory could be found') |
|
806 | 806 | elif os.name == 'dos': |
|
807 | 807 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
808 | 808 | return 'C:\\'.decode(sys.getfilesystemencoding()) |
|
809 | 809 | else: |
|
810 | 810 | raise HomeDirError('No valid home directory could be found for your OS') |
|
811 | 811 | |
|
812 | 812 | |
|
813 | 813 | def get_ipython_dir(): |
|
814 | 814 | """Get the IPython directory for this platform and user. |
|
815 | 815 | |
|
816 | 816 | This uses the logic in `get_home_dir` to find the home directory |
|
817 | 817 | and the adds .ipython to the end of the path. |
|
818 | 818 | """ |
|
819 | 819 | ipdir_def = '.ipython' |
|
820 | 820 | home_dir = get_home_dir() |
|
821 |
ipdir = os. |
|
|
822 | os.path.join(home_dir, ipdir_def))) | |
|
821 | ipdir = os.environ.get( | |
|
822 | 'IPYTHON_DIR', os.environ.get( | |
|
823 | 'IPYTHONDIR', os.path.join(home_dir, ipdir_def) | |
|
824 | ) | |
|
825 | ) | |
|
823 | 826 | return ipdir.decode(sys.getfilesystemencoding()) |
|
824 | 827 | |
|
825 | 828 | |
|
826 | 829 | #**************************************************************************** |
|
827 | 830 | # strings and text |
|
828 | 831 | |
|
829 | 832 | class LSString(str): |
|
830 | 833 | """String derivative with a special access attributes. |
|
831 | 834 | |
|
832 | 835 | These are normal strings, but with the special attributes: |
|
833 | 836 | |
|
834 | 837 | .l (or .list) : value as list (split on newlines). |
|
835 | 838 | .n (or .nlstr): original value (the string itself). |
|
836 | 839 | .s (or .spstr): value as whitespace-separated string. |
|
837 | 840 | .p (or .paths): list of path objects |
|
838 | 841 | |
|
839 | 842 | Any values which require transformations are computed only once and |
|
840 | 843 | cached. |
|
841 | 844 | |
|
842 | 845 | Such strings are very useful to efficiently interact with the shell, which |
|
843 | 846 | typically only understands whitespace-separated options for commands.""" |
|
844 | 847 | |
|
845 | 848 | def get_list(self): |
|
846 | 849 | try: |
|
847 | 850 | return self.__list |
|
848 | 851 | except AttributeError: |
|
849 | 852 | self.__list = self.split('\n') |
|
850 | 853 | return self.__list |
|
851 | 854 | |
|
852 | 855 | l = list = property(get_list) |
|
853 | 856 | |
|
854 | 857 | def get_spstr(self): |
|
855 | 858 | try: |
|
856 | 859 | return self.__spstr |
|
857 | 860 | except AttributeError: |
|
858 | 861 | self.__spstr = self.replace('\n',' ') |
|
859 | 862 | return self.__spstr |
|
860 | 863 | |
|
861 | 864 | s = spstr = property(get_spstr) |
|
862 | 865 | |
|
863 | 866 | def get_nlstr(self): |
|
864 | 867 | return self |
|
865 | 868 | |
|
866 | 869 | n = nlstr = property(get_nlstr) |
|
867 | 870 | |
|
868 | 871 | def get_paths(self): |
|
869 | 872 | try: |
|
870 | 873 | return self.__paths |
|
871 | 874 | except AttributeError: |
|
872 | 875 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
873 | 876 | return self.__paths |
|
874 | 877 | |
|
875 | 878 | p = paths = property(get_paths) |
|
876 | 879 | |
|
877 | 880 | def print_lsstring(arg): |
|
878 | 881 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
879 | 882 | print "LSString (.p, .n, .l, .s available). Value:" |
|
880 | 883 | print arg |
|
881 | 884 | |
|
882 | 885 | print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
883 | 886 | |
|
884 | 887 | #---------------------------------------------------------------------------- |
|
885 | 888 | class SList(list): |
|
886 | 889 | """List derivative with a special access attributes. |
|
887 | 890 | |
|
888 | 891 | These are normal lists, but with the special attributes: |
|
889 | 892 | |
|
890 | 893 | .l (or .list) : value as list (the list itself). |
|
891 | 894 | .n (or .nlstr): value as a string, joined on newlines. |
|
892 | 895 | .s (or .spstr): value as a string, joined on spaces. |
|
893 | 896 | .p (or .paths): list of path objects |
|
894 | 897 | |
|
895 | 898 | Any values which require transformations are computed only once and |
|
896 | 899 | cached.""" |
|
897 | 900 | |
|
898 | 901 | def get_list(self): |
|
899 | 902 | return self |
|
900 | 903 | |
|
901 | 904 | l = list = property(get_list) |
|
902 | 905 | |
|
903 | 906 | def get_spstr(self): |
|
904 | 907 | try: |
|
905 | 908 | return self.__spstr |
|
906 | 909 | except AttributeError: |
|
907 | 910 | self.__spstr = ' '.join(self) |
|
908 | 911 | return self.__spstr |
|
909 | 912 | |
|
910 | 913 | s = spstr = property(get_spstr) |
|
911 | 914 | |
|
912 | 915 | def get_nlstr(self): |
|
913 | 916 | try: |
|
914 | 917 | return self.__nlstr |
|
915 | 918 | except AttributeError: |
|
916 | 919 | self.__nlstr = '\n'.join(self) |
|
917 | 920 | return self.__nlstr |
|
918 | 921 | |
|
919 | 922 | n = nlstr = property(get_nlstr) |
|
920 | 923 | |
|
921 | 924 | def get_paths(self): |
|
922 | 925 | try: |
|
923 | 926 | return self.__paths |
|
924 | 927 | except AttributeError: |
|
925 | 928 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
926 | 929 | return self.__paths |
|
927 | 930 | |
|
928 | 931 | p = paths = property(get_paths) |
|
929 | 932 | |
|
930 | 933 | def grep(self, pattern, prune = False, field = None): |
|
931 | 934 | """ Return all strings matching 'pattern' (a regex or callable) |
|
932 | 935 | |
|
933 | 936 | This is case-insensitive. If prune is true, return all items |
|
934 | 937 | NOT matching the pattern. |
|
935 | 938 | |
|
936 | 939 | If field is specified, the match must occur in the specified |
|
937 | 940 | whitespace-separated field. |
|
938 | 941 | |
|
939 | 942 | Examples:: |
|
940 | 943 | |
|
941 | 944 | a.grep( lambda x: x.startswith('C') ) |
|
942 | 945 | a.grep('Cha.*log', prune=1) |
|
943 | 946 | a.grep('chm', field=-1) |
|
944 | 947 | """ |
|
945 | 948 | |
|
946 | 949 | def match_target(s): |
|
947 | 950 | if field is None: |
|
948 | 951 | return s |
|
949 | 952 | parts = s.split() |
|
950 | 953 | try: |
|
951 | 954 | tgt = parts[field] |
|
952 | 955 | return tgt |
|
953 | 956 | except IndexError: |
|
954 | 957 | return "" |
|
955 | 958 | |
|
956 | 959 | if isinstance(pattern, basestring): |
|
957 | 960 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
958 | 961 | else: |
|
959 | 962 | pred = pattern |
|
960 | 963 | if not prune: |
|
961 | 964 | return SList([el for el in self if pred(match_target(el))]) |
|
962 | 965 | else: |
|
963 | 966 | return SList([el for el in self if not pred(match_target(el))]) |
|
964 | 967 | def fields(self, *fields): |
|
965 | 968 | """ Collect whitespace-separated fields from string list |
|
966 | 969 | |
|
967 | 970 | Allows quick awk-like usage of string lists. |
|
968 | 971 | |
|
969 | 972 | Example data (in var a, created by 'a = !ls -l'):: |
|
970 | 973 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
971 | 974 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
972 | 975 | |
|
973 | 976 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
974 | 977 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
975 | 978 | (note the joining by space). |
|
976 | 979 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
977 | 980 | |
|
978 | 981 | IndexErrors are ignored. |
|
979 | 982 | |
|
980 | 983 | Without args, fields() just split()'s the strings. |
|
981 | 984 | """ |
|
982 | 985 | if len(fields) == 0: |
|
983 | 986 | return [el.split() for el in self] |
|
984 | 987 | |
|
985 | 988 | res = SList() |
|
986 | 989 | for el in [f.split() for f in self]: |
|
987 | 990 | lineparts = [] |
|
988 | 991 | |
|
989 | 992 | for fd in fields: |
|
990 | 993 | try: |
|
991 | 994 | lineparts.append(el[fd]) |
|
992 | 995 | except IndexError: |
|
993 | 996 | pass |
|
994 | 997 | if lineparts: |
|
995 | 998 | res.append(" ".join(lineparts)) |
|
996 | 999 | |
|
997 | 1000 | return res |
|
998 | 1001 | def sort(self,field= None, nums = False): |
|
999 | 1002 | """ sort by specified fields (see fields()) |
|
1000 | 1003 | |
|
1001 | 1004 | Example:: |
|
1002 | 1005 | a.sort(1, nums = True) |
|
1003 | 1006 | |
|
1004 | 1007 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
1005 | 1008 | |
|
1006 | 1009 | """ |
|
1007 | 1010 | |
|
1008 | 1011 | #decorate, sort, undecorate |
|
1009 | 1012 | if field is not None: |
|
1010 | 1013 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
1011 | 1014 | else: |
|
1012 | 1015 | dsu = [[line, line] for line in self] |
|
1013 | 1016 | if nums: |
|
1014 | 1017 | for i in range(len(dsu)): |
|
1015 | 1018 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
1016 | 1019 | try: |
|
1017 | 1020 | n = int(numstr) |
|
1018 | 1021 | except ValueError: |
|
1019 | 1022 | n = 0; |
|
1020 | 1023 | dsu[i][0] = n |
|
1021 | 1024 | |
|
1022 | 1025 | |
|
1023 | 1026 | dsu.sort() |
|
1024 | 1027 | return SList([t[1] for t in dsu]) |
|
1025 | 1028 | |
|
1026 | 1029 | def print_slist(arg): |
|
1027 | 1030 | """ Prettier (non-repr-like) and more informative printer for SList """ |
|
1028 | 1031 | print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
1029 | 1032 | if hasattr(arg, 'hideonce') and arg.hideonce: |
|
1030 | 1033 | arg.hideonce = False |
|
1031 | 1034 | return |
|
1032 | 1035 | |
|
1033 | 1036 | nlprint(arg) |
|
1034 | 1037 | |
|
1035 | 1038 | print_slist = result_display.when_type(SList)(print_slist) |
|
1036 | 1039 | |
|
1037 | 1040 | |
|
1038 | 1041 | |
|
1039 | 1042 | #---------------------------------------------------------------------------- |
|
1040 | 1043 | def esc_quotes(strng): |
|
1041 | 1044 | """Return the input string with single and double quotes escaped out""" |
|
1042 | 1045 | |
|
1043 | 1046 | return strng.replace('"','\\"').replace("'","\\'") |
|
1044 | 1047 | |
|
1045 | 1048 | #---------------------------------------------------------------------------- |
|
1046 | 1049 | def make_quoted_expr(s): |
|
1047 | 1050 | """Return string s in appropriate quotes, using raw string if possible. |
|
1048 | 1051 | |
|
1049 | 1052 | XXX - example removed because it caused encoding errors in documentation |
|
1050 | 1053 | generation. We need a new example that doesn't contain invalid chars. |
|
1051 | 1054 | |
|
1052 | 1055 | Note the use of raw string and padding at the end to allow trailing |
|
1053 | 1056 | backslash. |
|
1054 | 1057 | """ |
|
1055 | 1058 | |
|
1056 | 1059 | tail = '' |
|
1057 | 1060 | tailpadding = '' |
|
1058 | 1061 | raw = '' |
|
1059 | 1062 | if "\\" in s: |
|
1060 | 1063 | raw = 'r' |
|
1061 | 1064 | if s.endswith('\\'): |
|
1062 | 1065 | tail = '[:-1]' |
|
1063 | 1066 | tailpadding = '_' |
|
1064 | 1067 | if '"' not in s: |
|
1065 | 1068 | quote = '"' |
|
1066 | 1069 | elif "'" not in s: |
|
1067 | 1070 | quote = "'" |
|
1068 | 1071 | elif '"""' not in s and not s.endswith('"'): |
|
1069 | 1072 | quote = '"""' |
|
1070 | 1073 | elif "'''" not in s and not s.endswith("'"): |
|
1071 | 1074 | quote = "'''" |
|
1072 | 1075 | else: |
|
1073 | 1076 | # give up, backslash-escaped string will do |
|
1074 | 1077 | return '"%s"' % esc_quotes(s) |
|
1075 | 1078 | res = raw + quote + s + tailpadding + quote + tail |
|
1076 | 1079 | return res |
|
1077 | 1080 | |
|
1078 | 1081 | |
|
1079 | 1082 | #---------------------------------------------------------------------------- |
|
1080 | 1083 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
1081 | 1084 | """Take multiple lines of input. |
|
1082 | 1085 | |
|
1083 | 1086 | A list with each line of input as a separate element is returned when a |
|
1084 | 1087 | termination string is entered (defaults to a single '.'). Input can also |
|
1085 | 1088 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
1086 | 1089 | |
|
1087 | 1090 | Lines of input which end in \\ are joined into single entries (and a |
|
1088 | 1091 | secondary continuation prompt is issued as long as the user terminates |
|
1089 | 1092 | lines with \\). This allows entering very long strings which are still |
|
1090 | 1093 | meant to be treated as single entities. |
|
1091 | 1094 | """ |
|
1092 | 1095 | |
|
1093 | 1096 | try: |
|
1094 | 1097 | if header: |
|
1095 | 1098 | header += '\n' |
|
1096 | 1099 | lines = [raw_input(header + ps1)] |
|
1097 | 1100 | except EOFError: |
|
1098 | 1101 | return [] |
|
1099 | 1102 | terminate = [terminate_str] |
|
1100 | 1103 | try: |
|
1101 | 1104 | while lines[-1:] != terminate: |
|
1102 | 1105 | new_line = raw_input(ps1) |
|
1103 | 1106 | while new_line.endswith('\\'): |
|
1104 | 1107 | new_line = new_line[:-1] + raw_input(ps2) |
|
1105 | 1108 | lines.append(new_line) |
|
1106 | 1109 | |
|
1107 | 1110 | return lines[:-1] # don't return the termination command |
|
1108 | 1111 | except EOFError: |
|
1109 | 1112 | |
|
1110 | 1113 | return lines |
|
1111 | 1114 | |
|
1112 | 1115 | #---------------------------------------------------------------------------- |
|
1113 | 1116 | def raw_input_ext(prompt='', ps2='... '): |
|
1114 | 1117 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
1115 | 1118 | |
|
1116 | 1119 | line = raw_input(prompt) |
|
1117 | 1120 | while line.endswith('\\'): |
|
1118 | 1121 | line = line[:-1] + raw_input(ps2) |
|
1119 | 1122 | return line |
|
1120 | 1123 | |
|
1121 | 1124 | #---------------------------------------------------------------------------- |
|
1122 | 1125 | def ask_yes_no(prompt,default=None): |
|
1123 | 1126 | """Asks a question and returns a boolean (y/n) answer. |
|
1124 | 1127 | |
|
1125 | 1128 | If default is given (one of 'y','n'), it is used if the user input is |
|
1126 | 1129 | empty. Otherwise the question is repeated until an answer is given. |
|
1127 | 1130 | |
|
1128 | 1131 | An EOF is treated as the default answer. If there is no default, an |
|
1129 | 1132 | exception is raised to prevent infinite loops. |
|
1130 | 1133 | |
|
1131 | 1134 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1132 | 1135 | |
|
1133 | 1136 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1134 | 1137 | ans = None |
|
1135 | 1138 | while ans not in answers.keys(): |
|
1136 | 1139 | try: |
|
1137 | 1140 | ans = raw_input(prompt+' ').lower() |
|
1138 | 1141 | if not ans: # response was an empty string |
|
1139 | 1142 | ans = default |
|
1140 | 1143 | except KeyboardInterrupt: |
|
1141 | 1144 | pass |
|
1142 | 1145 | except EOFError: |
|
1143 | 1146 | if default in answers.keys(): |
|
1144 | 1147 | ans = default |
|
1145 | 1148 | |
|
1146 | 1149 | else: |
|
1147 | 1150 | raise |
|
1148 | 1151 | |
|
1149 | 1152 | return answers[ans] |
|
1150 | 1153 | |
|
1151 | 1154 | #---------------------------------------------------------------------------- |
|
1152 | 1155 | class EvalDict: |
|
1153 | 1156 | """ |
|
1154 | 1157 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1155 | 1158 | |
|
1156 | 1159 | Usage: |
|
1157 | 1160 | >>> number = 19 |
|
1158 | 1161 | |
|
1159 | 1162 | >>> text = "python" |
|
1160 | 1163 | |
|
1161 | 1164 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1162 | 1165 | Python 2.1 rules! |
|
1163 | 1166 | """ |
|
1164 | 1167 | |
|
1165 | 1168 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1166 | 1169 | # modified (shorter) version of: |
|
1167 | 1170 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1168 | 1171 | # Skip Montanaro (skip@pobox.com). |
|
1169 | 1172 | |
|
1170 | 1173 | def __getitem__(self, name): |
|
1171 | 1174 | frame = sys._getframe(1) |
|
1172 | 1175 | return eval(name, frame.f_globals, frame.f_locals) |
|
1173 | 1176 | |
|
1174 | 1177 | EvalString = EvalDict # for backwards compatibility |
|
1175 | 1178 | #---------------------------------------------------------------------------- |
|
1176 | 1179 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1177 | 1180 | """Similar to Perl's qw() operator, but with some more options. |
|
1178 | 1181 | |
|
1179 | 1182 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1180 | 1183 | |
|
1181 | 1184 | words can also be a list itself, and with flat=1, the output will be |
|
1182 | 1185 | recursively flattened. |
|
1183 | 1186 | |
|
1184 | 1187 | Examples: |
|
1185 | 1188 | |
|
1186 | 1189 | >>> qw('1 2') |
|
1187 | 1190 | ['1', '2'] |
|
1188 | 1191 | |
|
1189 | 1192 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1190 | 1193 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1191 | 1194 | |
|
1192 | 1195 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1193 | 1196 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] |
|
1194 | 1197 | """ |
|
1195 | 1198 | |
|
1196 | 1199 | if type(words) in StringTypes: |
|
1197 | 1200 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1198 | 1201 | if word and not word.isspace() ] |
|
1199 | 1202 | if flat: |
|
1200 | 1203 | return flatten(map(qw,words,[1]*len(words))) |
|
1201 | 1204 | return map(qw,words) |
|
1202 | 1205 | |
|
1203 | 1206 | #---------------------------------------------------------------------------- |
|
1204 | 1207 | def qwflat(words,sep=None,maxsplit=-1): |
|
1205 | 1208 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1206 | 1209 | return qw(words,1,sep,maxsplit) |
|
1207 | 1210 | |
|
1208 | 1211 | #---------------------------------------------------------------------------- |
|
1209 | 1212 | def qw_lol(indata): |
|
1210 | 1213 | """qw_lol('a b') -> [['a','b']], |
|
1211 | 1214 | otherwise it's just a call to qw(). |
|
1212 | 1215 | |
|
1213 | 1216 | We need this to make sure the modules_some keys *always* end up as a |
|
1214 | 1217 | list of lists.""" |
|
1215 | 1218 | |
|
1216 | 1219 | if type(indata) in StringTypes: |
|
1217 | 1220 | return [qw(indata)] |
|
1218 | 1221 | else: |
|
1219 | 1222 | return qw(indata) |
|
1220 | 1223 | |
|
1221 | 1224 | #---------------------------------------------------------------------------- |
|
1222 | 1225 | def grep(pat,list,case=1): |
|
1223 | 1226 | """Simple minded grep-like function. |
|
1224 | 1227 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1225 | 1228 | |
|
1226 | 1229 | It only does simple string matching, with no support for regexps. Use the |
|
1227 | 1230 | option case=0 for case-insensitive matching.""" |
|
1228 | 1231 | |
|
1229 | 1232 | # This is pretty crude. At least it should implement copying only references |
|
1230 | 1233 | # to the original data in case it's big. Now it copies the data for output. |
|
1231 | 1234 | out=[] |
|
1232 | 1235 | if case: |
|
1233 | 1236 | for term in list: |
|
1234 | 1237 | if term.find(pat)>-1: out.append(term) |
|
1235 | 1238 | else: |
|
1236 | 1239 | lpat=pat.lower() |
|
1237 | 1240 | for term in list: |
|
1238 | 1241 | if term.lower().find(lpat)>-1: out.append(term) |
|
1239 | 1242 | |
|
1240 | 1243 | if len(out): return out |
|
1241 | 1244 | else: return None |
|
1242 | 1245 | |
|
1243 | 1246 | #---------------------------------------------------------------------------- |
|
1244 | 1247 | def dgrep(pat,*opts): |
|
1245 | 1248 | """Return grep() on dir()+dir(__builtins__). |
|
1246 | 1249 | |
|
1247 | 1250 | A very common use of grep() when working interactively.""" |
|
1248 | 1251 | |
|
1249 | 1252 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1250 | 1253 | |
|
1251 | 1254 | #---------------------------------------------------------------------------- |
|
1252 | 1255 | def idgrep(pat): |
|
1253 | 1256 | """Case-insensitive dgrep()""" |
|
1254 | 1257 | |
|
1255 | 1258 | return dgrep(pat,0) |
|
1256 | 1259 | |
|
1257 | 1260 | #---------------------------------------------------------------------------- |
|
1258 | 1261 | def igrep(pat,list): |
|
1259 | 1262 | """Synonym for case-insensitive grep.""" |
|
1260 | 1263 | |
|
1261 | 1264 | return grep(pat,list,case=0) |
|
1262 | 1265 | |
|
1263 | 1266 | #---------------------------------------------------------------------------- |
|
1264 | 1267 | def indent(str,nspaces=4,ntabs=0): |
|
1265 | 1268 | """Indent a string a given number of spaces or tabstops. |
|
1266 | 1269 | |
|
1267 | 1270 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1268 | 1271 | """ |
|
1269 | 1272 | if str is None: |
|
1270 | 1273 | return |
|
1271 | 1274 | ind = '\t'*ntabs+' '*nspaces |
|
1272 | 1275 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1273 | 1276 | if outstr.endswith(os.linesep+ind): |
|
1274 | 1277 | return outstr[:-len(ind)] |
|
1275 | 1278 | else: |
|
1276 | 1279 | return outstr |
|
1277 | 1280 | |
|
1278 | 1281 | #----------------------------------------------------------------------------- |
|
1279 | 1282 | def native_line_ends(filename,backup=1): |
|
1280 | 1283 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1281 | 1284 | |
|
1282 | 1285 | If the optional backup argument is given as false, no backup of the |
|
1283 | 1286 | original file is left. """ |
|
1284 | 1287 | |
|
1285 | 1288 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1286 | 1289 | |
|
1287 | 1290 | bak_filename = filename + backup_suffixes[os.name] |
|
1288 | 1291 | |
|
1289 | 1292 | original = open(filename).read() |
|
1290 | 1293 | shutil.copy2(filename,bak_filename) |
|
1291 | 1294 | try: |
|
1292 | 1295 | new = open(filename,'wb') |
|
1293 | 1296 | new.write(os.linesep.join(original.splitlines())) |
|
1294 | 1297 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1295 | 1298 | new.close() |
|
1296 | 1299 | except: |
|
1297 | 1300 | os.rename(bak_filename,filename) |
|
1298 | 1301 | if not backup: |
|
1299 | 1302 | try: |
|
1300 | 1303 | os.remove(bak_filename) |
|
1301 | 1304 | except: |
|
1302 | 1305 | pass |
|
1303 | 1306 | |
|
1304 | 1307 | #**************************************************************************** |
|
1305 | 1308 | # lists, dicts and structures |
|
1306 | 1309 | |
|
1307 | 1310 | def belong(candidates,checklist): |
|
1308 | 1311 | """Check whether a list of items appear in a given list of options. |
|
1309 | 1312 | |
|
1310 | 1313 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1311 | 1314 | |
|
1312 | 1315 | return [x in checklist for x in candidates] |
|
1313 | 1316 | |
|
1314 | 1317 | #---------------------------------------------------------------------------- |
|
1315 | 1318 | def uniq_stable(elems): |
|
1316 | 1319 | """uniq_stable(elems) -> list |
|
1317 | 1320 | |
|
1318 | 1321 | Return from an iterable, a list of all the unique elements in the input, |
|
1319 | 1322 | but maintaining the order in which they first appear. |
|
1320 | 1323 | |
|
1321 | 1324 | A naive solution to this problem which just makes a dictionary with the |
|
1322 | 1325 | elements as keys fails to respect the stability condition, since |
|
1323 | 1326 | dictionaries are unsorted by nature. |
|
1324 | 1327 | |
|
1325 | 1328 | Note: All elements in the input must be valid dictionary keys for this |
|
1326 | 1329 | routine to work, as it internally uses a dictionary for efficiency |
|
1327 | 1330 | reasons.""" |
|
1328 | 1331 | |
|
1329 | 1332 | unique = [] |
|
1330 | 1333 | unique_dict = {} |
|
1331 | 1334 | for nn in elems: |
|
1332 | 1335 | if nn not in unique_dict: |
|
1333 | 1336 | unique.append(nn) |
|
1334 | 1337 | unique_dict[nn] = None |
|
1335 | 1338 | return unique |
|
1336 | 1339 | |
|
1337 | 1340 | #---------------------------------------------------------------------------- |
|
1338 | 1341 | class NLprinter: |
|
1339 | 1342 | """Print an arbitrarily nested list, indicating index numbers. |
|
1340 | 1343 | |
|
1341 | 1344 | An instance of this class called nlprint is available and callable as a |
|
1342 | 1345 | function. |
|
1343 | 1346 | |
|
1344 | 1347 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1345 | 1348 | and using 'sep' to separate the index from the value. """ |
|
1346 | 1349 | |
|
1347 | 1350 | def __init__(self): |
|
1348 | 1351 | self.depth = 0 |
|
1349 | 1352 | |
|
1350 | 1353 | def __call__(self,lst,pos='',**kw): |
|
1351 | 1354 | """Prints the nested list numbering levels.""" |
|
1352 | 1355 | kw.setdefault('indent',' ') |
|
1353 | 1356 | kw.setdefault('sep',': ') |
|
1354 | 1357 | kw.setdefault('start',0) |
|
1355 | 1358 | kw.setdefault('stop',len(lst)) |
|
1356 | 1359 | # we need to remove start and stop from kw so they don't propagate |
|
1357 | 1360 | # into a recursive call for a nested list. |
|
1358 | 1361 | start = kw['start']; del kw['start'] |
|
1359 | 1362 | stop = kw['stop']; del kw['stop'] |
|
1360 | 1363 | if self.depth == 0 and 'header' in kw.keys(): |
|
1361 | 1364 | print kw['header'] |
|
1362 | 1365 | |
|
1363 | 1366 | for idx in range(start,stop): |
|
1364 | 1367 | elem = lst[idx] |
|
1365 | 1368 | if type(elem)==type([]): |
|
1366 | 1369 | self.depth += 1 |
|
1367 | 1370 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1368 | 1371 | self.depth -= 1 |
|
1369 | 1372 | else: |
|
1370 | 1373 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1371 | 1374 | |
|
1372 | 1375 | nlprint = NLprinter() |
|
1373 | 1376 | #---------------------------------------------------------------------------- |
|
1374 | 1377 | def all_belong(candidates,checklist): |
|
1375 | 1378 | """Check whether a list of items ALL appear in a given list of options. |
|
1376 | 1379 | |
|
1377 | 1380 | Returns a single 1 or 0 value.""" |
|
1378 | 1381 | |
|
1379 | 1382 | return 1-(0 in [x in checklist for x in candidates]) |
|
1380 | 1383 | |
|
1381 | 1384 | #---------------------------------------------------------------------------- |
|
1382 | 1385 | def sort_compare(lst1,lst2,inplace = 1): |
|
1383 | 1386 | """Sort and compare two lists. |
|
1384 | 1387 | |
|
1385 | 1388 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1386 | 1389 | to avoid that (at the cost of temporary copy creation).""" |
|
1387 | 1390 | if not inplace: |
|
1388 | 1391 | lst1 = lst1[:] |
|
1389 | 1392 | lst2 = lst2[:] |
|
1390 | 1393 | lst1.sort(); lst2.sort() |
|
1391 | 1394 | return lst1 == lst2 |
|
1392 | 1395 | |
|
1393 | 1396 | #---------------------------------------------------------------------------- |
|
1394 | 1397 | def list2dict(lst): |
|
1395 | 1398 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1396 | 1399 | |
|
1397 | 1400 | dic = {} |
|
1398 | 1401 | for k,v in lst: dic[k] = v |
|
1399 | 1402 | return dic |
|
1400 | 1403 | |
|
1401 | 1404 | #---------------------------------------------------------------------------- |
|
1402 | 1405 | def list2dict2(lst,default=''): |
|
1403 | 1406 | """Takes a list and turns it into a dict. |
|
1404 | 1407 | Much slower than list2dict, but more versatile. This version can take |
|
1405 | 1408 | lists with sublists of arbitrary length (including sclars).""" |
|
1406 | 1409 | |
|
1407 | 1410 | dic = {} |
|
1408 | 1411 | for elem in lst: |
|
1409 | 1412 | if type(elem) in (types.ListType,types.TupleType): |
|
1410 | 1413 | size = len(elem) |
|
1411 | 1414 | if size == 0: |
|
1412 | 1415 | pass |
|
1413 | 1416 | elif size == 1: |
|
1414 | 1417 | dic[elem] = default |
|
1415 | 1418 | else: |
|
1416 | 1419 | k,v = elem[0], elem[1:] |
|
1417 | 1420 | if len(v) == 1: v = v[0] |
|
1418 | 1421 | dic[k] = v |
|
1419 | 1422 | else: |
|
1420 | 1423 | dic[elem] = default |
|
1421 | 1424 | return dic |
|
1422 | 1425 | |
|
1423 | 1426 | #---------------------------------------------------------------------------- |
|
1424 | 1427 | def flatten(seq): |
|
1425 | 1428 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1426 | 1429 | |
|
1427 | 1430 | return [x for subseq in seq for x in subseq] |
|
1428 | 1431 | |
|
1429 | 1432 | #---------------------------------------------------------------------------- |
|
1430 | 1433 | def get_slice(seq,start=0,stop=None,step=1): |
|
1431 | 1434 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1432 | 1435 | if stop == None: |
|
1433 | 1436 | stop = len(seq) |
|
1434 | 1437 | item = lambda i: seq[i] |
|
1435 | 1438 | return map(item,xrange(start,stop,step)) |
|
1436 | 1439 | |
|
1437 | 1440 | #---------------------------------------------------------------------------- |
|
1438 | 1441 | def chop(seq,size): |
|
1439 | 1442 | """Chop a sequence into chunks of the given size.""" |
|
1440 | 1443 | chunk = lambda i: seq[i:i+size] |
|
1441 | 1444 | return map(chunk,xrange(0,len(seq),size)) |
|
1442 | 1445 | |
|
1443 | 1446 | #---------------------------------------------------------------------------- |
|
1444 | 1447 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1445 | 1448 | # from its old 'with' name. |
|
1446 | 1449 | def with_obj(object, **args): |
|
1447 | 1450 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1448 | 1451 | |
|
1449 | 1452 | Example: |
|
1450 | 1453 | with_obj(jim, |
|
1451 | 1454 | born = 1960, |
|
1452 | 1455 | haircolour = 'Brown', |
|
1453 | 1456 | eyecolour = 'Green') |
|
1454 | 1457 | |
|
1455 | 1458 | Credit: Greg Ewing, in |
|
1456 | 1459 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1457 | 1460 | |
|
1458 | 1461 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1459 | 1462 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1460 | 1463 | |
|
1461 | 1464 | object.__dict__.update(args) |
|
1462 | 1465 | |
|
1463 | 1466 | #---------------------------------------------------------------------------- |
|
1464 | 1467 | def setattr_list(obj,alist,nspace = None): |
|
1465 | 1468 | """Set a list of attributes for an object taken from a namespace. |
|
1466 | 1469 | |
|
1467 | 1470 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1468 | 1471 | alist with their values taken from nspace, which must be a dict (something |
|
1469 | 1472 | like locals() will often do) If nspace isn't given, locals() of the |
|
1470 | 1473 | *caller* is used, so in most cases you can omit it. |
|
1471 | 1474 | |
|
1472 | 1475 | Note that alist can be given as a string, which will be automatically |
|
1473 | 1476 | split into a list on whitespace. If given as a list, it must be a list of |
|
1474 | 1477 | *strings* (the variable names themselves), not of variables.""" |
|
1475 | 1478 | |
|
1476 | 1479 | # this grabs the local variables from the *previous* call frame -- that is |
|
1477 | 1480 | # the locals from the function that called setattr_list(). |
|
1478 | 1481 | # - snipped from weave.inline() |
|
1479 | 1482 | if nspace is None: |
|
1480 | 1483 | call_frame = sys._getframe().f_back |
|
1481 | 1484 | nspace = call_frame.f_locals |
|
1482 | 1485 | |
|
1483 | 1486 | if type(alist) in StringTypes: |
|
1484 | 1487 | alist = alist.split() |
|
1485 | 1488 | for attr in alist: |
|
1486 | 1489 | val = eval(attr,nspace) |
|
1487 | 1490 | setattr(obj,attr,val) |
|
1488 | 1491 | |
|
1489 | 1492 | #---------------------------------------------------------------------------- |
|
1490 | 1493 | def getattr_list(obj,alist,*args): |
|
1491 | 1494 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1492 | 1495 | |
|
1493 | 1496 | Get a list of named attributes for an object. When a default argument is |
|
1494 | 1497 | given, it is returned when the attribute doesn't exist; without it, an |
|
1495 | 1498 | exception is raised in that case. |
|
1496 | 1499 | |
|
1497 | 1500 | Note that alist can be given as a string, which will be automatically |
|
1498 | 1501 | split into a list on whitespace. If given as a list, it must be a list of |
|
1499 | 1502 | *strings* (the variable names themselves), not of variables.""" |
|
1500 | 1503 | |
|
1501 | 1504 | if type(alist) in StringTypes: |
|
1502 | 1505 | alist = alist.split() |
|
1503 | 1506 | if args: |
|
1504 | 1507 | if len(args)==1: |
|
1505 | 1508 | default = args[0] |
|
1506 | 1509 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1507 | 1510 | else: |
|
1508 | 1511 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1509 | 1512 | else: |
|
1510 | 1513 | return map(lambda attr: getattr(obj,attr),alist) |
|
1511 | 1514 | |
|
1512 | 1515 | #---------------------------------------------------------------------------- |
|
1513 | 1516 | def map_method(method,object_list,*argseq,**kw): |
|
1514 | 1517 | """map_method(method,object_list,*args,**kw) -> list |
|
1515 | 1518 | |
|
1516 | 1519 | Return a list of the results of applying the methods to the items of the |
|
1517 | 1520 | argument sequence(s). If more than one sequence is given, the method is |
|
1518 | 1521 | called with an argument list consisting of the corresponding item of each |
|
1519 | 1522 | sequence. All sequences must be of the same length. |
|
1520 | 1523 | |
|
1521 | 1524 | Keyword arguments are passed verbatim to all objects called. |
|
1522 | 1525 | |
|
1523 | 1526 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1524 | 1527 | |
|
1525 | 1528 | out_list = [] |
|
1526 | 1529 | idx = 0 |
|
1527 | 1530 | for object in object_list: |
|
1528 | 1531 | try: |
|
1529 | 1532 | handler = getattr(object, method) |
|
1530 | 1533 | except AttributeError: |
|
1531 | 1534 | out_list.append(None) |
|
1532 | 1535 | else: |
|
1533 | 1536 | if argseq: |
|
1534 | 1537 | args = map(lambda lst:lst[idx],argseq) |
|
1535 | 1538 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1536 | 1539 | out_list.append(handler(args,**kw)) |
|
1537 | 1540 | else: |
|
1538 | 1541 | out_list.append(handler(**kw)) |
|
1539 | 1542 | idx += 1 |
|
1540 | 1543 | return out_list |
|
1541 | 1544 | |
|
1542 | 1545 | #---------------------------------------------------------------------------- |
|
1543 | 1546 | def get_class_members(cls): |
|
1544 | 1547 | ret = dir(cls) |
|
1545 | 1548 | if hasattr(cls,'__bases__'): |
|
1546 | 1549 | for base in cls.__bases__: |
|
1547 | 1550 | ret.extend(get_class_members(base)) |
|
1548 | 1551 | return ret |
|
1549 | 1552 | |
|
1550 | 1553 | #---------------------------------------------------------------------------- |
|
1551 | 1554 | def dir2(obj): |
|
1552 | 1555 | """dir2(obj) -> list of strings |
|
1553 | 1556 | |
|
1554 | 1557 | Extended version of the Python builtin dir(), which does a few extra |
|
1555 | 1558 | checks, and supports common objects with unusual internals that confuse |
|
1556 | 1559 | dir(), such as Traits and PyCrust. |
|
1557 | 1560 | |
|
1558 | 1561 | This version is guaranteed to return only a list of true strings, whereas |
|
1559 | 1562 | dir() returns anything that objects inject into themselves, even if they |
|
1560 | 1563 | are later not really valid for attribute access (many extension libraries |
|
1561 | 1564 | have such bugs). |
|
1562 | 1565 | """ |
|
1563 | 1566 | |
|
1564 | 1567 | # Start building the attribute list via dir(), and then complete it |
|
1565 | 1568 | # with a few extra special-purpose calls. |
|
1566 | 1569 | words = dir(obj) |
|
1567 | 1570 | |
|
1568 | 1571 | if hasattr(obj,'__class__'): |
|
1569 | 1572 | words.append('__class__') |
|
1570 | 1573 | words.extend(get_class_members(obj.__class__)) |
|
1571 | 1574 | #if '__base__' in words: 1/0 |
|
1572 | 1575 | |
|
1573 | 1576 | # Some libraries (such as traits) may introduce duplicates, we want to |
|
1574 | 1577 | # track and clean this up if it happens |
|
1575 | 1578 | may_have_dupes = False |
|
1576 | 1579 | |
|
1577 | 1580 | # this is the 'dir' function for objects with Enthought's traits |
|
1578 | 1581 | if hasattr(obj, 'trait_names'): |
|
1579 | 1582 | try: |
|
1580 | 1583 | words.extend(obj.trait_names()) |
|
1581 | 1584 | may_have_dupes = True |
|
1582 | 1585 | except TypeError: |
|
1583 | 1586 | # This will happen if `obj` is a class and not an instance. |
|
1584 | 1587 | pass |
|
1585 | 1588 | |
|
1586 | 1589 | # Support for PyCrust-style _getAttributeNames magic method. |
|
1587 | 1590 | if hasattr(obj, '_getAttributeNames'): |
|
1588 | 1591 | try: |
|
1589 | 1592 | words.extend(obj._getAttributeNames()) |
|
1590 | 1593 | may_have_dupes = True |
|
1591 | 1594 | except TypeError: |
|
1592 | 1595 | # `obj` is a class and not an instance. Ignore |
|
1593 | 1596 | # this error. |
|
1594 | 1597 | pass |
|
1595 | 1598 | |
|
1596 | 1599 | if may_have_dupes: |
|
1597 | 1600 | # eliminate possible duplicates, as some traits may also |
|
1598 | 1601 | # appear as normal attributes in the dir() call. |
|
1599 | 1602 | words = list(set(words)) |
|
1600 | 1603 | words.sort() |
|
1601 | 1604 | |
|
1602 | 1605 | # filter out non-string attributes which may be stuffed by dir() calls |
|
1603 | 1606 | # and poor coding in third-party modules |
|
1604 | 1607 | return [w for w in words if isinstance(w, basestring)] |
|
1605 | 1608 | |
|
1606 | 1609 | #---------------------------------------------------------------------------- |
|
1607 | 1610 | def import_fail_info(mod_name,fns=None): |
|
1608 | 1611 | """Inform load failure for a module.""" |
|
1609 | 1612 | |
|
1610 | 1613 | if fns == None: |
|
1611 | 1614 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
1612 | 1615 | else: |
|
1613 | 1616 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
1614 | 1617 | |
|
1615 | 1618 | #---------------------------------------------------------------------------- |
|
1616 | 1619 | # Proposed popitem() extension, written as a method |
|
1617 | 1620 | |
|
1618 | 1621 | |
|
1619 | 1622 | class NotGiven: pass |
|
1620 | 1623 | |
|
1621 | 1624 | def popkey(dct,key,default=NotGiven): |
|
1622 | 1625 | """Return dct[key] and delete dct[key]. |
|
1623 | 1626 | |
|
1624 | 1627 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1625 | 1628 | KeyError. """ |
|
1626 | 1629 | |
|
1627 | 1630 | try: |
|
1628 | 1631 | val = dct[key] |
|
1629 | 1632 | except KeyError: |
|
1630 | 1633 | if default is NotGiven: |
|
1631 | 1634 | raise |
|
1632 | 1635 | else: |
|
1633 | 1636 | return default |
|
1634 | 1637 | else: |
|
1635 | 1638 | del dct[key] |
|
1636 | 1639 | return val |
|
1637 | 1640 | |
|
1638 | 1641 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
1639 | 1642 | def newFunc(*args, **kwargs): |
|
1640 | 1643 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
1641 | 1644 | ( func.__name__, suggest), |
|
1642 | 1645 | category=DeprecationWarning, |
|
1643 | 1646 | stacklevel = 2) |
|
1644 | 1647 | return func(*args, **kwargs) |
|
1645 | 1648 | return newFunc |
|
1646 | 1649 | |
|
1647 | 1650 | |
|
1648 | 1651 | def _num_cpus_unix(): |
|
1649 | 1652 | """Return the number of active CPUs on a Unix system.""" |
|
1650 | 1653 | return os.sysconf("SC_NPROCESSORS_ONLN") |
|
1651 | 1654 | |
|
1652 | 1655 | |
|
1653 | 1656 | def _num_cpus_darwin(): |
|
1654 | 1657 | """Return the number of active CPUs on a Darwin system.""" |
|
1655 | 1658 | p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) |
|
1656 | 1659 | return p.stdout.read() |
|
1657 | 1660 | |
|
1658 | 1661 | |
|
1659 | 1662 | def _num_cpus_windows(): |
|
1660 | 1663 | """Return the number of active CPUs on a Windows system.""" |
|
1661 | 1664 | return os.environ.get("NUMBER_OF_PROCESSORS") |
|
1662 | 1665 | |
|
1663 | 1666 | |
|
1664 | 1667 | def num_cpus(): |
|
1665 | 1668 | """Return the effective number of CPUs in the system as an integer. |
|
1666 | 1669 | |
|
1667 | 1670 | This cross-platform function makes an attempt at finding the total number of |
|
1668 | 1671 | available CPUs in the system, as returned by various underlying system and |
|
1669 | 1672 | python calls. |
|
1670 | 1673 | |
|
1671 | 1674 | If it can't find a sensible answer, it returns 1 (though an error *may* make |
|
1672 | 1675 | it return a large positive number that's actually incorrect). |
|
1673 | 1676 | """ |
|
1674 | 1677 | |
|
1675 | 1678 | # Many thanks to the Parallel Python project (http://www.parallelpython.com) |
|
1676 | 1679 | # for the names of the keys we needed to look up for this function. This |
|
1677 | 1680 | # code was inspired by their equivalent function. |
|
1678 | 1681 | |
|
1679 | 1682 | ncpufuncs = {'Linux':_num_cpus_unix, |
|
1680 | 1683 | 'Darwin':_num_cpus_darwin, |
|
1681 | 1684 | 'Windows':_num_cpus_windows, |
|
1682 | 1685 | # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' |
|
1683 | 1686 | # See http://bugs.python.org/issue1082 for details. |
|
1684 | 1687 | 'Microsoft':_num_cpus_windows, |
|
1685 | 1688 | } |
|
1686 | 1689 | |
|
1687 | 1690 | ncpufunc = ncpufuncs.get(platform.system(), |
|
1688 | 1691 | # default to unix version (Solaris, AIX, etc) |
|
1689 | 1692 | _num_cpus_unix) |
|
1690 | 1693 | |
|
1691 | 1694 | try: |
|
1692 | 1695 | ncpus = max(1,int(ncpufunc())) |
|
1693 | 1696 | except: |
|
1694 | 1697 | ncpus = 1 |
|
1695 | 1698 | return ncpus |
|
1696 | 1699 | |
|
1697 | 1700 | def extract_vars(*names,**kw): |
|
1698 | 1701 | """Extract a set of variables by name from another frame. |
|
1699 | 1702 | |
|
1700 | 1703 | :Parameters: |
|
1701 | 1704 | - `*names`: strings |
|
1702 | 1705 | One or more variable names which will be extracted from the caller's |
|
1703 | 1706 | frame. |
|
1704 | 1707 | |
|
1705 | 1708 | :Keywords: |
|
1706 | 1709 | - `depth`: integer (0) |
|
1707 | 1710 | How many frames in the stack to walk when looking for your variables. |
|
1708 | 1711 | |
|
1709 | 1712 | |
|
1710 | 1713 | Examples: |
|
1711 | 1714 | |
|
1712 | 1715 | In [2]: def func(x): |
|
1713 | 1716 | ...: y = 1 |
|
1714 | 1717 | ...: print extract_vars('x','y') |
|
1715 | 1718 | ...: |
|
1716 | 1719 | |
|
1717 | 1720 | In [3]: func('hello') |
|
1718 | 1721 | {'y': 1, 'x': 'hello'} |
|
1719 | 1722 | """ |
|
1720 | 1723 | |
|
1721 | 1724 | depth = kw.get('depth',0) |
|
1722 | 1725 | |
|
1723 | 1726 | callerNS = sys._getframe(depth+1).f_locals |
|
1724 | 1727 | return dict((k,callerNS[k]) for k in names) |
|
1725 | 1728 | |
|
1726 | 1729 | |
|
1727 | 1730 | def extract_vars_above(*names): |
|
1728 | 1731 | """Extract a set of variables by name from another frame. |
|
1729 | 1732 | |
|
1730 | 1733 | Similar to extractVars(), but with a specified depth of 1, so that names |
|
1731 | 1734 | are exctracted exactly from above the caller. |
|
1732 | 1735 | |
|
1733 | 1736 | This is simply a convenience function so that the very common case (for us) |
|
1734 | 1737 | of skipping exactly 1 frame doesn't have to construct a special dict for |
|
1735 | 1738 | keyword passing.""" |
|
1736 | 1739 | |
|
1737 | 1740 | callerNS = sys._getframe(2).f_locals |
|
1738 | 1741 | return dict((k,callerNS[k]) for k in names) |
|
1739 | 1742 | |
|
1740 | 1743 | def shexp(s): |
|
1741 | 1744 | """Expand $VARS and ~names in a string, like a shell |
|
1742 | 1745 | |
|
1743 | 1746 | :Examples: |
|
1744 | 1747 | |
|
1745 | 1748 | In [2]: os.environ['FOO']='test' |
|
1746 | 1749 | |
|
1747 | 1750 | In [3]: shexp('variable FOO is $FOO') |
|
1748 | 1751 | Out[3]: 'variable FOO is test' |
|
1749 | 1752 | """ |
|
1750 | 1753 | return os.path.expandvars(os.path.expanduser(s)) |
|
1751 | 1754 | |
|
1752 | 1755 | |
|
1753 | 1756 | def list_strings(arg): |
|
1754 | 1757 | """Always return a list of strings, given a string or list of strings |
|
1755 | 1758 | as input. |
|
1756 | 1759 | |
|
1757 | 1760 | :Examples: |
|
1758 | 1761 | |
|
1759 | 1762 | In [7]: list_strings('A single string') |
|
1760 | 1763 | Out[7]: ['A single string'] |
|
1761 | 1764 | |
|
1762 | 1765 | In [8]: list_strings(['A single string in a list']) |
|
1763 | 1766 | Out[8]: ['A single string in a list'] |
|
1764 | 1767 | |
|
1765 | 1768 | In [9]: list_strings(['A','list','of','strings']) |
|
1766 | 1769 | Out[9]: ['A', 'list', 'of', 'strings'] |
|
1767 | 1770 | """ |
|
1768 | 1771 | |
|
1769 | 1772 | if isinstance(arg,basestring): return [arg] |
|
1770 | 1773 | else: return arg |
|
1771 | 1774 | |
|
1772 | 1775 | |
|
1773 | 1776 | #---------------------------------------------------------------------------- |
|
1774 | 1777 | def marquee(txt='',width=78,mark='*'): |
|
1775 | 1778 | """Return the input string centered in a 'marquee'. |
|
1776 | 1779 | |
|
1777 | 1780 | :Examples: |
|
1778 | 1781 | |
|
1779 | 1782 | In [16]: marquee('A test',40) |
|
1780 | 1783 | Out[16]: '**************** A test ****************' |
|
1781 | 1784 | |
|
1782 | 1785 | In [17]: marquee('A test',40,'-') |
|
1783 | 1786 | Out[17]: '---------------- A test ----------------' |
|
1784 | 1787 | |
|
1785 | 1788 | In [18]: marquee('A test',40,' ') |
|
1786 | 1789 | Out[18]: ' A test ' |
|
1787 | 1790 | |
|
1788 | 1791 | """ |
|
1789 | 1792 | if not txt: |
|
1790 | 1793 | return (mark*width)[:width] |
|
1791 | 1794 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1792 | 1795 | if nmark < 0: nmark =0 |
|
1793 | 1796 | marks = mark*nmark |
|
1794 | 1797 | return '%s %s %s' % (marks,txt,marks) |
|
1795 | 1798 | |
|
1796 | 1799 | #*************************** end of file <genutils.py> ********************** |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now