Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,65 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |
|
3 | """ | |
|
4 | The main IPython application object | |
|
5 | ||
|
6 | Authors: | |
|
7 | ||
|
8 | * Brian Granger | |
|
9 | * Fernando Perez | |
|
10 | ||
|
11 | Notes | |
|
12 | ----- | |
|
13 | """ | |
|
14 | ||
|
15 | #----------------------------------------------------------------------------- | |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
|
17 | # | |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
|
19 | # the file COPYING, distributed as part of this software. | |
|
20 | #----------------------------------------------------------------------------- | |
|
21 | ||
|
22 | #----------------------------------------------------------------------------- | |
|
23 | # Imports | |
|
24 | #----------------------------------------------------------------------------- | |
|
25 | ||
|
26 | from IPython.core.application import Application | |
|
27 | from IPython.core import release | |
|
28 | from IPython.core.iplib import InteractiveShell | |
|
29 | from IPython.config.loader import IPythonArgParseConfigLoader | |
|
30 | ||
|
31 | ipython_desc = """ | |
|
32 | A Python shell with automatic history (input and output), dynamic object | |
|
33 | introspection, easier configuration, command completion, access to the system | |
|
34 | shell and more. | |
|
35 | """ | |
|
36 | ||
|
37 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): | |
|
38 | arguments = ( | |
|
39 | () | |
|
40 | ) | |
|
41 | ||
|
42 | class IPythonApp(Application): | |
|
43 | name = 'ipython' | |
|
44 | config_file_name = 'ipython_config.py' | |
|
45 | ||
|
46 | def create_command_line_config(self): | |
|
47 | """Create and return a command line config loader.""" | |
|
48 | return IPythonAppCLConfigLoader( | |
|
49 | description=ipython_desc, | |
|
50 | version=release.version) | |
|
51 | ||
|
52 | def construct(self): | |
|
53 | self.shell = InteractiveShell( | |
|
54 | name='__IP', | |
|
55 | parent=None, | |
|
56 | config=self.master_config | |
|
57 | ) | |
|
58 | ||
|
59 | def start_app(self): | |
|
60 | self.shell.mainloop() | |
|
61 | ||
|
62 | ||
|
63 | if __name__ == '__main__': | |
|
64 | app = IPythonApp() | |
|
65 | app.start() No newline at end of file |
@@ -0,0 +1,219 b'' | |||
|
1 | # -*- coding: utf-8 -*- | |
|
2 | """ | |
|
3 | Main IPython Component | |
|
4 | """ | |
|
5 | ||
|
6 | #----------------------------------------------------------------------------- | |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
|
10 | # | |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
|
12 | # the file COPYING, distributed as part of this software. | |
|
13 | #----------------------------------------------------------------------------- | |
|
14 | ||
|
15 | #----------------------------------------------------------------------------- | |
|
16 | # Imports | |
|
17 | #----------------------------------------------------------------------------- | |
|
18 | ||
|
19 | import glob | |
|
20 | import os | |
|
21 | import shutil | |
|
22 | import sys | |
|
23 | ||
|
24 | from IPython.utils.genutils import * | |
|
25 | ||
|
26 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): | |
|
27 | """Install or upgrade the user configuration directory. | |
|
28 | ||
|
29 | Can be called when running for the first time or to upgrade the user's | |
|
30 | .ipython/ directory. | |
|
31 | ||
|
32 | Parameters | |
|
33 | ---------- | |
|
34 | ipythondir : path | |
|
35 | The directory to be used for installation/upgrade. In 'install' mode, | |
|
36 | if this path already exists, the function exits immediately. | |
|
37 | ||
|
38 | rc_suffix : str | |
|
39 | Extension for the config files. On *nix platforms it is typically the | |
|
40 | empty string, while Windows normally uses '.ini'. | |
|
41 | ||
|
42 | mode : str, optional | |
|
43 | Valid modes are 'install' and 'upgrade'. | |
|
44 | ||
|
45 | interactive : bool, optional | |
|
46 | If False, do not wait for user input on any errors. Normally after | |
|
47 | printing its status information, this function waits for the user to | |
|
48 | hit Return before proceeding. This is because the default use case is | |
|
49 | when first installing the IPython configuration, so we want the user to | |
|
50 | acknowledge the initial message, which contains some useful | |
|
51 | information. | |
|
52 | """ | |
|
53 | ||
|
54 | # For automatic use, deactivate all i/o | |
|
55 | if interactive: | |
|
56 | def wait(): | |
|
57 | try: | |
|
58 | raw_input("Please press <RETURN> to start IPython.") | |
|
59 | except EOFError: | |
|
60 | print >> Term.cout | |
|
61 | print '*'*70 | |
|
62 | ||
|
63 | def printf(s): | |
|
64 | print s | |
|
65 | else: | |
|
66 | wait = lambda : None | |
|
67 | printf = lambda s : None | |
|
68 | ||
|
69 | # Install mode should be re-entrant: if the install dir already exists, | |
|
70 | # bail out cleanly. | |
|
71 | # XXX. This is too hasty to return. We need to check to make sure that | |
|
72 | # all the expected config files and directories are actually there. We | |
|
73 | # currently have a failure mode if someone deletes a needed config file | |
|
74 | # but still has the ipythondir. | |
|
75 | if mode == 'install' and os.path.isdir(ipythondir): | |
|
76 | return | |
|
77 | ||
|
78 | cwd = os.getcwd() # remember where we started | |
|
79 | glb = glob.glob | |
|
80 | ||
|
81 | printf('*'*70) | |
|
82 | if mode == 'install': | |
|
83 | printf( | |
|
84 | """Welcome to IPython. I will try to create a personal configuration directory | |
|
85 | where you can customize many aspects of IPython's functionality in:\n""") | |
|
86 | else: | |
|
87 | printf('I am going to upgrade your configuration in:') | |
|
88 | ||
|
89 | printf(ipythondir) | |
|
90 | ||
|
91 | rcdirend = os.path.join('IPython','config','userconfig') | |
|
92 | cfg = lambda d: os.path.join(d,rcdirend) | |
|
93 | try: | |
|
94 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
|
95 | printf("Initializing from configuration: %s" % rcdir) | |
|
96 | except IndexError: | |
|
97 | warning = """ | |
|
98 | Installation error. IPython's directory was not found. | |
|
99 | ||
|
100 | Check the following: | |
|
101 | ||
|
102 | The ipython/IPython directory should be in a directory belonging to your | |
|
103 | PYTHONPATH environment variable (that is, it should be in a directory | |
|
104 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
|
105 | ||
|
106 | IPython will create a minimal default configuration for you. | |
|
107 | ||
|
108 | """ | |
|
109 | warn(warning) | |
|
110 | wait() | |
|
111 | ||
|
112 | if sys.platform =='win32': | |
|
113 | inif = 'ipythonrc.ini' | |
|
114 | else: | |
|
115 | inif = 'ipythonrc' | |
|
116 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
|
117 | inif : '# intentionally left blank' } | |
|
118 | os.makedirs(ipythondir, mode = 0777) | |
|
119 | for f, cont in minimal_setup.items(): | |
|
120 | # In 2.5, this can be more cleanly done using 'with' | |
|
121 | fobj = file(ipythondir + '/' + f,'w') | |
|
122 | fobj.write(cont) | |
|
123 | fobj.close() | |
|
124 | ||
|
125 | return | |
|
126 | ||
|
127 | if mode == 'install': | |
|
128 | try: | |
|
129 | shutil.copytree(rcdir,ipythondir) | |
|
130 | os.chdir(ipythondir) | |
|
131 | rc_files = glb("ipythonrc*") | |
|
132 | for rc_file in rc_files: | |
|
133 | os.rename(rc_file,rc_file+rc_suffix) | |
|
134 | except: | |
|
135 | warning = """ | |
|
136 | ||
|
137 | There was a problem with the installation: | |
|
138 | %s | |
|
139 | Try to correct it or contact the developers if you think it's a bug. | |
|
140 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
|
141 | warn(warning) | |
|
142 | wait() | |
|
143 | return | |
|
144 | ||
|
145 | elif mode == 'upgrade': | |
|
146 | try: | |
|
147 | os.chdir(ipythondir) | |
|
148 | except: | |
|
149 | printf(""" | |
|
150 | Can not upgrade: changing to directory %s failed. Details: | |
|
151 | %s | |
|
152 | """ % (ipythondir,sys.exc_info()[1]) ) | |
|
153 | wait() | |
|
154 | return | |
|
155 | else: | |
|
156 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
|
157 | for new_full_path in sources: | |
|
158 | new_filename = os.path.basename(new_full_path) | |
|
159 | if new_filename.startswith('ipythonrc'): | |
|
160 | new_filename = new_filename + rc_suffix | |
|
161 | # The config directory should only contain files, skip any | |
|
162 | # directories which may be there (like CVS) | |
|
163 | if os.path.isdir(new_full_path): | |
|
164 | continue | |
|
165 | if os.path.exists(new_filename): | |
|
166 | old_file = new_filename+'.old' | |
|
167 | if os.path.exists(old_file): | |
|
168 | os.remove(old_file) | |
|
169 | os.rename(new_filename,old_file) | |
|
170 | shutil.copy(new_full_path,new_filename) | |
|
171 | else: | |
|
172 | raise ValueError('unrecognized mode for install: %r' % mode) | |
|
173 | ||
|
174 | # Fix line-endings to those native to each platform in the config | |
|
175 | # directory. | |
|
176 | try: | |
|
177 | os.chdir(ipythondir) | |
|
178 | except: | |
|
179 | printf(""" | |
|
180 | Problem: changing to directory %s failed. | |
|
181 | Details: | |
|
182 | %s | |
|
183 | ||
|
184 | Some configuration files may have incorrect line endings. This should not | |
|
185 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) | |
|
186 | wait() | |
|
187 | else: | |
|
188 | for fname in glb('ipythonrc*'): | |
|
189 | try: | |
|
190 | native_line_ends(fname,backup=0) | |
|
191 | except IOError: | |
|
192 | pass | |
|
193 | ||
|
194 | if mode == 'install': | |
|
195 | printf(""" | |
|
196 | Successful installation! | |
|
197 | ||
|
198 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
|
199 | IPython manual (there are both HTML and PDF versions supplied with the | |
|
200 | distribution) to make sure that your system environment is properly configured | |
|
201 | to take advantage of IPython's features. | |
|
202 | ||
|
203 | Important note: the configuration system has changed! The old system is | |
|
204 | still in place, but its setting may be partly overridden by the settings in | |
|
205 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
|
206 | if some of the new settings bother you. | |
|
207 | ||
|
208 | """) | |
|
209 | else: | |
|
210 | printf(""" | |
|
211 | Successful upgrade! | |
|
212 | ||
|
213 | All files in your directory: | |
|
214 | %(ipythondir)s | |
|
215 | which would have been overwritten by the upgrade were backed up with a .old | |
|
216 | extension. If you had made particular customizations in those files you may | |
|
217 | want to merge them back into the new files.""" % locals() ) | |
|
218 | wait() | |
|
219 | os.chdir(cwd) No newline at end of file |
@@ -1,200 +1,200 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """A factory for creating configuration objects. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import os |
|
18 | 18 | import sys |
|
19 | 19 | |
|
20 | 20 | from IPython.external import argparse |
|
21 | 21 | from IPython.utils.ipstruct import Struct |
|
22 | 22 | from IPython.utils.genutils import filefind |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Code |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | |
|
29 | 29 | class ConfigLoaderError(Exception): |
|
30 | 30 | pass |
|
31 | 31 | |
|
32 | 32 | |
|
33 | 33 | class ConfigLoader(object): |
|
34 | 34 | """A object for loading configurations from just about anywhere. |
|
35 | 35 | |
|
36 | 36 | The resulting configuration is packaged as a :class:`Struct`. |
|
37 | 37 | |
|
38 | 38 | Notes |
|
39 | 39 | ----- |
|
40 | 40 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
41 | 41 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
42 | 42 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
43 | 43 | not implement complex logic for finding config files. It does not handle |
|
44 | 44 | default values or merge multiple configs. These things need to be |
|
45 | 45 | handled elsewhere. |
|
46 | 46 | """ |
|
47 | 47 | |
|
48 | 48 | def __init__(self): |
|
49 | 49 | """A base class for config loaders. |
|
50 | 50 | |
|
51 | 51 | Examples |
|
52 | 52 | -------- |
|
53 | 53 | |
|
54 | 54 | >>> cl = ConfigLoader() |
|
55 | 55 | >>> config = cl.load_config() |
|
56 | 56 | >>> config |
|
57 | 57 | {} |
|
58 | 58 | """ |
|
59 | 59 | self.clear() |
|
60 | 60 | |
|
61 | 61 | def clear(self): |
|
62 | 62 | self.config = Struct() |
|
63 | 63 | |
|
64 | 64 | def load_config(self): |
|
65 | 65 | """Load a config from somewhere, return a Struct. |
|
66 | 66 | |
|
67 | 67 | Usually, this will cause self.config to be set and then returned. |
|
68 | 68 | """ |
|
69 | 69 | return self.config |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class FileConfigLoader(ConfigLoader): |
|
73 | 73 | """A base class for file based configurations. |
|
74 | 74 | |
|
75 | 75 | As we add more file based config loaders, the common logic should go |
|
76 | 76 | here. |
|
77 | 77 | """ |
|
78 | 78 | pass |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | class PyFileConfigLoader(FileConfigLoader): |
|
82 | 82 | """A config loader for pure python files. |
|
83 | 83 | |
|
84 | 84 | This calls execfile on a plain python file and looks for attributes |
|
85 | 85 | that are all caps. These attribute are added to the config Struct. |
|
86 | 86 | """ |
|
87 | 87 | |
|
88 | 88 | def __init__(self, filename, path=None): |
|
89 | 89 | """Build a config loader for a filename and path. |
|
90 | 90 | |
|
91 | 91 | Parameters |
|
92 | 92 | ---------- |
|
93 | 93 | filename : str |
|
94 | 94 | The file name of the config file. |
|
95 | 95 | path : str, list, tuple |
|
96 | 96 | The path to search for the config file on, or a sequence of |
|
97 | 97 | paths to try in order. |
|
98 | 98 | """ |
|
99 | 99 | super(PyFileConfigLoader, self).__init__() |
|
100 | 100 | self.filename = filename |
|
101 | 101 | self.path = path |
|
102 | 102 | self.full_filename = '' |
|
103 | 103 | self.data = None |
|
104 | 104 | |
|
105 | 105 | def load_config(self): |
|
106 | 106 | """Load the config from a file and return it as a Struct.""" |
|
107 | 107 | self._find_file() |
|
108 | 108 | self._read_file_as_dict() |
|
109 | 109 | self._convert_to_struct() |
|
110 | 110 | return self.config |
|
111 | 111 | |
|
112 | 112 | def _find_file(self): |
|
113 | 113 | """Try to find the file by searching the paths.""" |
|
114 | 114 | self.full_filename = filefind(self.filename, self.path) |
|
115 | 115 | |
|
116 | 116 | def _read_file_as_dict(self): |
|
117 | 117 | self.data = {} |
|
118 | 118 | execfile(self.full_filename, self.data) |
|
119 | 119 | |
|
120 | 120 | def _convert_to_struct(self): |
|
121 | 121 | if self.data is None: |
|
122 | 122 | ConfigLoaderError('self.data does not exist') |
|
123 | 123 | for k, v in self.data.iteritems(): |
|
124 | 124 | if k == k.upper(): |
|
125 | 125 | self.config[k] = v |
|
126 | 126 | |
|
127 | 127 | |
|
128 | 128 | class CommandLineConfigLoader(ConfigLoader): |
|
129 | 129 | """A config loader for command line arguments. |
|
130 | 130 | |
|
131 | 131 | As we add more command line based loaders, the common logic should go |
|
132 | 132 | here. |
|
133 | 133 | """ |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | class NoDefault(object): pass |
|
137 | 137 | NoDefault = NoDefault() |
|
138 | 138 | |
|
139 | 139 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
140 | 140 | |
|
141 | 141 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] |
|
142 | 142 | arguments = () |
|
143 | 143 | |
|
144 | 144 | def __init__(self, *args, **kw): |
|
145 | 145 | """Create a config loader for use with argparse. |
|
146 | 146 | |
|
147 | 147 | The args and kwargs arguments here are passed onto the constructor |
|
148 | 148 | of :class:`argparse.ArgumentParser`. |
|
149 | 149 | """ |
|
150 | 150 | super(CommandLineConfigLoader, self).__init__() |
|
151 | 151 | self.args = args |
|
152 | 152 | self.kw = kw |
|
153 | 153 | |
|
154 | 154 | def load_config(self, args=None): |
|
155 | 155 | """Parse command line arguments and return as a Struct.""" |
|
156 | 156 | self._create_parser() |
|
157 | 157 | self._parse_args(args) |
|
158 | 158 | self._convert_to_struct() |
|
159 | 159 | return self.config |
|
160 | 160 | |
|
161 | 161 | def _create_parser(self): |
|
162 | 162 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) |
|
163 | 163 | self._add_arguments() |
|
164 | 164 | self._add_other_arguments() |
|
165 | 165 | |
|
166 | def _add_other_arguments(): | |
|
166 | def _add_other_arguments(self): | |
|
167 | 167 | pass |
|
168 | 168 | |
|
169 | 169 | def _add_arguments(self): |
|
170 | 170 | for argument in self.arguments: |
|
171 | 171 | if not argument[1].has_key('default'): |
|
172 | 172 | argument[1]['default'] = NoDefault |
|
173 | 173 | self.parser.add_argument(*argument[0],**argument[1]) |
|
174 | 174 | |
|
175 | 175 | def _parse_args(self, args=None): |
|
176 | 176 | """self.parser->self.parsed_data""" |
|
177 | 177 | if args is None: |
|
178 | 178 | self.parsed_data = self.parser.parse_args() |
|
179 | 179 | else: |
|
180 | 180 | self.parsed_data = self.parser.parse_args(args) |
|
181 | 181 | |
|
182 | 182 | def _convert_to_struct(self): |
|
183 | 183 | """self.parsed_data->self.config""" |
|
184 | 184 | self.config = Struct() |
|
185 | 185 | for k, v in vars(self.parsed_data).items(): |
|
186 | 186 | if v is not NoDefault: |
|
187 | 187 | setattr(self.config, k, v) |
|
188 | 188 | |
|
189 | 189 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): |
|
190 | 190 | |
|
191 | 191 | def _add_other_arguments(self): |
|
192 | 192 | self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str, |
|
193 | 193 | help='set to override default location of IPYTHONDIR', |
|
194 | 194 | default=NoDefault) |
|
195 | 195 | self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str, |
|
196 | 196 | help='the string name of the ipython profile to be used', |
|
197 | 197 | default=None) |
|
198 | 198 | self.parser.add_argument('--debug',dest="DEBUG",action='store_true', |
|
199 | 199 | help='debug the application startup process', |
|
200 | 200 | default=NoDefault) |
@@ -1,639 +1,639 b'' | |||
|
1 | 1 | """Word completion for IPython. |
|
2 | 2 | |
|
3 | 3 | This module is a fork of the rlcompleter module in the Python standard |
|
4 | 4 | library. The original enhancements made to rlcompleter have been sent |
|
5 | 5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
6 | 6 | functionality specific to IPython, so this module will continue to live as an |
|
7 | 7 | IPython-specific utility. |
|
8 | 8 | |
|
9 | 9 | Original rlcompleter documentation: |
|
10 | 10 | |
|
11 | 11 | This requires the latest extension to the readline module (the |
|
12 | 12 | completes keywords, built-ins and globals in __main__; when completing |
|
13 | 13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
14 | 14 | completes its attributes. |
|
15 | 15 | |
|
16 | 16 | It's very cool to do "import string" type "string.", hit the |
|
17 | 17 | completion key (twice), and see the list of names defined by the |
|
18 | 18 | string module! |
|
19 | 19 | |
|
20 | 20 | Tip: to use the tab key as the completion key, call |
|
21 | 21 | |
|
22 | 22 | readline.parse_and_bind("tab: complete") |
|
23 | 23 | |
|
24 | 24 | Notes: |
|
25 | 25 | |
|
26 | 26 | - Exceptions raised by the completer function are *ignored* (and |
|
27 | 27 | generally cause the completion to fail). This is a feature -- since |
|
28 | 28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
29 | 29 | traceback wouldn't work well without some complicated hoopla to save, |
|
30 | 30 | reset and restore the tty state. |
|
31 | 31 | |
|
32 | 32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
33 | 33 | application defined code to be executed if an object with a |
|
34 | 34 | __getattr__ hook is found. Since it is the responsibility of the |
|
35 | 35 | application (or the user) to enable this feature, I consider this an |
|
36 | 36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
37 | 37 | indexing operations) are *not* evaluated. |
|
38 | 38 | |
|
39 | 39 | - GNU readline is also used by the built-in functions input() and |
|
40 | 40 | raw_input(), and thus these also benefit/suffer from the completer |
|
41 | 41 | features. Clearly an interactive application can benefit by |
|
42 | 42 | specifying its own completer function and using raw_input() for all |
|
43 | 43 | its input. |
|
44 | 44 | |
|
45 | 45 | - When the original stdin is not a tty device, GNU readline is never |
|
46 | 46 | used, and this module (and the readline module) are silently inactive. |
|
47 | 47 | |
|
48 | 48 | """ |
|
49 | 49 | |
|
50 | 50 | #***************************************************************************** |
|
51 | 51 | # |
|
52 | 52 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
53 | 53 | # module which is part of the standard Python distribution, I assume that the |
|
54 | 54 | # proper procedure is to maintain its copyright as belonging to the Python |
|
55 | 55 | # Software Foundation (in addition to my own, for all new code). |
|
56 | 56 | # |
|
57 | 57 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | 58 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
59 | 59 | # |
|
60 | 60 | # Distributed under the terms of the BSD License. The full license is in |
|
61 | 61 | # the file COPYING, distributed as part of this software. |
|
62 | 62 | # |
|
63 | 63 | #***************************************************************************** |
|
64 | 64 | |
|
65 | 65 | import __builtin__ |
|
66 | 66 | import __main__ |
|
67 | 67 | import glob |
|
68 | 68 | import keyword |
|
69 | 69 | import os |
|
70 | 70 | import re |
|
71 | 71 | import shlex |
|
72 | 72 | import sys |
|
73 | 73 | import IPython.utils.rlineimpl as readline |
|
74 | 74 | import itertools |
|
75 | 75 | from IPython.utils.ipstruct import Struct |
|
76 | 76 | from IPython.core import ipapi |
|
77 | 77 | from IPython.utils import generics |
|
78 | 78 | import types |
|
79 | 79 | |
|
80 | 80 | # Python 2.4 offers sets as a builtin |
|
81 | 81 | try: |
|
82 | 82 | set() |
|
83 | 83 | except NameError: |
|
84 | 84 | from sets import Set as set |
|
85 | 85 | |
|
86 | 86 | from IPython.utils.genutils import debugx, dir2 |
|
87 | 87 | |
|
88 | 88 | __all__ = ['Completer','IPCompleter'] |
|
89 | 89 | |
|
90 | 90 | class Completer: |
|
91 | 91 | def __init__(self,namespace=None,global_namespace=None): |
|
92 | 92 | """Create a new completer for the command line. |
|
93 | 93 | |
|
94 | 94 | Completer([namespace,global_namespace]) -> completer instance. |
|
95 | 95 | |
|
96 | 96 | If unspecified, the default namespace where completions are performed |
|
97 | 97 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
98 | 98 | given as dictionaries. |
|
99 | 99 | |
|
100 | 100 | An optional second namespace can be given. This allows the completer |
|
101 | 101 | to handle cases where both the local and global scopes need to be |
|
102 | 102 | distinguished. |
|
103 | 103 | |
|
104 | 104 | Completer instances should be used as the completion mechanism of |
|
105 | 105 | readline via the set_completer() call: |
|
106 | 106 | |
|
107 | 107 | readline.set_completer(Completer(my_namespace).complete) |
|
108 | 108 | """ |
|
109 | 109 | |
|
110 | 110 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
111 | 111 | # specific namespace or to use __main__.__dict__. This will allow us |
|
112 | 112 | # to bind to __main__.__dict__ at completion time, not now. |
|
113 | 113 | if namespace is None: |
|
114 | 114 | self.use_main_ns = 1 |
|
115 | 115 | else: |
|
116 | 116 | self.use_main_ns = 0 |
|
117 | 117 | self.namespace = namespace |
|
118 | 118 | |
|
119 | 119 | # The global namespace, if given, can be bound directly |
|
120 | 120 | if global_namespace is None: |
|
121 | 121 | self.global_namespace = {} |
|
122 | 122 | else: |
|
123 | 123 | self.global_namespace = global_namespace |
|
124 | 124 | |
|
125 | 125 | def complete(self, text, state): |
|
126 | 126 | """Return the next possible completion for 'text'. |
|
127 | 127 | |
|
128 | 128 | This is called successively with state == 0, 1, 2, ... until it |
|
129 | 129 | returns None. The completion should begin with 'text'. |
|
130 | 130 | |
|
131 | 131 | """ |
|
132 | 132 | if self.use_main_ns: |
|
133 | 133 | self.namespace = __main__.__dict__ |
|
134 | 134 | |
|
135 | 135 | if state == 0: |
|
136 | 136 | if "." in text: |
|
137 | 137 | self.matches = self.attr_matches(text) |
|
138 | 138 | else: |
|
139 | 139 | self.matches = self.global_matches(text) |
|
140 | 140 | try: |
|
141 | 141 | return self.matches[state] |
|
142 | 142 | except IndexError: |
|
143 | 143 | return None |
|
144 | 144 | |
|
145 | 145 | def global_matches(self, text): |
|
146 | 146 | """Compute matches when text is a simple name. |
|
147 | 147 | |
|
148 | 148 | Return a list of all keywords, built-in functions and names currently |
|
149 | 149 | defined in self.namespace or self.global_namespace that match. |
|
150 | 150 | |
|
151 | 151 | """ |
|
152 | 152 | matches = [] |
|
153 | 153 | match_append = matches.append |
|
154 | 154 | n = len(text) |
|
155 | 155 | for lst in [keyword.kwlist, |
|
156 | 156 | __builtin__.__dict__.keys(), |
|
157 | 157 | self.namespace.keys(), |
|
158 | 158 | self.global_namespace.keys()]: |
|
159 | 159 | for word in lst: |
|
160 | 160 | if word[:n] == text and word != "__builtins__": |
|
161 | 161 | match_append(word) |
|
162 | 162 | return matches |
|
163 | 163 | |
|
164 | 164 | def attr_matches(self, text): |
|
165 | 165 | """Compute matches when text contains a dot. |
|
166 | 166 | |
|
167 | 167 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
168 | 168 | evaluatable in self.namespace or self.global_namespace, it will be |
|
169 | 169 | evaluated and its attributes (as revealed by dir()) are used as |
|
170 | 170 | possible completions. (For class instances, class members are are |
|
171 | 171 | also considered.) |
|
172 | 172 | |
|
173 | 173 | WARNING: this can still invoke arbitrary C code, if an object |
|
174 | 174 | with a __getattr__ hook is evaluated. |
|
175 | 175 | |
|
176 | 176 | """ |
|
177 | 177 | import re |
|
178 | 178 | |
|
179 | 179 | # Another option, seems to work great. Catches things like ''.<tab> |
|
180 | 180 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
181 | 181 | |
|
182 | 182 | if not m: |
|
183 | 183 | return [] |
|
184 | 184 | |
|
185 | 185 | expr, attr = m.group(1, 3) |
|
186 | 186 | try: |
|
187 | 187 | obj = eval(expr, self.namespace) |
|
188 | 188 | except: |
|
189 | 189 | try: |
|
190 | 190 | obj = eval(expr, self.global_namespace) |
|
191 | 191 | except: |
|
192 | 192 | return [] |
|
193 | 193 | |
|
194 | 194 | words = dir2(obj) |
|
195 | 195 | |
|
196 | 196 | try: |
|
197 | 197 | words = generics.complete_object(obj, words) |
|
198 | 198 | except ipapi.TryNext: |
|
199 | 199 | pass |
|
200 | 200 | # Build match list to return |
|
201 | 201 | n = len(attr) |
|
202 | 202 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
203 | 203 | return res |
|
204 | 204 | |
|
205 | 205 | class IPCompleter(Completer): |
|
206 | 206 | """Extension of the completer class with IPython-specific features""" |
|
207 | 207 | |
|
208 | 208 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
209 | 209 | omit__names=0,alias_table=None): |
|
210 | 210 | """IPCompleter() -> completer |
|
211 | 211 | |
|
212 | 212 | Return a completer object suitable for use by the readline library |
|
213 | 213 | via readline.set_completer(). |
|
214 | 214 | |
|
215 | 215 | Inputs: |
|
216 | 216 | |
|
217 | 217 | - shell: a pointer to the ipython shell itself. This is needed |
|
218 | 218 | because this completer knows about magic functions, and those can |
|
219 | 219 | only be accessed via the ipython instance. |
|
220 | 220 | |
|
221 | 221 | - namespace: an optional dict where completions are performed. |
|
222 | 222 | |
|
223 | 223 | - global_namespace: secondary optional dict for completions, to |
|
224 | 224 | handle cases (such as IPython embedded inside functions) where |
|
225 | 225 | both Python scopes are visible. |
|
226 | 226 | |
|
227 | 227 | - The optional omit__names parameter sets the completer to omit the |
|
228 | 228 | 'magic' names (__magicname__) for python objects unless the text |
|
229 | 229 | to be completed explicitly starts with one or more underscores. |
|
230 | 230 | |
|
231 | 231 | - If alias_table is supplied, it should be a dictionary of aliases |
|
232 | 232 | to complete. """ |
|
233 | 233 | |
|
234 | 234 | Completer.__init__(self,namespace,global_namespace) |
|
235 | 235 | self.magic_prefix = shell.name+'.magic_' |
|
236 | 236 | self.magic_escape = shell.ESC_MAGIC |
|
237 | 237 | self.readline = readline |
|
238 | 238 | delims = self.readline.get_completer_delims() |
|
239 | 239 | delims = delims.replace(self.magic_escape,'') |
|
240 | 240 | self.readline.set_completer_delims(delims) |
|
241 | 241 | self.get_line_buffer = self.readline.get_line_buffer |
|
242 | 242 | self.get_endidx = self.readline.get_endidx |
|
243 | 243 | self.omit__names = omit__names |
|
244 |
self.merge_completions = shell. |
|
|
244 | self.merge_completions = shell.readline_merge_completions | |
|
245 | 245 | if alias_table is None: |
|
246 | 246 | alias_table = {} |
|
247 | 247 | self.alias_table = alias_table |
|
248 | 248 | # Regexp to split filenames with spaces in them |
|
249 | 249 | self.space_name_re = re.compile(r'([^\\] )') |
|
250 | 250 | # Hold a local ref. to glob.glob for speed |
|
251 | 251 | self.glob = glob.glob |
|
252 | 252 | |
|
253 | 253 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
254 | 254 | # buffers, to avoid completion problems. |
|
255 | 255 | term = os.environ.get('TERM','xterm') |
|
256 | 256 | self.dumb_terminal = term in ['dumb','emacs'] |
|
257 | 257 | |
|
258 | 258 | # Special handling of backslashes needed in win32 platforms |
|
259 | 259 | if sys.platform == "win32": |
|
260 | 260 | self.clean_glob = self._clean_glob_win32 |
|
261 | 261 | else: |
|
262 | 262 | self.clean_glob = self._clean_glob |
|
263 | 263 | self.matchers = [self.python_matches, |
|
264 | 264 | self.file_matches, |
|
265 | 265 | self.alias_matches, |
|
266 | 266 | self.python_func_kw_matches] |
|
267 | 267 | |
|
268 | 268 | |
|
269 | 269 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
270 | 270 | def all_completions(self, text): |
|
271 | 271 | """Return all possible completions for the benefit of emacs.""" |
|
272 | 272 | |
|
273 | 273 | completions = [] |
|
274 | 274 | comp_append = completions.append |
|
275 | 275 | try: |
|
276 | 276 | for i in xrange(sys.maxint): |
|
277 | 277 | res = self.complete(text, i) |
|
278 | 278 | |
|
279 | 279 | if not res: break |
|
280 | 280 | |
|
281 | 281 | comp_append(res) |
|
282 | 282 | #XXX workaround for ``notDefined.<tab>`` |
|
283 | 283 | except NameError: |
|
284 | 284 | pass |
|
285 | 285 | return completions |
|
286 | 286 | # /end Alex Schmolck code. |
|
287 | 287 | |
|
288 | 288 | def _clean_glob(self,text): |
|
289 | 289 | return self.glob("%s*" % text) |
|
290 | 290 | |
|
291 | 291 | def _clean_glob_win32(self,text): |
|
292 | 292 | return [f.replace("\\","/") |
|
293 | 293 | for f in self.glob("%s*" % text)] |
|
294 | 294 | |
|
295 | 295 | def file_matches(self, text): |
|
296 | 296 | """Match filenames, expanding ~USER type strings. |
|
297 | 297 | |
|
298 | 298 | Most of the seemingly convoluted logic in this completer is an |
|
299 | 299 | attempt to handle filenames with spaces in them. And yet it's not |
|
300 | 300 | quite perfect, because Python's readline doesn't expose all of the |
|
301 | 301 | GNU readline details needed for this to be done correctly. |
|
302 | 302 | |
|
303 | 303 | For a filename with a space in it, the printed completions will be |
|
304 | 304 | only the parts after what's already been typed (instead of the |
|
305 | 305 | full completions, as is normally done). I don't think with the |
|
306 | 306 | current (as of Python 2.3) Python readline it's possible to do |
|
307 | 307 | better.""" |
|
308 | 308 | |
|
309 | 309 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
310 | 310 | |
|
311 | 311 | # chars that require escaping with backslash - i.e. chars |
|
312 | 312 | # that readline treats incorrectly as delimiters, but we |
|
313 | 313 | # don't want to treat as delimiters in filename matching |
|
314 | 314 | # when escaped with backslash |
|
315 | 315 | |
|
316 | 316 | if sys.platform == 'win32': |
|
317 | 317 | protectables = ' ' |
|
318 | 318 | else: |
|
319 | 319 | protectables = ' ()' |
|
320 | 320 | |
|
321 | 321 | if text.startswith('!'): |
|
322 | 322 | text = text[1:] |
|
323 | 323 | text_prefix = '!' |
|
324 | 324 | else: |
|
325 | 325 | text_prefix = '' |
|
326 | 326 | |
|
327 | 327 | def protect_filename(s): |
|
328 | 328 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
329 | 329 | for ch in s]) |
|
330 | 330 | |
|
331 | 331 | def single_dir_expand(matches): |
|
332 | 332 | "Recursively expand match lists containing a single dir." |
|
333 | 333 | |
|
334 | 334 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
335 | 335 | # Takes care of links to directories also. Use '/' |
|
336 | 336 | # explicitly, even under Windows, so that name completions |
|
337 | 337 | # don't end up escaped. |
|
338 | 338 | d = matches[0] |
|
339 | 339 | if d[-1] in ['/','\\']: |
|
340 | 340 | d = d[:-1] |
|
341 | 341 | |
|
342 | 342 | subdirs = os.listdir(d) |
|
343 | 343 | if subdirs: |
|
344 | 344 | matches = [ (d + '/' + p) for p in subdirs] |
|
345 | 345 | return single_dir_expand(matches) |
|
346 | 346 | else: |
|
347 | 347 | return matches |
|
348 | 348 | else: |
|
349 | 349 | return matches |
|
350 | 350 | |
|
351 | 351 | lbuf = self.lbuf |
|
352 | 352 | open_quotes = 0 # track strings with open quotes |
|
353 | 353 | try: |
|
354 | 354 | lsplit = shlex.split(lbuf)[-1] |
|
355 | 355 | except ValueError: |
|
356 | 356 | # typically an unmatched ", or backslash without escaped char. |
|
357 | 357 | if lbuf.count('"')==1: |
|
358 | 358 | open_quotes = 1 |
|
359 | 359 | lsplit = lbuf.split('"')[-1] |
|
360 | 360 | elif lbuf.count("'")==1: |
|
361 | 361 | open_quotes = 1 |
|
362 | 362 | lsplit = lbuf.split("'")[-1] |
|
363 | 363 | else: |
|
364 | 364 | return [] |
|
365 | 365 | except IndexError: |
|
366 | 366 | # tab pressed on empty line |
|
367 | 367 | lsplit = "" |
|
368 | 368 | |
|
369 | 369 | if lsplit != protect_filename(lsplit): |
|
370 | 370 | # if protectables are found, do matching on the whole escaped |
|
371 | 371 | # name |
|
372 | 372 | has_protectables = 1 |
|
373 | 373 | text0,text = text,lsplit |
|
374 | 374 | else: |
|
375 | 375 | has_protectables = 0 |
|
376 | 376 | text = os.path.expanduser(text) |
|
377 | 377 | |
|
378 | 378 | if text == "": |
|
379 | 379 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
380 | 380 | |
|
381 | 381 | m0 = self.clean_glob(text.replace('\\','')) |
|
382 | 382 | if has_protectables: |
|
383 | 383 | # If we had protectables, we need to revert our changes to the |
|
384 | 384 | # beginning of filename so that we don't double-write the part |
|
385 | 385 | # of the filename we have so far |
|
386 | 386 | len_lsplit = len(lsplit) |
|
387 | 387 | matches = [text_prefix + text0 + |
|
388 | 388 | protect_filename(f[len_lsplit:]) for f in m0] |
|
389 | 389 | else: |
|
390 | 390 | if open_quotes: |
|
391 | 391 | # if we have a string with an open quote, we don't need to |
|
392 | 392 | # protect the names at all (and we _shouldn't_, as it |
|
393 | 393 | # would cause bugs when the filesystem call is made). |
|
394 | 394 | matches = m0 |
|
395 | 395 | else: |
|
396 | 396 | matches = [text_prefix + |
|
397 | 397 | protect_filename(f) for f in m0] |
|
398 | 398 | |
|
399 | 399 | #print 'mm',matches # dbg |
|
400 | 400 | return single_dir_expand(matches) |
|
401 | 401 | |
|
402 | 402 | def alias_matches(self, text): |
|
403 | 403 | """Match internal system aliases""" |
|
404 | 404 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
405 | 405 | |
|
406 | 406 | # if we are not in the first 'item', alias matching |
|
407 | 407 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
408 | 408 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): |
|
409 | 409 | return [] |
|
410 | 410 | text = os.path.expanduser(text) |
|
411 | 411 | aliases = self.alias_table.keys() |
|
412 | 412 | if text == "": |
|
413 | 413 | return aliases |
|
414 | 414 | else: |
|
415 | 415 | return [alias for alias in aliases if alias.startswith(text)] |
|
416 | 416 | |
|
417 | 417 | def python_matches(self,text): |
|
418 | 418 | """Match attributes or global python names""" |
|
419 | 419 | |
|
420 | 420 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
421 | 421 | if "." in text: |
|
422 | 422 | try: |
|
423 | 423 | matches = self.attr_matches(text) |
|
424 | 424 | if text.endswith('.') and self.omit__names: |
|
425 | 425 | if self.omit__names == 1: |
|
426 | 426 | # true if txt is _not_ a __ name, false otherwise: |
|
427 | 427 | no__name = (lambda txt: |
|
428 | 428 | re.match(r'.*\.__.*?__',txt) is None) |
|
429 | 429 | else: |
|
430 | 430 | # true if txt is _not_ a _ name, false otherwise: |
|
431 | 431 | no__name = (lambda txt: |
|
432 | 432 | re.match(r'.*\._.*?',txt) is None) |
|
433 | 433 | matches = filter(no__name, matches) |
|
434 | 434 | except NameError: |
|
435 | 435 | # catches <undefined attributes>.<tab> |
|
436 | 436 | matches = [] |
|
437 | 437 | else: |
|
438 | 438 | matches = self.global_matches(text) |
|
439 | 439 | # this is so completion finds magics when automagic is on: |
|
440 | 440 | if (matches == [] and |
|
441 | 441 | not text.startswith(os.sep) and |
|
442 | 442 | not ' ' in self.lbuf): |
|
443 | 443 | matches = self.attr_matches(self.magic_prefix+text) |
|
444 | 444 | return matches |
|
445 | 445 | |
|
446 | 446 | def _default_arguments(self, obj): |
|
447 | 447 | """Return the list of default arguments of obj if it is callable, |
|
448 | 448 | or empty list otherwise.""" |
|
449 | 449 | |
|
450 | 450 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
451 | 451 | # for classes, check for __init__,__new__ |
|
452 | 452 | if inspect.isclass(obj): |
|
453 | 453 | obj = (getattr(obj,'__init__',None) or |
|
454 | 454 | getattr(obj,'__new__',None)) |
|
455 | 455 | # for all others, check if they are __call__able |
|
456 | 456 | elif hasattr(obj, '__call__'): |
|
457 | 457 | obj = obj.__call__ |
|
458 | 458 | # XXX: is there a way to handle the builtins ? |
|
459 | 459 | try: |
|
460 | 460 | args,_,_1,defaults = inspect.getargspec(obj) |
|
461 | 461 | if defaults: |
|
462 | 462 | return args[-len(defaults):] |
|
463 | 463 | except TypeError: pass |
|
464 | 464 | return [] |
|
465 | 465 | |
|
466 | 466 | def python_func_kw_matches(self,text): |
|
467 | 467 | """Match named parameters (kwargs) of the last open function""" |
|
468 | 468 | |
|
469 | 469 | if "." in text: # a parameter cannot be dotted |
|
470 | 470 | return [] |
|
471 | 471 | try: regexp = self.__funcParamsRegex |
|
472 | 472 | except AttributeError: |
|
473 | 473 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
474 | 474 | '.*?' | # single quoted strings or |
|
475 | 475 | ".*?" | # double quoted strings or |
|
476 | 476 | \w+ | # identifier |
|
477 | 477 | \S # other characters |
|
478 | 478 | ''', re.VERBOSE | re.DOTALL) |
|
479 | 479 | # 1. find the nearest identifier that comes before an unclosed |
|
480 | 480 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
481 | 481 | tokens = regexp.findall(self.get_line_buffer()) |
|
482 | 482 | tokens.reverse() |
|
483 | 483 | iterTokens = iter(tokens); openPar = 0 |
|
484 | 484 | for token in iterTokens: |
|
485 | 485 | if token == ')': |
|
486 | 486 | openPar -= 1 |
|
487 | 487 | elif token == '(': |
|
488 | 488 | openPar += 1 |
|
489 | 489 | if openPar > 0: |
|
490 | 490 | # found the last unclosed parenthesis |
|
491 | 491 | break |
|
492 | 492 | else: |
|
493 | 493 | return [] |
|
494 | 494 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
495 | 495 | ids = [] |
|
496 | 496 | isId = re.compile(r'\w+$').match |
|
497 | 497 | while True: |
|
498 | 498 | try: |
|
499 | 499 | ids.append(iterTokens.next()) |
|
500 | 500 | if not isId(ids[-1]): |
|
501 | 501 | ids.pop(); break |
|
502 | 502 | if not iterTokens.next() == '.': |
|
503 | 503 | break |
|
504 | 504 | except StopIteration: |
|
505 | 505 | break |
|
506 | 506 | # lookup the candidate callable matches either using global_matches |
|
507 | 507 | # or attr_matches for dotted names |
|
508 | 508 | if len(ids) == 1: |
|
509 | 509 | callableMatches = self.global_matches(ids[0]) |
|
510 | 510 | else: |
|
511 | 511 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
512 | 512 | argMatches = [] |
|
513 | 513 | for callableMatch in callableMatches: |
|
514 | 514 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
515 | 515 | self.namespace)) |
|
516 | 516 | except: continue |
|
517 | 517 | for namedArg in namedArgs: |
|
518 | 518 | if namedArg.startswith(text): |
|
519 | 519 | argMatches.append("%s=" %namedArg) |
|
520 | 520 | return argMatches |
|
521 | 521 | |
|
522 | 522 | def dispatch_custom_completer(self,text): |
|
523 | 523 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
524 | 524 | line = self.full_lbuf |
|
525 | 525 | if not line.strip(): |
|
526 | 526 | return None |
|
527 | 527 | |
|
528 | 528 | event = Struct() |
|
529 | 529 | event.line = line |
|
530 | 530 | event.symbol = text |
|
531 | 531 | cmd = line.split(None,1)[0] |
|
532 | 532 | event.command = cmd |
|
533 | 533 | #print "\ncustom:{%s]\n" % event # dbg |
|
534 | 534 | |
|
535 | 535 | # for foo etc, try also to find completer for %foo |
|
536 | 536 | if not cmd.startswith(self.magic_escape): |
|
537 | 537 | try_magic = self.custom_completers.s_matches( |
|
538 | 538 | self.magic_escape + cmd) |
|
539 | 539 | else: |
|
540 | 540 | try_magic = [] |
|
541 | 541 | |
|
542 | 542 | |
|
543 | 543 | for c in itertools.chain( |
|
544 | 544 | self.custom_completers.s_matches(cmd), |
|
545 | 545 | try_magic, |
|
546 | 546 | self.custom_completers.flat_matches(self.lbuf)): |
|
547 | 547 | #print "try",c # dbg |
|
548 | 548 | try: |
|
549 | 549 | res = c(event) |
|
550 | 550 | # first, try case sensitive match |
|
551 | 551 | withcase = [r for r in res if r.startswith(text)] |
|
552 | 552 | if withcase: |
|
553 | 553 | return withcase |
|
554 | 554 | # if none, then case insensitive ones are ok too |
|
555 | 555 | return [r for r in res if r.lower().startswith(text.lower())] |
|
556 | 556 | except ipapi.TryNext: |
|
557 | 557 | pass |
|
558 | 558 | |
|
559 | 559 | return None |
|
560 | 560 | |
|
561 | 561 | def complete(self, text, state,line_buffer=None): |
|
562 | 562 | """Return the next possible completion for 'text'. |
|
563 | 563 | |
|
564 | 564 | This is called successively with state == 0, 1, 2, ... until it |
|
565 | 565 | returns None. The completion should begin with 'text'. |
|
566 | 566 | |
|
567 | 567 | :Keywords: |
|
568 | 568 | - line_buffer: string |
|
569 | 569 | If not given, the completer attempts to obtain the current line buffer |
|
570 | 570 | via readline. This keyword allows clients which are requesting for |
|
571 | 571 | text completions in non-readline contexts to inform the completer of |
|
572 | 572 | the entire text. |
|
573 | 573 | """ |
|
574 | 574 | |
|
575 | 575 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
576 | 576 | |
|
577 | 577 | # if there is only a tab on a line with only whitespace, instead |
|
578 | 578 | # of the mostly useless 'do you want to see all million |
|
579 | 579 | # completions' message, just do the right thing and give the user |
|
580 | 580 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
581 | 581 | # an editor (as long as autoindent is off). |
|
582 | 582 | |
|
583 | 583 | # It should be noted that at least pyreadline still shows |
|
584 | 584 | # file completions - is there a way around it? |
|
585 | 585 | |
|
586 | 586 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
587 | 587 | # don't interfere with their own tab-completion mechanism. |
|
588 | 588 | if line_buffer is None: |
|
589 | 589 | self.full_lbuf = self.get_line_buffer() |
|
590 | 590 | else: |
|
591 | 591 | self.full_lbuf = line_buffer |
|
592 | 592 | |
|
593 | 593 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
594 | 594 | self.readline.insert_text('\t') |
|
595 | 595 | return None |
|
596 | 596 | |
|
597 | 597 | magic_escape = self.magic_escape |
|
598 | 598 | magic_prefix = self.magic_prefix |
|
599 | 599 | |
|
600 | 600 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
601 | 601 | |
|
602 | 602 | try: |
|
603 | 603 | if text.startswith(magic_escape): |
|
604 | 604 | text = text.replace(magic_escape,magic_prefix) |
|
605 | 605 | elif text.startswith('~'): |
|
606 | 606 | text = os.path.expanduser(text) |
|
607 | 607 | if state == 0: |
|
608 | 608 | custom_res = self.dispatch_custom_completer(text) |
|
609 | 609 | if custom_res is not None: |
|
610 | 610 | # did custom completers produce something? |
|
611 | 611 | self.matches = custom_res |
|
612 | 612 | else: |
|
613 | 613 | # Extend the list of completions with the results of each |
|
614 | 614 | # matcher, so we return results to the user from all |
|
615 | 615 | # namespaces. |
|
616 | 616 | if self.merge_completions: |
|
617 | 617 | self.matches = [] |
|
618 | 618 | for matcher in self.matchers: |
|
619 | 619 | self.matches.extend(matcher(text)) |
|
620 | 620 | else: |
|
621 | 621 | for matcher in self.matchers: |
|
622 | 622 | self.matches = matcher(text) |
|
623 | 623 | if self.matches: |
|
624 | 624 | break |
|
625 | 625 | def uniq(alist): |
|
626 | 626 | set = {} |
|
627 | 627 | return [set.setdefault(e,e) for e in alist if e not in set] |
|
628 | 628 | self.matches = uniq(self.matches) |
|
629 | 629 | try: |
|
630 | 630 | ret = self.matches[state].replace(magic_prefix,magic_escape) |
|
631 | 631 | return ret |
|
632 | 632 | except IndexError: |
|
633 | 633 | return None |
|
634 | 634 | except: |
|
635 | 635 | #from IPython.core.ultratb import AutoFormattedTB; # dbg |
|
636 | 636 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
637 | 637 | |
|
638 | 638 | # If completion fails, don't annoy the user. |
|
639 | 639 | return None |
@@ -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.config.IPYTHONDIR | |
|
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 |
rpt_add(pformat(self.IP. |
|
|
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 |
rpt_add(pformat(self.IP. |
|
|
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,266 +1,266 b'' | |||
|
1 | 1 | """hooks for IPython. |
|
2 | 2 | |
|
3 | 3 | In Python, it is possible to overwrite any method of any object if you really |
|
4 | 4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
5 | 5 | be overwritten by users for customization purposes. This module defines the |
|
6 | 6 | default versions of all such hooks, which get used by IPython if not |
|
7 | 7 | overridden by the user. |
|
8 | 8 | |
|
9 | 9 | hooks are simple functions, but they should be declared with 'self' as their |
|
10 | 10 | first argument, because when activated they are registered into IPython as |
|
11 | 11 | instance methods. The self argument will be the IPython running instance |
|
12 | 12 | itself, so hooks have full access to the entire IPython object. |
|
13 | 13 | |
|
14 | 14 | If you wish to define a new hook and activate it, you need to put the |
|
15 | 15 | necessary code into a python file which can be either imported or execfile()'d |
|
16 | 16 | from within your ipythonrc configuration. |
|
17 | 17 | |
|
18 | 18 | For example, suppose that you have a module called 'myiphooks' in your |
|
19 | 19 | PYTHONPATH, which contains the following definition: |
|
20 | 20 | |
|
21 | 21 | import os |
|
22 | 22 | from IPython.core import ipapi |
|
23 | 23 | ip = ipapi.get() |
|
24 | 24 | |
|
25 | 25 | def calljed(self,filename, linenum): |
|
26 | 26 | "My editor hook calls the jed editor directly." |
|
27 | 27 | print "Calling my own editor, jed ..." |
|
28 | 28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
29 | 29 | raise ipapi.TryNext() |
|
30 | 30 | |
|
31 | 31 | ip.set_hook('editor', calljed) |
|
32 | 32 | |
|
33 | 33 | You can then enable the functionality by doing 'import myiphooks' |
|
34 | 34 | somewhere in your configuration files or ipython command line. |
|
35 | 35 | """ |
|
36 | 36 | |
|
37 | 37 | #***************************************************************************** |
|
38 | 38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
39 | 39 | # |
|
40 | 40 | # Distributed under the terms of the BSD License. The full license is in |
|
41 | 41 | # the file COPYING, distributed as part of this software. |
|
42 | 42 | #***************************************************************************** |
|
43 | 43 | |
|
44 | 44 | from IPython.core import ipapi |
|
45 | 45 | |
|
46 | 46 | import os, bisect |
|
47 | 47 | import sys |
|
48 | 48 | from IPython.utils.genutils import Term, shell |
|
49 | 49 | from pprint import PrettyPrinter |
|
50 | 50 | |
|
51 | 51 | # List here all the default hooks. For now it's just the editor functions |
|
52 | 52 | # but over time we'll move here all the public API for user-accessible things. |
|
53 | 53 | # vds: >> |
|
54 | 54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', |
|
55 | 55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
56 | 56 | 'generate_prompt', 'generate_output_prompt','shell_hook', |
|
57 | 57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', |
|
58 | 58 | 'clipboard_get'] |
|
59 | 59 | # vds: << |
|
60 | 60 | |
|
61 | 61 | pformat = PrettyPrinter().pformat |
|
62 | 62 | |
|
63 | 63 | def editor(self,filename, linenum=None): |
|
64 | 64 | """Open the default editor at the given filename and linenumber. |
|
65 | 65 | |
|
66 | 66 | This is IPython's default editor hook, you can use it as an example to |
|
67 | 67 | write your own modified one. To set your own editor function as the |
|
68 | 68 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
69 | 69 | |
|
70 | 70 | # IPython configures a default editor at startup by reading $EDITOR from |
|
71 | 71 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
72 |
editor = self. |
|
|
72 | editor = self.editor | |
|
73 | 73 | |
|
74 | 74 | # marker for at which line to open the file (for existing objects) |
|
75 | 75 | if linenum is None or editor=='notepad': |
|
76 | 76 | linemark = '' |
|
77 | 77 | else: |
|
78 | 78 | linemark = '+%d' % int(linenum) |
|
79 | 79 | |
|
80 | 80 | # Enclose in quotes if necessary and legal |
|
81 | 81 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
82 | 82 | editor = '"%s"' % editor |
|
83 | 83 | |
|
84 | 84 | # Call the actual editor |
|
85 | 85 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
86 | 86 | raise ipapi.TryNext() |
|
87 | 87 | |
|
88 | 88 | import tempfile |
|
89 | 89 | def fix_error_editor(self,filename,linenum,column,msg): |
|
90 | 90 | """Open the editor at the given filename, linenumber, column and |
|
91 | 91 | show an error message. This is used for correcting syntax errors. |
|
92 | 92 | The current implementation only has special support for the VIM editor, |
|
93 | 93 | and falls back on the 'editor' hook if VIM is not used. |
|
94 | 94 | |
|
95 | 95 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
96 | 96 | """ |
|
97 | 97 | def vim_quickfix_file(): |
|
98 | 98 | t = tempfile.NamedTemporaryFile() |
|
99 | 99 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
100 | 100 | t.flush() |
|
101 | 101 | return t |
|
102 |
if os.path.basename(self. |
|
|
102 | if os.path.basename(self.editor) != 'vim': | |
|
103 | 103 | self.hooks.editor(filename,linenum) |
|
104 | 104 | return |
|
105 | 105 | t = vim_quickfix_file() |
|
106 | 106 | try: |
|
107 | 107 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
108 | 108 | raise ipapi.TryNext() |
|
109 | 109 | finally: |
|
110 | 110 | t.close() |
|
111 | 111 | |
|
112 | 112 | # vds: >> |
|
113 | 113 | def synchronize_with_editor(self, filename, linenum, column): |
|
114 | 114 | pass |
|
115 | 115 | # vds: << |
|
116 | 116 | |
|
117 | 117 | class CommandChainDispatcher: |
|
118 | 118 | """ Dispatch calls to a chain of commands until some func can handle it |
|
119 | 119 | |
|
120 | 120 | Usage: instantiate, execute "add" to add commands (with optional |
|
121 | 121 | priority), execute normally via f() calling mechanism. |
|
122 | 122 | |
|
123 | 123 | """ |
|
124 | 124 | def __init__(self,commands=None): |
|
125 | 125 | if commands is None: |
|
126 | 126 | self.chain = [] |
|
127 | 127 | else: |
|
128 | 128 | self.chain = commands |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | def __call__(self,*args, **kw): |
|
132 | 132 | """ Command chain is called just like normal func. |
|
133 | 133 | |
|
134 | 134 | This will call all funcs in chain with the same args as were given to this |
|
135 | 135 | function, and return the result of first func that didn't raise |
|
136 | 136 | TryNext """ |
|
137 | 137 | |
|
138 | 138 | for prio,cmd in self.chain: |
|
139 | 139 | #print "prio",prio,"cmd",cmd #dbg |
|
140 | 140 | try: |
|
141 | 141 | ret = cmd(*args, **kw) |
|
142 | 142 | return ret |
|
143 | 143 | except ipapi.TryNext, exc: |
|
144 | 144 | if exc.args or exc.kwargs: |
|
145 | 145 | args = exc.args |
|
146 | 146 | kw = exc.kwargs |
|
147 | 147 | # if no function will accept it, raise TryNext up to the caller |
|
148 | 148 | raise ipapi.TryNext |
|
149 | 149 | |
|
150 | 150 | def __str__(self): |
|
151 | 151 | return str(self.chain) |
|
152 | 152 | |
|
153 | 153 | def add(self, func, priority=0): |
|
154 | 154 | """ Add a func to the cmd chain with given priority """ |
|
155 | 155 | bisect.insort(self.chain,(priority,func)) |
|
156 | 156 | |
|
157 | 157 | def __iter__(self): |
|
158 | 158 | """ Return all objects in chain. |
|
159 | 159 | |
|
160 | 160 | Handy if the objects are not callable. |
|
161 | 161 | """ |
|
162 | 162 | return iter(self.chain) |
|
163 | 163 | |
|
164 | 164 | def result_display(self,arg): |
|
165 | 165 | """ Default display hook. |
|
166 | 166 | |
|
167 | 167 | Called for displaying the result to the user. |
|
168 | 168 | """ |
|
169 | 169 | |
|
170 |
if self. |
|
|
170 | if self.pprint: | |
|
171 | 171 | out = pformat(arg) |
|
172 | 172 | if '\n' in out: |
|
173 | 173 | # So that multi-line strings line up with the left column of |
|
174 | 174 | # the screen, instead of having the output prompt mess up |
|
175 | 175 | # their first line. |
|
176 | 176 | Term.cout.write('\n') |
|
177 | 177 | print >>Term.cout, out |
|
178 | 178 | else: |
|
179 | 179 | # By default, the interactive prompt uses repr() to display results, |
|
180 | 180 | # so we should honor this. Users who'd rather use a different |
|
181 | 181 | # mechanism can easily override this hook. |
|
182 | 182 | print >>Term.cout, repr(arg) |
|
183 | 183 | # the default display hook doesn't manipulate the value to put in history |
|
184 | 184 | return None |
|
185 | 185 | |
|
186 | 186 | def input_prefilter(self,line): |
|
187 | 187 | """ Default input prefilter |
|
188 | 188 | |
|
189 | 189 | This returns the line as unchanged, so that the interpreter |
|
190 | 190 | knows that nothing was done and proceeds with "classic" prefiltering |
|
191 | 191 | (%magics, !shell commands etc.). |
|
192 | 192 | |
|
193 | 193 | Note that leading whitespace is not passed to this hook. Prefilter |
|
194 | 194 | can't alter indentation. |
|
195 | 195 | |
|
196 | 196 | """ |
|
197 | 197 | #print "attempt to rewrite",line #dbg |
|
198 | 198 | return line |
|
199 | 199 | |
|
200 | 200 | def shutdown_hook(self): |
|
201 | 201 | """ default shutdown hook |
|
202 | 202 | |
|
203 | 203 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
204 | 204 | """ |
|
205 | 205 | |
|
206 | 206 | #print "default shutdown hook ok" # dbg |
|
207 | 207 | return |
|
208 | 208 | |
|
209 | 209 | def late_startup_hook(self): |
|
210 | 210 | """ Executed after ipython has been constructed and configured |
|
211 | 211 | |
|
212 | 212 | """ |
|
213 | 213 | #print "default startup hook ok" # dbg |
|
214 | 214 | |
|
215 | 215 | def generate_prompt(self, is_continuation): |
|
216 | 216 | """ calculate and return a string with the prompt to display """ |
|
217 | 217 | ip = self.api |
|
218 | 218 | if is_continuation: |
|
219 | 219 | return str(ip.IP.outputcache.prompt2) |
|
220 | 220 | return str(ip.IP.outputcache.prompt1) |
|
221 | 221 | |
|
222 | 222 | def generate_output_prompt(self): |
|
223 | 223 | ip = self.api |
|
224 | 224 | return str(ip.IP.outputcache.prompt_out) |
|
225 | 225 | |
|
226 | 226 | def shell_hook(self,cmd): |
|
227 | 227 | """ Run system/shell command a'la os.system() """ |
|
228 | 228 | |
|
229 |
shell(cmd, header=self. |
|
|
229 | shell(cmd, header=self.system_header, verbose=self.system_verbose) | |
|
230 | 230 | |
|
231 | 231 | def show_in_pager(self,s): |
|
232 | 232 | """ Run a string through pager """ |
|
233 | 233 | # raising TryNext here will use the default paging functionality |
|
234 | 234 | raise ipapi.TryNext |
|
235 | 235 | |
|
236 | 236 | def pre_prompt_hook(self): |
|
237 | 237 | """ Run before displaying the next prompt |
|
238 | 238 | |
|
239 | 239 | Use this e.g. to display output from asynchronous operations (in order |
|
240 | 240 | to not mess up text entry) |
|
241 | 241 | """ |
|
242 | 242 | |
|
243 | 243 | return None |
|
244 | 244 | |
|
245 | 245 | def pre_runcode_hook(self): |
|
246 | 246 | """ Executed before running the (prefiltered) code in IPython """ |
|
247 | 247 | return None |
|
248 | 248 | |
|
249 | 249 | def clipboard_get(self): |
|
250 | 250 | """ Get text from the clipboard. |
|
251 | 251 | """ |
|
252 | 252 | from IPython.lib.clipboard import ( |
|
253 | 253 | osx_clipboard_get, tkinter_clipboard_get, |
|
254 | 254 | win32_clipboard_get |
|
255 | 255 | ) |
|
256 | 256 | if sys.platform == 'win32': |
|
257 | 257 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
258 | 258 | elif sys.platform == 'darwin': |
|
259 | 259 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
260 | 260 | else: |
|
261 | 261 | chain = [tkinter_clipboard_get] |
|
262 | 262 | dispatcher = CommandChainDispatcher() |
|
263 | 263 | for func in chain: |
|
264 | 264 | dispatcher.add(func) |
|
265 | 265 | text = dispatcher() |
|
266 | 266 | return text |
@@ -1,685 +1,684 b'' | |||
|
1 | 1 | """IPython customization API |
|
2 | 2 | |
|
3 | 3 | Your one-stop module for configuring & extending ipython |
|
4 | 4 | |
|
5 | 5 | The API will probably break when ipython 1.0 is released, but so |
|
6 | 6 | will the other configuration method (rc files). |
|
7 | 7 | |
|
8 | 8 | All names prefixed by underscores are for internal use, not part |
|
9 | 9 | of the public api. |
|
10 | 10 | |
|
11 | 11 | Below is an example that you can just put to a module and import from ipython. |
|
12 | 12 | |
|
13 | 13 | A good practice is to install the config script below as e.g. |
|
14 | 14 | |
|
15 | 15 | ~/.ipython/my_private_conf.py |
|
16 | 16 | |
|
17 | 17 | And do |
|
18 | 18 | |
|
19 | 19 | import_mod my_private_conf |
|
20 | 20 | |
|
21 | 21 | in ~/.ipython/ipythonrc |
|
22 | 22 | |
|
23 | 23 | That way the module is imported at startup and you can have all your |
|
24 | 24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
25 | 25 | stuff) in there. |
|
26 | 26 | |
|
27 | 27 | from IPython.core import ipapi |
|
28 | 28 | ip = ipapi.get() |
|
29 | 29 | |
|
30 | 30 | def ankka_f(self, arg): |
|
31 | 31 | print 'Ankka',self,'says uppercase:',arg.upper() |
|
32 | 32 | |
|
33 | 33 | ip.expose_magic('ankka',ankka_f) |
|
34 | 34 | |
|
35 | 35 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
36 | 36 | ip.magic('alias helloworld echo "Hello world"') |
|
37 | 37 | ip.system('pwd') |
|
38 | 38 | |
|
39 | 39 | ip.ex('import re') |
|
40 | 40 | ip.ex(''' |
|
41 | 41 | def funcci(a,b): |
|
42 | 42 | print a+b |
|
43 | 43 | print funcci(3,4) |
|
44 | 44 | ''') |
|
45 | 45 | ip.ex('funcci(348,9)') |
|
46 | 46 | |
|
47 | 47 | def jed_editor(self,filename, linenum=None): |
|
48 | 48 | print 'Calling my own editor, jed ... via hook!' |
|
49 | 49 | import os |
|
50 | 50 | if linenum is None: linenum = 0 |
|
51 | 51 | os.system('jed +%d %s' % (linenum, filename)) |
|
52 | 52 | print 'exiting jed' |
|
53 | 53 | |
|
54 | 54 | ip.set_hook('editor',jed_editor) |
|
55 | 55 | |
|
56 | 56 | o = ip.options |
|
57 | 57 | o.autocall = 2 # FULL autocall mode |
|
58 | 58 | |
|
59 | 59 | print 'done!' |
|
60 | 60 | """ |
|
61 | 61 | |
|
62 | 62 | #----------------------------------------------------------------------------- |
|
63 | 63 | # Modules and globals |
|
64 | 64 | |
|
65 | 65 | # stdlib imports |
|
66 | 66 | import __builtin__ |
|
67 | 67 | import sys |
|
68 | 68 | |
|
69 | 69 | # contains the most recently instantiated IPApi |
|
70 | 70 | _RECENT_IP = None |
|
71 | 71 | |
|
72 | 72 | #----------------------------------------------------------------------------- |
|
73 | 73 | # Code begins |
|
74 | 74 | |
|
75 | 75 | class TryNext(Exception): |
|
76 | 76 | """Try next hook exception. |
|
77 | 77 | |
|
78 | 78 | Raise this in your hook function to indicate that the next hook handler |
|
79 | 79 | should be used to handle the operation. If you pass arguments to the |
|
80 | 80 | constructor those arguments will be used by the next hook instead of the |
|
81 | 81 | original ones. |
|
82 | 82 | """ |
|
83 | 83 | |
|
84 | 84 | def __init__(self, *args, **kwargs): |
|
85 | 85 | self.args = args |
|
86 | 86 | self.kwargs = kwargs |
|
87 | 87 | |
|
88 | 88 | |
|
89 | 89 | class UsageError(Exception): |
|
90 | 90 | """ Error in magic function arguments, etc. |
|
91 | 91 | |
|
92 | 92 | Something that probably won't warrant a full traceback, but should |
|
93 | 93 | nevertheless interrupt a macro / batch file. |
|
94 | 94 | """ |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | class IPyAutocall: |
|
98 | 98 | """ Instances of this class are always autocalled |
|
99 | 99 | |
|
100 | 100 | This happens regardless of 'autocall' variable state. Use this to |
|
101 | 101 | develop macro-like mechanisms. |
|
102 | 102 | """ |
|
103 | 103 | |
|
104 | 104 | def set_ip(self,ip): |
|
105 | 105 | """ Will be used to set _ip point to current ipython instance b/f call |
|
106 | 106 | |
|
107 | 107 | Override this method if you don't want this to happen. |
|
108 | 108 | |
|
109 | 109 | """ |
|
110 | 110 | self._ip = ip |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | class IPythonNotRunning: |
|
114 | 114 | """Dummy do-nothing class. |
|
115 | 115 | |
|
116 | 116 | Instances of this class return a dummy attribute on all accesses, which |
|
117 | 117 | can be called and warns. This makes it easier to write scripts which use |
|
118 | 118 | the ipapi.get() object for informational purposes to operate both with and |
|
119 | 119 | without ipython. Obviously code which uses the ipython object for |
|
120 | 120 | computations will not work, but this allows a wider range of code to |
|
121 | 121 | transparently work whether ipython is being used or not.""" |
|
122 | 122 | |
|
123 | 123 | def __init__(self,warn=True): |
|
124 | 124 | if warn: |
|
125 | 125 | self.dummy = self._dummy_warn |
|
126 | 126 | else: |
|
127 | 127 | self.dummy = self._dummy_silent |
|
128 | 128 | |
|
129 | 129 | def __str__(self): |
|
130 | 130 | return "<IPythonNotRunning>" |
|
131 | 131 | |
|
132 | 132 | __repr__ = __str__ |
|
133 | 133 | |
|
134 | 134 | def __getattr__(self,name): |
|
135 | 135 | return self.dummy |
|
136 | 136 | |
|
137 | 137 | def _dummy_warn(self,*args,**kw): |
|
138 | 138 | """Dummy function, which doesn't do anything but warn.""" |
|
139 | 139 | |
|
140 | 140 | print ("IPython is not running, this is a dummy no-op function") |
|
141 | 141 | |
|
142 | 142 | def _dummy_silent(self,*args,**kw): |
|
143 | 143 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
144 | 144 | pass |
|
145 | 145 | |
|
146 | 146 | |
|
147 | 147 | def get(allow_dummy=False,dummy_warn=True): |
|
148 | 148 | """Get an IPApi object. |
|
149 | 149 | |
|
150 | 150 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
151 | 151 | instead of None if not running under IPython. |
|
152 | 152 | |
|
153 | 153 | If dummy_warn is false, the dummy instance will be completely silent. |
|
154 | 154 | |
|
155 | 155 | Running this should be the first thing you do when writing extensions that |
|
156 | 156 | can be imported as normal modules. You can then direct all the |
|
157 | 157 | configuration operations against the returned object. |
|
158 | 158 | """ |
|
159 | 159 | global _RECENT_IP |
|
160 | 160 | if allow_dummy and not _RECENT_IP: |
|
161 | 161 | _RECENT_IP = IPythonNotRunning(dummy_warn) |
|
162 | 162 | return _RECENT_IP |
|
163 | 163 | |
|
164 | 164 | |
|
165 | 165 | class IPApi(object): |
|
166 | 166 | """ The actual API class for configuring IPython |
|
167 | 167 | |
|
168 | 168 | You should do all of the IPython configuration by getting an IPApi object |
|
169 | 169 | with IPython.ipapi.get() and using the attributes and methods of the |
|
170 | 170 | returned object.""" |
|
171 | 171 | |
|
172 | 172 | def __init__(self,ip): |
|
173 | 173 | |
|
174 | 174 | global _RECENT_IP |
|
175 | 175 | |
|
176 | 176 | # All attributes exposed here are considered to be the public API of |
|
177 | 177 | # IPython. As needs dictate, some of these may be wrapped as |
|
178 | 178 | # properties. |
|
179 | 179 | |
|
180 | 180 | self.magic = ip.ipmagic |
|
181 | 181 | |
|
182 | 182 | self.system = ip.system |
|
183 | 183 | |
|
184 | 184 | self.set_hook = ip.set_hook |
|
185 | 185 | |
|
186 | 186 | self.set_custom_exc = ip.set_custom_exc |
|
187 | 187 | |
|
188 | 188 | self.user_ns = ip.user_ns |
|
189 | 189 | |
|
190 | 190 | self.set_crash_handler = ip.set_crash_handler |
|
191 | 191 | |
|
192 | 192 | # Session-specific data store, which can be used to store |
|
193 | 193 | # data that should persist through the ipython session. |
|
194 | 194 | self.meta = ip.meta |
|
195 | 195 | |
|
196 | 196 | # The ipython instance provided |
|
197 | 197 | self.IP = ip |
|
198 | 198 | |
|
199 | 199 | self.extensions = {} |
|
200 | 200 | |
|
201 | 201 | self.dbg = DebugTools(self) |
|
202 | 202 | |
|
203 | 203 | _RECENT_IP = self |
|
204 | 204 | |
|
205 | 205 | # Use a property for some things which are added to the instance very |
|
206 | 206 | # late. I don't have time right now to disentangle the initialization |
|
207 | 207 | # order issues, so a property lets us delay item extraction while |
|
208 | 208 | # providing a normal attribute API. |
|
209 | 209 | def get_db(self): |
|
210 | 210 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
211 | 211 | return self.IP.db |
|
212 | 212 | |
|
213 | 213 | db = property(get_db,None,None,get_db.__doc__) |
|
214 | 214 | |
|
215 | 215 | def get_options(self): |
|
216 | 216 | """All configurable variables.""" |
|
217 | 217 | |
|
218 | 218 | # catch typos by disabling new attribute creation. If new attr creation |
|
219 | 219 | # is in fact wanted (e.g. when exposing new options), do |
|
220 | 220 | # allow_new_attr(True) for the received rc struct. |
|
221 | 221 | |
|
222 | self.IP.rc.allow_new_attr(False) | |
|
223 | return self.IP.rc | |
|
222 | return self.IP | |
|
224 | 223 | |
|
225 | 224 | options = property(get_options,None,None,get_options.__doc__) |
|
226 | 225 | |
|
227 | 226 | def expose_magic(self,magicname, func): |
|
228 | 227 | """Expose own function as magic function for ipython |
|
229 | 228 | |
|
230 | 229 | def foo_impl(self,parameter_s=''): |
|
231 | 230 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
232 | 231 | print 'Magic function. Passed parameter is between < >:' |
|
233 | 232 | print '<%s>' % parameter_s |
|
234 | 233 | print 'The self object is:',self |
|
235 | 234 | |
|
236 | 235 | ipapi.expose_magic('foo',foo_impl) |
|
237 | 236 | """ |
|
238 | 237 | |
|
239 | 238 | import new |
|
240 | 239 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
241 | 240 | old = getattr(self.IP, "magic_" + magicname, None) |
|
242 | 241 | if old: |
|
243 | 242 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % |
|
244 | 243 | (magicname,old) ) |
|
245 | 244 | |
|
246 | 245 | setattr(self.IP, "magic_" + magicname, im) |
|
247 | 246 | |
|
248 | 247 | def ex(self,cmd): |
|
249 | 248 | """ Execute a normal python statement in user namespace """ |
|
250 | 249 | exec cmd in self.user_ns |
|
251 | 250 | |
|
252 | 251 | def ev(self,expr): |
|
253 | 252 | """ Evaluate python expression expr in user namespace |
|
254 | 253 | |
|
255 | 254 | Returns the result of evaluation""" |
|
256 | 255 | return eval(expr,self.user_ns) |
|
257 | 256 | |
|
258 | 257 | def runlines(self,lines): |
|
259 | 258 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
260 | 259 | |
|
261 | 260 | This allows %magic and !shell escape notations. |
|
262 | 261 | |
|
263 | 262 | Takes either all lines in one string or list of lines. |
|
264 | 263 | """ |
|
265 | 264 | |
|
266 | 265 | def cleanup_ipy_script(script): |
|
267 | 266 | """ Make a script safe for _ip.runlines() |
|
268 | 267 | |
|
269 | 268 | - Removes empty lines Suffixes all indented blocks that end with |
|
270 | 269 | - unindented lines with empty lines |
|
271 | 270 | """ |
|
272 | 271 | |
|
273 | 272 | res = [] |
|
274 | 273 | lines = script.splitlines() |
|
275 | 274 | |
|
276 | 275 | level = 0 |
|
277 | 276 | for l in lines: |
|
278 | 277 | lstripped = l.lstrip() |
|
279 | 278 | stripped = l.strip() |
|
280 | 279 | if not stripped: |
|
281 | 280 | continue |
|
282 | 281 | newlevel = len(l) - len(lstripped) |
|
283 | 282 | def is_secondary_block_start(s): |
|
284 | 283 | if not s.endswith(':'): |
|
285 | 284 | return False |
|
286 | 285 | if (s.startswith('elif') or |
|
287 | 286 | s.startswith('else') or |
|
288 | 287 | s.startswith('except') or |
|
289 | 288 | s.startswith('finally')): |
|
290 | 289 | return True |
|
291 | 290 | |
|
292 | 291 | if level > 0 and newlevel == 0 and \ |
|
293 | 292 | not is_secondary_block_start(stripped): |
|
294 | 293 | # add empty line |
|
295 | 294 | res.append('') |
|
296 | 295 | |
|
297 | 296 | res.append(l) |
|
298 | 297 | level = newlevel |
|
299 | 298 | return '\n'.join(res) + '\n' |
|
300 | 299 | |
|
301 | 300 | if isinstance(lines,basestring): |
|
302 | 301 | script = lines |
|
303 | 302 | else: |
|
304 | 303 | script = '\n'.join(lines) |
|
305 | 304 | clean=cleanup_ipy_script(script) |
|
306 | 305 | # print "_ip.runlines() script:\n",clean # dbg |
|
307 | 306 | self.IP.runlines(clean) |
|
308 | 307 | |
|
309 | 308 | def to_user_ns(self,vars, interactive = True): |
|
310 | 309 | """Inject a group of variables into the IPython user namespace. |
|
311 | 310 | |
|
312 | 311 | Inputs: |
|
313 | 312 | |
|
314 | 313 | - vars: string with variable names separated by whitespace, or a |
|
315 | 314 | dict with name/value pairs. |
|
316 | 315 | |
|
317 | 316 | - interactive: if True (default), the var will be listed with |
|
318 | 317 | %whos et. al. |
|
319 | 318 | |
|
320 | 319 | This utility routine is meant to ease interactive debugging work, |
|
321 | 320 | where you want to easily propagate some internal variable in your code |
|
322 | 321 | up to the interactive namespace for further exploration. |
|
323 | 322 | |
|
324 | 323 | When you run code via %run, globals in your script become visible at |
|
325 | 324 | the interactive prompt, but this doesn't happen for locals inside your |
|
326 | 325 | own functions and methods. Yet when debugging, it is common to want |
|
327 | 326 | to explore some internal variables further at the interactive propmt. |
|
328 | 327 | |
|
329 | 328 | Examples: |
|
330 | 329 | |
|
331 | 330 | To use this, you first must obtain a handle on the ipython object as |
|
332 | 331 | indicated above, via: |
|
333 | 332 | |
|
334 | 333 | from IPython.core import ipapi |
|
335 | 334 | ip = ipapi.get() |
|
336 | 335 | |
|
337 | 336 | Once this is done, inside a routine foo() where you want to expose |
|
338 | 337 | variables x and y, you do the following: |
|
339 | 338 | |
|
340 | 339 | def foo(): |
|
341 | 340 | ... |
|
342 | 341 | x = your_computation() |
|
343 | 342 | y = something_else() |
|
344 | 343 | |
|
345 | 344 | # This pushes x and y to the interactive prompt immediately, even |
|
346 | 345 | # if this routine crashes on the next line after: |
|
347 | 346 | ip.to_user_ns('x y') |
|
348 | 347 | ... |
|
349 | 348 | |
|
350 | 349 | # To expose *ALL* the local variables from the function, use: |
|
351 | 350 | ip.to_user_ns(locals()) |
|
352 | 351 | |
|
353 | 352 | ... |
|
354 | 353 | # return |
|
355 | 354 | |
|
356 | 355 | |
|
357 | 356 | If you need to rename variables, the dict input makes it easy. For |
|
358 | 357 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
359 | 358 | in IPython user namespace: |
|
360 | 359 | |
|
361 | 360 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
362 | 361 | """ |
|
363 | 362 | |
|
364 | 363 | # print 'vars given:',vars # dbg |
|
365 | 364 | |
|
366 | 365 | # We need a dict of name/value pairs to do namespace updates. |
|
367 | 366 | if isinstance(vars,dict): |
|
368 | 367 | # If a dict was given, no need to change anything. |
|
369 | 368 | vdict = vars |
|
370 | 369 | elif isinstance(vars,basestring): |
|
371 | 370 | # If a string with names was given, get the caller's frame to |
|
372 | 371 | # evaluate the given names in |
|
373 | 372 | cf = sys._getframe(1) |
|
374 | 373 | vdict = {} |
|
375 | 374 | for name in vars.split(): |
|
376 | 375 | try: |
|
377 | 376 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
378 | 377 | except: |
|
379 | 378 | print ('could not get var. %s from %s' % |
|
380 | 379 | (name,cf.f_code.co_name)) |
|
381 | 380 | else: |
|
382 | 381 | raise ValueError('vars must be a string or a dict') |
|
383 | 382 | |
|
384 | 383 | # Propagate variables to user namespace |
|
385 | 384 | self.user_ns.update(vdict) |
|
386 | 385 | |
|
387 | 386 | # And configure interactive visibility |
|
388 | 387 | config_ns = self.IP.user_config_ns |
|
389 | 388 | if interactive: |
|
390 | 389 | for name,val in vdict.iteritems(): |
|
391 | 390 | config_ns.pop(name,None) |
|
392 | 391 | else: |
|
393 | 392 | for name,val in vdict.iteritems(): |
|
394 | 393 | config_ns[name] = val |
|
395 | 394 | |
|
396 | 395 | def expand_alias(self,line): |
|
397 | 396 | """ Expand an alias in the command line |
|
398 | 397 | |
|
399 | 398 | Returns the provided command line, possibly with the first word |
|
400 | 399 | (command) translated according to alias expansion rules. |
|
401 | 400 | |
|
402 | 401 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
403 | 402 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
404 | 403 | """ |
|
405 | 404 | |
|
406 | 405 | pre,fn,rest = self.IP.split_user_input(line) |
|
407 | 406 | res = pre + self.IP.expand_aliases(fn,rest) |
|
408 | 407 | return res |
|
409 | 408 | |
|
410 | 409 | def itpl(self, s, depth = 1): |
|
411 | 410 | """ Expand Itpl format string s. |
|
412 | 411 | |
|
413 | 412 | Only callable from command line (i.e. prefilter results); |
|
414 | 413 | If you use in your scripts, you need to use a bigger depth! |
|
415 | 414 | """ |
|
416 | 415 | return self.IP.var_expand(s, depth) |
|
417 | 416 | |
|
418 | 417 | def defalias(self, name, cmd): |
|
419 | 418 | """ Define a new alias |
|
420 | 419 | |
|
421 | 420 | _ip.defalias('bb','bldmake bldfiles') |
|
422 | 421 | |
|
423 | 422 | Creates a new alias named 'bb' in ipython user namespace |
|
424 | 423 | """ |
|
425 | 424 | |
|
426 | 425 | self.dbg.check_hotname(name) |
|
427 | 426 | |
|
428 | 427 | if name in self.IP.alias_table: |
|
429 | 428 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" |
|
430 | 429 | % (name, cmd, self.IP.alias_table[name])) |
|
431 | 430 | |
|
432 | 431 | if callable(cmd): |
|
433 | 432 | self.IP.alias_table[name] = cmd |
|
434 | 433 | from IPython.core import shadowns |
|
435 | 434 | setattr(shadowns, name,cmd) |
|
436 | 435 | return |
|
437 | 436 | |
|
438 | 437 | if isinstance(cmd,basestring): |
|
439 | 438 | nargs = cmd.count('%s') |
|
440 | 439 | if nargs>0 and cmd.find('%l')>=0: |
|
441 | 440 | raise Exception('The %s and %l specifiers are mutually ' |
|
442 | 441 | 'exclusive in alias definitions.') |
|
443 | 442 | |
|
444 | 443 | self.IP.alias_table[name] = (nargs,cmd) |
|
445 | 444 | return |
|
446 | 445 | |
|
447 | 446 | # just put it in - it's probably (0,'foo') |
|
448 | 447 | self.IP.alias_table[name] = cmd |
|
449 | 448 | |
|
450 | 449 | def defmacro(self, *args): |
|
451 | 450 | """ Define a new macro |
|
452 | 451 | |
|
453 | 452 | 2 forms of calling: |
|
454 | 453 | |
|
455 | 454 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
456 | 455 | |
|
457 | 456 | (doesn't put the created macro on user namespace) |
|
458 | 457 | |
|
459 | 458 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
460 | 459 | |
|
461 | 460 | (creates a macro named 'build' in user namespace) |
|
462 | 461 | """ |
|
463 | 462 | |
|
464 | 463 | from IPython.core import macro |
|
465 | 464 | |
|
466 | 465 | if len(args) == 1: |
|
467 | 466 | return macro.Macro(args[0]) |
|
468 | 467 | elif len(args) == 2: |
|
469 | 468 | self.user_ns[args[0]] = macro.Macro(args[1]) |
|
470 | 469 | else: |
|
471 | 470 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
472 | 471 | |
|
473 | 472 | def set_next_input(self, s): |
|
474 | 473 | """ Sets the 'default' input string for the next command line. |
|
475 | 474 | |
|
476 | 475 | Requires readline. |
|
477 | 476 | |
|
478 | 477 | Example: |
|
479 | 478 | |
|
480 | 479 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
481 | 480 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
482 | 481 | """ |
|
483 | 482 | |
|
484 | 483 | self.IP.rl_next_input = s |
|
485 | 484 | |
|
486 | 485 | def load(self, mod): |
|
487 | 486 | """ Load an extension. |
|
488 | 487 | |
|
489 | 488 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
490 | 489 | |
|
491 | 490 | Loading will do: |
|
492 | 491 | |
|
493 | 492 | - run init_ipython(ip) |
|
494 | 493 | - run ipython_firstrun(ip) |
|
495 | 494 | """ |
|
496 | 495 | |
|
497 | 496 | if mod in self.extensions: |
|
498 | 497 | # just to make sure we don't init it twice |
|
499 | 498 | # note that if you 'load' a module that has already been |
|
500 | 499 | # imported, init_ipython gets run anyway |
|
501 | 500 | |
|
502 | 501 | return self.extensions[mod] |
|
503 | 502 | __import__(mod) |
|
504 | 503 | m = sys.modules[mod] |
|
505 | 504 | if hasattr(m,'init_ipython'): |
|
506 | 505 | m.init_ipython(self) |
|
507 | 506 | |
|
508 | 507 | if hasattr(m,'ipython_firstrun'): |
|
509 | 508 | already_loaded = self.db.get('firstrun_done', set()) |
|
510 | 509 | if mod not in already_loaded: |
|
511 | 510 | m.ipython_firstrun(self) |
|
512 | 511 | already_loaded.add(mod) |
|
513 | 512 | self.db['firstrun_done'] = already_loaded |
|
514 | 513 | |
|
515 | 514 | self.extensions[mod] = m |
|
516 | 515 | return m |
|
517 | 516 | |
|
518 | 517 | |
|
519 | 518 | class DebugTools: |
|
520 | 519 | """ Used for debugging mishaps in api usage |
|
521 | 520 | |
|
522 | 521 | So far, tracing redefinitions is supported. |
|
523 | 522 | """ |
|
524 | 523 | |
|
525 | 524 | def __init__(self, ip): |
|
526 | 525 | self.ip = ip |
|
527 | 526 | self.debugmode = False |
|
528 | 527 | self.hotnames = set() |
|
529 | 528 | |
|
530 | 529 | def hotname(self, name_to_catch): |
|
531 | 530 | self.hotnames.add(name_to_catch) |
|
532 | 531 | |
|
533 | 532 | def debug_stack(self, msg = None): |
|
534 | 533 | if not self.debugmode: |
|
535 | 534 | return |
|
536 | 535 | |
|
537 | 536 | import traceback |
|
538 | 537 | if msg is not None: |
|
539 | 538 | print '====== %s ========' % msg |
|
540 | 539 | traceback.print_stack() |
|
541 | 540 | |
|
542 | 541 | def check_hotname(self,name): |
|
543 | 542 | if name in self.hotnames: |
|
544 | 543 | self.debug_stack( "HotName '%s' caught" % name) |
|
545 | 544 | |
|
546 | 545 | |
|
547 | 546 | def launch_new_instance(user_ns = None,shellclass = None): |
|
548 | 547 | """ Make and start a new ipython instance. |
|
549 | 548 | |
|
550 | 549 | This can be called even without having an already initialized |
|
551 | 550 | ipython session running. |
|
552 | 551 | |
|
553 | 552 | This is also used as the egg entry point for the 'ipython' script. |
|
554 | 553 | |
|
555 | 554 | """ |
|
556 | 555 | ses = make_session(user_ns,shellclass) |
|
557 | 556 | ses.mainloop() |
|
558 | 557 | |
|
559 | 558 | |
|
560 | 559 | def make_user_ns(user_ns = None): |
|
561 | 560 | """Return a valid user interactive namespace. |
|
562 | 561 | |
|
563 | 562 | This builds a dict with the minimal information needed to operate as a |
|
564 | 563 | valid IPython user namespace, which you can pass to the various embedding |
|
565 | 564 | classes in ipython. |
|
566 | 565 | |
|
567 | 566 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
568 | 567 | to make both the local and global namespace objects simultaneously. |
|
569 | 568 | |
|
570 | 569 | :Parameters: |
|
571 | 570 | user_ns : dict-like, optional |
|
572 | 571 | The current user namespace. The items in this namespace should be |
|
573 | 572 | included in the output. If None, an appropriate blank namespace |
|
574 | 573 | should be created. |
|
575 | 574 | |
|
576 | 575 | :Returns: |
|
577 | 576 | A dictionary-like object to be used as the local namespace of the |
|
578 | 577 | interpreter. |
|
579 | 578 | """ |
|
580 | 579 | |
|
581 | 580 | raise NotImplementedError |
|
582 | 581 | |
|
583 | 582 | |
|
584 | 583 | def make_user_global_ns(ns = None): |
|
585 | 584 | """Return a valid user global namespace. |
|
586 | 585 | |
|
587 | 586 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
588 | 587 | embedded applications, where there is a distinction between the user's |
|
589 | 588 | interactive namespace and the global one where ipython is running. |
|
590 | 589 | |
|
591 | 590 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
592 | 591 | to make both the local and global namespace objects simultaneously. |
|
593 | 592 | |
|
594 | 593 | :Parameters: |
|
595 | 594 | ns : dict, optional |
|
596 | 595 | The current user global namespace. The items in this namespace |
|
597 | 596 | should be included in the output. If None, an appropriate blank |
|
598 | 597 | namespace should be created. |
|
599 | 598 | |
|
600 | 599 | :Returns: |
|
601 | 600 | A true dict to be used as the global namespace of the interpreter. |
|
602 | 601 | """ |
|
603 | 602 | |
|
604 | 603 | raise NotImplementedError |
|
605 | 604 | |
|
606 | 605 | # Record the true objects in order to be able to test if the user has overridden |
|
607 | 606 | # these API functions. |
|
608 | 607 | _make_user_ns = make_user_ns |
|
609 | 608 | _make_user_global_ns = make_user_global_ns |
|
610 | 609 | |
|
611 | 610 | |
|
612 | def make_user_namespaces(user_ns = None,user_global_ns = None): | |
|
611 | def make_user_namespaces(user_ns = None, user_global_ns = None): | |
|
613 | 612 | """Return a valid local and global user interactive namespaces. |
|
614 | 613 | |
|
615 | 614 | This builds a dict with the minimal information needed to operate as a |
|
616 | 615 | valid IPython user namespace, which you can pass to the various embedding |
|
617 | 616 | classes in ipython. The default implementation returns the same dict for |
|
618 | 617 | both the locals and the globals to allow functions to refer to variables in |
|
619 | 618 | the namespace. Customized implementations can return different dicts. The |
|
620 | 619 | locals dictionary can actually be anything following the basic mapping |
|
621 | 620 | protocol of a dict, but the globals dict must be a true dict, not even |
|
622 | 621 | a subclass. It is recommended that any custom object for the locals |
|
623 | 622 | namespace synchronize with the globals dict somehow. |
|
624 | 623 | |
|
625 | 624 | Raises TypeError if the provided globals namespace is not a true dict. |
|
626 | 625 | |
|
627 | 626 | :Parameters: |
|
628 | 627 | user_ns : dict-like, optional |
|
629 | 628 | The current user namespace. The items in this namespace should be |
|
630 | 629 | included in the output. If None, an appropriate blank namespace |
|
631 | 630 | should be created. |
|
632 | 631 | user_global_ns : dict, optional |
|
633 | 632 | The current user global namespace. The items in this namespace |
|
634 | 633 | should be included in the output. If None, an appropriate blank |
|
635 | 634 | namespace should be created. |
|
636 | 635 | |
|
637 | 636 | :Returns: |
|
638 | 637 | A tuple pair of dictionary-like object to be used as the local namespace |
|
639 | 638 | of the interpreter and a dict to be used as the global namespace. |
|
640 | 639 | """ |
|
641 | 640 | |
|
642 | 641 | if user_ns is None: |
|
643 | 642 | if make_user_ns is not _make_user_ns: |
|
644 | 643 | # Old API overridden. |
|
645 | 644 | # FIXME: Issue DeprecationWarning, or just let the old API live on? |
|
646 | 645 | user_ns = make_user_ns(user_ns) |
|
647 | 646 | else: |
|
648 | 647 | # Set __name__ to __main__ to better match the behavior of the |
|
649 | 648 | # normal interpreter. |
|
650 | 649 | user_ns = {'__name__' :'__main__', |
|
651 | 650 | '__builtins__' : __builtin__, |
|
652 | 651 | } |
|
653 | 652 | else: |
|
654 | 653 | user_ns.setdefault('__name__','__main__') |
|
655 | 654 | user_ns.setdefault('__builtins__',__builtin__) |
|
656 | 655 | |
|
657 | 656 | if user_global_ns is None: |
|
658 | 657 | if make_user_global_ns is not _make_user_global_ns: |
|
659 | 658 | # Old API overridden. |
|
660 | 659 | user_global_ns = make_user_global_ns(user_global_ns) |
|
661 | 660 | else: |
|
662 | 661 | user_global_ns = user_ns |
|
663 | 662 | if type(user_global_ns) is not dict: |
|
664 | 663 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
665 | 664 | % type(user_global_ns)) |
|
666 | 665 | |
|
667 | 666 | return user_ns, user_global_ns |
|
668 | 667 | |
|
669 | 668 | |
|
670 | 669 | def make_session(user_ns = None, shellclass = None): |
|
671 | 670 | """Makes, but does not launch an IPython session. |
|
672 | 671 | |
|
673 | 672 | Later on you can call obj.mainloop() on the returned object. |
|
674 | 673 | |
|
675 | 674 | Inputs: |
|
676 | 675 | |
|
677 | 676 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
678 | 677 | data. |
|
679 | 678 | |
|
680 | 679 | WARNING: This should *not* be run when a session exists already.""" |
|
681 | 680 | |
|
682 | 681 | import IPython.core.shell |
|
683 | 682 | if shellclass is None: |
|
684 | 683 | return IPython.core.shell.start(user_ns) |
|
685 | 684 | return shellclass(user_ns = user_ns) |
This diff has been collapsed as it changes many lines, (862 lines changed) Show them Hide them | |||
@@ -1,2865 +1,2737 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | IPython -- An enhanced Interactive Python | |
|
4 | ||
|
5 | Requires Python 2.4 or newer. | |
|
6 | ||
|
7 | This file contains all the classes and helper functions specific to IPython. | |
|
3 | Main IPython Component | |
|
8 | 4 | """ |
|
9 | 5 | |
|
10 | #***************************************************************************** | |
|
11 |
# |
|
|
12 |
# |
|
|
6 | #----------------------------------------------------------------------------- | |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
|
13 | 10 | # |
|
14 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 12 | # the file COPYING, distributed as part of this software. |
|
16 | # | |
|
17 | # Note: this code originally subclassed code.InteractiveConsole from the | |
|
18 | # Python standard library. Over time, all of that class has been copied | |
|
19 | # verbatim here for modifications which could not be accomplished by | |
|
20 | # subclassing. At this point, there are no dependencies at all on the code | |
|
21 | # module anymore (it is not even imported). The Python License (sec. 2) | |
|
22 | # allows for this, but it's always nice to acknowledge credit where credit is | |
|
23 | # due. | |
|
24 | #***************************************************************************** | |
|
25 | ||
|
26 | #**************************************************************************** | |
|
27 | # Modules and globals | |
|
28 | ||
|
29 | # Python standard modules | |
|
13 | #----------------------------------------------------------------------------- | |
|
14 | ||
|
15 | #----------------------------------------------------------------------------- | |
|
16 | # Imports | |
|
17 | #----------------------------------------------------------------------------- | |
|
18 | ||
|
30 | 19 | import __main__ |
|
31 | 20 | import __builtin__ |
|
32 | 21 | import StringIO |
|
33 | 22 | import bdb |
|
34 | 23 | import codeop |
|
35 | 24 | import exceptions |
|
36 | 25 | import glob |
|
37 | 26 | import keyword |
|
38 | 27 | import new |
|
39 | 28 | import os |
|
40 | 29 | import re |
|
41 | 30 | import shutil |
|
42 | 31 | import string |
|
43 | 32 | import sys |
|
44 | 33 | import tempfile |
|
45 | 34 | |
|
46 | # IPython's own modules | |
|
47 | #import IPython | |
|
48 | 35 | from IPython.core import ultratb |
|
49 | from IPython.utils import PyColorize | |
|
50 | 36 | from IPython.core import debugger, oinspect |
|
51 |
from IPython. |
|
|
37 | from IPython.core import ipapi | |
|
38 | from IPython.core import shadowns | |
|
39 | from IPython.core import history as ipcorehist | |
|
40 | from IPython.core import prefilter | |
|
52 | 41 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
53 | from IPython.external.Itpl import ItplNS | |
|
54 | 42 | from IPython.core.logger import Logger |
|
55 | 43 | from IPython.core.magic import Magic |
|
56 | 44 | from IPython.core.prompts import CachedOutput |
|
57 | from IPython.utils.ipstruct import Struct | |
|
45 | from IPython.core.component import Component | |
|
46 | from IPython.core.oldusersetup import user_setup | |
|
47 | from IPython.core.usage import interactive_usage, banner_parts | |
|
48 | ||
|
49 | from IPython.extensions import pickleshare | |
|
50 | from IPython.external.Itpl import ItplNS | |
|
58 | 51 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
52 | from IPython.utils.ipstruct import Struct | |
|
53 | from IPython.utils import PyColorize | |
|
59 | 54 | from IPython.utils.genutils import * |
|
60 | 55 | from IPython.utils.strdispatch import StrDispatch |
|
61 | from IPython.core import ipapi | |
|
62 | import IPython.core.history | |
|
63 | import IPython.core.prefilter as prefilter | |
|
64 | from IPython.core import shadowns | |
|
56 | ||
|
57 | from IPython.utils.traitlets import ( | |
|
58 | Int, Float, Str, Bool | |
|
59 | ) | |
|
60 | ||
|
61 | #----------------------------------------------------------------------------- | |
|
65 | 62 | # Globals |
|
63 | #----------------------------------------------------------------------------- | |
|
64 | ||
|
66 | 65 | |
|
67 | 66 | # store the builtin raw_input globally, and use this always, in case user code |
|
68 | 67 | # overwrites it (like wx.py.PyShell does) |
|
69 | 68 | raw_input_original = raw_input |
|
70 | 69 | |
|
71 | 70 | # compiled regexps for autoindent management |
|
72 | 71 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
73 | 72 | |
|
74 | 73 | |
|
75 | #**************************************************************************** | |
|
76 | # Some utility function definitions | |
|
74 | #----------------------------------------------------------------------------- | |
|
75 | # Utilities | |
|
76 | #----------------------------------------------------------------------------- | |
|
77 | ||
|
77 | 78 | |
|
78 | 79 | ini_spaces_re = re.compile(r'^(\s+)') |
|
79 | 80 | |
|
81 | ||
|
80 | 82 | def num_ini_spaces(strng): |
|
81 | 83 | """Return the number of initial spaces in a string""" |
|
82 | 84 | |
|
83 | 85 | ini_spaces = ini_spaces_re.match(strng) |
|
84 | 86 | if ini_spaces: |
|
85 | 87 | return ini_spaces.end() |
|
86 | 88 | else: |
|
87 | 89 | return 0 |
|
88 | 90 | |
|
91 | ||
|
89 | 92 | def softspace(file, newvalue): |
|
90 | 93 | """Copied from code.py, to remove the dependency""" |
|
91 | 94 | |
|
92 | 95 | oldvalue = 0 |
|
93 | 96 | try: |
|
94 | 97 | oldvalue = file.softspace |
|
95 | 98 | except AttributeError: |
|
96 | 99 | pass |
|
97 | 100 | try: |
|
98 | 101 | file.softspace = newvalue |
|
99 | 102 | except (AttributeError, TypeError): |
|
100 | 103 | # "attribute-less object" or "read-only attributes" |
|
101 | 104 | pass |
|
102 | 105 | return oldvalue |
|
103 | 106 | |
|
104 | 107 | |
|
105 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): | |
|
106 | """Install or upgrade the user configuration directory. | |
|
107 | ||
|
108 | Can be called when running for the first time or to upgrade the user's | |
|
109 | .ipython/ directory. | |
|
110 | ||
|
111 | Parameters | |
|
112 | ---------- | |
|
113 | ipythondir : path | |
|
114 | The directory to be used for installation/upgrade. In 'install' mode, | |
|
115 | if this path already exists, the function exits immediately. | |
|
116 | ||
|
117 | rc_suffix : str | |
|
118 | Extension for the config files. On *nix platforms it is typically the | |
|
119 | empty string, while Windows normally uses '.ini'. | |
|
120 | ||
|
121 | mode : str, optional | |
|
122 | Valid modes are 'install' and 'upgrade'. | |
|
123 | ||
|
124 | interactive : bool, optional | |
|
125 | If False, do not wait for user input on any errors. Normally after | |
|
126 | printing its status information, this function waits for the user to | |
|
127 | hit Return before proceeding. This is because the default use case is | |
|
128 | when first installing the IPython configuration, so we want the user to | |
|
129 | acknowledge the initial message, which contains some useful | |
|
130 | information. | |
|
131 | """ | |
|
132 | ||
|
133 | # For automatic use, deactivate all i/o | |
|
134 | if interactive: | |
|
135 | def wait(): | |
|
136 | try: | |
|
137 | raw_input("Please press <RETURN> to start IPython.") | |
|
138 | except EOFError: | |
|
139 | print >> Term.cout | |
|
140 | print '*'*70 | |
|
141 | ||
|
142 | def printf(s): | |
|
143 | print s | |
|
144 | else: | |
|
145 | wait = lambda : None | |
|
146 | printf = lambda s : None | |
|
147 | ||
|
148 | # Install mode should be re-entrant: if the install dir already exists, | |
|
149 | # bail out cleanly. | |
|
150 | # XXX. This is too hasty to return. We need to check to make sure that | |
|
151 | # all the expected config files and directories are actually there. We | |
|
152 | # currently have a failure mode if someone deletes a needed config file | |
|
153 | # but still has the ipythondir. | |
|
154 | if mode == 'install' and os.path.isdir(ipythondir): | |
|
155 | return | |
|
156 | ||
|
157 | cwd = os.getcwd() # remember where we started | |
|
158 | glb = glob.glob | |
|
159 | ||
|
160 | printf('*'*70) | |
|
161 | if mode == 'install': | |
|
162 | printf( | |
|
163 | """Welcome to IPython. I will try to create a personal configuration directory | |
|
164 | where you can customize many aspects of IPython's functionality in:\n""") | |
|
165 | else: | |
|
166 | printf('I am going to upgrade your configuration in:') | |
|
167 | ||
|
168 | printf(ipythondir) | |
|
169 | ||
|
170 | rcdirend = os.path.join('IPython','config','userconfig') | |
|
171 | cfg = lambda d: os.path.join(d,rcdirend) | |
|
172 | try: | |
|
173 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
|
174 | printf("Initializing from configuration: %s" % rcdir) | |
|
175 | except IndexError: | |
|
176 | warning = """ | |
|
177 | Installation error. IPython's directory was not found. | |
|
178 | ||
|
179 | Check the following: | |
|
180 | ||
|
181 | The ipython/IPython directory should be in a directory belonging to your | |
|
182 | PYTHONPATH environment variable (that is, it should be in a directory | |
|
183 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
|
184 | ||
|
185 | IPython will create a minimal default configuration for you. | |
|
186 | ||
|
187 | """ | |
|
188 | warn(warning) | |
|
189 | wait() | |
|
190 | ||
|
191 | if sys.platform =='win32': | |
|
192 | inif = 'ipythonrc.ini' | |
|
193 | else: | |
|
194 | inif = 'ipythonrc' | |
|
195 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
|
196 | inif : '# intentionally left blank' } | |
|
197 | os.makedirs(ipythondir, mode = 0777) | |
|
198 | for f, cont in minimal_setup.items(): | |
|
199 | # In 2.5, this can be more cleanly done using 'with' | |
|
200 | fobj = file(ipythondir + '/' + f,'w') | |
|
201 | fobj.write(cont) | |
|
202 | fobj.close() | |
|
203 | ||
|
204 | return | |
|
205 | ||
|
206 | if mode == 'install': | |
|
207 | try: | |
|
208 | shutil.copytree(rcdir,ipythondir) | |
|
209 | os.chdir(ipythondir) | |
|
210 | rc_files = glb("ipythonrc*") | |
|
211 | for rc_file in rc_files: | |
|
212 | os.rename(rc_file,rc_file+rc_suffix) | |
|
213 | except: | |
|
214 | warning = """ | |
|
215 | ||
|
216 | There was a problem with the installation: | |
|
217 | %s | |
|
218 | Try to correct it or contact the developers if you think it's a bug. | |
|
219 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
|
220 | warn(warning) | |
|
221 | wait() | |
|
222 | return | |
|
223 | ||
|
224 | elif mode == 'upgrade': | |
|
225 | try: | |
|
226 | os.chdir(ipythondir) | |
|
227 | except: | |
|
228 | printf(""" | |
|
229 | Can not upgrade: changing to directory %s failed. Details: | |
|
230 | %s | |
|
231 | """ % (ipythondir,sys.exc_info()[1]) ) | |
|
232 | wait() | |
|
233 | return | |
|
234 | else: | |
|
235 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
|
236 | for new_full_path in sources: | |
|
237 | new_filename = os.path.basename(new_full_path) | |
|
238 | if new_filename.startswith('ipythonrc'): | |
|
239 | new_filename = new_filename + rc_suffix | |
|
240 | # The config directory should only contain files, skip any | |
|
241 | # directories which may be there (like CVS) | |
|
242 | if os.path.isdir(new_full_path): | |
|
243 | continue | |
|
244 | if os.path.exists(new_filename): | |
|
245 | old_file = new_filename+'.old' | |
|
246 | if os.path.exists(old_file): | |
|
247 | os.remove(old_file) | |
|
248 | os.rename(new_filename,old_file) | |
|
249 | shutil.copy(new_full_path,new_filename) | |
|
250 | else: | |
|
251 | raise ValueError('unrecognized mode for install: %r' % mode) | |
|
252 | ||
|
253 | # Fix line-endings to those native to each platform in the config | |
|
254 | # directory. | |
|
255 | try: | |
|
256 | os.chdir(ipythondir) | |
|
257 | except: | |
|
258 | printf(""" | |
|
259 | Problem: changing to directory %s failed. | |
|
260 | Details: | |
|
261 | %s | |
|
262 | ||
|
263 | Some configuration files may have incorrect line endings. This should not | |
|
264 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) | |
|
265 | wait() | |
|
266 | else: | |
|
267 | for fname in glb('ipythonrc*'): | |
|
268 | try: | |
|
269 | native_line_ends(fname,backup=0) | |
|
270 | except IOError: | |
|
271 | pass | |
|
272 | ||
|
273 | if mode == 'install': | |
|
274 | printf(""" | |
|
275 | Successful installation! | |
|
276 | ||
|
277 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
|
278 | IPython manual (there are both HTML and PDF versions supplied with the | |
|
279 | distribution) to make sure that your system environment is properly configured | |
|
280 | to take advantage of IPython's features. | |
|
281 | ||
|
282 | Important note: the configuration system has changed! The old system is | |
|
283 | still in place, but its setting may be partly overridden by the settings in | |
|
284 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
|
285 | if some of the new settings bother you. | |
|
286 | ||
|
287 | """) | |
|
288 | else: | |
|
289 | printf(""" | |
|
290 | Successful upgrade! | |
|
291 | ||
|
292 | All files in your directory: | |
|
293 | %(ipythondir)s | |
|
294 | which would have been overwritten by the upgrade were backed up with a .old | |
|
295 | extension. If you had made particular customizations in those files you may | |
|
296 | want to merge them back into the new files.""" % locals() ) | |
|
297 | wait() | |
|
298 | os.chdir(cwd) | |
|
299 | ||
|
300 | #**************************************************************************** | |
|
301 | # Local use exceptions | |
|
302 | 108 | class SpaceInInput(exceptions.Exception): pass |
|
303 | 109 | |
|
304 | ||
|
305 | #**************************************************************************** | |
|
306 | # Local use classes | |
|
307 | 110 | class Bunch: pass |
|
308 | 111 | |
|
309 | 112 | class Undefined: pass |
|
310 | 113 | |
|
311 | 114 | class Quitter(object): |
|
312 | 115 | """Simple class to handle exit, similar to Python 2.5's. |
|
313 | 116 | |
|
314 | 117 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
315 | 118 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
316 | 119 | |
|
317 | 120 | def __init__(self,shell,name): |
|
318 | 121 | self.shell = shell |
|
319 | 122 | self.name = name |
|
320 | 123 | |
|
321 | 124 | def __repr__(self): |
|
322 | 125 | return 'Type %s() to exit.' % self.name |
|
323 | 126 | __str__ = __repr__ |
|
324 | 127 | |
|
325 | 128 | def __call__(self): |
|
326 | 129 | self.shell.exit() |
|
327 | 130 | |
|
328 | 131 | class InputList(list): |
|
329 | 132 | """Class to store user input. |
|
330 | 133 | |
|
331 | 134 | It's basically a list, but slices return a string instead of a list, thus |
|
332 | 135 | allowing things like (assuming 'In' is an instance): |
|
333 | 136 | |
|
334 | 137 | exec In[4:7] |
|
335 | 138 | |
|
336 | 139 | or |
|
337 | 140 | |
|
338 | 141 | exec In[5:9] + In[14] + In[21:25]""" |
|
339 | 142 | |
|
340 | 143 | def __getslice__(self,i,j): |
|
341 | 144 | return ''.join(list.__getslice__(self,i,j)) |
|
342 | 145 | |
|
343 | 146 | class SyntaxTB(ultratb.ListTB): |
|
344 | 147 | """Extension which holds some state: the last exception value""" |
|
345 | 148 | |
|
346 | 149 | def __init__(self,color_scheme = 'NoColor'): |
|
347 | 150 | ultratb.ListTB.__init__(self,color_scheme) |
|
348 | 151 | self.last_syntax_error = None |
|
349 | 152 | |
|
350 | 153 | def __call__(self, etype, value, elist): |
|
351 | 154 | self.last_syntax_error = value |
|
352 | 155 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
353 | 156 | |
|
354 | 157 | def clear_err_state(self): |
|
355 | 158 | """Return the current error state and clear it""" |
|
356 | 159 | e = self.last_syntax_error |
|
357 | 160 | self.last_syntax_error = None |
|
358 | 161 | return e |
|
359 | 162 | |
|
360 | #**************************************************************************** | |
|
163 | ||
|
164 | #----------------------------------------------------------------------------- | |
|
361 | 165 | # Main IPython class |
|
166 | #----------------------------------------------------------------------------- | |
|
362 | 167 | |
|
363 | 168 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
364 | 169 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
365 | 170 | # attributes and methods, but too much user code out there relies on the |
|
366 | 171 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
367 | 172 | # |
|
368 | 173 | # But at least now, all the pieces have been separated and we could, in |
|
369 | 174 | # principle, stop using the mixin. This will ease the transition to the |
|
370 | 175 | # chainsaw branch. |
|
371 | 176 | |
|
372 | 177 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
373 | 178 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
374 | 179 | # class, to prevent clashes. |
|
375 | 180 | |
|
376 | 181 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
377 | 182 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
378 | 183 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
379 | 184 | # 'self.value'] |
|
380 | 185 | |
|
381 |
class InteractiveShell( |
|
|
186 | class InteractiveShell(Component, Magic): | |
|
382 | 187 | """An enhanced console for Python.""" |
|
383 | 188 | |
|
189 | alias = [] | |
|
190 | autocall = Bool(True) | |
|
191 | autoedit_syntax = Bool(False) | |
|
192 | autoindent = Bool(False) | |
|
193 | automagic = Bool(True) | |
|
194 | autoexec = [] | |
|
195 | display_banner = Bool(True) | |
|
196 | banner = Str('') | |
|
197 | c = Str('') | |
|
198 | cache_size = Int(1000) | |
|
199 | classic = Bool(False) | |
|
200 | color_info = Int(0) | |
|
201 | colors = Str('LightBG') | |
|
202 | confirm_exit = Bool(True) | |
|
203 | debug = Bool(False) | |
|
204 | deep_reload = Bool(False) | |
|
205 | embedded = Bool(False) | |
|
206 | editor = Str('0') | |
|
207 | filename = Str("<ipython console>") | |
|
208 | help = Bool(False) | |
|
209 | interactive = Bool(False) | |
|
210 | logstart = Bool(False, config_key='LOGSTART') | |
|
211 | logfile = Str('') | |
|
212 | logplay = Str('') | |
|
213 | messages = Bool(True) | |
|
214 | multi_line_specials = Bool(True) | |
|
215 | nosep = Bool(False) | |
|
216 | object_info_string_level = Int(0) | |
|
217 | pager = Str('less') | |
|
218 | pdb = Bool(False) | |
|
219 | pprint = Bool(True) | |
|
220 | profile = Str('') | |
|
221 | prompt_in1 = Str('In [\\#]: ') | |
|
222 | prompt_in2 = Str(' .\\D.: ') | |
|
223 | prompt_out = Str('Out[\\#]: ') | |
|
224 | prompts_pad_left = Bool(True) | |
|
225 | pydb = Bool(False) | |
|
226 | quick = Bool(False) | |
|
227 | quiet = Bool(False) | |
|
228 | ||
|
229 | readline_use = Bool(True) | |
|
230 | readline_merge_completions = Bool(True) | |
|
231 | readline_omit__names = Int(0) | |
|
232 | readline_remove_delims = '-/~' | |
|
233 | readline_parse_and_bind = [ | |
|
234 | 'tab: complete', | |
|
235 | '"\C-l": possible-completions', | |
|
236 | 'set show-all-if-ambiguous on', | |
|
237 | '"\C-o": tab-insert', | |
|
238 | '"\M-i": " "', | |
|
239 | '"\M-o": "\d\d\d\d"', | |
|
240 | '"\M-I": "\d\d\d\d"', | |
|
241 | '"\C-r": reverse-search-history', | |
|
242 | '"\C-s": forward-search-history', | |
|
243 | '"\C-p": history-search-backward', | |
|
244 | '"\C-n": history-search-forward', | |
|
245 | '"\e[A": history-search-backward', | |
|
246 | '"\e[B": history-search-forward', | |
|
247 | '"\C-k": kill-line', | |
|
248 | '"\C-u": unix-line-discard', | |
|
249 | ] | |
|
250 | ||
|
251 | screen_length = Int(0) | |
|
252 | separate_in = Str('\n') | |
|
253 | separate_out = Str('') | |
|
254 | separate_out2 = Str('') | |
|
255 | system_header = Str('IPython system call: ') | |
|
256 | system_verbose = Bool(False) | |
|
257 | term_title = Bool(True) | |
|
258 | wildcards_case_sensitive = Bool(True) | |
|
259 | xmode = Str('Context') | |
|
260 | magic_docstrings = Bool(False) | |
|
261 | ||
|
384 | 262 | # class attribute to indicate whether the class supports threads or not. |
|
385 | 263 | # Subclasses with thread support should override this as needed. |
|
386 | 264 | isthreaded = False |
|
387 | 265 | |
|
388 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
|
389 | user_ns=None,user_global_ns=None,banner2='', | |
|
390 | custom_exceptions=((),None),embedded=False): | |
|
266 | def __init__(self, name, parent=None, config=None, usage=None, | |
|
267 | user_ns=None, user_global_ns=None, banner2='', | |
|
268 | custom_exceptions=((),None), embedded=False): | |
|
391 | 269 | |
|
392 | # log system | |
|
393 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
|
394 | ||
|
395 | # Job manager (for jobs run as background threads) | |
|
396 | self.jobs = BackgroundJobManager() | |
|
270 | super(InteractiveShell, self).__init__(parent, config=config, name=name) | |
|
397 | 271 | |
|
398 | # Store the actual shell's name | |
|
399 |
self. |
|
|
400 | self.more = False | |
|
272 | self.init_instance_attrs() | |
|
273 | self.init_usage(usage) | |
|
274 | self.init_banner(banner2) | |
|
275 | self.init_embedded(embedded) | |
|
276 | self.init_create_namespaces(user_ns, user_global_ns) | |
|
277 | self.init_history() | |
|
278 | self.init_encoding() | |
|
279 | self.init_handlers() | |
|
401 | 280 | |
|
402 | # We need to know whether the instance is meant for embedding, since | |
|
403 | # global/local namespaces need to be handled differently in that case | |
|
404 | self.embedded = embedded | |
|
405 | if embedded: | |
|
406 | # Control variable so users can, from within the embedded instance, | |
|
407 | # permanently deactivate it. | |
|
408 | self.embedded_active = True | |
|
281 | Magic.__init__(self, self) | |
|
282 | ||
|
283 | self.init_syntax_highlighting() | |
|
284 | self.init_hooks() | |
|
285 | self.init_pushd_popd_magic() | |
|
286 | self.init_traceback_handlers(custom_exceptions) | |
|
287 | ||
|
288 | # Produce a public API instance | |
|
289 | self.api = ipapi.IPApi(self) | |
|
290 | ||
|
291 | self.init_namespaces() | |
|
292 | self.init_logger() | |
|
293 | self.init_aliases() | |
|
294 | self.init_builtins() | |
|
295 | self.init_shadow_hist() | |
|
296 | self.init_logstart() | |
|
297 | self.post_config_initialization() | |
|
298 | ||
|
299 | def init_instance_attrs(self): | |
|
300 | self.jobs = BackgroundJobManager() | |
|
301 | self.more = False | |
|
409 | 302 | |
|
410 | 303 | # command compiler |
|
411 | 304 | self.compile = codeop.CommandCompiler() |
|
412 | 305 | |
|
413 | 306 | # User input buffer |
|
414 | 307 | self.buffer = [] |
|
415 | 308 | |
|
416 | # Default name given in compilation of code | |
|
417 | self.filename = '<ipython console>' | |
|
418 | ||
|
419 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
|
420 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
|
421 | __builtin__.exit = Quitter(self,'exit') | |
|
422 | __builtin__.quit = Quitter(self,'quit') | |
|
423 | ||
|
424 | 309 | # Make an empty namespace, which extension writers can rely on both |
|
425 | 310 | # existing and NEVER being used by ipython itself. This gives them a |
|
426 | 311 | # convenient location for storing additional information and state |
|
427 | 312 | # their extensions may require, without fear of collisions with other |
|
428 | 313 | # ipython names that may develop later. |
|
429 | 314 | self.meta = Struct() |
|
430 | 315 | |
|
316 | # Object variable to store code object waiting execution. This is | |
|
317 | # used mainly by the multithreaded shells, but it can come in handy in | |
|
318 | # other situations. No need to use a Queue here, since it's a single | |
|
319 | # item which gets cleared once run. | |
|
320 | self.code_to_run = None | |
|
321 | ||
|
322 | # Flag to mark unconditional exit | |
|
323 | self.exit_now = False | |
|
324 | ||
|
325 | # Temporary files used for various purposes. Deleted at exit. | |
|
326 | self.tempfiles = [] | |
|
327 | ||
|
328 | # Keep track of readline usage (later set by init_readline) | |
|
329 | self.has_readline = False | |
|
330 | ||
|
331 | # keep track of where we started running (mainly for crash post-mortem) | |
|
332 | # This is not being used anywhere currently. | |
|
333 | self.starting_dir = os.getcwd() | |
|
334 | ||
|
335 | # Indentation management | |
|
336 | self.indent_current_nsp = 0 | |
|
337 | ||
|
338 | def init_usage(self, usage=None): | |
|
339 | if usage is None: | |
|
340 | self.usage = interactive_usage | |
|
341 | else: | |
|
342 | self.usage = usage | |
|
343 | ||
|
344 | def init_banner(self, banner2): | |
|
345 | if self.c: # regular python doesn't print the banner with -c | |
|
346 | self.display_banner = False | |
|
347 | bp = banner_parts | |
|
348 | if self.profile: | |
|
349 | bp.append('IPython profile: %s\n' % self.profile) | |
|
350 | if banner2 is not None: | |
|
351 | bp.append(banner2) | |
|
352 | self.banner = '\n'.join(bp) | |
|
353 | ||
|
354 | def init_embedded(self, embedded): | |
|
355 | # We need to know whether the instance is meant for embedding, since | |
|
356 | # global/local namespaces need to be handled differently in that case | |
|
357 | self.embedded = embedded | |
|
358 | if embedded: | |
|
359 | # Control variable so users can, from within the embedded instance, | |
|
360 | # permanently deactivate it. | |
|
361 | self.embedded_active = True | |
|
362 | ||
|
363 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
|
431 | 364 | # Create the namespace where the user will operate. user_ns is |
|
432 | 365 | # normally the only one used, and it is passed to the exec calls as |
|
433 | 366 | # the locals argument. But we do carry a user_global_ns namespace |
|
434 | 367 | # given as the exec 'globals' argument, This is useful in embedding |
|
435 | 368 | # situations where the ipython shell opens in a context where the |
|
436 | 369 | # distinction between locals and globals is meaningful. For |
|
437 | 370 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
438 | 371 | |
|
439 | 372 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
440 | 373 | # level as a dict instead of a module. This is a manual fix, but I |
|
441 | 374 | # should really track down where the problem is coming from. Alex |
|
442 | 375 | # Schmolck reported this problem first. |
|
443 | 376 | |
|
444 | 377 | # A useful post by Alex Martelli on this topic: |
|
445 | 378 | # Re: inconsistent value from __builtins__ |
|
446 | 379 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
447 | 380 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
448 | 381 | # Gruppen: comp.lang.python |
|
449 | 382 | |
|
450 | 383 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
451 | 384 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
452 | 385 | # > <type 'dict'> |
|
453 | 386 | # > >>> print type(__builtins__) |
|
454 | 387 | # > <type 'module'> |
|
455 | 388 | # > Is this difference in return value intentional? |
|
456 | 389 | |
|
457 | 390 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
458 | 391 | # or a module, and it's been that way for a long time. Whether it's |
|
459 | 392 | # intentional (or sensible), I don't know. In any case, the idea is |
|
460 | 393 | # that if you need to access the built-in namespace directly, you |
|
461 | 394 | # should start with "import __builtin__" (note, no 's') which will |
|
462 | 395 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
463 | 396 | |
|
464 | 397 | # These routines return properly built dicts as needed by the rest of |
|
465 | 398 | # the code, and can also be used by extension writers to generate |
|
466 | 399 | # properly initialized namespaces. |
|
467 | 400 | user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns, |
|
468 | 401 | user_global_ns) |
|
469 | 402 | |
|
470 | 403 | # Assign namespaces |
|
471 | 404 | # This is the namespace where all normal user variables live |
|
472 | 405 | self.user_ns = user_ns |
|
473 | 406 | self.user_global_ns = user_global_ns |
|
474 | 407 | |
|
475 | 408 | # An auxiliary namespace that checks what parts of the user_ns were |
|
476 | 409 | # loaded at startup, so we can list later only variables defined in |
|
477 | 410 | # actual interactive use. Since it is always a subset of user_ns, it |
|
478 | 411 | # doesn't need to be seaparately tracked in the ns_table |
|
479 | 412 | self.user_config_ns = {} |
|
480 | 413 | |
|
481 | 414 | # A namespace to keep track of internal data structures to prevent |
|
482 | 415 | # them from cluttering user-visible stuff. Will be updated later |
|
483 | 416 | self.internal_ns = {} |
|
484 | 417 | |
|
485 | 418 | # Namespace of system aliases. Each entry in the alias |
|
486 | 419 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
487 | 420 | # of positional arguments of the alias. |
|
488 | 421 | self.alias_table = {} |
|
489 | 422 | |
|
490 | 423 | # Now that FakeModule produces a real module, we've run into a nasty |
|
491 | 424 | # problem: after script execution (via %run), the module where the user |
|
492 | 425 | # code ran is deleted. Now that this object is a true module (needed |
|
493 | 426 | # so docetst and other tools work correctly), the Python module |
|
494 | 427 | # teardown mechanism runs over it, and sets to None every variable |
|
495 | 428 | # present in that module. Top-level references to objects from the |
|
496 | 429 | # script survive, because the user_ns is updated with them. However, |
|
497 | 430 | # calling functions defined in the script that use other things from |
|
498 | 431 | # the script will fail, because the function's closure had references |
|
499 | 432 | # to the original objects, which are now all None. So we must protect |
|
500 | 433 | # these modules from deletion by keeping a cache. |
|
501 | 434 | # |
|
502 | 435 | # To avoid keeping stale modules around (we only need the one from the |
|
503 | 436 | # last run), we use a dict keyed with the full path to the script, so |
|
504 | 437 | # only the last version of the module is held in the cache. Note, |
|
505 | 438 | # however, that we must cache the module *namespace contents* (their |
|
506 | 439 | # __dict__). Because if we try to cache the actual modules, old ones |
|
507 | 440 | # (uncached) could be destroyed while still holding references (such as |
|
508 | 441 | # those held by GUI objects that tend to be long-lived)> |
|
509 | 442 | # |
|
510 | 443 | # The %reset command will flush this cache. See the cache_main_mod() |
|
511 | 444 | # and clear_main_mod_cache() methods for details on use. |
|
512 | 445 | |
|
513 | 446 | # This is the cache used for 'main' namespaces |
|
514 | 447 | self._main_ns_cache = {} |
|
515 | 448 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
516 | 449 | # copying and clearing for reuse on each %run |
|
517 | 450 | self._user_main_module = FakeModule() |
|
518 | 451 | |
|
519 | 452 | # A table holding all the namespaces IPython deals with, so that |
|
520 | 453 | # introspection facilities can search easily. |
|
521 | 454 | self.ns_table = {'user':user_ns, |
|
522 | 455 | 'user_global':user_global_ns, |
|
523 | 456 | 'alias':self.alias_table, |
|
524 | 457 | 'internal':self.internal_ns, |
|
525 | 458 | 'builtin':__builtin__.__dict__ |
|
526 | 459 | } |
|
527 | 460 | |
|
528 | 461 | # Similarly, track all namespaces where references can be held and that |
|
529 | 462 | # we can safely clear (so it can NOT include builtin). This one can be |
|
530 | 463 | # a simple list. |
|
531 | 464 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
532 | 465 | self.alias_table, self.internal_ns, |
|
533 | 466 | self._main_ns_cache ] |
|
534 | 467 | |
|
535 | 468 | # We need to insert into sys.modules something that looks like a |
|
536 | 469 | # module but which accesses the IPython namespace, for shelve and |
|
537 | 470 | # pickle to work interactively. Normally they rely on getting |
|
538 | 471 | # everything out of __main__, but for embedding purposes each IPython |
|
539 | 472 | # instance has its own private namespace, so we can't go shoving |
|
540 | 473 | # everything into __main__. |
|
541 | 474 | |
|
542 | 475 | # note, however, that we should only do this for non-embedded |
|
543 | 476 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
544 | 477 | # namespace. Embedded instances, on the other hand, should not do |
|
545 | 478 | # this because they need to manage the user local/global namespaces |
|
546 | 479 | # only, but they live within a 'normal' __main__ (meaning, they |
|
547 | 480 | # shouldn't overtake the execution environment of the script they're |
|
548 | 481 | # embedded in). |
|
549 | 482 | |
|
550 | if not embedded: | |
|
483 | if not self.embedded: | |
|
551 | 484 | try: |
|
552 | 485 | main_name = self.user_ns['__name__'] |
|
553 | 486 | except KeyError: |
|
554 | 487 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
555 | 488 | else: |
|
556 | #print "pickle hack in place" # dbg | |
|
557 | #print 'main_name:',main_name # dbg | |
|
558 | 489 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
559 | ||
|
490 | ||
|
491 | def init_history(self): | |
|
560 | 492 | # List of input with multi-line handling. |
|
561 | 493 | self.input_hist = InputList() |
|
562 | 494 | # This one will hold the 'raw' input history, without any |
|
563 | 495 | # pre-processing. This will allow users to retrieve the input just as |
|
564 | 496 | # it was exactly typed in by the user, with %hist -r. |
|
565 | 497 | self.input_hist_raw = InputList() |
|
566 | 498 | |
|
567 | 499 | # list of visited directories |
|
568 | 500 | try: |
|
569 | 501 | self.dir_hist = [os.getcwd()] |
|
570 | 502 | except OSError: |
|
571 | 503 | self.dir_hist = [] |
|
572 | 504 | |
|
573 | 505 | # dict of output history |
|
574 | 506 | self.output_hist = {} |
|
575 | 507 | |
|
508 | # Now the history file | |
|
509 | try: | |
|
510 | histfname = 'history-%s' % self.config.PROFILE | |
|
511 | except AttributeError: | |
|
512 | histfname = 'history' | |
|
513 | self.histfile = os.path.join(self.config.IPYTHONDIR, histfname) | |
|
514 | ||
|
515 | def init_encoding(self): | |
|
576 | 516 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
577 | 517 | # under Win32 have it set to None, and we need to have a known valid |
|
578 | 518 | # encoding to use in the raw_input() method |
|
579 | 519 | try: |
|
580 | 520 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
581 | 521 | except AttributeError: |
|
582 | 522 | self.stdin_encoding = 'ascii' |
|
583 | 523 | |
|
584 | # dict of things NOT to alias (keywords, builtins and some magics) | |
|
585 | no_alias = {} | |
|
586 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
|
587 | for key in keyword.kwlist + no_alias_magics: | |
|
588 | no_alias[key] = 1 | |
|
589 | no_alias.update(__builtin__.__dict__) | |
|
590 | self.no_alias = no_alias | |
|
591 | ||
|
592 | # Object variable to store code object waiting execution. This is | |
|
593 | # used mainly by the multithreaded shells, but it can come in handy in | |
|
594 | # other situations. No need to use a Queue here, since it's a single | |
|
595 | # item which gets cleared once run. | |
|
596 | self.code_to_run = None | |
|
597 | ||
|
524 | def init_handlers(self): | |
|
598 | 525 | # escapes for automatic behavior on the command line |
|
599 | 526 | self.ESC_SHELL = '!' |
|
600 | 527 | self.ESC_SH_CAP = '!!' |
|
601 | 528 | self.ESC_HELP = '?' |
|
602 | 529 | self.ESC_MAGIC = '%' |
|
603 | 530 | self.ESC_QUOTE = ',' |
|
604 | 531 | self.ESC_QUOTE2 = ';' |
|
605 | 532 | self.ESC_PAREN = '/' |
|
606 | 533 | |
|
607 | 534 | # And their associated handlers |
|
608 | 535 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
609 | 536 | self.ESC_QUOTE : self.handle_auto, |
|
610 | 537 | self.ESC_QUOTE2 : self.handle_auto, |
|
611 | 538 | self.ESC_MAGIC : self.handle_magic, |
|
612 | 539 | self.ESC_HELP : self.handle_help, |
|
613 | 540 | self.ESC_SHELL : self.handle_shell_escape, |
|
614 | 541 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
615 | 542 | } |
|
616 | 543 | |
|
617 | # class initializations | |
|
618 | Magic.__init__(self,self) | |
|
619 | ||
|
544 | def init_syntax_highlighting(self): | |
|
620 | 545 | # Python source parser/formatter for syntax highlighting |
|
621 | 546 | pyformat = PyColorize.Parser().format |
|
622 |
self.pycolorize = lambda src: pyformat(src,'str',self. |
|
|
547 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
|
623 | 548 | |
|
549 | def init_hooks(self): | |
|
624 | 550 | # hooks holds pointers used for user-side customizations |
|
625 | 551 | self.hooks = Struct() |
|
626 | 552 | |
|
627 | 553 | self.strdispatchers = {} |
|
628 | 554 | |
|
629 | 555 | # Set all default hooks, defined in the IPython.hooks module. |
|
630 | 556 | import IPython.core.hooks |
|
631 | 557 | hooks = IPython.core.hooks |
|
632 | 558 | for hook_name in hooks.__all__: |
|
633 | 559 | # default hooks have priority 100, i.e. low; user hooks should have |
|
634 | 560 | # 0-100 priority |
|
635 | 561 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
636 | #print "bound hook",hook_name | |
|
637 | ||
|
638 | # Flag to mark unconditional exit | |
|
639 | self.exit_now = False | |
|
640 | ||
|
641 | self.usage_min = """\ | |
|
642 | An enhanced console for Python. | |
|
643 | Some of its features are: | |
|
644 | - Readline support if the readline library is present. | |
|
645 | - Tab completion in the local namespace. | |
|
646 | - Logging of input, see command-line options. | |
|
647 | - System shell escape via ! , eg !ls. | |
|
648 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
|
649 | - Keeps track of locally defined variables via %who, %whos. | |
|
650 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
|
651 | """ | |
|
652 | if usage: self.usage = usage | |
|
653 | else: self.usage = self.usage_min | |
|
654 | ||
|
655 | # Storage | |
|
656 | self.rc = rc # This will hold all configuration information | |
|
657 | self.pager = 'less' | |
|
658 | # temporary files used for various purposes. Deleted at exit. | |
|
659 | self.tempfiles = [] | |
|
660 | 562 | |
|
661 | # Keep track of readline usage (later set by init_readline) | |
|
662 | self.has_readline = False | |
|
663 | ||
|
664 | # template for logfile headers. It gets resolved at runtime by the | |
|
665 | # logstart method. | |
|
666 | self.loghead_tpl = \ | |
|
667 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
|
668 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
|
669 | #log# opts = %s | |
|
670 | #log# args = %s | |
|
671 | #log# It is safe to make manual edits below here. | |
|
672 | #log#----------------------------------------------------------------------- | |
|
673 | """ | |
|
563 | def init_pushd_popd_magic(self): | |
|
674 | 564 | # for pushd/popd management |
|
675 | 565 | try: |
|
676 | 566 | self.home_dir = get_home_dir() |
|
677 | except HomeDirError,msg: | |
|
567 | except HomeDirError, msg: | |
|
678 | 568 | fatal(msg) |
|
679 | 569 | |
|
680 | 570 | self.dir_stack = [] |
|
681 | 571 | |
|
682 | # Functions to call the underlying shell. | |
|
683 | ||
|
684 | # The first is similar to os.system, but it doesn't return a value, | |
|
685 | # and it allows interpolation of variables in the user's namespace. | |
|
686 | self.system = lambda cmd: \ | |
|
687 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
|
688 | ||
|
689 | # These are for getoutput and getoutputerror: | |
|
690 | self.getoutput = lambda cmd: \ | |
|
691 | getoutput(self.var_expand(cmd,depth=2), | |
|
692 | header=self.rc.system_header, | |
|
693 | verbose=self.rc.system_verbose) | |
|
694 | ||
|
695 | self.getoutputerror = lambda cmd: \ | |
|
696 | getoutputerror(self.var_expand(cmd,depth=2), | |
|
697 | header=self.rc.system_header, | |
|
698 | verbose=self.rc.system_verbose) | |
|
699 | ||
|
700 | ||
|
701 | # keep track of where we started running (mainly for crash post-mortem) | |
|
702 | self.starting_dir = os.getcwd() | |
|
703 | ||
|
704 | # Various switches which can be set | |
|
705 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
|
706 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
|
707 | self.banner2 = banner2 | |
|
708 | ||
|
709 | # TraceBack handlers: | |
|
710 | ||
|
572 | def init_traceback_handlers(self, custom_exceptions): | |
|
711 | 573 | # Syntax error handler. |
|
712 | 574 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
713 | 575 | |
|
714 | 576 | # The interactive one is initialized with an offset, meaning we always |
|
715 | 577 | # want to remove the topmost item in the traceback, which is our own |
|
716 | 578 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
717 | 579 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
718 | 580 | color_scheme='NoColor', |
|
719 | 581 | tb_offset = 1) |
|
720 | 582 | |
|
721 | 583 | # IPython itself shouldn't crash. This will produce a detailed |
|
722 | 584 | # post-mortem if it does. But we only install the crash handler for |
|
723 | 585 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
724 | 586 | # and lose the crash handler. This is because exceptions in the main |
|
725 | 587 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
726 | 588 | # and there's no point in printing crash dumps for every user exception. |
|
727 | 589 | if self.isthreaded: |
|
728 | 590 | ipCrashHandler = ultratb.FormattedTB() |
|
729 | 591 | else: |
|
730 | 592 | from IPython.core import crashhandler |
|
731 | 593 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
732 | 594 | self.set_crash_handler(ipCrashHandler) |
|
733 | 595 | |
|
734 | 596 | # and add any custom exception handlers the user may have specified |
|
735 | 597 | self.set_custom_exc(*custom_exceptions) |
|
736 | 598 | |
|
737 | # indentation management | |
|
738 | self.autoindent = False | |
|
739 | self.indent_current_nsp = 0 | |
|
599 | def init_logger(self): | |
|
600 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
|
601 | # local shortcut, this is used a LOT | |
|
602 | self.log = self.logger.log | |
|
603 | # template for logfile headers. It gets resolved at runtime by the | |
|
604 | # logstart method. | |
|
605 | self.loghead_tpl = \ | |
|
606 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
|
607 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
|
608 | #log# opts = %s | |
|
609 | #log# args = %s | |
|
610 | #log# It is safe to make manual edits below here. | |
|
611 | #log#----------------------------------------------------------------------- | |
|
612 | """ | |
|
613 | ||
|
614 | def init_logstart(self): | |
|
615 | if self.logplay: | |
|
616 | IP.magic_logstart(self.logplay + ' append') | |
|
617 | elif self.logfile: | |
|
618 | IP.magic_logstart(self.logfile) | |
|
619 | elif self.logstart: | |
|
620 | self.magic_logstart() | |
|
621 | ||
|
622 | def init_aliases(self): | |
|
623 | # dict of things NOT to alias (keywords, builtins and some magics) | |
|
624 | no_alias = {} | |
|
625 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
|
626 | for key in keyword.kwlist + no_alias_magics: | |
|
627 | no_alias[key] = 1 | |
|
628 | no_alias.update(__builtin__.__dict__) | |
|
629 | self.no_alias = no_alias | |
|
740 | 630 | |
|
741 | 631 | # Make some aliases automatically |
|
742 | 632 | # Prepare list of shell aliases to auto-define |
|
743 | 633 | if os.name == 'posix': |
|
744 | 634 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
745 | 635 | 'mv mv -i','rm rm -i','cp cp -i', |
|
746 | 636 | 'cat cat','less less','clear clear', |
|
747 | 637 | # a better ls |
|
748 | 638 | 'ls ls -F', |
|
749 | 639 | # long ls |
|
750 | 640 | 'll ls -lF') |
|
751 | 641 | # Extra ls aliases with color, which need special treatment on BSD |
|
752 | 642 | # variants |
|
753 | 643 | ls_extra = ( # color ls |
|
754 | 644 | 'lc ls -F -o --color', |
|
755 | 645 | # ls normal files only |
|
756 | 646 | 'lf ls -F -o --color %l | grep ^-', |
|
757 | 647 | # ls symbolic links |
|
758 | 648 | 'lk ls -F -o --color %l | grep ^l', |
|
759 | 649 | # directories or links to directories, |
|
760 | 650 | 'ldir ls -F -o --color %l | grep /$', |
|
761 | 651 | # things which are executable |
|
762 | 652 | 'lx ls -F -o --color %l | grep ^-..x', |
|
763 | 653 | ) |
|
764 | 654 | # The BSDs don't ship GNU ls, so they don't understand the |
|
765 | 655 | # --color switch out of the box |
|
766 | 656 | if 'bsd' in sys.platform: |
|
767 | 657 | ls_extra = ( # ls normal files only |
|
768 | 658 | 'lf ls -lF | grep ^-', |
|
769 | 659 | # ls symbolic links |
|
770 | 660 | 'lk ls -lF | grep ^l', |
|
771 | 661 | # directories or links to directories, |
|
772 | 662 | 'ldir ls -lF | grep /$', |
|
773 | 663 | # things which are executable |
|
774 | 664 | 'lx ls -lF | grep ^-..x', |
|
775 | 665 | ) |
|
776 | 666 | auto_alias = auto_alias + ls_extra |
|
777 | 667 | elif os.name in ['nt','dos']: |
|
778 | 668 | auto_alias = ('ls dir /on', |
|
779 | 669 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
780 | 670 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
781 | 671 | 'ren ren','cls cls','copy copy') |
|
782 | 672 | else: |
|
783 | 673 | auto_alias = () |
|
784 | 674 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
785 | 675 | |
|
786 | # Produce a public API instance | |
|
787 | self.api = ipapi.IPApi(self) | |
|
676 | # Load default aliases | |
|
677 | for alias, cmd in self.auto_alias: | |
|
678 | self.define_alias(alias,cmd) | |
|
788 | 679 | |
|
789 | # Initialize all user-visible namespaces | |
|
790 | self.init_namespaces() | |
|
791 | ||
|
792 | # Call the actual (public) initializer | |
|
793 | self.init_auto_alias() | |
|
680 | # Load user aliases | |
|
681 | for alias in self.alias: | |
|
682 | self.magic_alias(alias) | |
|
794 | 683 | |
|
684 | def init_builtins(self): | |
|
795 | 685 | # track which builtins we add, so we can clean up later |
|
796 | 686 | self.builtins_added = {} |
|
797 | 687 | # This method will add the necessary builtins for operation, but |
|
798 | 688 | # tracking what it did via the builtins_added dict. |
|
799 | 689 | |
|
800 | 690 | #TODO: remove this, redundant |
|
801 | 691 | self.add_builtins() |
|
802 | # end __init__ | |
|
803 | 692 | |
|
804 | def var_expand(self,cmd,depth=0): | |
|
805 | """Expand python variables in a string. | |
|
806 | ||
|
807 | The depth argument indicates how many frames above the caller should | |
|
808 | be walked to look for the local namespace where to expand variables. | |
|
809 | ||
|
810 | The global namespace for expansion is always the user's interactive | |
|
811 | namespace. | |
|
812 | """ | |
|
813 | ||
|
814 | return str(ItplNS(cmd, | |
|
815 | self.user_ns, # globals | |
|
816 | # Skip our own frame in searching for locals: | |
|
817 | sys._getframe(depth+1).f_locals # locals | |
|
818 | )) | |
|
819 | ||
|
820 | def pre_config_initialization(self): | |
|
821 | """Pre-configuration init method | |
|
822 | ||
|
823 | This is called before the configuration files are processed to | |
|
824 | prepare the services the config files might need. | |
|
825 | ||
|
826 | self.rc already has reasonable default values at this point. | |
|
827 | """ | |
|
828 | rc = self.rc | |
|
693 | def init_shadow_hist(self): | |
|
829 | 694 | try: |
|
830 |
self.db = pickleshare.PickleShareDB( |
|
|
695 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") | |
|
831 | 696 | except exceptions.UnicodeDecodeError: |
|
832 | 697 | print "Your ipythondir can't be decoded to unicode!" |
|
833 | 698 | print "Please set HOME environment variable to something that" |
|
834 | 699 | print r"only has ASCII characters, e.g. c:\home" |
|
835 |
print "Now it is", |
|
|
700 | print "Now it is", self.config.IPYTHONDIR | |
|
836 | 701 | sys.exit() |
|
837 |
self.shadowhist = |
|
|
702 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
|
838 | 703 | |
|
839 | 704 | def post_config_initialization(self): |
|
840 | 705 | """Post configuration init method |
|
841 | 706 | |
|
842 | 707 | This is called after the configuration files have been processed to |
|
843 | 708 | 'finalize' the initialization.""" |
|
844 | 709 | |
|
845 | rc = self.rc | |
|
846 | ||
|
847 | 710 | # Object inspector |
|
848 | 711 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
849 | 712 | PyColorize.ANSICodeColors, |
|
850 | 713 | 'NoColor', |
|
851 |
|
|
|
714 | self.object_info_string_level) | |
|
852 | 715 | |
|
853 | 716 | self.rl_next_input = None |
|
854 | 717 | self.rl_do_indent = False |
|
855 | 718 | # Load readline proper |
|
856 |
if |
|
|
719 | if self.readline_use: | |
|
857 | 720 | self.init_readline() |
|
858 | ||
|
859 | # local shortcut, this is used a LOT | |
|
860 | self.log = self.logger.log | |
|
861 | 721 | |
|
862 | 722 | # Initialize cache, set in/out prompts and printing system |
|
863 | 723 | self.outputcache = CachedOutput(self, |
|
864 |
|
|
|
865 |
|
|
|
866 |
input_sep = |
|
|
867 |
output_sep = |
|
|
868 |
output_sep2 = |
|
|
869 |
ps1 = |
|
|
870 |
ps2 = |
|
|
871 |
ps_out = |
|
|
872 |
pad_left = |
|
|
724 | self.cache_size, | |
|
725 | self.pprint, | |
|
726 | input_sep = self.separate_in, | |
|
727 | output_sep = self.separate_out, | |
|
728 | output_sep2 = self.separate_out2, | |
|
729 | ps1 = self.prompt_in1, | |
|
730 | ps2 = self.prompt_in2, | |
|
731 | ps_out = self.prompt_out, | |
|
732 | pad_left = self.prompts_pad_left) | |
|
873 | 733 | |
|
874 | 734 | # user may have over-ridden the default print hook: |
|
875 | 735 | try: |
|
876 | 736 | self.outputcache.__class__.display = self.hooks.display |
|
877 | 737 | except AttributeError: |
|
878 | 738 | pass |
|
879 | 739 | |
|
880 | 740 | # I don't like assigning globally to sys, because it means when |
|
881 | 741 | # embedding instances, each embedded instance overrides the previous |
|
882 | 742 | # choice. But sys.displayhook seems to be called internally by exec, |
|
883 | 743 | # so I don't see a way around it. We first save the original and then |
|
884 | 744 | # overwrite it. |
|
885 | 745 | self.sys_displayhook = sys.displayhook |
|
886 | 746 | sys.displayhook = self.outputcache |
|
887 | 747 | |
|
888 | 748 | # Do a proper resetting of doctest, including the necessary displayhook |
|
889 | 749 | # monkeypatching |
|
890 | 750 | try: |
|
891 | 751 | doctest_reload() |
|
892 | 752 | except ImportError: |
|
893 | 753 | warn("doctest module does not exist.") |
|
894 | 754 | |
|
895 | 755 | # Set user colors (don't do it in the constructor above so that it |
|
896 | 756 | # doesn't crash if colors option is invalid) |
|
897 |
self.magic_colors( |
|
|
757 | self.magic_colors(self.colors) | |
|
898 | 758 | |
|
899 | 759 | # Set calling of pdb on exceptions |
|
900 |
self.call_pdb = |
|
|
760 | self.call_pdb = self.pdb | |
|
761 | ||
|
901 | 762 | |
|
902 | # Load user aliases | |
|
903 | for alias in rc.alias: | |
|
904 | self.magic_alias(alias) | |
|
905 | 763 | |
|
906 | 764 | self.hooks.late_startup_hook() |
|
907 | 765 | |
|
908 |
for cmd in self. |
|
|
766 | for cmd in self.autoexec: | |
|
909 | 767 | #print "autoexec>",cmd #dbg |
|
910 | 768 | self.api.runlines(cmd) |
|
911 | 769 | |
|
912 | 770 | batchrun = False |
|
913 | for batchfile in [path(arg) for arg in self.rc.args | |
|
914 | if arg.lower().endswith('.ipy')]: | |
|
915 | if not batchfile.isfile(): | |
|
916 |
|
|
|
917 | continue | |
|
918 | self.api.runlines(batchfile.text()) | |
|
919 | batchrun = True | |
|
771 | if self.config.has_key('EXECFILE'): | |
|
772 | for batchfile in [path(arg) for arg in self.config.EXECFILE | |
|
773 | if arg.lower().endswith('.ipy')]: | |
|
774 | if not batchfile.isfile(): | |
|
775 | print "No such batch file:", batchfile | |
|
776 | continue | |
|
777 | self.api.runlines(batchfile.text()) | |
|
778 | batchrun = True | |
|
920 | 779 | # without -i option, exit after running the batch file |
|
921 |
if batchrun and not self. |
|
|
780 | if batchrun and not self.interactive: | |
|
922 | 781 | self.ask_exit() |
|
923 | 782 | |
|
924 | 783 | def init_namespaces(self): |
|
925 | 784 | """Initialize all user-visible namespaces to their minimum defaults. |
|
926 | 785 | |
|
927 | 786 | Certain history lists are also initialized here, as they effectively |
|
928 | 787 | act as user namespaces. |
|
929 | 788 | |
|
930 | 789 | Notes |
|
931 | 790 | ----- |
|
932 | 791 | All data structures here are only filled in, they are NOT reset by this |
|
933 | 792 | method. If they were not empty before, data will simply be added to |
|
934 | 793 | therm. |
|
935 | 794 | """ |
|
936 | 795 | # The user namespace MUST have a pointer to the shell itself. |
|
937 | 796 | self.user_ns[self.name] = self |
|
938 | 797 | |
|
939 | 798 | # Store the public api instance |
|
940 | 799 | self.user_ns['_ip'] = self.api |
|
941 | 800 | |
|
942 | 801 | # make global variables for user access to the histories |
|
943 | 802 | self.user_ns['_ih'] = self.input_hist |
|
944 | 803 | self.user_ns['_oh'] = self.output_hist |
|
945 | 804 | self.user_ns['_dh'] = self.dir_hist |
|
946 | 805 | |
|
947 | 806 | # user aliases to input and output histories |
|
948 | 807 | self.user_ns['In'] = self.input_hist |
|
949 | 808 | self.user_ns['Out'] = self.output_hist |
|
950 | 809 | |
|
951 | 810 | self.user_ns['_sh'] = shadowns |
|
952 | 811 | |
|
953 | 812 | # Fill the history zero entry, user counter starts at 1 |
|
954 | 813 | self.input_hist.append('\n') |
|
955 | 814 | self.input_hist_raw.append('\n') |
|
956 | 815 | |
|
957 | 816 | def add_builtins(self): |
|
958 | 817 | """Store ipython references into the builtin namespace. |
|
959 | 818 | |
|
960 | 819 | Some parts of ipython operate via builtins injected here, which hold a |
|
961 | 820 | reference to IPython itself.""" |
|
962 | 821 | |
|
963 | # TODO: deprecate all of these, they are unsafe | |
|
822 | # Install our own quitter instead of the builtins. | |
|
823 | # This used to be in the __init__ method, but this is a better | |
|
824 | # place for it. These can be incorporated to the logic below | |
|
825 | # when it is refactored. | |
|
826 | __builtin__.exit = Quitter(self,'exit') | |
|
827 | __builtin__.quit = Quitter(self,'quit') | |
|
828 | ||
|
829 | # TODO: deprecate all of these, they are unsafe. Why though? | |
|
964 | 830 | builtins_new = dict(__IPYTHON__ = self, |
|
965 | 831 | ip_set_hook = self.set_hook, |
|
966 | 832 | jobs = self.jobs, |
|
967 | 833 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
968 | 834 | ipalias = wrap_deprecated(self.ipalias), |
|
969 | 835 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
970 | 836 | #_ip = self.api |
|
971 | 837 | ) |
|
972 | 838 | for biname,bival in builtins_new.items(): |
|
973 | 839 | try: |
|
974 | 840 | # store the orignal value so we can restore it |
|
975 | 841 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
976 | 842 | except KeyError: |
|
977 | 843 | # or mark that it wasn't defined, and we'll just delete it at |
|
978 | 844 | # cleanup |
|
979 | 845 | self.builtins_added[biname] = Undefined |
|
980 | 846 | __builtin__.__dict__[biname] = bival |
|
981 | 847 | |
|
982 | 848 | # Keep in the builtins a flag for when IPython is active. We set it |
|
983 | 849 | # with setdefault so that multiple nested IPythons don't clobber one |
|
984 | 850 | # another. Each will increase its value by one upon being activated, |
|
985 | 851 | # which also gives us a way to determine the nesting level. |
|
986 | 852 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
987 | 853 | |
|
988 | 854 | def clean_builtins(self): |
|
989 | 855 | """Remove any builtins which might have been added by add_builtins, or |
|
990 | 856 | restore overwritten ones to their previous values.""" |
|
991 | 857 | for biname,bival in self.builtins_added.items(): |
|
992 | 858 | if bival is Undefined: |
|
993 | 859 | del __builtin__.__dict__[biname] |
|
994 | 860 | else: |
|
995 | 861 | __builtin__.__dict__[biname] = bival |
|
996 | 862 | self.builtins_added.clear() |
|
997 | 863 | |
|
998 | 864 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
999 | 865 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1000 | 866 | |
|
1001 | 867 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1002 | 868 | adding your function to one of these hooks, you can modify IPython's |
|
1003 | 869 | behavior to call at runtime your own routines.""" |
|
1004 | 870 | |
|
1005 | 871 | # At some point in the future, this should validate the hook before it |
|
1006 | 872 | # accepts it. Probably at least check that the hook takes the number |
|
1007 | 873 | # of args it's supposed to. |
|
1008 | 874 | |
|
1009 | 875 | f = new.instancemethod(hook,self,self.__class__) |
|
1010 | 876 | |
|
1011 | 877 | # check if the hook is for strdispatcher first |
|
1012 | 878 | if str_key is not None: |
|
1013 | 879 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1014 | 880 | sdp.add_s(str_key, f, priority ) |
|
1015 | 881 | self.strdispatchers[name] = sdp |
|
1016 | 882 | return |
|
1017 | 883 | if re_key is not None: |
|
1018 | 884 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1019 | 885 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1020 | 886 | self.strdispatchers[name] = sdp |
|
1021 | 887 | return |
|
1022 | 888 | |
|
1023 | 889 | dp = getattr(self.hooks, name, None) |
|
1024 | 890 | if name not in IPython.core.hooks.__all__: |
|
1025 | 891 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
1026 | 892 | if not dp: |
|
1027 | 893 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
1028 | 894 | |
|
1029 | 895 | try: |
|
1030 | 896 | dp.add(f,priority) |
|
1031 | 897 | except AttributeError: |
|
1032 | 898 | # it was not commandchain, plain old func - replace |
|
1033 | 899 | dp = f |
|
1034 | 900 | |
|
1035 | 901 | setattr(self.hooks,name, dp) |
|
1036 | 902 | |
|
1037 | 903 | |
|
1038 | 904 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
1039 | 905 | |
|
1040 | 906 | def set_crash_handler(self,crashHandler): |
|
1041 | 907 | """Set the IPython crash handler. |
|
1042 | 908 | |
|
1043 | 909 | This must be a callable with a signature suitable for use as |
|
1044 | 910 | sys.excepthook.""" |
|
1045 | 911 | |
|
1046 | 912 | # Install the given crash handler as the Python exception hook |
|
1047 | 913 | sys.excepthook = crashHandler |
|
1048 | 914 | |
|
1049 | 915 | # The instance will store a pointer to this, so that runtime code |
|
1050 | 916 | # (such as magics) can access it. This is because during the |
|
1051 | 917 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1052 | 918 | # frameworks). |
|
1053 | 919 | self.sys_excepthook = sys.excepthook |
|
1054 | 920 | |
|
1055 | 921 | |
|
1056 | 922 | def set_custom_exc(self,exc_tuple,handler): |
|
1057 | 923 | """set_custom_exc(exc_tuple,handler) |
|
1058 | 924 | |
|
1059 | 925 | Set a custom exception handler, which will be called if any of the |
|
1060 | 926 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1061 | 927 | runcode() method. |
|
1062 | 928 | |
|
1063 | 929 | Inputs: |
|
1064 | 930 | |
|
1065 | 931 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1066 | 932 | handler for. It is very important that you use a tuple, and NOT A |
|
1067 | 933 | LIST here, because of the way Python's except statement works. If |
|
1068 | 934 | you only want to trap a single exception, use a singleton tuple: |
|
1069 | 935 | |
|
1070 | 936 | exc_tuple == (MyCustomException,) |
|
1071 | 937 | |
|
1072 | 938 | - handler: this must be defined as a function with the following |
|
1073 | 939 | basic interface: def my_handler(self,etype,value,tb). |
|
1074 | 940 | |
|
1075 | 941 | This will be made into an instance method (via new.instancemethod) |
|
1076 | 942 | of IPython itself, and it will be called if any of the exceptions |
|
1077 | 943 | listed in the exc_tuple are caught. If the handler is None, an |
|
1078 | 944 | internal basic one is used, which just prints basic info. |
|
1079 | 945 | |
|
1080 | 946 | WARNING: by putting in your own exception handler into IPython's main |
|
1081 | 947 | execution loop, you run a very good chance of nasty crashes. This |
|
1082 | 948 | facility should only be used if you really know what you are doing.""" |
|
1083 | 949 | |
|
1084 | 950 | assert type(exc_tuple)==type(()) , \ |
|
1085 | 951 | "The custom exceptions must be given AS A TUPLE." |
|
1086 | 952 | |
|
1087 | 953 | def dummy_handler(self,etype,value,tb): |
|
1088 | 954 | print '*** Simple custom exception handler ***' |
|
1089 | 955 | print 'Exception type :',etype |
|
1090 | 956 | print 'Exception value:',value |
|
1091 | 957 | print 'Traceback :',tb |
|
1092 | 958 | print 'Source code :','\n'.join(self.buffer) |
|
1093 | 959 | |
|
1094 | 960 | if handler is None: handler = dummy_handler |
|
1095 | 961 | |
|
1096 | 962 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1097 | 963 | self.custom_exceptions = exc_tuple |
|
1098 | 964 | |
|
1099 | 965 | def set_custom_completer(self,completer,pos=0): |
|
1100 | 966 | """set_custom_completer(completer,pos=0) |
|
1101 | 967 | |
|
1102 | 968 | Adds a new custom completer function. |
|
1103 | 969 | |
|
1104 | 970 | The position argument (defaults to 0) is the index in the completers |
|
1105 | 971 | list where you want the completer to be inserted.""" |
|
1106 | 972 | |
|
1107 | 973 | newcomp = new.instancemethod(completer,self.Completer, |
|
1108 | 974 | self.Completer.__class__) |
|
1109 | 975 | self.Completer.matchers.insert(pos,newcomp) |
|
1110 | 976 | |
|
1111 | 977 | def set_completer(self): |
|
1112 | 978 | """reset readline's completer to be our own.""" |
|
1113 | 979 | self.readline.set_completer(self.Completer.complete) |
|
1114 | 980 | |
|
1115 | 981 | def _get_call_pdb(self): |
|
1116 | 982 | return self._call_pdb |
|
1117 | 983 | |
|
1118 | 984 | def _set_call_pdb(self,val): |
|
1119 | 985 | |
|
1120 | 986 | if val not in (0,1,False,True): |
|
1121 | 987 | raise ValueError,'new call_pdb value must be boolean' |
|
1122 | 988 | |
|
1123 | 989 | # store value in instance |
|
1124 | 990 | self._call_pdb = val |
|
1125 | 991 | |
|
1126 | 992 | # notify the actual exception handlers |
|
1127 | 993 | self.InteractiveTB.call_pdb = val |
|
1128 | 994 | if self.isthreaded: |
|
1129 | 995 | try: |
|
1130 | 996 | self.sys_excepthook.call_pdb = val |
|
1131 | 997 | except: |
|
1132 | 998 | warn('Failed to activate pdb for threaded exception handler') |
|
1133 | 999 | |
|
1134 | 1000 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1135 | 1001 | 'Control auto-activation of pdb at exceptions') |
|
1136 | 1002 | |
|
1137 | 1003 | # These special functions get installed in the builtin namespace, to |
|
1138 | 1004 | # provide programmatic (pure python) access to magics, aliases and system |
|
1139 | 1005 | # calls. This is important for logging, user scripting, and more. |
|
1140 | 1006 | |
|
1141 | 1007 | # We are basically exposing, via normal python functions, the three |
|
1142 | 1008 | # mechanisms in which ipython offers special call modes (magics for |
|
1143 | 1009 | # internal control, aliases for direct system access via pre-selected |
|
1144 | 1010 | # names, and !cmd for calling arbitrary system commands). |
|
1145 | 1011 | |
|
1146 | 1012 | def ipmagic(self,arg_s): |
|
1147 | 1013 | """Call a magic function by name. |
|
1148 | 1014 | |
|
1149 | 1015 | Input: a string containing the name of the magic function to call and any |
|
1150 | 1016 | additional arguments to be passed to the magic. |
|
1151 | 1017 | |
|
1152 | 1018 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
1153 | 1019 | prompt: |
|
1154 | 1020 | |
|
1155 | 1021 | In[1]: %name -opt foo bar |
|
1156 | 1022 | |
|
1157 | 1023 | To call a magic without arguments, simply use ipmagic('name'). |
|
1158 | 1024 | |
|
1159 | 1025 | This provides a proper Python function to call IPython's magics in any |
|
1160 | 1026 | valid Python code you can type at the interpreter, including loops and |
|
1161 | 1027 | compound statements. It is added by IPython to the Python builtin |
|
1162 | 1028 | namespace upon initialization.""" |
|
1163 | 1029 | |
|
1164 | 1030 | args = arg_s.split(' ',1) |
|
1165 | 1031 | magic_name = args[0] |
|
1166 | 1032 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1167 | 1033 | |
|
1168 | 1034 | try: |
|
1169 | 1035 | magic_args = args[1] |
|
1170 | 1036 | except IndexError: |
|
1171 | 1037 | magic_args = '' |
|
1172 | 1038 | fn = getattr(self,'magic_'+magic_name,None) |
|
1173 | 1039 | if fn is None: |
|
1174 | 1040 | error("Magic function `%s` not found." % magic_name) |
|
1175 | 1041 | else: |
|
1176 | 1042 | magic_args = self.var_expand(magic_args,1) |
|
1177 | 1043 | return fn(magic_args) |
|
1178 | 1044 | |
|
1045 | def define_alias(self, name, cmd): | |
|
1046 | """ Define a new alias.""" | |
|
1047 | ||
|
1048 | if callable(cmd): | |
|
1049 | self.alias_table[name] = cmd | |
|
1050 | from IPython.core import shadowns | |
|
1051 | setattr(shadowns, name, cmd) | |
|
1052 | return | |
|
1053 | ||
|
1054 | if isinstance(cmd, basestring): | |
|
1055 | nargs = cmd.count('%s') | |
|
1056 | if nargs>0 and cmd.find('%l')>=0: | |
|
1057 | raise Exception('The %s and %l specifiers are mutually ' | |
|
1058 | 'exclusive in alias definitions.') | |
|
1059 | ||
|
1060 | self.alias_table[name] = (nargs,cmd) | |
|
1061 | return | |
|
1062 | ||
|
1063 | self.alias_table[name] = cmd | |
|
1064 | ||
|
1179 | 1065 | def ipalias(self,arg_s): |
|
1180 | 1066 | """Call an alias by name. |
|
1181 | 1067 | |
|
1182 | 1068 | Input: a string containing the name of the alias to call and any |
|
1183 | 1069 | additional arguments to be passed to the magic. |
|
1184 | 1070 | |
|
1185 | 1071 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1186 | 1072 | prompt: |
|
1187 | 1073 | |
|
1188 | 1074 | In[1]: name -opt foo bar |
|
1189 | 1075 | |
|
1190 | 1076 | To call an alias without arguments, simply use ipalias('name'). |
|
1191 | 1077 | |
|
1192 | 1078 | This provides a proper Python function to call IPython's aliases in any |
|
1193 | 1079 | valid Python code you can type at the interpreter, including loops and |
|
1194 | 1080 | compound statements. It is added by IPython to the Python builtin |
|
1195 | 1081 | namespace upon initialization.""" |
|
1196 | 1082 | |
|
1197 | 1083 | args = arg_s.split(' ',1) |
|
1198 | 1084 | alias_name = args[0] |
|
1199 | 1085 | try: |
|
1200 | 1086 | alias_args = args[1] |
|
1201 | 1087 | except IndexError: |
|
1202 | 1088 | alias_args = '' |
|
1203 | 1089 | if alias_name in self.alias_table: |
|
1204 | 1090 | self.call_alias(alias_name,alias_args) |
|
1205 | 1091 | else: |
|
1206 | 1092 | error("Alias `%s` not found." % alias_name) |
|
1207 | 1093 | |
|
1208 |
def |
|
|
1094 | def system(self, cmd): | |
|
1209 | 1095 | """Make a system call, using IPython.""" |
|
1096 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
|
1097 | ||
|
1098 | ipsystem = system | |
|
1210 | 1099 | |
|
1211 | self.system(arg_s) | |
|
1100 | def getoutput(self, cmd): | |
|
1101 | return getoutput(self.var_expand(cmd,depth=2), | |
|
1102 | header=self.system_header, | |
|
1103 | verbose=self.system_verbose) | |
|
1104 | ||
|
1105 | def getoutputerror(self, cmd): | |
|
1106 | return getoutputerror(self.var_expand(cmd,depth=2), | |
|
1107 | header=self.system_header, | |
|
1108 | verbose=self.system_verbose) | |
|
1212 | 1109 | |
|
1213 | 1110 | def complete(self,text): |
|
1214 | 1111 | """Return a sorted list of all possible completions on text. |
|
1215 | 1112 | |
|
1216 | 1113 | Inputs: |
|
1217 | 1114 | |
|
1218 | 1115 | - text: a string of text to be completed on. |
|
1219 | 1116 | |
|
1220 | 1117 | This is a wrapper around the completion mechanism, similar to what |
|
1221 | 1118 | readline does at the command line when the TAB key is hit. By |
|
1222 | 1119 | exposing it as a method, it can be used by other non-readline |
|
1223 | 1120 | environments (such as GUIs) for text completion. |
|
1224 | 1121 | |
|
1225 | 1122 | Simple usage example: |
|
1226 | 1123 | |
|
1227 | 1124 | In [7]: x = 'hello' |
|
1228 | 1125 | |
|
1229 | 1126 | In [8]: x |
|
1230 | 1127 | Out[8]: 'hello' |
|
1231 | 1128 | |
|
1232 | 1129 | In [9]: print x |
|
1233 | 1130 | hello |
|
1234 | 1131 | |
|
1235 | 1132 | In [10]: _ip.IP.complete('x.l') |
|
1236 | 1133 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1237 | 1134 | """ |
|
1238 | 1135 | |
|
1239 | 1136 | complete = self.Completer.complete |
|
1240 | 1137 | state = 0 |
|
1241 | 1138 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1242 | 1139 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1243 | 1140 | # start using sets instead, which are faster. |
|
1244 | 1141 | comps = {} |
|
1245 | 1142 | while True: |
|
1246 | 1143 | newcomp = complete(text,state,line_buffer=text) |
|
1247 | 1144 | if newcomp is None: |
|
1248 | 1145 | break |
|
1249 | 1146 | comps[newcomp] = 1 |
|
1250 | 1147 | state += 1 |
|
1251 | 1148 | outcomps = comps.keys() |
|
1252 | 1149 | outcomps.sort() |
|
1253 | 1150 | #print "T:",text,"OC:",outcomps # dbg |
|
1254 | 1151 | #print "vars:",self.user_ns.keys() |
|
1255 | 1152 | return outcomps |
|
1256 | 1153 | |
|
1257 | 1154 | def set_completer_frame(self, frame=None): |
|
1258 | 1155 | if frame: |
|
1259 | 1156 | self.Completer.namespace = frame.f_locals |
|
1260 | 1157 | self.Completer.global_namespace = frame.f_globals |
|
1261 | 1158 | else: |
|
1262 | 1159 | self.Completer.namespace = self.user_ns |
|
1263 | 1160 | self.Completer.global_namespace = self.user_global_ns |
|
1264 | 1161 | |
|
1265 | 1162 | def init_auto_alias(self): |
|
1266 | 1163 | """Define some aliases automatically. |
|
1267 | 1164 | |
|
1268 | 1165 | These are ALL parameter-less aliases""" |
|
1269 | 1166 | |
|
1270 | 1167 | for alias,cmd in self.auto_alias: |
|
1271 | 1168 | self.getapi().defalias(alias,cmd) |
|
1272 | 1169 | |
|
1273 | 1170 | |
|
1274 | 1171 | def alias_table_validate(self,verbose=0): |
|
1275 | 1172 | """Update information about the alias table. |
|
1276 | 1173 | |
|
1277 | 1174 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1278 | 1175 | |
|
1279 | 1176 | no_alias = self.no_alias |
|
1280 | 1177 | for k in self.alias_table.keys(): |
|
1281 | 1178 | if k in no_alias: |
|
1282 | 1179 | del self.alias_table[k] |
|
1283 | 1180 | if verbose: |
|
1284 | 1181 | print ("Deleting alias <%s>, it's a Python " |
|
1285 | 1182 | "keyword or builtin." % k) |
|
1286 | 1183 | |
|
1287 | 1184 | def set_autoindent(self,value=None): |
|
1288 | 1185 | """Set the autoindent flag, checking for readline support. |
|
1289 | 1186 | |
|
1290 | 1187 | If called with no arguments, it acts as a toggle.""" |
|
1291 | 1188 | |
|
1292 | 1189 | if not self.has_readline: |
|
1293 | 1190 | if os.name == 'posix': |
|
1294 | 1191 | warn("The auto-indent feature requires the readline library") |
|
1295 | 1192 | self.autoindent = 0 |
|
1296 | 1193 | return |
|
1297 | 1194 | if value is None: |
|
1298 | 1195 | self.autoindent = not self.autoindent |
|
1299 | 1196 | else: |
|
1300 | 1197 | self.autoindent = value |
|
1301 | 1198 | |
|
1302 | def rc_set_toggle(self,rc_field,value=None): | |
|
1303 | """Set or toggle a field in IPython's rc config. structure. | |
|
1304 | ||
|
1305 | If called with no arguments, it acts as a toggle. | |
|
1306 | ||
|
1307 | If called with a non-existent field, the resulting AttributeError | |
|
1308 | exception will propagate out.""" | |
|
1309 | ||
|
1310 | rc_val = getattr(self.rc,rc_field) | |
|
1311 | if value is None: | |
|
1312 | value = not rc_val | |
|
1313 | setattr(self.rc,rc_field,value) | |
|
1314 | ||
|
1315 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
|
1316 | """Install the user configuration directory. | |
|
1317 | ||
|
1318 | Notes | |
|
1319 | ----- | |
|
1320 | DEPRECATED: use the top-level user_setup() function instead. | |
|
1321 | """ | |
|
1322 | return user_setup(ipythondir,rc_suffix,mode) | |
|
1323 | ||
|
1324 | 1199 | def atexit_operations(self): |
|
1325 | 1200 | """This will be executed at the time of exit. |
|
1326 | 1201 | |
|
1327 | 1202 | Saving of persistent data should be performed here. """ |
|
1328 | 1203 | |
|
1329 | 1204 | #print '*** IPython exit cleanup ***' # dbg |
|
1330 | 1205 | # input history |
|
1331 | 1206 | self.savehist() |
|
1332 | 1207 | |
|
1333 | 1208 | # Cleanup all tempfiles left around |
|
1334 | 1209 | for tfile in self.tempfiles: |
|
1335 | 1210 | try: |
|
1336 | 1211 | os.unlink(tfile) |
|
1337 | 1212 | except OSError: |
|
1338 | 1213 | pass |
|
1339 | 1214 | |
|
1340 | 1215 | # Clear all user namespaces to release all references cleanly. |
|
1341 | 1216 | self.reset() |
|
1342 | 1217 | |
|
1343 | 1218 | # Run user hooks |
|
1344 | 1219 | self.hooks.shutdown_hook() |
|
1345 | 1220 | |
|
1346 | 1221 | def reset(self): |
|
1347 | 1222 | """Clear all internal namespaces. |
|
1348 | 1223 | |
|
1349 | 1224 | Note that this is much more aggressive than %reset, since it clears |
|
1350 | 1225 | fully all namespaces, as well as all input/output lists. |
|
1351 | 1226 | """ |
|
1352 | 1227 | for ns in self.ns_refs_table: |
|
1353 | 1228 | ns.clear() |
|
1354 | 1229 | |
|
1355 | 1230 | # Clear input and output histories |
|
1356 | 1231 | self.input_hist[:] = [] |
|
1357 | 1232 | self.input_hist_raw[:] = [] |
|
1358 | 1233 | self.output_hist.clear() |
|
1359 | 1234 | # Restore the user namespaces to minimal usability |
|
1360 | 1235 | self.init_namespaces() |
|
1361 | 1236 | |
|
1362 | 1237 | def savehist(self): |
|
1363 | 1238 | """Save input history to a file (via readline library).""" |
|
1364 | 1239 | |
|
1365 | 1240 | if not self.has_readline: |
|
1366 | 1241 | return |
|
1367 | 1242 | |
|
1368 | 1243 | try: |
|
1369 | 1244 | self.readline.write_history_file(self.histfile) |
|
1370 | 1245 | except: |
|
1371 | 1246 | print 'Unable to save IPython command history to file: ' + \ |
|
1372 | 1247 | `self.histfile` |
|
1373 | 1248 | |
|
1374 | 1249 | def reloadhist(self): |
|
1375 | 1250 | """Reload the input history from disk file.""" |
|
1376 | 1251 | |
|
1377 | 1252 | if self.has_readline: |
|
1378 | 1253 | try: |
|
1379 | 1254 | self.readline.clear_history() |
|
1380 | 1255 | self.readline.read_history_file(self.shell.histfile) |
|
1381 | 1256 | except AttributeError: |
|
1382 | 1257 | pass |
|
1383 | 1258 | |
|
1384 | 1259 | |
|
1385 | 1260 | def history_saving_wrapper(self, func): |
|
1386 | 1261 | """ Wrap func for readline history saving |
|
1387 | 1262 | |
|
1388 | 1263 | Convert func into callable that saves & restores |
|
1389 | 1264 | history around the call """ |
|
1390 | 1265 | |
|
1391 | 1266 | if not self.has_readline: |
|
1392 | 1267 | return func |
|
1393 | 1268 | |
|
1394 | 1269 | def wrapper(): |
|
1395 | 1270 | self.savehist() |
|
1396 | 1271 | try: |
|
1397 | 1272 | func() |
|
1398 | 1273 | finally: |
|
1399 | 1274 | readline.read_history_file(self.histfile) |
|
1400 | 1275 | return wrapper |
|
1401 | 1276 | |
|
1402 | 1277 | def pre_readline(self): |
|
1403 | 1278 | """readline hook to be used at the start of each line. |
|
1404 | 1279 | |
|
1405 | 1280 | Currently it handles auto-indent only.""" |
|
1406 | 1281 | |
|
1407 | 1282 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1408 | 1283 | |
|
1409 | 1284 | if self.rl_do_indent: |
|
1410 | 1285 | self.readline.insert_text(self.indent_current_str()) |
|
1411 | 1286 | if self.rl_next_input is not None: |
|
1412 | 1287 | self.readline.insert_text(self.rl_next_input) |
|
1413 | 1288 | self.rl_next_input = None |
|
1414 | 1289 | |
|
1415 | 1290 | def init_readline(self): |
|
1416 | 1291 | """Command history completion/saving/reloading.""" |
|
1417 | 1292 | |
|
1418 | 1293 | |
|
1419 | 1294 | import IPython.utils.rlineimpl as readline |
|
1420 | 1295 | |
|
1421 | 1296 | if not readline.have_readline: |
|
1422 | 1297 | self.has_readline = 0 |
|
1423 | 1298 | self.readline = None |
|
1424 | 1299 | # no point in bugging windows users with this every time: |
|
1425 | 1300 | warn('Readline services not available on this platform.') |
|
1426 | 1301 | else: |
|
1427 | 1302 | sys.modules['readline'] = readline |
|
1428 | 1303 | import atexit |
|
1429 | 1304 | from IPython.core.completer import IPCompleter |
|
1430 | 1305 | self.Completer = IPCompleter(self, |
|
1431 | 1306 | self.user_ns, |
|
1432 | 1307 | self.user_global_ns, |
|
1433 |
self. |
|
|
1308 | self.readline_omit__names, | |
|
1434 | 1309 | self.alias_table) |
|
1435 | 1310 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1436 | 1311 | self.strdispatchers['complete_command'] = sdisp |
|
1437 | 1312 | self.Completer.custom_completers = sdisp |
|
1438 | 1313 | # Platform-specific configuration |
|
1439 | 1314 | if os.name == 'nt': |
|
1440 | 1315 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1441 | 1316 | else: |
|
1442 | 1317 | self.readline_startup_hook = readline.set_startup_hook |
|
1443 | 1318 | |
|
1444 | 1319 | # Load user's initrc file (readline config) |
|
1445 | 1320 | # Or if libedit is used, load editrc. |
|
1446 | 1321 | inputrc_name = os.environ.get('INPUTRC') |
|
1447 | 1322 | if inputrc_name is None: |
|
1448 | 1323 | home_dir = get_home_dir() |
|
1449 | 1324 | if home_dir is not None: |
|
1450 | 1325 | inputrc_name = '.inputrc' |
|
1451 | 1326 | if readline.uses_libedit: |
|
1452 | 1327 | inputrc_name = '.editrc' |
|
1453 | 1328 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1454 | 1329 | if os.path.isfile(inputrc_name): |
|
1455 | 1330 | try: |
|
1456 | 1331 | readline.read_init_file(inputrc_name) |
|
1457 | 1332 | except: |
|
1458 | 1333 | warn('Problems reading readline initialization file <%s>' |
|
1459 | 1334 | % inputrc_name) |
|
1460 | 1335 | |
|
1461 | 1336 | self.has_readline = 1 |
|
1462 | 1337 | self.readline = readline |
|
1463 | 1338 | # save this in sys so embedded copies can restore it properly |
|
1464 | 1339 | sys.ipcompleter = self.Completer.complete |
|
1465 | 1340 | self.set_completer() |
|
1466 | 1341 | |
|
1467 | 1342 | # Configure readline according to user's prefs |
|
1468 | 1343 | # This is only done if GNU readline is being used. If libedit |
|
1469 | 1344 | # is being used (as on Leopard) the readline config is |
|
1470 | 1345 | # not run as the syntax for libedit is different. |
|
1471 | 1346 | if not readline.uses_libedit: |
|
1472 |
for rlcommand in self. |
|
|
1347 | for rlcommand in self.readline_parse_and_bind: | |
|
1473 | 1348 | #print "loading rl:",rlcommand # dbg |
|
1474 | 1349 | readline.parse_and_bind(rlcommand) |
|
1475 | 1350 | |
|
1476 | 1351 | # Remove some chars from the delimiters list. If we encounter |
|
1477 | 1352 | # unicode chars, discard them. |
|
1478 | 1353 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1479 | 1354 | delims = delims.translate(string._idmap, |
|
1480 |
self. |
|
|
1355 | self.readline_remove_delims) | |
|
1481 | 1356 | readline.set_completer_delims(delims) |
|
1482 | 1357 | # otherwise we end up with a monster history after a while: |
|
1483 | 1358 | readline.set_history_length(1000) |
|
1484 | 1359 | try: |
|
1485 | 1360 | #print '*** Reading readline history' # dbg |
|
1486 | 1361 | readline.read_history_file(self.histfile) |
|
1487 | 1362 | except IOError: |
|
1488 | 1363 | pass # It doesn't exist yet. |
|
1489 | 1364 | |
|
1490 | 1365 | atexit.register(self.atexit_operations) |
|
1491 | 1366 | del atexit |
|
1492 | 1367 | |
|
1493 | 1368 | # Configure auto-indent for all platforms |
|
1494 |
self.set_autoindent(self. |
|
|
1369 | self.set_autoindent(self.autoindent) | |
|
1495 | 1370 | |
|
1496 | 1371 | def ask_yes_no(self,prompt,default=True): |
|
1497 |
if self. |
|
|
1372 | if self.quiet: | |
|
1498 | 1373 | return True |
|
1499 | 1374 | return ask_yes_no(prompt,default) |
|
1500 | 1375 | |
|
1501 | 1376 | def new_main_mod(self,ns=None): |
|
1502 | 1377 | """Return a new 'main' module object for user code execution. |
|
1503 | 1378 | """ |
|
1504 | 1379 | main_mod = self._user_main_module |
|
1505 | 1380 | init_fakemod_dict(main_mod,ns) |
|
1506 | 1381 | return main_mod |
|
1507 | 1382 | |
|
1508 | 1383 | def cache_main_mod(self,ns,fname): |
|
1509 | 1384 | """Cache a main module's namespace. |
|
1510 | 1385 | |
|
1511 | 1386 | When scripts are executed via %run, we must keep a reference to the |
|
1512 | 1387 | namespace of their __main__ module (a FakeModule instance) around so |
|
1513 | 1388 | that Python doesn't clear it, rendering objects defined therein |
|
1514 | 1389 | useless. |
|
1515 | 1390 | |
|
1516 | 1391 | This method keeps said reference in a private dict, keyed by the |
|
1517 | 1392 | absolute path of the module object (which corresponds to the script |
|
1518 | 1393 | path). This way, for multiple executions of the same script we only |
|
1519 | 1394 | keep one copy of the namespace (the last one), thus preventing memory |
|
1520 | 1395 | leaks from old references while allowing the objects from the last |
|
1521 | 1396 | execution to be accessible. |
|
1522 | 1397 | |
|
1523 | 1398 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1524 | 1399 | because of how Python tears down modules (it hard-sets all their |
|
1525 | 1400 | references to None without regard for reference counts). This method |
|
1526 | 1401 | must therefore make a *copy* of the given namespace, to allow the |
|
1527 | 1402 | original module's __dict__ to be cleared and reused. |
|
1528 | 1403 | |
|
1529 | 1404 | |
|
1530 | 1405 | Parameters |
|
1531 | 1406 | ---------- |
|
1532 | 1407 | ns : a namespace (a dict, typically) |
|
1533 | 1408 | |
|
1534 | 1409 | fname : str |
|
1535 | 1410 | Filename associated with the namespace. |
|
1536 | 1411 | |
|
1537 | 1412 | Examples |
|
1538 | 1413 | -------- |
|
1539 | 1414 | |
|
1540 | 1415 | In [10]: import IPython |
|
1541 | 1416 | |
|
1542 | 1417 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1543 | 1418 | |
|
1544 | 1419 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache |
|
1545 | 1420 | Out[12]: True |
|
1546 | 1421 | """ |
|
1547 | 1422 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
1548 | 1423 | |
|
1549 | 1424 | def clear_main_mod_cache(self): |
|
1550 | 1425 | """Clear the cache of main modules. |
|
1551 | 1426 | |
|
1552 | 1427 | Mainly for use by utilities like %reset. |
|
1553 | 1428 | |
|
1554 | 1429 | Examples |
|
1555 | 1430 | -------- |
|
1556 | 1431 | |
|
1557 | 1432 | In [15]: import IPython |
|
1558 | 1433 | |
|
1559 | 1434 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1560 | 1435 | |
|
1561 | 1436 | In [17]: len(_ip.IP._main_ns_cache) > 0 |
|
1562 | 1437 | Out[17]: True |
|
1563 | 1438 | |
|
1564 | 1439 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1565 | 1440 | |
|
1566 | 1441 | In [19]: len(_ip.IP._main_ns_cache) == 0 |
|
1567 | 1442 | Out[19]: True |
|
1568 | 1443 | """ |
|
1569 | 1444 | self._main_ns_cache.clear() |
|
1570 | 1445 | |
|
1571 | 1446 | def _should_recompile(self,e): |
|
1572 | 1447 | """Utility routine for edit_syntax_error""" |
|
1573 | 1448 | |
|
1574 | 1449 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1575 | 1450 | '<console>','<BackgroundJob compilation>', |
|
1576 | 1451 | None): |
|
1577 | 1452 | |
|
1578 | 1453 | return False |
|
1579 | 1454 | try: |
|
1580 |
if (self. |
|
|
1455 | if (self.autoedit_syntax and | |
|
1581 | 1456 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1582 | 1457 | '[Y/n] ','y')): |
|
1583 | 1458 | return False |
|
1584 | 1459 | except EOFError: |
|
1585 | 1460 | return False |
|
1586 | 1461 | |
|
1587 | 1462 | def int0(x): |
|
1588 | 1463 | try: |
|
1589 | 1464 | return int(x) |
|
1590 | 1465 | except TypeError: |
|
1591 | 1466 | return 0 |
|
1592 | 1467 | # always pass integer line and offset values to editor hook |
|
1593 | 1468 | try: |
|
1594 | 1469 | self.hooks.fix_error_editor(e.filename, |
|
1595 | 1470 | int0(e.lineno),int0(e.offset),e.msg) |
|
1596 | 1471 | except ipapi.TryNext: |
|
1597 | 1472 | warn('Could not open editor') |
|
1598 | 1473 | return False |
|
1599 | 1474 | return True |
|
1600 | 1475 | |
|
1601 | 1476 | def edit_syntax_error(self): |
|
1602 | 1477 | """The bottom half of the syntax error handler called in the main loop. |
|
1603 | 1478 | |
|
1604 | 1479 | Loop until syntax error is fixed or user cancels. |
|
1605 | 1480 | """ |
|
1606 | 1481 | |
|
1607 | 1482 | while self.SyntaxTB.last_syntax_error: |
|
1608 | 1483 | # copy and clear last_syntax_error |
|
1609 | 1484 | err = self.SyntaxTB.clear_err_state() |
|
1610 | 1485 | if not self._should_recompile(err): |
|
1611 | 1486 | return |
|
1612 | 1487 | try: |
|
1613 | 1488 | # may set last_syntax_error again if a SyntaxError is raised |
|
1614 | 1489 | self.safe_execfile(err.filename,self.user_ns) |
|
1615 | 1490 | except: |
|
1616 | 1491 | self.showtraceback() |
|
1617 | 1492 | else: |
|
1618 | 1493 | try: |
|
1619 | 1494 | f = file(err.filename) |
|
1620 | 1495 | try: |
|
1621 | 1496 | sys.displayhook(f.read()) |
|
1622 | 1497 | finally: |
|
1623 | 1498 | f.close() |
|
1624 | 1499 | except: |
|
1625 | 1500 | self.showtraceback() |
|
1626 | 1501 | |
|
1627 | 1502 | def showsyntaxerror(self, filename=None): |
|
1628 | 1503 | """Display the syntax error that just occurred. |
|
1629 | 1504 | |
|
1630 | 1505 | This doesn't display a stack trace because there isn't one. |
|
1631 | 1506 | |
|
1632 | 1507 | If a filename is given, it is stuffed in the exception instead |
|
1633 | 1508 | of what was there before (because Python's parser always uses |
|
1634 | 1509 | "<string>" when reading from a string). |
|
1635 | 1510 | """ |
|
1636 | 1511 | etype, value, last_traceback = sys.exc_info() |
|
1637 | 1512 | |
|
1638 | 1513 | # See note about these variables in showtraceback() below |
|
1639 | 1514 | sys.last_type = etype |
|
1640 | 1515 | sys.last_value = value |
|
1641 | 1516 | sys.last_traceback = last_traceback |
|
1642 | 1517 | |
|
1643 | 1518 | if filename and etype is SyntaxError: |
|
1644 | 1519 | # Work hard to stuff the correct filename in the exception |
|
1645 | 1520 | try: |
|
1646 | 1521 | msg, (dummy_filename, lineno, offset, line) = value |
|
1647 | 1522 | except: |
|
1648 | 1523 | # Not the format we expect; leave it alone |
|
1649 | 1524 | pass |
|
1650 | 1525 | else: |
|
1651 | 1526 | # Stuff in the right filename |
|
1652 | 1527 | try: |
|
1653 | 1528 | # Assume SyntaxError is a class exception |
|
1654 | 1529 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1655 | 1530 | except: |
|
1656 | 1531 | # If that failed, assume SyntaxError is a string |
|
1657 | 1532 | value = msg, (filename, lineno, offset, line) |
|
1658 | 1533 | self.SyntaxTB(etype,value,[]) |
|
1659 | 1534 | |
|
1660 | 1535 | def debugger(self,force=False): |
|
1661 | 1536 | """Call the pydb/pdb debugger. |
|
1662 | 1537 | |
|
1663 | 1538 | Keywords: |
|
1664 | 1539 | |
|
1665 | 1540 | - force(False): by default, this routine checks the instance call_pdb |
|
1666 | 1541 | flag and does not actually invoke the debugger if the flag is false. |
|
1667 | 1542 | The 'force' option forces the debugger to activate even if the flag |
|
1668 | 1543 | is false. |
|
1669 | 1544 | """ |
|
1670 | 1545 | |
|
1671 | 1546 | if not (force or self.call_pdb): |
|
1672 | 1547 | return |
|
1673 | 1548 | |
|
1674 | 1549 | if not hasattr(sys,'last_traceback'): |
|
1675 | 1550 | error('No traceback has been produced, nothing to debug.') |
|
1676 | 1551 | return |
|
1677 | 1552 | |
|
1678 | 1553 | # use pydb if available |
|
1679 | 1554 | if debugger.has_pydb: |
|
1680 | 1555 | from pydb import pm |
|
1681 | 1556 | else: |
|
1682 | 1557 | # fallback to our internal debugger |
|
1683 | 1558 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1684 | 1559 | self.history_saving_wrapper(pm)() |
|
1685 | 1560 | |
|
1686 | 1561 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1687 | 1562 | """Display the exception that just occurred. |
|
1688 | 1563 | |
|
1689 | 1564 | If nothing is known about the exception, this is the method which |
|
1690 | 1565 | should be used throughout the code for presenting user tracebacks, |
|
1691 | 1566 | rather than directly invoking the InteractiveTB object. |
|
1692 | 1567 | |
|
1693 | 1568 | A specific showsyntaxerror() also exists, but this method can take |
|
1694 | 1569 | care of calling it if needed, so unless you are explicitly catching a |
|
1695 | 1570 | SyntaxError exception, don't try to analyze the stack manually and |
|
1696 | 1571 | simply call this method.""" |
|
1697 | 1572 | |
|
1698 | 1573 | |
|
1699 | 1574 | # Though this won't be called by syntax errors in the input line, |
|
1700 | 1575 | # there may be SyntaxError cases whith imported code. |
|
1701 | 1576 | |
|
1702 | 1577 | try: |
|
1703 | 1578 | if exc_tuple is None: |
|
1704 | 1579 | etype, value, tb = sys.exc_info() |
|
1705 | 1580 | else: |
|
1706 | 1581 | etype, value, tb = exc_tuple |
|
1707 | 1582 | |
|
1708 | 1583 | if etype is SyntaxError: |
|
1709 | 1584 | self.showsyntaxerror(filename) |
|
1710 | 1585 | elif etype is ipapi.UsageError: |
|
1711 | 1586 | print "UsageError:", value |
|
1712 | 1587 | else: |
|
1713 | 1588 | # WARNING: these variables are somewhat deprecated and not |
|
1714 | 1589 | # necessarily safe to use in a threaded environment, but tools |
|
1715 | 1590 | # like pdb depend on their existence, so let's set them. If we |
|
1716 | 1591 | # find problems in the field, we'll need to revisit their use. |
|
1717 | 1592 | sys.last_type = etype |
|
1718 | 1593 | sys.last_value = value |
|
1719 | 1594 | sys.last_traceback = tb |
|
1720 | 1595 | |
|
1721 | 1596 | if etype in self.custom_exceptions: |
|
1722 | 1597 | self.CustomTB(etype,value,tb) |
|
1723 | 1598 | else: |
|
1724 | 1599 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1725 | 1600 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1726 | 1601 | # pdb mucks up readline, fix it back |
|
1727 | 1602 | self.set_completer() |
|
1728 | 1603 | except KeyboardInterrupt: |
|
1729 | 1604 | self.write("\nKeyboardInterrupt\n") |
|
1730 | 1605 | |
|
1731 | def mainloop(self,banner=None): | |
|
1732 |
""" |
|
|
1606 | def mainloop(self, banner=None): | |
|
1607 | """Start the mainloop. | |
|
1733 | 1608 | |
|
1734 | 1609 | If an optional banner argument is given, it will override the |
|
1735 |
internally created default banner. |
|
|
1736 | ||
|
1737 |
if self. |
|
|
1610 | internally created default banner. | |
|
1611 | """ | |
|
1612 | if self.c: # Emulate Python's -c option | |
|
1738 | 1613 | self.exec_init_cmd() |
|
1739 | if banner is None: | |
|
1740 |
|
|
|
1741 |
|
|
|
1742 | # banner is string? Use it directly! | |
|
1743 | elif isinstance(self.rc.banner,basestring): | |
|
1744 | banner = self.rc.banner | |
|
1745 | else: | |
|
1746 | banner = self.BANNER+self.banner2 | |
|
1614 | ||
|
1615 | if self.display_banner: | |
|
1616 | if banner is None: | |
|
1617 | banner = self.banner | |
|
1747 | 1618 | |
|
1748 | 1619 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1749 | 1620 | # ensure that it's in sync |
|
1750 | 1621 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1751 | 1622 | self.input_hist_raw = InputList(self.input_hist) |
|
1752 | 1623 | |
|
1753 | 1624 | while 1: |
|
1754 | 1625 | try: |
|
1755 |
self.interact( |
|
|
1626 | self.interact() | |
|
1756 | 1627 | #self.interact_with_readline() |
|
1757 | ||
|
1758 | 1628 | # XXX for testing of a readline-decoupled repl loop, call |
|
1759 | 1629 | # interact_with_readline above |
|
1760 | ||
|
1761 | 1630 | break |
|
1762 | 1631 | except KeyboardInterrupt: |
|
1763 | 1632 | # this should not be necessary, but KeyboardInterrupt |
|
1764 | 1633 | # handling seems rather unpredictable... |
|
1765 | 1634 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1766 | 1635 | |
|
1767 | 1636 | def exec_init_cmd(self): |
|
1768 | 1637 | """Execute a command given at the command line. |
|
1769 | 1638 | |
|
1770 | 1639 | This emulates Python's -c option.""" |
|
1771 | 1640 | |
|
1772 | 1641 | #sys.argv = ['-c'] |
|
1773 |
self.push(self.prefilter(self. |
|
|
1774 |
if not self. |
|
|
1642 | self.push(self.prefilter(self.c, False)) | |
|
1643 | if not self.interactive: | |
|
1775 | 1644 | self.ask_exit() |
|
1776 | 1645 | |
|
1777 | 1646 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1778 | 1647 | """Embeds IPython into a running python program. |
|
1779 | 1648 | |
|
1780 | 1649 | Input: |
|
1781 | 1650 | |
|
1782 | 1651 | - header: An optional header message can be specified. |
|
1783 | 1652 | |
|
1784 | 1653 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1785 | 1654 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1786 | 1655 | program variables become visible but user-specific configuration |
|
1787 | 1656 | remains possible. |
|
1788 | 1657 | |
|
1789 | 1658 | - stack_depth: specifies how many levels in the stack to go to |
|
1790 | 1659 | looking for namespaces (when local_ns and global_ns are None). This |
|
1791 | 1660 | allows an intermediate caller to make sure that this function gets |
|
1792 | 1661 | the namespace from the intended level in the stack. By default (0) |
|
1793 | 1662 | it will get its locals and globals from the immediate caller. |
|
1794 | 1663 | |
|
1795 | 1664 | Warning: it's possible to use this in a program which is being run by |
|
1796 | 1665 | IPython itself (via %run), but some funny things will happen (a few |
|
1797 | 1666 | globals get overwritten). In the future this will be cleaned up, as |
|
1798 | 1667 | there is no fundamental reason why it can't work perfectly.""" |
|
1799 | 1668 | |
|
1800 | 1669 | # Get locals and globals from caller |
|
1801 | 1670 | if local_ns is None or global_ns is None: |
|
1802 | 1671 | call_frame = sys._getframe(stack_depth).f_back |
|
1803 | 1672 | |
|
1804 | 1673 | if local_ns is None: |
|
1805 | 1674 | local_ns = call_frame.f_locals |
|
1806 | 1675 | if global_ns is None: |
|
1807 | 1676 | global_ns = call_frame.f_globals |
|
1808 | 1677 | |
|
1809 | 1678 | # Update namespaces and fire up interpreter |
|
1810 | 1679 | |
|
1811 | 1680 | # The global one is easy, we can just throw it in |
|
1812 | 1681 | self.user_global_ns = global_ns |
|
1813 | 1682 | |
|
1814 | 1683 | # but the user/local one is tricky: ipython needs it to store internal |
|
1815 | 1684 | # data, but we also need the locals. We'll copy locals in the user |
|
1816 | 1685 | # one, but will track what got copied so we can delete them at exit. |
|
1817 | 1686 | # This is so that a later embedded call doesn't see locals from a |
|
1818 | 1687 | # previous call (which most likely existed in a separate scope). |
|
1819 | 1688 | local_varnames = local_ns.keys() |
|
1820 | 1689 | self.user_ns.update(local_ns) |
|
1821 | 1690 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1822 | 1691 | |
|
1823 | 1692 | # Patch for global embedding to make sure that things don't overwrite |
|
1824 | 1693 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1825 | 1694 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1826 | 1695 | if local_ns is None and global_ns is None: |
|
1827 | 1696 | self.user_global_ns.update(__main__.__dict__) |
|
1828 | 1697 | |
|
1829 | 1698 | # make sure the tab-completer has the correct frame information, so it |
|
1830 | 1699 | # actually completes using the frame's locals/globals |
|
1831 | 1700 | self.set_completer_frame() |
|
1832 | 1701 | |
|
1833 | 1702 | # before activating the interactive mode, we need to make sure that |
|
1834 | 1703 | # all names in the builtin namespace needed by ipython point to |
|
1835 | 1704 | # ourselves, and not to other instances. |
|
1836 | 1705 | self.add_builtins() |
|
1837 | 1706 | |
|
1838 | 1707 | self.interact(header) |
|
1839 | 1708 | |
|
1840 | 1709 | # now, purge out the user namespace from anything we might have added |
|
1841 | 1710 | # from the caller's local namespace |
|
1842 | 1711 | delvar = self.user_ns.pop |
|
1843 | 1712 | for var in local_varnames: |
|
1844 | 1713 | delvar(var,None) |
|
1845 | 1714 | # and clean builtins we may have overridden |
|
1846 | 1715 | self.clean_builtins() |
|
1847 | 1716 | |
|
1848 | 1717 | def interact_prompt(self): |
|
1849 | 1718 | """ Print the prompt (in read-eval-print loop) |
|
1850 | 1719 | |
|
1851 | 1720 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1852 | 1721 | used in standard IPython flow. |
|
1853 | 1722 | """ |
|
1854 | 1723 | if self.more: |
|
1855 | 1724 | try: |
|
1856 | 1725 | prompt = self.hooks.generate_prompt(True) |
|
1857 | 1726 | except: |
|
1858 | 1727 | self.showtraceback() |
|
1859 | 1728 | if self.autoindent: |
|
1860 | 1729 | self.rl_do_indent = True |
|
1861 | 1730 | |
|
1862 | 1731 | else: |
|
1863 | 1732 | try: |
|
1864 | 1733 | prompt = self.hooks.generate_prompt(False) |
|
1865 | 1734 | except: |
|
1866 | 1735 | self.showtraceback() |
|
1867 | 1736 | self.write(prompt) |
|
1868 | 1737 | |
|
1869 | 1738 | def interact_handle_input(self,line): |
|
1870 | 1739 | """ Handle the input line (in read-eval-print loop) |
|
1871 | 1740 | |
|
1872 | 1741 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1873 | 1742 | used in standard IPython flow. |
|
1874 | 1743 | """ |
|
1875 | 1744 | if line.lstrip() == line: |
|
1876 | 1745 | self.shadowhist.add(line.strip()) |
|
1877 | 1746 | lineout = self.prefilter(line,self.more) |
|
1878 | 1747 | |
|
1879 | 1748 | if line.strip(): |
|
1880 | 1749 | if self.more: |
|
1881 | 1750 | self.input_hist_raw[-1] += '%s\n' % line |
|
1882 | 1751 | else: |
|
1883 | 1752 | self.input_hist_raw.append('%s\n' % line) |
|
1884 | 1753 | |
|
1885 | 1754 | |
|
1886 | 1755 | self.more = self.push(lineout) |
|
1887 | 1756 | if (self.SyntaxTB.last_syntax_error and |
|
1888 |
self |
|
|
1757 | self.autoedit_syntax): | |
|
1889 | 1758 | self.edit_syntax_error() |
|
1890 | 1759 | |
|
1891 | 1760 | def interact_with_readline(self): |
|
1892 | 1761 | """ Demo of using interact_handle_input, interact_prompt |
|
1893 | 1762 | |
|
1894 | 1763 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1895 | 1764 | it should work like this. |
|
1896 | 1765 | """ |
|
1897 | 1766 | self.readline_startup_hook(self.pre_readline) |
|
1898 | 1767 | while not self.exit_now: |
|
1899 | 1768 | self.interact_prompt() |
|
1900 | 1769 | if self.more: |
|
1901 | 1770 | self.rl_do_indent = True |
|
1902 | 1771 | else: |
|
1903 | 1772 | self.rl_do_indent = False |
|
1904 | 1773 | line = raw_input_original().decode(self.stdin_encoding) |
|
1905 | 1774 | self.interact_handle_input(line) |
|
1906 | 1775 | |
|
1907 | ||
|
1908 | 1776 | def interact(self, banner=None): |
|
1909 | """Closely emulate the interactive Python console. | |
|
1777 | """Closely emulate the interactive Python console.""" | |
|
1910 | 1778 | |
|
1911 | The optional banner argument specify the banner to print | |
|
1912 | before the first interaction; by default it prints a banner | |
|
1913 | similar to the one printed by the real Python interpreter, | |
|
1914 | followed by the current class name in parentheses (so as not | |
|
1915 | to confuse this with the real interpreter -- since it's so | |
|
1916 | close!). | |
|
1917 | ||
|
1918 | """ | |
|
1919 | ||
|
1779 | # batch run -> do not interact | |
|
1920 | 1780 | if self.exit_now: |
|
1921 | # batch run -> do not interact | |
|
1922 | 1781 | return |
|
1923 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
|
1924 |
if banner |
|
|
1925 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
|
1926 | (sys.version, sys.platform, cprt, | |
|
1927 | self.__class__.__name__)) | |
|
1928 | else: | |
|
1782 | ||
|
1783 | if self.display_banner: | |
|
1784 | if banner is None: | |
|
1785 | banner = self.banner | |
|
1929 | 1786 | self.write(banner) |
|
1930 | 1787 | |
|
1931 | 1788 | more = 0 |
|
1932 | 1789 | |
|
1933 | 1790 | # Mark activity in the builtins |
|
1934 | 1791 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1935 | 1792 | |
|
1936 | 1793 | if self.has_readline: |
|
1937 | 1794 | self.readline_startup_hook(self.pre_readline) |
|
1938 | 1795 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1939 | 1796 | # ask_exit callback. |
|
1940 | 1797 | |
|
1941 | 1798 | while not self.exit_now: |
|
1942 | 1799 | self.hooks.pre_prompt_hook() |
|
1943 | 1800 | if more: |
|
1944 | 1801 | try: |
|
1945 | 1802 | prompt = self.hooks.generate_prompt(True) |
|
1946 | 1803 | except: |
|
1947 | 1804 | self.showtraceback() |
|
1948 | 1805 | if self.autoindent: |
|
1949 | 1806 | self.rl_do_indent = True |
|
1950 | 1807 | |
|
1951 | 1808 | else: |
|
1952 | 1809 | try: |
|
1953 | 1810 | prompt = self.hooks.generate_prompt(False) |
|
1954 | 1811 | except: |
|
1955 | 1812 | self.showtraceback() |
|
1956 | 1813 | try: |
|
1957 | line = self.raw_input(prompt,more) | |
|
1814 | line = self.raw_input(prompt, more) | |
|
1958 | 1815 | if self.exit_now: |
|
1959 | 1816 | # quick exit on sys.std[in|out] close |
|
1960 | 1817 | break |
|
1961 | 1818 | if self.autoindent: |
|
1962 | 1819 | self.rl_do_indent = False |
|
1963 | 1820 | |
|
1964 | 1821 | except KeyboardInterrupt: |
|
1965 | 1822 | #double-guard against keyboardinterrupts during kbdint handling |
|
1966 | 1823 | try: |
|
1967 | 1824 | self.write('\nKeyboardInterrupt\n') |
|
1968 | 1825 | self.resetbuffer() |
|
1969 | 1826 | # keep cache in sync with the prompt counter: |
|
1970 | 1827 | self.outputcache.prompt_count -= 1 |
|
1971 | 1828 | |
|
1972 | 1829 | if self.autoindent: |
|
1973 | 1830 | self.indent_current_nsp = 0 |
|
1974 | 1831 | more = 0 |
|
1975 | 1832 | except KeyboardInterrupt: |
|
1976 | 1833 | pass |
|
1977 | 1834 | except EOFError: |
|
1978 | 1835 | if self.autoindent: |
|
1979 | 1836 | self.rl_do_indent = False |
|
1980 | 1837 | self.readline_startup_hook(None) |
|
1981 | 1838 | self.write('\n') |
|
1982 | 1839 | self.exit() |
|
1983 | 1840 | except bdb.BdbQuit: |
|
1984 | 1841 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1985 | 1842 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1986 | 1843 | 'for IPython to properly format this particular exception.\n' |
|
1987 | 1844 | 'IPython will resume normal operation.') |
|
1988 | 1845 | except: |
|
1989 | 1846 | # exceptions here are VERY RARE, but they can be triggered |
|
1990 | 1847 | # asynchronously by signal handlers, for example. |
|
1991 | 1848 | self.showtraceback() |
|
1992 | 1849 | else: |
|
1993 | 1850 | more = self.push(line) |
|
1994 | 1851 | if (self.SyntaxTB.last_syntax_error and |
|
1995 |
self |
|
|
1852 | self.autoedit_syntax): | |
|
1996 | 1853 | self.edit_syntax_error() |
|
1997 | 1854 | |
|
1998 | 1855 | # We are off again... |
|
1999 | 1856 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
2000 | 1857 | |
|
2001 | 1858 | def excepthook(self, etype, value, tb): |
|
2002 | 1859 | """One more defense for GUI apps that call sys.excepthook. |
|
2003 | 1860 | |
|
2004 | 1861 | GUI frameworks like wxPython trap exceptions and call |
|
2005 | 1862 | sys.excepthook themselves. I guess this is a feature that |
|
2006 | 1863 | enables them to keep running after exceptions that would |
|
2007 | 1864 | otherwise kill their mainloop. This is a bother for IPython |
|
2008 | 1865 | which excepts to catch all of the program exceptions with a try: |
|
2009 | 1866 | except: statement. |
|
2010 | 1867 | |
|
2011 | 1868 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
2012 | 1869 | any app directly invokes sys.excepthook, it will look to the user like |
|
2013 | 1870 | IPython crashed. In order to work around this, we can disable the |
|
2014 | 1871 | CrashHandler and replace it with this excepthook instead, which prints a |
|
2015 | 1872 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
2016 | 1873 | call sys.excepthook will generate a regular-looking exception from |
|
2017 | 1874 | IPython, and the CrashHandler will only be triggered by real IPython |
|
2018 | 1875 | crashes. |
|
2019 | 1876 | |
|
2020 | 1877 | This hook should be used sparingly, only in places which are not likely |
|
2021 | 1878 | to be true IPython errors. |
|
2022 | 1879 | """ |
|
2023 | 1880 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
2024 | 1881 | |
|
2025 | 1882 | def expand_aliases(self,fn,rest): |
|
2026 | 1883 | """ Expand multiple levels of aliases: |
|
2027 | 1884 | |
|
2028 | 1885 | if: |
|
2029 | 1886 | |
|
2030 | 1887 | alias foo bar /tmp |
|
2031 | 1888 | alias baz foo |
|
2032 | 1889 | |
|
2033 | 1890 | then: |
|
2034 | 1891 | |
|
2035 | 1892 | baz huhhahhei -> bar /tmp huhhahhei |
|
2036 | 1893 | |
|
2037 | 1894 | """ |
|
2038 | 1895 | line = fn + " " + rest |
|
2039 | 1896 | |
|
2040 | 1897 | done = set() |
|
2041 | 1898 | while 1: |
|
2042 | 1899 | pre,fn,rest = prefilter.splitUserInput(line, |
|
2043 | 1900 | prefilter.shell_line_split) |
|
2044 | 1901 | if fn in self.alias_table: |
|
2045 | 1902 | if fn in done: |
|
2046 | 1903 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
2047 | 1904 | return "" |
|
2048 | 1905 | done.add(fn) |
|
2049 | 1906 | |
|
2050 | 1907 | l2 = self.transform_alias(fn,rest) |
|
2051 | 1908 | # dir -> dir |
|
2052 | 1909 | # print "alias",line, "->",l2 #dbg |
|
2053 | 1910 | if l2 == line: |
|
2054 | 1911 | break |
|
2055 | 1912 | # ls -> ls -F should not recurse forever |
|
2056 | 1913 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
2057 | 1914 | line = l2 |
|
2058 | 1915 | break |
|
2059 | 1916 | |
|
2060 | 1917 | line=l2 |
|
2061 | 1918 | |
|
2062 | 1919 | |
|
2063 | 1920 | # print "al expand to",line #dbg |
|
2064 | 1921 | else: |
|
2065 | 1922 | break |
|
2066 | 1923 | |
|
2067 | 1924 | return line |
|
2068 | 1925 | |
|
2069 | 1926 | def transform_alias(self, alias,rest=''): |
|
2070 | 1927 | """ Transform alias to system command string. |
|
2071 | 1928 | """ |
|
2072 | 1929 | trg = self.alias_table[alias] |
|
2073 | 1930 | |
|
2074 | 1931 | nargs,cmd = trg |
|
2075 | 1932 | # print trg #dbg |
|
2076 | 1933 | if ' ' in cmd and os.path.isfile(cmd): |
|
2077 | 1934 | cmd = '"%s"' % cmd |
|
2078 | 1935 | |
|
2079 | 1936 | # Expand the %l special to be the user's input line |
|
2080 | 1937 | if cmd.find('%l') >= 0: |
|
2081 | 1938 | cmd = cmd.replace('%l',rest) |
|
2082 | 1939 | rest = '' |
|
2083 | 1940 | if nargs==0: |
|
2084 | 1941 | # Simple, argument-less aliases |
|
2085 | 1942 | cmd = '%s %s' % (cmd,rest) |
|
2086 | 1943 | else: |
|
2087 | 1944 | # Handle aliases with positional arguments |
|
2088 | 1945 | args = rest.split(None,nargs) |
|
2089 | 1946 | if len(args)< nargs: |
|
2090 | 1947 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2091 | 1948 | (alias,nargs,len(args))) |
|
2092 | 1949 | return None |
|
2093 | 1950 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2094 | 1951 | # Now call the macro, evaluating in the user's namespace |
|
2095 | 1952 | #print 'new command: <%r>' % cmd # dbg |
|
2096 | 1953 | return cmd |
|
2097 | 1954 | |
|
2098 | 1955 | def call_alias(self,alias,rest=''): |
|
2099 | 1956 | """Call an alias given its name and the rest of the line. |
|
2100 | 1957 | |
|
2101 | 1958 | This is only used to provide backwards compatibility for users of |
|
2102 | 1959 | ipalias(), use of which is not recommended for anymore.""" |
|
2103 | 1960 | |
|
2104 | 1961 | # Now call the macro, evaluating in the user's namespace |
|
2105 | 1962 | cmd = self.transform_alias(alias, rest) |
|
2106 | 1963 | try: |
|
2107 | 1964 | self.system(cmd) |
|
2108 | 1965 | except: |
|
2109 | 1966 | self.showtraceback() |
|
2110 | 1967 | |
|
2111 | 1968 | def indent_current_str(self): |
|
2112 | 1969 | """return the current level of indentation as a string""" |
|
2113 | 1970 | return self.indent_current_nsp * ' ' |
|
2114 | 1971 | |
|
2115 | 1972 | def autoindent_update(self,line): |
|
2116 | 1973 | """Keep track of the indent level.""" |
|
2117 | 1974 | |
|
2118 | 1975 | #debugx('line') |
|
2119 | 1976 | #debugx('self.indent_current_nsp') |
|
2120 | 1977 | if self.autoindent: |
|
2121 | 1978 | if line: |
|
2122 | 1979 | inisp = num_ini_spaces(line) |
|
2123 | 1980 | if inisp < self.indent_current_nsp: |
|
2124 | 1981 | self.indent_current_nsp = inisp |
|
2125 | 1982 | |
|
2126 | 1983 | if line[-1] == ':': |
|
2127 | 1984 | self.indent_current_nsp += 4 |
|
2128 | 1985 | elif dedent_re.match(line): |
|
2129 | 1986 | self.indent_current_nsp -= 4 |
|
2130 | 1987 | else: |
|
2131 | 1988 | self.indent_current_nsp = 0 |
|
2132 | 1989 | |
|
2133 | 1990 | def runlines(self,lines): |
|
2134 | 1991 | """Run a string of one or more lines of source. |
|
2135 | 1992 | |
|
2136 | 1993 | This method is capable of running a string containing multiple source |
|
2137 | 1994 | lines, as if they had been entered at the IPython prompt. Since it |
|
2138 | 1995 | exposes IPython's processing machinery, the given strings can contain |
|
2139 | 1996 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2140 | 1997 | |
|
2141 | 1998 | # We must start with a clean buffer, in case this is run from an |
|
2142 | 1999 | # interactive IPython session (via a magic, for example). |
|
2143 | 2000 | self.resetbuffer() |
|
2144 | 2001 | lines = lines.split('\n') |
|
2145 | 2002 | more = 0 |
|
2146 | 2003 | |
|
2147 | 2004 | for line in lines: |
|
2148 | 2005 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2149 | 2006 | # NOT skip even a blank line if we are in a code block (more is |
|
2150 | 2007 | # true) |
|
2151 | 2008 | |
|
2152 | 2009 | if line or more: |
|
2153 | 2010 | # push to raw history, so hist line numbers stay in sync |
|
2154 | 2011 | self.input_hist_raw.append("# " + line + "\n") |
|
2155 | 2012 | more = self.push(self.prefilter(line,more)) |
|
2156 | 2013 | # IPython's runsource returns None if there was an error |
|
2157 | 2014 | # compiling the code. This allows us to stop processing right |
|
2158 | 2015 | # away, so the user gets the error message at the right place. |
|
2159 | 2016 | if more is None: |
|
2160 | 2017 | break |
|
2161 | 2018 | else: |
|
2162 | 2019 | self.input_hist_raw.append("\n") |
|
2163 | 2020 | # final newline in case the input didn't have it, so that the code |
|
2164 | 2021 | # actually does get executed |
|
2165 | 2022 | if more: |
|
2166 | 2023 | self.push('\n') |
|
2167 | 2024 | |
|
2168 | 2025 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2169 | 2026 | """Compile and run some source in the interpreter. |
|
2170 | 2027 | |
|
2171 | 2028 | Arguments are as for compile_command(). |
|
2172 | 2029 | |
|
2173 | 2030 | One several things can happen: |
|
2174 | 2031 | |
|
2175 | 2032 | 1) The input is incorrect; compile_command() raised an |
|
2176 | 2033 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2177 | 2034 | will be printed by calling the showsyntaxerror() method. |
|
2178 | 2035 | |
|
2179 | 2036 | 2) The input is incomplete, and more input is required; |
|
2180 | 2037 | compile_command() returned None. Nothing happens. |
|
2181 | 2038 | |
|
2182 | 2039 | 3) The input is complete; compile_command() returned a code |
|
2183 | 2040 | object. The code is executed by calling self.runcode() (which |
|
2184 | 2041 | also handles run-time exceptions, except for SystemExit). |
|
2185 | 2042 | |
|
2186 | 2043 | The return value is: |
|
2187 | 2044 | |
|
2188 | 2045 | - True in case 2 |
|
2189 | 2046 | |
|
2190 | 2047 | - False in the other cases, unless an exception is raised, where |
|
2191 | 2048 | None is returned instead. This can be used by external callers to |
|
2192 | 2049 | know whether to continue feeding input or not. |
|
2193 | 2050 | |
|
2194 | 2051 | The return value can be used to decide whether to use sys.ps1 or |
|
2195 | 2052 | sys.ps2 to prompt the next line.""" |
|
2196 | 2053 | |
|
2197 | 2054 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2198 | 2055 | # this allows execution of indented pasted code. It is tempting |
|
2199 | 2056 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2200 | 2057 | # directly, but this fails for more complicated scenarios |
|
2201 | 2058 | source=source.encode(self.stdin_encoding) |
|
2202 | 2059 | if source[:1] in [' ', '\t']: |
|
2203 | 2060 | source = 'if 1:\n%s' % source |
|
2204 | 2061 | |
|
2205 | 2062 | try: |
|
2206 | 2063 | code = self.compile(source,filename,symbol) |
|
2207 | 2064 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2208 | 2065 | # Case 1 |
|
2209 | 2066 | self.showsyntaxerror(filename) |
|
2210 | 2067 | return None |
|
2211 | 2068 | |
|
2212 | 2069 | if code is None: |
|
2213 | 2070 | # Case 2 |
|
2214 | 2071 | return True |
|
2215 | 2072 | |
|
2216 | 2073 | # Case 3 |
|
2217 | 2074 | # We store the code object so that threaded shells and |
|
2218 | 2075 | # custom exception handlers can access all this info if needed. |
|
2219 | 2076 | # The source corresponding to this can be obtained from the |
|
2220 | 2077 | # buffer attribute as '\n'.join(self.buffer). |
|
2221 | 2078 | self.code_to_run = code |
|
2222 | 2079 | # now actually execute the code object |
|
2223 | 2080 | if self.runcode(code) == 0: |
|
2224 | 2081 | return False |
|
2225 | 2082 | else: |
|
2226 | 2083 | return None |
|
2227 | 2084 | |
|
2228 | 2085 | def runcode(self,code_obj): |
|
2229 | 2086 | """Execute a code object. |
|
2230 | 2087 | |
|
2231 | 2088 | When an exception occurs, self.showtraceback() is called to display a |
|
2232 | 2089 | traceback. |
|
2233 | 2090 | |
|
2234 | 2091 | Return value: a flag indicating whether the code to be run completed |
|
2235 | 2092 | successfully: |
|
2236 | 2093 | |
|
2237 | 2094 | - 0: successful execution. |
|
2238 | 2095 | - 1: an error occurred. |
|
2239 | 2096 | """ |
|
2240 | 2097 | |
|
2241 | 2098 | # Set our own excepthook in case the user code tries to call it |
|
2242 | 2099 | # directly, so that the IPython crash handler doesn't get triggered |
|
2243 | 2100 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2244 | 2101 | |
|
2245 | 2102 | # we save the original sys.excepthook in the instance, in case config |
|
2246 | 2103 | # code (such as magics) needs access to it. |
|
2247 | 2104 | self.sys_excepthook = old_excepthook |
|
2248 | 2105 | outflag = 1 # happens in more places, so it's easier as default |
|
2249 | 2106 | try: |
|
2250 | 2107 | try: |
|
2251 | 2108 | self.hooks.pre_runcode_hook() |
|
2252 | 2109 | exec code_obj in self.user_global_ns, self.user_ns |
|
2253 | 2110 | finally: |
|
2254 | 2111 | # Reset our crash handler in place |
|
2255 | 2112 | sys.excepthook = old_excepthook |
|
2256 | 2113 | except SystemExit: |
|
2257 | 2114 | self.resetbuffer() |
|
2258 | 2115 | self.showtraceback() |
|
2259 | 2116 | warn("Type %exit or %quit to exit IPython " |
|
2260 | 2117 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2261 | 2118 | except self.custom_exceptions: |
|
2262 | 2119 | etype,value,tb = sys.exc_info() |
|
2263 | 2120 | self.CustomTB(etype,value,tb) |
|
2264 | 2121 | except: |
|
2265 | 2122 | self.showtraceback() |
|
2266 | 2123 | else: |
|
2267 | 2124 | outflag = 0 |
|
2268 | 2125 | if softspace(sys.stdout, 0): |
|
2269 | 2126 | |
|
2270 | 2127 | # Flush out code object which has been run (and source) |
|
2271 | 2128 | self.code_to_run = None |
|
2272 | 2129 | return outflag |
|
2273 | 2130 | |
|
2274 | 2131 | def push(self, line): |
|
2275 | 2132 | """Push a line to the interpreter. |
|
2276 | 2133 | |
|
2277 | 2134 | The line should not have a trailing newline; it may have |
|
2278 | 2135 | internal newlines. The line is appended to a buffer and the |
|
2279 | 2136 | interpreter's runsource() method is called with the |
|
2280 | 2137 | concatenated contents of the buffer as source. If this |
|
2281 | 2138 | indicates that the command was executed or invalid, the buffer |
|
2282 | 2139 | is reset; otherwise, the command is incomplete, and the buffer |
|
2283 | 2140 | is left as it was after the line was appended. The return |
|
2284 | 2141 | value is 1 if more input is required, 0 if the line was dealt |
|
2285 | 2142 | with in some way (this is the same as runsource()). |
|
2286 | 2143 | """ |
|
2287 | 2144 | |
|
2288 | 2145 | # autoindent management should be done here, and not in the |
|
2289 | 2146 | # interactive loop, since that one is only seen by keyboard input. We |
|
2290 | 2147 | # need this done correctly even for code run via runlines (which uses |
|
2291 | 2148 | # push). |
|
2292 | 2149 | |
|
2293 | 2150 | #print 'push line: <%s>' % line # dbg |
|
2294 | 2151 | for subline in line.splitlines(): |
|
2295 | 2152 | self.autoindent_update(subline) |
|
2296 | 2153 | self.buffer.append(line) |
|
2297 | 2154 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2298 | 2155 | if not more: |
|
2299 | 2156 | self.resetbuffer() |
|
2300 | 2157 | return more |
|
2301 | 2158 | |
|
2302 | 2159 | def split_user_input(self, line): |
|
2303 | 2160 | # This is really a hold-over to support ipapi and some extensions |
|
2304 | 2161 | return prefilter.splitUserInput(line) |
|
2305 | 2162 | |
|
2306 | 2163 | def resetbuffer(self): |
|
2307 | 2164 | """Reset the input buffer.""" |
|
2308 | 2165 | self.buffer[:] = [] |
|
2309 | 2166 | |
|
2310 | 2167 | def raw_input(self,prompt='',continue_prompt=False): |
|
2311 | 2168 | """Write a prompt and read a line. |
|
2312 | 2169 | |
|
2313 | 2170 | The returned line does not include the trailing newline. |
|
2314 | 2171 | When the user enters the EOF key sequence, EOFError is raised. |
|
2315 | 2172 | |
|
2316 | 2173 | Optional inputs: |
|
2317 | 2174 | |
|
2318 | 2175 | - prompt(''): a string to be printed to prompt the user. |
|
2319 | 2176 | |
|
2320 | 2177 | - continue_prompt(False): whether this line is the first one or a |
|
2321 | 2178 | continuation in a sequence of inputs. |
|
2322 | 2179 | """ |
|
2323 | 2180 | |
|
2324 | 2181 | # Code run by the user may have modified the readline completer state. |
|
2325 | 2182 | # We must ensure that our completer is back in place. |
|
2326 | 2183 | if self.has_readline: |
|
2327 | 2184 | self.set_completer() |
|
2328 | 2185 | |
|
2329 | 2186 | try: |
|
2330 | 2187 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2331 | 2188 | except ValueError: |
|
2332 | 2189 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2333 | 2190 | " or sys.stdout.close()!\nExiting IPython!") |
|
2334 | 2191 | self.ask_exit() |
|
2335 | 2192 | return "" |
|
2336 | 2193 | |
|
2337 | 2194 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2338 | 2195 | # than necessary. We do this by trimming out the auto-indent initial |
|
2339 | 2196 | # spaces, if the user's actual input started itself with whitespace. |
|
2340 | 2197 | #debugx('self.buffer[-1]') |
|
2341 | 2198 | |
|
2342 | 2199 | if self.autoindent: |
|
2343 | 2200 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2344 | 2201 | line = line[self.indent_current_nsp:] |
|
2345 | 2202 | self.indent_current_nsp = 0 |
|
2346 | 2203 | |
|
2347 | 2204 | # store the unfiltered input before the user has any chance to modify |
|
2348 | 2205 | # it. |
|
2349 | 2206 | if line.strip(): |
|
2350 | 2207 | if continue_prompt: |
|
2351 | 2208 | self.input_hist_raw[-1] += '%s\n' % line |
|
2352 | 2209 | if self.has_readline: # and some config option is set? |
|
2353 | 2210 | try: |
|
2354 | 2211 | histlen = self.readline.get_current_history_length() |
|
2355 | 2212 | if histlen > 1: |
|
2356 | 2213 | newhist = self.input_hist_raw[-1].rstrip() |
|
2357 | 2214 | self.readline.remove_history_item(histlen-1) |
|
2358 | 2215 | self.readline.replace_history_item(histlen-2, |
|
2359 | 2216 | newhist.encode(self.stdin_encoding)) |
|
2360 | 2217 | except AttributeError: |
|
2361 | 2218 | pass # re{move,place}_history_item are new in 2.4. |
|
2362 | 2219 | else: |
|
2363 | 2220 | self.input_hist_raw.append('%s\n' % line) |
|
2364 | 2221 | # only entries starting at first column go to shadow history |
|
2365 | 2222 | if line.lstrip() == line: |
|
2366 | 2223 | self.shadowhist.add(line.strip()) |
|
2367 | 2224 | elif not continue_prompt: |
|
2368 | 2225 | self.input_hist_raw.append('\n') |
|
2369 | 2226 | try: |
|
2370 | 2227 | lineout = self.prefilter(line,continue_prompt) |
|
2371 | 2228 | except: |
|
2372 | 2229 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2373 | 2230 | # can't take all of ipython with it. |
|
2374 | 2231 | self.showtraceback() |
|
2375 | 2232 | return '' |
|
2376 | 2233 | else: |
|
2377 | 2234 | return lineout |
|
2378 | 2235 | |
|
2379 | 2236 | def _prefilter(self, line, continue_prompt): |
|
2380 | 2237 | """Calls different preprocessors, depending on the form of line.""" |
|
2381 | 2238 | |
|
2382 | 2239 | # All handlers *must* return a value, even if it's blank (''). |
|
2383 | 2240 | |
|
2384 | 2241 | # Lines are NOT logged here. Handlers should process the line as |
|
2385 | 2242 | # needed, update the cache AND log it (so that the input cache array |
|
2386 | 2243 | # stays synced). |
|
2387 | 2244 | |
|
2388 | 2245 | #..................................................................... |
|
2389 | 2246 | # Code begins |
|
2390 | 2247 | |
|
2391 | 2248 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2392 | 2249 | |
|
2393 | 2250 | # save the line away in case we crash, so the post-mortem handler can |
|
2394 | 2251 | # record it |
|
2395 | 2252 | self._last_input_line = line |
|
2396 | 2253 | |
|
2397 | 2254 | #print '***line: <%s>' % line # dbg |
|
2398 | 2255 | |
|
2399 | 2256 | if not line: |
|
2400 | 2257 | # Return immediately on purely empty lines, so that if the user |
|
2401 | 2258 | # previously typed some whitespace that started a continuation |
|
2402 | 2259 | # prompt, he can break out of that loop with just an empty line. |
|
2403 | 2260 | # This is how the default python prompt works. |
|
2404 | 2261 | |
|
2405 | 2262 | # Only return if the accumulated input buffer was just whitespace! |
|
2406 | 2263 | if ''.join(self.buffer).isspace(): |
|
2407 | 2264 | self.buffer[:] = [] |
|
2408 | 2265 | return '' |
|
2409 | 2266 | |
|
2410 | 2267 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2411 | 2268 | |
|
2412 | 2269 | # the input history needs to track even empty lines |
|
2413 | 2270 | stripped = line.strip() |
|
2414 | 2271 | |
|
2415 | 2272 | if not stripped: |
|
2416 | 2273 | if not continue_prompt: |
|
2417 | 2274 | self.outputcache.prompt_count -= 1 |
|
2418 | 2275 | return self.handle_normal(line_info) |
|
2419 | 2276 | |
|
2420 | 2277 | # print '***cont',continue_prompt # dbg |
|
2421 | 2278 | # special handlers are only allowed for single line statements |
|
2422 |
if continue_prompt and not self. |
|
|
2279 | if continue_prompt and not self.multi_line_specials: | |
|
2423 | 2280 | return self.handle_normal(line_info) |
|
2424 | 2281 | |
|
2425 | 2282 | |
|
2426 | 2283 | # See whether any pre-existing handler can take care of it |
|
2427 | 2284 | rewritten = self.hooks.input_prefilter(stripped) |
|
2428 | 2285 | if rewritten != stripped: # ok, some prefilter did something |
|
2429 | 2286 | rewritten = line_info.pre + rewritten # add indentation |
|
2430 | 2287 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2431 | 2288 | continue_prompt)) |
|
2432 | 2289 | |
|
2433 | 2290 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2434 | 2291 | |
|
2435 | 2292 | return prefilter.prefilter(line_info, self) |
|
2436 | 2293 | |
|
2437 | 2294 | |
|
2438 | 2295 | def _prefilter_dumb(self, line, continue_prompt): |
|
2439 | 2296 | """simple prefilter function, for debugging""" |
|
2440 | 2297 | return self.handle_normal(line,continue_prompt) |
|
2441 | 2298 | |
|
2442 | 2299 | |
|
2443 | 2300 | def multiline_prefilter(self, line, continue_prompt): |
|
2444 | 2301 | """ Run _prefilter for each line of input |
|
2445 | 2302 | |
|
2446 | 2303 | Covers cases where there are multiple lines in the user entry, |
|
2447 | 2304 | which is the case when the user goes back to a multiline history |
|
2448 | 2305 | entry and presses enter. |
|
2449 | 2306 | |
|
2450 | 2307 | """ |
|
2451 | 2308 | out = [] |
|
2452 | 2309 | for l in line.rstrip('\n').split('\n'): |
|
2453 | 2310 | out.append(self._prefilter(l, continue_prompt)) |
|
2454 | 2311 | return '\n'.join(out) |
|
2455 | 2312 | |
|
2456 | 2313 | # Set the default prefilter() function (this can be user-overridden) |
|
2457 | 2314 | prefilter = multiline_prefilter |
|
2458 | 2315 | |
|
2459 | 2316 | def handle_normal(self,line_info): |
|
2460 | 2317 | """Handle normal input lines. Use as a template for handlers.""" |
|
2461 | 2318 | |
|
2462 | 2319 | # With autoindent on, we need some way to exit the input loop, and I |
|
2463 | 2320 | # don't want to force the user to have to backspace all the way to |
|
2464 | 2321 | # clear the line. The rule will be in this case, that either two |
|
2465 | 2322 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2466 | 2323 | # of a size different to the indent level, will exit the input loop. |
|
2467 | 2324 | line = line_info.line |
|
2468 | 2325 | continue_prompt = line_info.continue_prompt |
|
2469 | 2326 | |
|
2470 | 2327 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2471 | 2328 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2472 | 2329 | (self.buffer[-1]).isspace() )): |
|
2473 | 2330 | line = '' |
|
2474 | 2331 | |
|
2475 | 2332 | self.log(line,line,continue_prompt) |
|
2476 | 2333 | return line |
|
2477 | 2334 | |
|
2478 | 2335 | def handle_alias(self,line_info): |
|
2479 | 2336 | """Handle alias input lines. """ |
|
2480 | 2337 | tgt = self.alias_table[line_info.iFun] |
|
2481 | 2338 | # print "=>",tgt #dbg |
|
2482 | 2339 | if callable(tgt): |
|
2483 | 2340 | if '$' in line_info.line: |
|
2484 | 2341 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2485 | 2342 | else: |
|
2486 | 2343 | call_meth = '(_ip,%s)' |
|
2487 | 2344 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2488 | 2345 | line_info.iFun, |
|
2489 | 2346 | make_quoted_expr(line_info.line)) |
|
2490 | 2347 | else: |
|
2491 | 2348 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2492 | 2349 | |
|
2493 | 2350 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2494 | 2351 | # aliases won't work in indented sections. |
|
2495 | 2352 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2496 | 2353 | make_quoted_expr( transformed )) |
|
2497 | 2354 | |
|
2498 | 2355 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2499 | 2356 | #print 'line out:',line_out # dbg |
|
2500 | 2357 | return line_out |
|
2501 | 2358 | |
|
2502 | 2359 | def handle_shell_escape(self, line_info): |
|
2503 | 2360 | """Execute the line in a shell, empty return value""" |
|
2504 | 2361 | #print 'line in :', `line` # dbg |
|
2505 | 2362 | line = line_info.line |
|
2506 | 2363 | if line.lstrip().startswith('!!'): |
|
2507 | 2364 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2508 | 2365 | # call to %sx and the actual command to be executed, so |
|
2509 | 2366 | # handle_magic can work correctly. Note that this works even if |
|
2510 | 2367 | # the line is indented, so it handles multi_line_specials |
|
2511 | 2368 | # properly. |
|
2512 | 2369 | new_rest = line.lstrip()[2:] |
|
2513 | 2370 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2514 | 2371 | line_info.iFun = 'sx' |
|
2515 | 2372 | line_info.theRest = new_rest |
|
2516 | 2373 | return self.handle_magic(line_info) |
|
2517 | 2374 | else: |
|
2518 | 2375 | cmd = line.lstrip().lstrip('!') |
|
2519 | 2376 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2520 | 2377 | make_quoted_expr(cmd)) |
|
2521 | 2378 | # update cache/log and return |
|
2522 | 2379 | self.log(line,line_out,line_info.continue_prompt) |
|
2523 | 2380 | return line_out |
|
2524 | 2381 | |
|
2525 | 2382 | def handle_magic(self, line_info): |
|
2526 | 2383 | """Execute magic functions.""" |
|
2527 | 2384 | iFun = line_info.iFun |
|
2528 | 2385 | theRest = line_info.theRest |
|
2529 | 2386 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2530 | 2387 | make_quoted_expr(iFun + " " + theRest)) |
|
2531 | 2388 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2532 | 2389 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2533 | 2390 | return cmd |
|
2534 | 2391 | |
|
2535 | 2392 | def handle_auto(self, line_info): |
|
2536 | 2393 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2537 | 2394 | |
|
2538 | 2395 | line = line_info.line |
|
2539 | 2396 | iFun = line_info.iFun |
|
2540 | 2397 | theRest = line_info.theRest |
|
2541 | 2398 | pre = line_info.pre |
|
2542 | 2399 | continue_prompt = line_info.continue_prompt |
|
2543 | 2400 | obj = line_info.ofind(self)['obj'] |
|
2544 | 2401 | |
|
2545 | 2402 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2546 | 2403 | |
|
2547 | 2404 | # This should only be active for single-line input! |
|
2548 | 2405 | if continue_prompt: |
|
2549 | 2406 | self.log(line,line,continue_prompt) |
|
2550 | 2407 | return line |
|
2551 | 2408 | |
|
2552 | 2409 | force_auto = isinstance(obj, ipapi.IPyAutocall) |
|
2553 | 2410 | auto_rewrite = True |
|
2554 | 2411 | |
|
2555 | 2412 | if pre == self.ESC_QUOTE: |
|
2556 | 2413 | # Auto-quote splitting on whitespace |
|
2557 | 2414 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2558 | 2415 | elif pre == self.ESC_QUOTE2: |
|
2559 | 2416 | # Auto-quote whole string |
|
2560 | 2417 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2561 | 2418 | elif pre == self.ESC_PAREN: |
|
2562 | 2419 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2563 | 2420 | else: |
|
2564 | 2421 | # Auto-paren. |
|
2565 | 2422 | # We only apply it to argument-less calls if the autocall |
|
2566 | 2423 | # parameter is set to 2. We only need to check that autocall is < |
|
2567 | 2424 | # 2, since this function isn't called unless it's at least 1. |
|
2568 |
if not theRest and (self |
|
|
2425 | if not theRest and (self.autocall < 2) and not force_auto: | |
|
2569 | 2426 | newcmd = '%s %s' % (iFun,theRest) |
|
2570 | 2427 | auto_rewrite = False |
|
2571 | 2428 | else: |
|
2572 | 2429 | if not force_auto and theRest.startswith('['): |
|
2573 | 2430 | if hasattr(obj,'__getitem__'): |
|
2574 | 2431 | # Don't autocall in this case: item access for an object |
|
2575 | 2432 | # which is BOTH callable and implements __getitem__. |
|
2576 | 2433 | newcmd = '%s %s' % (iFun,theRest) |
|
2577 | 2434 | auto_rewrite = False |
|
2578 | 2435 | else: |
|
2579 | 2436 | # if the object doesn't support [] access, go ahead and |
|
2580 | 2437 | # autocall |
|
2581 | 2438 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2582 | 2439 | elif theRest.endswith(';'): |
|
2583 | 2440 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2584 | 2441 | else: |
|
2585 | 2442 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2586 | 2443 | |
|
2587 | 2444 | if auto_rewrite: |
|
2588 | 2445 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2589 | 2446 | |
|
2590 | 2447 | try: |
|
2591 | 2448 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2592 | 2449 | # we use it and only print uncolored rewrite if we have unicode |
|
2593 | 2450 | rw = str(rw) |
|
2594 | 2451 | print >>Term.cout, rw |
|
2595 | 2452 | except UnicodeEncodeError: |
|
2596 | 2453 | print "-------------->" + newcmd |
|
2597 | 2454 | |
|
2598 | 2455 | # log what is now valid Python, not the actual user input (without the |
|
2599 | 2456 | # final newline) |
|
2600 | 2457 | self.log(line,newcmd,continue_prompt) |
|
2601 | 2458 | return newcmd |
|
2602 | 2459 | |
|
2603 | 2460 | def handle_help(self, line_info): |
|
2604 | 2461 | """Try to get some help for the object. |
|
2605 | 2462 | |
|
2606 | 2463 | obj? or ?obj -> basic information. |
|
2607 | 2464 | obj?? or ??obj -> more details. |
|
2608 | 2465 | """ |
|
2609 | 2466 | |
|
2610 | 2467 | line = line_info.line |
|
2611 | 2468 | # We need to make sure that we don't process lines which would be |
|
2612 | 2469 | # otherwise valid python, such as "x=1 # what?" |
|
2613 | 2470 | try: |
|
2614 | 2471 | codeop.compile_command(line) |
|
2615 | 2472 | except SyntaxError: |
|
2616 | 2473 | # We should only handle as help stuff which is NOT valid syntax |
|
2617 | 2474 | if line[0]==self.ESC_HELP: |
|
2618 | 2475 | line = line[1:] |
|
2619 | 2476 | elif line[-1]==self.ESC_HELP: |
|
2620 | 2477 | line = line[:-1] |
|
2621 | 2478 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2622 | 2479 | if line: |
|
2623 | 2480 | #print 'line:<%r>' % line # dbg |
|
2624 | 2481 | self.magic_pinfo(line) |
|
2625 | 2482 | else: |
|
2626 |
page(self.usage,screen_lines=self. |
|
|
2483 | page(self.usage,screen_lines=self.screen_length) | |
|
2627 | 2484 | return '' # Empty string is needed here! |
|
2628 | 2485 | except: |
|
2629 | 2486 | # Pass any other exceptions through to the normal handler |
|
2630 | 2487 | return self.handle_normal(line_info) |
|
2631 | 2488 | else: |
|
2632 | 2489 | # If the code compiles ok, we should handle it normally |
|
2633 | 2490 | return self.handle_normal(line_info) |
|
2634 | 2491 | |
|
2635 | 2492 | def getapi(self): |
|
2636 | 2493 | """ Get an IPApi object for this shell instance |
|
2637 | 2494 | |
|
2638 | 2495 | Getting an IPApi object is always preferable to accessing the shell |
|
2639 | 2496 | directly, but this holds true especially for extensions. |
|
2640 | 2497 | |
|
2641 | 2498 | It should always be possible to implement an extension with IPApi |
|
2642 | 2499 | alone. If not, contact maintainer to request an addition. |
|
2643 | 2500 | |
|
2644 | 2501 | """ |
|
2645 | 2502 | return self.api |
|
2646 | 2503 | |
|
2647 | 2504 | def handle_emacs(self, line_info): |
|
2648 | 2505 | """Handle input lines marked by python-mode.""" |
|
2649 | 2506 | |
|
2650 | 2507 | # Currently, nothing is done. Later more functionality can be added |
|
2651 | 2508 | # here if needed. |
|
2652 | 2509 | |
|
2653 | 2510 | # The input cache shouldn't be updated |
|
2654 | 2511 | return line_info.line |
|
2655 | 2512 | |
|
2513 | def var_expand(self,cmd,depth=0): | |
|
2514 | """Expand python variables in a string. | |
|
2515 | ||
|
2516 | The depth argument indicates how many frames above the caller should | |
|
2517 | be walked to look for the local namespace where to expand variables. | |
|
2518 | ||
|
2519 | The global namespace for expansion is always the user's interactive | |
|
2520 | namespace. | |
|
2521 | """ | |
|
2522 | ||
|
2523 | return str(ItplNS(cmd, | |
|
2524 | self.user_ns, # globals | |
|
2525 | # Skip our own frame in searching for locals: | |
|
2526 | sys._getframe(depth+1).f_locals # locals | |
|
2527 | )) | |
|
2656 | 2528 | |
|
2657 | 2529 | def mktempfile(self,data=None): |
|
2658 | 2530 | """Make a new tempfile and return its filename. |
|
2659 | 2531 | |
|
2660 | 2532 | This makes a call to tempfile.mktemp, but it registers the created |
|
2661 | 2533 | filename internally so ipython cleans it up at exit time. |
|
2662 | 2534 | |
|
2663 | 2535 | Optional inputs: |
|
2664 | 2536 | |
|
2665 | 2537 | - data(None): if data is given, it gets written out to the temp file |
|
2666 | 2538 | immediately, and the file is closed again.""" |
|
2667 | 2539 | |
|
2668 | 2540 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2669 | 2541 | self.tempfiles.append(filename) |
|
2670 | 2542 | |
|
2671 | 2543 | if data: |
|
2672 | 2544 | tmp_file = open(filename,'w') |
|
2673 | 2545 | tmp_file.write(data) |
|
2674 | 2546 | tmp_file.close() |
|
2675 | 2547 | return filename |
|
2676 | 2548 | |
|
2677 | 2549 | def write(self,data): |
|
2678 | 2550 | """Write a string to the default output""" |
|
2679 | 2551 | Term.cout.write(data) |
|
2680 | 2552 | |
|
2681 | 2553 | def write_err(self,data): |
|
2682 | 2554 | """Write a string to the default error output""" |
|
2683 | 2555 | Term.cerr.write(data) |
|
2684 | 2556 | |
|
2685 | 2557 | def ask_exit(self): |
|
2686 | 2558 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2687 | 2559 | self.exit_now = True |
|
2688 | 2560 | |
|
2689 | 2561 | def exit(self): |
|
2690 | 2562 | """Handle interactive exit. |
|
2691 | 2563 | |
|
2692 | 2564 | This method calls the ask_exit callback.""" |
|
2693 | ||
|
2694 |
if self. |
|
|
2565 | print "IN self.exit", self.confirm_exit | |
|
2566 | if self.confirm_exit: | |
|
2695 | 2567 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2696 | 2568 | self.ask_exit() |
|
2697 | 2569 | else: |
|
2698 | 2570 | self.ask_exit() |
|
2699 | 2571 | |
|
2700 | 2572 | def safe_execfile(self,fname,*where,**kw): |
|
2701 | 2573 | """A safe version of the builtin execfile(). |
|
2702 | 2574 | |
|
2703 | 2575 | This version will never throw an exception, and knows how to handle |
|
2704 | 2576 | ipython logs as well. |
|
2705 | 2577 | |
|
2706 | 2578 | :Parameters: |
|
2707 | 2579 | fname : string |
|
2708 | 2580 | Name of the file to be executed. |
|
2709 | 2581 | |
|
2710 | 2582 | where : tuple |
|
2711 | 2583 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2712 | 2584 | If only one is given, it is passed as both. |
|
2713 | 2585 | |
|
2714 | 2586 | :Keywords: |
|
2715 | 2587 | islog : boolean (False) |
|
2716 | 2588 | |
|
2717 | 2589 | quiet : boolean (True) |
|
2718 | 2590 | |
|
2719 | 2591 | exit_ignore : boolean (False) |
|
2720 | 2592 | """ |
|
2721 | 2593 | |
|
2722 | 2594 | def syspath_cleanup(): |
|
2723 | 2595 | """Internal cleanup routine for sys.path.""" |
|
2724 | 2596 | if add_dname: |
|
2725 | 2597 | try: |
|
2726 | 2598 | sys.path.remove(dname) |
|
2727 | 2599 | except ValueError: |
|
2728 | 2600 | # For some reason the user has already removed it, ignore. |
|
2729 | 2601 | pass |
|
2730 | 2602 | |
|
2731 | 2603 | fname = os.path.expanduser(fname) |
|
2732 | 2604 | |
|
2733 | 2605 | # Find things also in current directory. This is needed to mimic the |
|
2734 | 2606 | # behavior of running a script from the system command line, where |
|
2735 | 2607 | # Python inserts the script's directory into sys.path |
|
2736 | 2608 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2737 | 2609 | add_dname = False |
|
2738 | 2610 | if dname not in sys.path: |
|
2739 | 2611 | sys.path.insert(0,dname) |
|
2740 | 2612 | add_dname = True |
|
2741 | 2613 | |
|
2742 | 2614 | try: |
|
2743 | 2615 | xfile = open(fname) |
|
2744 | 2616 | except: |
|
2745 | 2617 | print >> Term.cerr, \ |
|
2746 | 2618 | 'Could not open file <%s> for safe execution.' % fname |
|
2747 | 2619 | syspath_cleanup() |
|
2748 | 2620 | return None |
|
2749 | 2621 | |
|
2750 | 2622 | kw.setdefault('islog',0) |
|
2751 | 2623 | kw.setdefault('quiet',1) |
|
2752 | 2624 | kw.setdefault('exit_ignore',0) |
|
2753 | 2625 | |
|
2754 | 2626 | first = xfile.readline() |
|
2755 | 2627 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2756 | 2628 | xfile.close() |
|
2757 | 2629 | # line by line execution |
|
2758 | 2630 | if first.startswith(loghead) or kw['islog']: |
|
2759 | 2631 | print 'Loading log file <%s> one line at a time...' % fname |
|
2760 | 2632 | if kw['quiet']: |
|
2761 | 2633 | stdout_save = sys.stdout |
|
2762 | 2634 | sys.stdout = StringIO.StringIO() |
|
2763 | 2635 | try: |
|
2764 | 2636 | globs,locs = where[0:2] |
|
2765 | 2637 | except: |
|
2766 | 2638 | try: |
|
2767 | 2639 | globs = locs = where[0] |
|
2768 | 2640 | except: |
|
2769 | 2641 | globs = locs = globals() |
|
2770 | 2642 | badblocks = [] |
|
2771 | 2643 | |
|
2772 | 2644 | # we also need to identify indented blocks of code when replaying |
|
2773 | 2645 | # logs and put them together before passing them to an exec |
|
2774 | 2646 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2775 | 2647 | # file. It's easiest if we swallow the whole thing in memory |
|
2776 | 2648 | # first, and manually walk through the lines list moving the |
|
2777 | 2649 | # counter ourselves. |
|
2778 | 2650 | indent_re = re.compile('\s+\S') |
|
2779 | 2651 | xfile = open(fname) |
|
2780 | 2652 | filelines = xfile.readlines() |
|
2781 | 2653 | xfile.close() |
|
2782 | 2654 | nlines = len(filelines) |
|
2783 | 2655 | lnum = 0 |
|
2784 | 2656 | while lnum < nlines: |
|
2785 | 2657 | line = filelines[lnum] |
|
2786 | 2658 | lnum += 1 |
|
2787 | 2659 | # don't re-insert logger status info into cache |
|
2788 | 2660 | if line.startswith('#log#'): |
|
2789 | 2661 | continue |
|
2790 | 2662 | else: |
|
2791 | 2663 | # build a block of code (maybe a single line) for execution |
|
2792 | 2664 | block = line |
|
2793 | 2665 | try: |
|
2794 | 2666 | next = filelines[lnum] # lnum has already incremented |
|
2795 | 2667 | except: |
|
2796 | 2668 | next = None |
|
2797 | 2669 | while next and indent_re.match(next): |
|
2798 | 2670 | block += next |
|
2799 | 2671 | lnum += 1 |
|
2800 | 2672 | try: |
|
2801 | 2673 | next = filelines[lnum] |
|
2802 | 2674 | except: |
|
2803 | 2675 | next = None |
|
2804 | 2676 | # now execute the block of one or more lines |
|
2805 | 2677 | try: |
|
2806 | 2678 | exec block in globs,locs |
|
2807 | 2679 | except SystemExit: |
|
2808 | 2680 | pass |
|
2809 | 2681 | except: |
|
2810 | 2682 | badblocks.append(block.rstrip()) |
|
2811 | 2683 | if kw['quiet']: # restore stdout |
|
2812 | 2684 | sys.stdout.close() |
|
2813 | 2685 | sys.stdout = stdout_save |
|
2814 | 2686 | print 'Finished replaying log file <%s>' % fname |
|
2815 | 2687 | if badblocks: |
|
2816 | 2688 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2817 | 2689 | '<%s> reported errors:' % fname) |
|
2818 | 2690 | |
|
2819 | 2691 | for badline in badblocks: |
|
2820 | 2692 | print >> sys.stderr, badline |
|
2821 | 2693 | else: # regular file execution |
|
2822 | 2694 | try: |
|
2823 | 2695 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2824 | 2696 | # Work around a bug in Python for Windows. The bug was |
|
2825 | 2697 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2826 | 2698 | # SVN Python as of March/07. For details, see: |
|
2827 | 2699 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2828 | 2700 | try: |
|
2829 | 2701 | globs,locs = where[0:2] |
|
2830 | 2702 | except: |
|
2831 | 2703 | try: |
|
2832 | 2704 | globs = locs = where[0] |
|
2833 | 2705 | except: |
|
2834 | 2706 | globs = locs = globals() |
|
2835 | 2707 | exec file(fname) in globs,locs |
|
2836 | 2708 | else: |
|
2837 | 2709 | execfile(fname,*where) |
|
2838 | 2710 | except SyntaxError: |
|
2839 | 2711 | self.showsyntaxerror() |
|
2840 | 2712 | warn('Failure executing file: <%s>' % fname) |
|
2841 | 2713 | except SystemExit,status: |
|
2842 | 2714 | # Code that correctly sets the exit status flag to success (0) |
|
2843 | 2715 | # shouldn't be bothered with a traceback. Note that a plain |
|
2844 | 2716 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2845 | 2717 | # will still get a traceback. Note that the structure of the |
|
2846 | 2718 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2847 | 2719 | # the checks must be done in a version-dependent way. |
|
2848 | 2720 | show = False |
|
2849 | 2721 | |
|
2850 | 2722 | if sys.version_info[:2] > (2,5): |
|
2851 | 2723 | if status.message!=0 and not kw['exit_ignore']: |
|
2852 | 2724 | show = True |
|
2853 | 2725 | else: |
|
2854 | 2726 | if status.code and not kw['exit_ignore']: |
|
2855 | 2727 | show = True |
|
2856 | 2728 | if show: |
|
2857 | 2729 | self.showtraceback() |
|
2858 | 2730 | warn('Failure executing file: <%s>' % fname) |
|
2859 | 2731 | except: |
|
2860 | 2732 | self.showtraceback() |
|
2861 | 2733 | warn('Failure executing file: <%s>' % fname) |
|
2862 | 2734 | |
|
2863 | 2735 | syspath_cleanup() |
|
2864 | 2736 | |
|
2865 | 2737 | #************************* end of file <iplib.py> ***************************** |
@@ -1,792 +1,793 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.1 or better. |
|
6 | 6 | |
|
7 | 7 | This file contains the main make_IPython() starter function. |
|
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 | try: |
|
19 | 19 | credits._Printer__data = """ |
|
20 | 20 | Python: %s |
|
21 | 21 | |
|
22 | 22 | IPython: The IPython Development Team. |
|
23 | 23 | See http://ipython.scipy.org for more information.""" \ |
|
24 | 24 | % credits._Printer__data |
|
25 | 25 | |
|
26 | 26 | copyright._Printer__data += """ |
|
27 | 27 | |
|
28 | 28 | Copyright (c) 2008-2009 The IPython Development Team. |
|
29 | 29 | Copyright (c) 2001-2007 Fernando Perez, Janko Hauser, Nathan Gray. |
|
30 | 30 | All Rights Reserved.""" |
|
31 | 31 | except NameError: |
|
32 | 32 | # Can happen if ipython was started with 'python -S', so that site.py is |
|
33 | 33 | # not loaded |
|
34 | 34 | pass |
|
35 | 35 | |
|
36 | 36 | #**************************************************************************** |
|
37 | 37 | # Required modules |
|
38 | 38 | |
|
39 | 39 | # From the standard library |
|
40 | 40 | import __main__ |
|
41 | 41 | import __builtin__ |
|
42 | 42 | import os |
|
43 | 43 | import sys |
|
44 | 44 | from pprint import pprint |
|
45 | 45 | import warnings |
|
46 | 46 | |
|
47 | 47 | # Our own |
|
48 | 48 | from IPython.utils import DPyGetOpt |
|
49 | 49 | from IPython.core import release |
|
50 | from IPython.core.oldusersetup import user_setup | |
|
50 | 51 | from IPython.utils.ipstruct import Struct |
|
51 | 52 | from IPython.core.outputtrap import OutputTrap |
|
52 | 53 | from IPython.config.configloader import ConfigLoader |
|
53 | 54 | from IPython.core.iplib import InteractiveShell |
|
54 | 55 | from IPython.core.usage import cmd_line_usage, interactive_usage |
|
55 | 56 | from IPython.utils.genutils import * |
|
56 | 57 | |
|
57 | 58 | |
|
58 | 59 | def force_import(modname,force_reload=False): |
|
59 | 60 | if modname in sys.modules and force_reload: |
|
60 | 61 | info("reloading: %s" % modname) |
|
61 | 62 | reload(sys.modules[modname]) |
|
62 | 63 | else: |
|
63 | 64 | __import__(modname) |
|
64 | 65 | |
|
65 | 66 | |
|
66 | 67 | def threaded_shell_warning(): |
|
67 | 68 | msg = """ |
|
68 | 69 | |
|
69 | 70 | The IPython threaded shells and their associated command line |
|
70 | 71 | arguments (pylab/wthread/gthread/qthread/q4thread) have been |
|
71 | 72 | deprecated. See the %gui magic for information on the new interface. |
|
72 | 73 | """ |
|
73 | 74 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) |
|
74 | 75 | |
|
75 | 76 | |
|
76 | 77 | #----------------------------------------------------------------------------- |
|
77 | 78 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, |
|
78 | 79 | rc_override=None,shell_class=InteractiveShell, |
|
79 | 80 | embedded=False,**kw): |
|
80 | 81 | """This is a dump of IPython into a single function. |
|
81 | 82 | |
|
82 | 83 | Later it will have to be broken up in a sensible manner. |
|
83 | 84 | |
|
84 | 85 | Arguments: |
|
85 | 86 | |
|
86 | 87 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired |
|
87 | 88 | script name, b/c DPyGetOpt strips the first argument only for the real |
|
88 | 89 | sys.argv. |
|
89 | 90 | |
|
90 | 91 | - user_ns: a dict to be used as the user's namespace.""" |
|
91 | 92 | |
|
92 | 93 | #---------------------------------------------------------------------- |
|
93 | 94 | # Defaults and initialization |
|
94 | 95 | |
|
95 | 96 | # For developer debugging, deactivates crash handler and uses pdb. |
|
96 | 97 | DEVDEBUG = True |
|
97 | 98 | |
|
98 | 99 | if argv is None: |
|
99 | 100 | argv = sys.argv |
|
100 | 101 | |
|
101 | 102 | # __IP is the main global that lives throughout and represents the whole |
|
102 | 103 | # application. If the user redefines it, all bets are off as to what |
|
103 | 104 | # happens. |
|
104 | 105 | |
|
105 | 106 | # __IP is the name of he global which the caller will have accessible as |
|
106 | 107 | # __IP.name. We set its name via the first parameter passed to |
|
107 | 108 | # InteractiveShell: |
|
108 | 109 | |
|
109 | 110 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, |
|
110 | 111 | embedded=embedded,**kw) |
|
111 | 112 | |
|
112 | 113 | # Put 'help' in the user namespace |
|
113 | 114 | try: |
|
114 | 115 | from site import _Helper |
|
115 | 116 | IP.user_ns['help'] = _Helper() |
|
116 | 117 | except ImportError: |
|
117 | 118 | warn('help() not available - check site.py') |
|
118 | 119 | |
|
119 | 120 | if DEVDEBUG: |
|
120 | 121 | # For developer debugging only (global flag) |
|
121 | 122 | from IPython.core import ultratb |
|
122 | 123 | sys.excepthook = ultratb.VerboseTB(call_pdb=1) |
|
123 | 124 | |
|
124 | 125 | IP.BANNER_PARTS = ['Python %s\n' |
|
125 | 126 | 'Type "copyright", "credits" or "license" ' |
|
126 | 127 | 'for more information.\n' |
|
127 | 128 | % (sys.version.split('\n')[0],), |
|
128 | 129 | "IPython %s -- An enhanced Interactive Python." |
|
129 | 130 | % (release.version,), |
|
130 | 131 | """\ |
|
131 | 132 | ? -> Introduction and overview of IPython's features. |
|
132 | 133 | %quickref -> Quick reference. |
|
133 | 134 | help -> Python's own help system. |
|
134 | 135 | object? -> Details about 'object'. ?object also works, ?? prints more. |
|
135 | 136 | """ ] |
|
136 | 137 | |
|
137 | 138 | IP.usage = interactive_usage |
|
138 | 139 | |
|
139 | 140 | # Platform-dependent suffix. |
|
140 | 141 | if os.name == 'posix': |
|
141 | 142 | rc_suffix = '' |
|
142 | 143 | else: |
|
143 | 144 | rc_suffix = '.ini' |
|
144 | 145 | |
|
145 | 146 | # default directory for configuration |
|
146 | 147 | ipythondir_def = get_ipython_dir() |
|
147 | 148 | |
|
148 | 149 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
149 | 150 | |
|
150 | 151 | # we need the directory where IPython itself is installed |
|
151 | 152 | import IPython |
|
152 | 153 | IPython_dir = os.path.dirname(IPython.__file__) |
|
153 | 154 | del IPython |
|
154 | 155 | |
|
155 | 156 | #------------------------------------------------------------------------- |
|
156 | 157 | # Command line handling |
|
157 | 158 | |
|
158 | 159 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
159 | 160 | # GetOpt::Long) |
|
160 | 161 | |
|
161 | 162 | # Any key not listed here gets deleted even if in the file (like session |
|
162 | 163 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
163 | 164 | |
|
164 | 165 | # Each set of options appears twice: under _conv only the names are |
|
165 | 166 | # listed, indicating which type they must be converted to when reading the |
|
166 | 167 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
167 | 168 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
168 | 169 | |
|
169 | 170 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
170 | 171 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' |
|
171 | 172 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
172 | 173 | 'debug! deep_reload! editor=s log|l messages! nosep ' |
|
173 | 174 | 'object_info_string_level=i pdb! ' |
|
174 | 175 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
175 | 176 | 'pydb! ' |
|
176 | 177 | 'pylab_import_all! ' |
|
177 | 178 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
178 | 179 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
179 | 180 | 'readline! readline_merge_completions! ' |
|
180 | 181 | 'readline_omit__names! ' |
|
181 | 182 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
182 | 183 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
183 | 184 | 'magic_docstrings system_verbose! ' |
|
184 | 185 | 'multi_line_specials! ' |
|
185 | 186 | 'term_title! wxversion=s ' |
|
186 | 187 | 'autoedit_syntax!') |
|
187 | 188 | |
|
188 | 189 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
189 | 190 | |
|
190 | 191 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' |
|
191 | 192 | 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! ' |
|
192 | 193 | # 'twisted!' # disabled for now. |
|
193 | 194 | ) |
|
194 | 195 | |
|
195 | 196 | # Build the actual name list to be used by DPyGetOpt |
|
196 | 197 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
197 | 198 | |
|
198 | 199 | # Set sensible command line defaults. |
|
199 | 200 | # This should have everything from cmdline_opts and cmdline_only |
|
200 | 201 | opts_def = Struct(autocall = 1, |
|
201 | 202 | autoedit_syntax = 0, |
|
202 | 203 | autoindent = 0, |
|
203 | 204 | automagic = 1, |
|
204 | 205 | autoexec = [], |
|
205 | 206 | banner = 1, |
|
206 | 207 | c = '', |
|
207 | 208 | cache_size = 1000, |
|
208 | 209 | classic = 0, |
|
209 | 210 | color_info = 0, |
|
210 | 211 | colors = 'NoColor', |
|
211 | 212 | confirm_exit = 1, |
|
212 | 213 | debug = 0, |
|
213 | 214 | deep_reload = 0, |
|
214 | 215 | editor = '0', |
|
215 | 216 | gthread = 0, |
|
216 | 217 | help = 0, |
|
217 | 218 | interact = 0, |
|
218 | 219 | ipythondir = ipythondir_def, |
|
219 | 220 | log = 0, |
|
220 | 221 | logfile = '', |
|
221 | 222 | logplay = '', |
|
222 | 223 | messages = 1, |
|
223 | 224 | multi_line_specials = 1, |
|
224 | 225 | nosep = 0, |
|
225 | 226 | object_info_string_level = 0, |
|
226 | 227 | pdb = 0, |
|
227 | 228 | pprint = 0, |
|
228 | 229 | profile = '', |
|
229 | 230 | prompt_in1 = 'In [\\#]: ', |
|
230 | 231 | prompt_in2 = ' .\\D.: ', |
|
231 | 232 | prompt_out = 'Out[\\#]: ', |
|
232 | 233 | prompts_pad_left = 1, |
|
233 | 234 | pydb = 0, |
|
234 | 235 | pylab = 0, |
|
235 | 236 | pylab_import_all = 1, |
|
236 | 237 | q4thread = 0, |
|
237 | 238 | qthread = 0, |
|
238 | 239 | quick = 0, |
|
239 | 240 | quiet = 0, |
|
240 | 241 | rcfile = 'ipythonrc' + rc_suffix, |
|
241 | 242 | readline = 1, |
|
242 | 243 | readline_merge_completions = 1, |
|
243 | 244 | readline_omit__names = 0, |
|
244 | 245 | screen_length = 0, |
|
245 | 246 | separate_in = '\n', |
|
246 | 247 | separate_out = '\n', |
|
247 | 248 | separate_out2 = '', |
|
248 | 249 | system_header = 'IPython system call: ', |
|
249 | 250 | system_verbose = 0, |
|
250 | 251 | term_title = 1, |
|
251 | 252 | tk = 0, |
|
252 | 253 | #twisted= 0, # disabled for now |
|
253 | 254 | upgrade = 0, |
|
254 | 255 | Version = 0, |
|
255 | 256 | wildcards_case_sensitive = 1, |
|
256 | 257 | wthread = 0, |
|
257 | 258 | wxversion = '0', |
|
258 | 259 | xmode = 'Context', |
|
259 | 260 | magic_docstrings = 0, # undocumented, for doc generation |
|
260 | 261 | ) |
|
261 | 262 | |
|
262 | 263 | # Things that will *only* appear in rcfiles (not at the command line). |
|
263 | 264 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
264 | 265 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
265 | 266 | qw_lol: 'import_some ', |
|
266 | 267 | # for things with embedded whitespace: |
|
267 | 268 | list_strings:'execute alias readline_parse_and_bind ', |
|
268 | 269 | # Regular strings need no conversion: |
|
269 | 270 | None:'readline_remove_delims ', |
|
270 | 271 | } |
|
271 | 272 | # Default values for these |
|
272 | 273 | rc_def = Struct(include = [], |
|
273 | 274 | import_mod = [], |
|
274 | 275 | import_all = [], |
|
275 | 276 | import_some = [[]], |
|
276 | 277 | execute = [], |
|
277 | 278 | execfile = [], |
|
278 | 279 | alias = [], |
|
279 | 280 | readline_parse_and_bind = [], |
|
280 | 281 | readline_remove_delims = '', |
|
281 | 282 | ) |
|
282 | 283 | |
|
283 | 284 | # Build the type conversion dictionary from the above tables: |
|
284 | 285 | typeconv = rcfile_opts.copy() |
|
285 | 286 | typeconv.update(optstr2types(cmdline_opts)) |
|
286 | 287 | |
|
287 | 288 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
288 | 289 | typeconv[None] += ' ' + rcfile_opts[None] |
|
289 | 290 | |
|
290 | 291 | # Remove quotes at ends of all strings (used to protect spaces) |
|
291 | 292 | typeconv[unquote_ends] = typeconv[None] |
|
292 | 293 | del typeconv[None] |
|
293 | 294 | |
|
294 | 295 | # Build the list we'll use to make all config decisions with defaults: |
|
295 | 296 | opts_all = opts_def.copy() |
|
296 | 297 | opts_all.update(rc_def) |
|
297 | 298 | |
|
298 | 299 | # Build conflict resolver for recursive loading of config files: |
|
299 | 300 | # - preserve means the outermost file maintains the value, it is not |
|
300 | 301 | # overwritten if an included file has the same key. |
|
301 | 302 | # - add_flip applies + to the two values, so it better make sense to add |
|
302 | 303 | # those types of keys. But it flips them first so that things loaded |
|
303 | 304 | # deeper in the inclusion chain have lower precedence. |
|
304 | 305 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
305 | 306 | typeconv[unquote_ends] ]), |
|
306 | 307 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
307 | 308 | typeconv[qw_lol], |
|
308 | 309 | typeconv[list_strings] ]) |
|
309 | 310 | } |
|
310 | 311 | |
|
311 | 312 | # Now actually process the command line |
|
312 | 313 | getopt = DPyGetOpt.DPyGetOpt() |
|
313 | 314 | getopt.setIgnoreCase(0) |
|
314 | 315 | |
|
315 | 316 | getopt.parseConfiguration(opts_names) |
|
316 | 317 | |
|
317 | 318 | try: |
|
318 | 319 | getopt.processArguments(argv) |
|
319 | 320 | except DPyGetOpt.ArgumentError, exc: |
|
320 | 321 | print cmd_line_usage |
|
321 | 322 | warn('\nError in Arguments: "%s"' % exc) |
|
322 | 323 | sys.exit(1) |
|
323 | 324 | |
|
324 | 325 | # convert the options dict to a struct for much lighter syntax later |
|
325 | 326 | opts = Struct(getopt.optionValues) |
|
326 | 327 | args = getopt.freeValues |
|
327 | 328 | |
|
328 | 329 | # this is the struct (which has default values at this point) with which |
|
329 | 330 | # we make all decisions: |
|
330 | 331 | opts_all.update(opts) |
|
331 | 332 | |
|
332 | 333 | # Options that force an immediate exit |
|
333 | 334 | if opts_all.help: |
|
334 | 335 | page(cmd_line_usage) |
|
335 | 336 | sys.exit() |
|
336 | 337 | |
|
337 | 338 | if opts_all.Version: |
|
338 | 339 | print release.version |
|
339 | 340 | sys.exit() |
|
340 | 341 | |
|
341 | 342 | if opts_all.magic_docstrings: |
|
342 | 343 | IP.magic_magic('-latex') |
|
343 | 344 | sys.exit() |
|
344 | 345 | |
|
345 | 346 | # Display the deprecation warnings about threaded shells |
|
346 | 347 | if opts_all.pylab == 1: threaded_shell_warning() |
|
347 | 348 | if opts_all.wthread == 1: threaded_shell_warning() |
|
348 | 349 | if opts_all.qthread == 1: threaded_shell_warning() |
|
349 | 350 | if opts_all.q4thread == 1: threaded_shell_warning() |
|
350 | 351 | if opts_all.gthread == 1: threaded_shell_warning() |
|
351 | 352 | |
|
352 | 353 | # add personal ipythondir to sys.path so that users can put things in |
|
353 | 354 | # there for customization |
|
354 | 355 | sys.path.append(os.path.abspath(opts_all.ipythondir)) |
|
355 | 356 | |
|
356 | 357 | # Create user config directory if it doesn't exist. This must be done |
|
357 | 358 | # *after* getting the cmd line options. |
|
358 | 359 | if not os.path.isdir(opts_all.ipythondir): |
|
359 |
|
|
|
360 | user_setup(opts_all.ipythondir,rc_suffix,'install') | |
|
360 | 361 | |
|
361 | 362 | # upgrade user config files while preserving a copy of the originals |
|
362 | 363 | if opts_all.upgrade: |
|
363 |
|
|
|
364 | user_setup(opts_all.ipythondir,rc_suffix,'upgrade') | |
|
364 | 365 | |
|
365 | 366 | # check mutually exclusive options in the *original* command line |
|
366 | 367 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
367 | 368 | qw('classic profile'),qw('classic rcfile')]) |
|
368 | 369 | |
|
369 | 370 | #--------------------------------------------------------------------------- |
|
370 | 371 | # Log replay |
|
371 | 372 | |
|
372 | 373 | # if -logplay, we need to 'become' the other session. That basically means |
|
373 | 374 | # replacing the current command line environment with that of the old |
|
374 | 375 | # session and moving on. |
|
375 | 376 | |
|
376 | 377 | # this is needed so that later we know we're in session reload mode, as |
|
377 | 378 | # opts_all will get overwritten: |
|
378 | 379 | load_logplay = 0 |
|
379 | 380 | |
|
380 | 381 | if opts_all.logplay: |
|
381 | 382 | load_logplay = opts_all.logplay |
|
382 | 383 | opts_debug_save = opts_all.debug |
|
383 | 384 | try: |
|
384 | 385 | logplay = open(opts_all.logplay) |
|
385 | 386 | except IOError: |
|
386 | 387 | if opts_all.debug: IP.InteractiveTB() |
|
387 | 388 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
388 | 389 | # restore state as if nothing had happened and move on, but make |
|
389 | 390 | # sure that later we don't try to actually load the session file |
|
390 | 391 | logplay = None |
|
391 | 392 | load_logplay = 0 |
|
392 | 393 | del opts_all.logplay |
|
393 | 394 | else: |
|
394 | 395 | try: |
|
395 | 396 | logplay.readline() |
|
396 | 397 | logplay.readline(); |
|
397 | 398 | # this reloads that session's command line |
|
398 | 399 | cmd = logplay.readline()[6:] |
|
399 | 400 | exec cmd |
|
400 | 401 | # restore the true debug flag given so that the process of |
|
401 | 402 | # session loading itself can be monitored. |
|
402 | 403 | opts.debug = opts_debug_save |
|
403 | 404 | # save the logplay flag so later we don't overwrite the log |
|
404 | 405 | opts.logplay = load_logplay |
|
405 | 406 | # now we must update our own structure with defaults |
|
406 | 407 | opts_all.update(opts) |
|
407 | 408 | # now load args |
|
408 | 409 | cmd = logplay.readline()[6:] |
|
409 | 410 | exec cmd |
|
410 | 411 | logplay.close() |
|
411 | 412 | except: |
|
412 | 413 | logplay.close() |
|
413 | 414 | if opts_all.debug: IP.InteractiveTB() |
|
414 | 415 | warn("Logplay file lacking full configuration information.\n" |
|
415 | 416 | "I'll try to read it, but some things may not work.") |
|
416 | 417 | |
|
417 | 418 | #------------------------------------------------------------------------- |
|
418 | 419 | # set up output traps: catch all output from files, being run, modules |
|
419 | 420 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
420 | 421 | |
|
421 | 422 | msg_out = 'Output messages. ' |
|
422 | 423 | msg_err = 'Error messages. ' |
|
423 | 424 | msg_sep = '\n' |
|
424 | 425 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
425 | 426 | msg_err,msg_sep,debug, |
|
426 | 427 | quiet_out=1), |
|
427 | 428 | user_exec = OutputTrap('User File Execution',msg_out, |
|
428 | 429 | msg_err,msg_sep,debug), |
|
429 | 430 | logplay = OutputTrap('Log Loader',msg_out, |
|
430 | 431 | msg_err,msg_sep,debug), |
|
431 | 432 | summary = '' |
|
432 | 433 | ) |
|
433 | 434 | |
|
434 | 435 | #------------------------------------------------------------------------- |
|
435 | 436 | # Process user ipythonrc-type configuration files |
|
436 | 437 | |
|
437 | 438 | # turn on output trapping and log to msg.config |
|
438 | 439 | # remember that with debug on, trapping is actually disabled |
|
439 | 440 | msg.config.trap_all() |
|
440 | 441 | |
|
441 | 442 | # look for rcfile in current or default directory |
|
442 | 443 | try: |
|
443 | 444 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
444 | 445 | except IOError: |
|
445 | 446 | if opts_all.debug: IP.InteractiveTB() |
|
446 | 447 | warn('Configuration file %s not found. Ignoring request.' |
|
447 | 448 | % (opts_all.rcfile) ) |
|
448 | 449 | |
|
449 | 450 | print opts_all.rcfile, opts_all.ipythondir |
|
450 | 451 | |
|
451 | 452 | # 'profiles' are a shorthand notation for config filenames |
|
452 | 453 | profile_handled_by_legacy = False |
|
453 | 454 | if opts_all.profile: |
|
454 | 455 | |
|
455 | 456 | try: |
|
456 | 457 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
457 | 458 | + rc_suffix, |
|
458 | 459 | opts_all.ipythondir) |
|
459 | 460 | profile_handled_by_legacy = True |
|
460 | 461 | except IOError: |
|
461 | 462 | if opts_all.debug: IP.InteractiveTB() |
|
462 | 463 | opts.profile = '' # remove profile from options if invalid |
|
463 | 464 | # We won't warn anymore, primary method is ipy_profile_PROFNAME |
|
464 | 465 | # which does trigger a warning. |
|
465 | 466 | |
|
466 | 467 | # load the config file |
|
467 | 468 | rcfiledata = None |
|
468 | 469 | if opts_all.quick: |
|
469 | 470 | print 'Launching IPython in quick mode. No config file read.' |
|
470 | 471 | elif opts_all.rcfile: |
|
471 | 472 | try: |
|
472 | 473 | cfg_loader = ConfigLoader(conflict) |
|
473 | 474 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
474 | 475 | 'include',opts_all.ipythondir, |
|
475 | 476 | purge = 1, |
|
476 | 477 | unique = conflict['preserve']) |
|
477 | 478 | except: |
|
478 | 479 | IP.InteractiveTB() |
|
479 | 480 | warn('Problems loading configuration file '+ |
|
480 | 481 | `opts_all.rcfile`+ |
|
481 | 482 | '\nStarting with default -bare bones- configuration.') |
|
482 | 483 | else: |
|
483 | 484 | warn('No valid configuration file found in either currrent directory\n'+ |
|
484 | 485 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
485 | 486 | '\nProceeding with internal defaults.') |
|
486 | 487 | |
|
487 | 488 | #------------------------------------------------------------------------ |
|
488 | 489 | # Set exception handlers in mode requested by user. |
|
489 | 490 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
490 | 491 | IP.magic_xmode(opts_all.xmode) |
|
491 | 492 | otrap.release_out() |
|
492 | 493 | |
|
493 | 494 | #------------------------------------------------------------------------ |
|
494 | 495 | # Execute user config |
|
495 | 496 | |
|
496 | 497 | # Create a valid config structure with the right precedence order: |
|
497 | 498 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
498 | 499 | # that method calls below that rely on it find it. |
|
499 | 500 | IP.rc = rc_def.copy() |
|
500 | 501 | |
|
501 | 502 | # Work with a local alias inside this routine to avoid unnecessary |
|
502 | 503 | # attribute lookups. |
|
503 | 504 | IP_rc = IP.rc |
|
504 | 505 | |
|
505 | 506 | IP_rc.update(opts_def) |
|
506 | 507 | if rcfiledata: |
|
507 | 508 | IP_rc.update(rcfiledata) |
|
508 | 509 | IP_rc.update(opts) |
|
509 | 510 | if rc_override is not None: |
|
510 | 511 | IP_rc.update(rc_override) |
|
511 | 512 | |
|
512 | 513 | # Store the original cmd line for reference: |
|
513 | 514 | IP_rc.opts = opts |
|
514 | 515 | IP_rc.args = args |
|
515 | 516 | |
|
516 | 517 | # create a *runtime* Struct like rc for holding parameters which may be |
|
517 | 518 | # created and/or modified by runtime user extensions. |
|
518 | 519 | IP.runtime_rc = Struct() |
|
519 | 520 | |
|
520 | 521 | # from this point on, all config should be handled through IP_rc, |
|
521 | 522 | # opts* shouldn't be used anymore. |
|
522 | 523 | |
|
523 | 524 | |
|
524 | 525 | # update IP_rc with some special things that need manual |
|
525 | 526 | # tweaks. Basically options which affect other options. I guess this |
|
526 | 527 | # should just be written so that options are fully orthogonal and we |
|
527 | 528 | # wouldn't worry about this stuff! |
|
528 | 529 | |
|
529 | 530 | if IP_rc.classic: |
|
530 | 531 | IP_rc.quick = 1 |
|
531 | 532 | IP_rc.cache_size = 0 |
|
532 | 533 | IP_rc.pprint = 0 |
|
533 | 534 | IP_rc.prompt_in1 = '>>> ' |
|
534 | 535 | IP_rc.prompt_in2 = '... ' |
|
535 | 536 | IP_rc.prompt_out = '' |
|
536 | 537 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
537 | 538 | IP_rc.colors = 'NoColor' |
|
538 | 539 | IP_rc.xmode = 'Plain' |
|
539 | 540 | |
|
540 | 541 | IP.pre_config_initialization() |
|
541 | 542 | # configure readline |
|
542 | 543 | |
|
543 | 544 | # update exception handlers with rc file status |
|
544 | 545 | otrap.trap_out() # I don't want these messages ever. |
|
545 | 546 | IP.magic_xmode(IP_rc.xmode) |
|
546 | 547 | otrap.release_out() |
|
547 | 548 | |
|
548 | 549 | # activate logging if requested and not reloading a log |
|
549 | 550 | if IP_rc.logplay: |
|
550 | 551 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
551 | 552 | elif IP_rc.logfile: |
|
552 | 553 | IP.magic_logstart(IP_rc.logfile) |
|
553 | 554 | elif IP_rc.log: |
|
554 | 555 | IP.magic_logstart() |
|
555 | 556 | |
|
556 | 557 | # find user editor so that it we don't have to look it up constantly |
|
557 | 558 | if IP_rc.editor.strip()=='0': |
|
558 | 559 | try: |
|
559 | 560 | ed = os.environ['EDITOR'] |
|
560 | 561 | except KeyError: |
|
561 | 562 | if os.name == 'posix': |
|
562 | 563 | ed = 'vi' # the only one guaranteed to be there! |
|
563 | 564 | else: |
|
564 | 565 | ed = 'notepad' # same in Windows! |
|
565 | 566 | IP_rc.editor = ed |
|
566 | 567 | |
|
567 | 568 | # Keep track of whether this is an embedded instance or not (useful for |
|
568 | 569 | # post-mortems). |
|
569 | 570 | IP_rc.embedded = IP.embedded |
|
570 | 571 | |
|
571 | 572 | # Recursive reload |
|
572 | 573 | try: |
|
573 | 574 | from IPython.lib import deepreload |
|
574 | 575 | if IP_rc.deep_reload: |
|
575 | 576 | __builtin__.reload = deepreload.reload |
|
576 | 577 | else: |
|
577 | 578 | __builtin__.dreload = deepreload.reload |
|
578 | 579 | del deepreload |
|
579 | 580 | except ImportError: |
|
580 | 581 | pass |
|
581 | 582 | |
|
582 | 583 | # Save the current state of our namespace so that the interactive shell |
|
583 | 584 | # can later know which variables have been created by us from config files |
|
584 | 585 | # and loading. This way, loading a file (in any way) is treated just like |
|
585 | 586 | # defining things on the command line, and %who works as expected. |
|
586 | 587 | |
|
587 | 588 | # DON'T do anything that affects the namespace beyond this point! |
|
588 | 589 | IP.internal_ns.update(__main__.__dict__) |
|
589 | 590 | |
|
590 | 591 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
591 | 592 | |
|
592 | 593 | # Now run through the different sections of the users's config |
|
593 | 594 | if IP_rc.debug: |
|
594 | 595 | print 'Trying to execute the following configuration structure:' |
|
595 | 596 | print '(Things listed first are deeper in the inclusion tree and get' |
|
596 | 597 | print 'loaded first).\n' |
|
597 | 598 | pprint(IP_rc.__dict__) |
|
598 | 599 | |
|
599 | 600 | for mod in IP_rc.import_mod: |
|
600 | 601 | try: |
|
601 | 602 | exec 'import '+mod in IP.user_ns |
|
602 | 603 | except : |
|
603 | 604 | IP.InteractiveTB() |
|
604 | 605 | import_fail_info(mod) |
|
605 | 606 | |
|
606 | 607 | for mod_fn in IP_rc.import_some: |
|
607 | 608 | if not mod_fn == []: |
|
608 | 609 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
609 | 610 | try: |
|
610 | 611 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
611 | 612 | except : |
|
612 | 613 | IP.InteractiveTB() |
|
613 | 614 | import_fail_info(mod,fn) |
|
614 | 615 | |
|
615 | 616 | for mod in IP_rc.import_all: |
|
616 | 617 | try: |
|
617 | 618 | exec 'from '+mod+' import *' in IP.user_ns |
|
618 | 619 | except : |
|
619 | 620 | IP.InteractiveTB() |
|
620 | 621 | import_fail_info(mod) |
|
621 | 622 | |
|
622 | 623 | for code in IP_rc.execute: |
|
623 | 624 | try: |
|
624 | 625 | exec code in IP.user_ns |
|
625 | 626 | except: |
|
626 | 627 | IP.InteractiveTB() |
|
627 | 628 | warn('Failure executing code: ' + `code`) |
|
628 | 629 | |
|
629 | 630 | # Execute the files the user wants in ipythonrc |
|
630 | 631 | for file in IP_rc.execfile: |
|
631 | 632 | try: |
|
632 | 633 | file = filefind(file,sys.path+[IPython_dir]) |
|
633 | 634 | except IOError: |
|
634 | 635 | warn(itpl('File $file not found. Skipping it.')) |
|
635 | 636 | else: |
|
636 | 637 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
637 | 638 | |
|
638 | 639 | # finally, try importing ipy_*_conf for final configuration |
|
639 | 640 | try: |
|
640 | 641 | import ipy_system_conf |
|
641 | 642 | except ImportError: |
|
642 | 643 | if opts_all.debug: IP.InteractiveTB() |
|
643 | 644 | warn("Could not import 'ipy_system_conf'") |
|
644 | 645 | except: |
|
645 | 646 | IP.InteractiveTB() |
|
646 | 647 | import_fail_info('ipy_system_conf') |
|
647 | 648 | |
|
648 | 649 | # only import prof module if ipythonrc-PROF was not found |
|
649 | 650 | if opts_all.profile and not profile_handled_by_legacy: |
|
650 | 651 | profmodname = 'ipy_profile_' + opts_all.profile |
|
651 | 652 | try: |
|
652 | 653 | force_import(profmodname) |
|
653 | 654 | except: |
|
654 | 655 | IP.InteractiveTB() |
|
655 | 656 | print "Error importing",profmodname,\ |
|
656 | 657 | "- perhaps you should run %upgrade?" |
|
657 | 658 | import_fail_info(profmodname) |
|
658 | 659 | else: |
|
659 | 660 | opts.profile = opts_all.profile |
|
660 | 661 | else: |
|
661 | 662 | force_import('ipy_profile_none') |
|
662 | 663 | # XXX - this is wrong: ipy_user_conf should not be loaded unconditionally, |
|
663 | 664 | # since the user could have specified a config file path by hand. |
|
664 | 665 | try: |
|
665 | 666 | force_import('ipy_user_conf') |
|
666 | 667 | except: |
|
667 | 668 | conf = opts_all.ipythondir + "/ipy_user_conf.py" |
|
668 | 669 | IP.InteractiveTB() |
|
669 | 670 | if not os.path.isfile(conf): |
|
670 | 671 | warn(conf + ' does not exist, please run %upgrade!') |
|
671 | 672 | |
|
672 | 673 | import_fail_info("ipy_user_conf") |
|
673 | 674 | |
|
674 | 675 | # Define the history file for saving commands in between sessions |
|
675 | 676 | try: |
|
676 | 677 | histfname = 'history-%s' % opts.profile |
|
677 | 678 | except AttributeError: |
|
678 | 679 | histfname = 'history' |
|
679 | 680 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
680 | 681 | |
|
681 | 682 | # finally, push the argv to options again to ensure highest priority |
|
682 | 683 | IP_rc.update(opts) |
|
683 | 684 | |
|
684 | 685 | # release stdout and stderr and save config log into a global summary |
|
685 | 686 | msg.config.release_all() |
|
686 | 687 | if IP_rc.messages: |
|
687 | 688 | msg.summary += msg.config.summary_all() |
|
688 | 689 | |
|
689 | 690 | #------------------------------------------------------------------------ |
|
690 | 691 | # Setup interactive session |
|
691 | 692 | |
|
692 | 693 | # Now we should be fully configured. We can then execute files or load |
|
693 | 694 | # things only needed for interactive use. Then we'll open the shell. |
|
694 | 695 | |
|
695 | 696 | # Take a snapshot of the user namespace before opening the shell. That way |
|
696 | 697 | # we'll be able to identify which things were interactively defined and |
|
697 | 698 | # which were defined through config files. |
|
698 | 699 | IP.user_config_ns.update(IP.user_ns) |
|
699 | 700 | |
|
700 | 701 | # Force reading a file as if it were a session log. Slower but safer. |
|
701 | 702 | if load_logplay: |
|
702 | 703 | print 'Replaying log...' |
|
703 | 704 | try: |
|
704 | 705 | if IP_rc.debug: |
|
705 | 706 | logplay_quiet = 0 |
|
706 | 707 | else: |
|
707 | 708 | logplay_quiet = 1 |
|
708 | 709 | |
|
709 | 710 | msg.logplay.trap_all() |
|
710 | 711 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
711 | 712 | islog = 1, quiet = logplay_quiet) |
|
712 | 713 | msg.logplay.release_all() |
|
713 | 714 | if IP_rc.messages: |
|
714 | 715 | msg.summary += msg.logplay.summary_all() |
|
715 | 716 | except: |
|
716 | 717 | warn('Problems replaying logfile %s.' % load_logplay) |
|
717 | 718 | IP.InteractiveTB() |
|
718 | 719 | |
|
719 | 720 | # Load remaining files in command line |
|
720 | 721 | msg.user_exec.trap_all() |
|
721 | 722 | |
|
722 | 723 | # Do NOT execute files named in the command line as scripts to be loaded |
|
723 | 724 | # by embedded instances. Doing so has the potential for an infinite |
|
724 | 725 | # recursion if there are exceptions thrown in the process. |
|
725 | 726 | |
|
726 | 727 | # XXX FIXME: the execution of user files should be moved out to after |
|
727 | 728 | # ipython is fully initialized, just as if they were run via %run at the |
|
728 | 729 | # ipython prompt. This would also give them the benefit of ipython's |
|
729 | 730 | # nice tracebacks. |
|
730 | 731 | |
|
731 | 732 | if (not embedded and IP_rc.args and |
|
732 | 733 | not IP_rc.args[0].lower().endswith('.ipy')): |
|
733 | 734 | name_save = IP.user_ns['__name__'] |
|
734 | 735 | IP.user_ns['__name__'] = '__main__' |
|
735 | 736 | # Set our own excepthook in case the user code tries to call it |
|
736 | 737 | # directly. This prevents triggering the IPython crash handler. |
|
737 | 738 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
738 | 739 | |
|
739 | 740 | save_argv = sys.argv[1:] # save it for later restoring |
|
740 | 741 | |
|
741 | 742 | sys.argv = args |
|
742 | 743 | |
|
743 | 744 | try: |
|
744 | 745 | IP.safe_execfile(args[0], IP.user_ns) |
|
745 | 746 | finally: |
|
746 | 747 | # Reset our crash handler in place |
|
747 | 748 | sys.excepthook = old_excepthook |
|
748 | 749 | sys.argv[:] = save_argv |
|
749 | 750 | IP.user_ns['__name__'] = name_save |
|
750 | 751 | |
|
751 | 752 | msg.user_exec.release_all() |
|
752 | 753 | |
|
753 | 754 | if IP_rc.messages: |
|
754 | 755 | msg.summary += msg.user_exec.summary_all() |
|
755 | 756 | |
|
756 | 757 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
757 | 758 | if IP_rc.nosep: |
|
758 | 759 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
759 | 760 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
760 | 761 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
761 | 762 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
762 | 763 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
763 | 764 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
764 | 765 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
765 | 766 | |
|
766 | 767 | # Determine how many lines at the bottom of the screen are needed for |
|
767 | 768 | # showing prompts, so we can know wheter long strings are to be printed or |
|
768 | 769 | # paged: |
|
769 | 770 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
770 | 771 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
771 | 772 | |
|
772 | 773 | # configure startup banner |
|
773 | 774 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
774 | 775 | IP_rc.banner = 0 |
|
775 | 776 | if IP_rc.banner: |
|
776 | 777 | BANN_P = IP.BANNER_PARTS |
|
777 | 778 | else: |
|
778 | 779 | BANN_P = [] |
|
779 | 780 | |
|
780 | 781 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
781 | 782 | |
|
782 | 783 | # add message log (possibly empty) |
|
783 | 784 | if msg.summary: BANN_P.append(msg.summary) |
|
784 | 785 | # Final banner is a string |
|
785 | 786 | IP.BANNER = '\n'.join(BANN_P) |
|
786 | 787 | |
|
787 | 788 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
788 | 789 | # in place. |
|
789 | 790 | IP.post_config_initialization() |
|
790 | 791 | |
|
791 | 792 | return IP |
|
792 | 793 | #************************ end of file <ipmaker.py> ************************** |
@@ -1,3587 +1,3588 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 re |
|
25 | 25 | import tempfile |
|
26 | 26 | import time |
|
27 | 27 | import cPickle as pickle |
|
28 | 28 | import textwrap |
|
29 | 29 | from cStringIO import StringIO |
|
30 | 30 | from getopt import getopt,GetoptError |
|
31 | 31 | from pprint import pprint, pformat |
|
32 | 32 | |
|
33 | 33 | # cProfile was added in Python2.5 |
|
34 | 34 | try: |
|
35 | 35 | import cProfile as profile |
|
36 | 36 | import pstats |
|
37 | 37 | except ImportError: |
|
38 | 38 | # profile isn't bundled by default in Debian for license reasons |
|
39 | 39 | try: |
|
40 | 40 | import profile,pstats |
|
41 | 41 | except ImportError: |
|
42 | 42 | profile = pstats = None |
|
43 | 43 | |
|
44 | 44 | # Homebrewed |
|
45 | 45 | import IPython |
|
46 | 46 | from IPython.utils import wildcard |
|
47 | 47 | from IPython.core import debugger, oinspect |
|
48 | 48 | from IPython.core.fakemodule import FakeModule |
|
49 | 49 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
50 | 50 | from IPython.utils.PyColorize import Parser |
|
51 | 51 | from IPython.utils.ipstruct import Struct |
|
52 | 52 | from IPython.core.macro import Macro |
|
53 | 53 | from IPython.utils.genutils import * |
|
54 | 54 | from IPython.utils import platutils |
|
55 | 55 | import IPython.utils.generics |
|
56 | 56 | from IPython.core import ipapi |
|
57 | 57 | from IPython.core.ipapi import UsageError |
|
58 | 58 | from IPython.testing import decorators as testdec |
|
59 | 59 | |
|
60 | 60 | #*************************************************************************** |
|
61 | 61 | # Utility functions |
|
62 | 62 | def on_off(tag): |
|
63 | 63 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
64 | 64 | return ['OFF','ON'][tag] |
|
65 | 65 | |
|
66 | 66 | class Bunch: pass |
|
67 | 67 | |
|
68 | 68 | def compress_dhist(dh): |
|
69 | 69 | head, tail = dh[:-10], dh[-10:] |
|
70 | 70 | |
|
71 | 71 | newhead = [] |
|
72 | 72 | done = set() |
|
73 | 73 | for h in head: |
|
74 | 74 | if h in done: |
|
75 | 75 | continue |
|
76 | 76 | newhead.append(h) |
|
77 | 77 | done.add(h) |
|
78 | 78 | |
|
79 | 79 | return newhead + tail |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | #*************************************************************************** |
|
83 | 83 | # Main class implementing Magic functionality |
|
84 | 84 | class Magic: |
|
85 | 85 | """Magic functions for InteractiveShell. |
|
86 | 86 | |
|
87 | 87 | Shell functions which can be reached as %function_name. All magic |
|
88 | 88 | functions should accept a string, which they can parse for their own |
|
89 | 89 | needs. This can make some functions easier to type, eg `%cd ../` |
|
90 | 90 | vs. `%cd("../")` |
|
91 | 91 | |
|
92 | 92 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
93 | 93 | at the command line, but it is is needed in the definition. """ |
|
94 | 94 | |
|
95 | 95 | # class globals |
|
96 | 96 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
97 | 97 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
98 | 98 | |
|
99 | 99 | #...................................................................... |
|
100 | 100 | # some utility functions |
|
101 | 101 | |
|
102 | 102 | def __init__(self,shell): |
|
103 | 103 | |
|
104 | 104 | self.options_table = {} |
|
105 | 105 | if profile is None: |
|
106 | 106 | self.magic_prun = self.profile_missing_notice |
|
107 | 107 | self.shell = shell |
|
108 | 108 | |
|
109 | 109 | # namespace for holding state we may need |
|
110 | 110 | self._magic_state = Bunch() |
|
111 | 111 | |
|
112 | 112 | def profile_missing_notice(self, *args, **kwargs): |
|
113 | 113 | error("""\ |
|
114 | 114 | The profile module could not be found. It has been removed from the standard |
|
115 | 115 | python packages because of its non-free license. To use profiling, install the |
|
116 | 116 | python-profiler package from non-free.""") |
|
117 | 117 | |
|
118 | 118 | def default_option(self,fn,optstr): |
|
119 | 119 | """Make an entry in the options_table for fn, with value optstr""" |
|
120 | 120 | |
|
121 | 121 | if fn not in self.lsmagic(): |
|
122 | 122 | error("%s is not a magic function" % fn) |
|
123 | 123 | self.options_table[fn] = optstr |
|
124 | 124 | |
|
125 | 125 | def lsmagic(self): |
|
126 | 126 | """Return a list of currently available magic functions. |
|
127 | 127 | |
|
128 | 128 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
129 | 129 | ['magic_ls','magic_cd',...]""" |
|
130 | 130 | |
|
131 | 131 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
132 | 132 | |
|
133 | 133 | # magics in class definition |
|
134 | 134 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
135 | 135 | callable(Magic.__dict__[fn]) |
|
136 | 136 | # in instance namespace (run-time user additions) |
|
137 | 137 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
138 | 138 | callable(self.__dict__[fn]) |
|
139 | 139 | # and bound magics by user (so they can access self): |
|
140 | 140 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | 141 | callable(self.__class__.__dict__[fn]) |
|
142 | 142 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
143 | 143 | filter(inst_magic,self.__dict__.keys()) + \ |
|
144 | 144 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
145 | 145 | out = [] |
|
146 | 146 | for fn in set(magics): |
|
147 | 147 | out.append(fn.replace('magic_','',1)) |
|
148 | 148 | out.sort() |
|
149 | 149 | return out |
|
150 | 150 | |
|
151 | 151 | def extract_input_slices(self,slices,raw=False): |
|
152 | 152 | """Return as a string a set of input history slices. |
|
153 | 153 | |
|
154 | 154 | Inputs: |
|
155 | 155 | |
|
156 | 156 | - slices: the set of slices is given as a list of strings (like |
|
157 | 157 | ['1','4:8','9'], since this function is for use by magic functions |
|
158 | 158 | which get their arguments as strings. |
|
159 | 159 | |
|
160 | 160 | Optional inputs: |
|
161 | 161 | |
|
162 | 162 | - raw(False): by default, the processed input is used. If this is |
|
163 | 163 | true, the raw input history is used instead. |
|
164 | 164 | |
|
165 | 165 | Note that slices can be called with two notations: |
|
166 | 166 | |
|
167 | 167 | N:M -> standard python form, means including items N...(M-1). |
|
168 | 168 | |
|
169 | 169 | N-M -> include items N..M (closed endpoint).""" |
|
170 | 170 | |
|
171 | 171 | if raw: |
|
172 | 172 | hist = self.shell.input_hist_raw |
|
173 | 173 | else: |
|
174 | 174 | hist = self.shell.input_hist |
|
175 | 175 | |
|
176 | 176 | cmds = [] |
|
177 | 177 | for chunk in slices: |
|
178 | 178 | if ':' in chunk: |
|
179 | 179 | ini,fin = map(int,chunk.split(':')) |
|
180 | 180 | elif '-' in chunk: |
|
181 | 181 | ini,fin = map(int,chunk.split('-')) |
|
182 | 182 | fin += 1 |
|
183 | 183 | else: |
|
184 | 184 | ini = int(chunk) |
|
185 | 185 | fin = ini+1 |
|
186 | 186 | cmds.append(hist[ini:fin]) |
|
187 | 187 | return cmds |
|
188 | 188 | |
|
189 | 189 | def _ofind(self, oname, namespaces=None): |
|
190 | 190 | """Find an object in the available namespaces. |
|
191 | 191 | |
|
192 | 192 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
193 | 193 | |
|
194 | 194 | Has special code to detect magic functions. |
|
195 | 195 | """ |
|
196 | 196 | |
|
197 | 197 | oname = oname.strip() |
|
198 | 198 | |
|
199 | 199 | alias_ns = None |
|
200 | 200 | if namespaces is None: |
|
201 | 201 | # Namespaces to search in: |
|
202 | 202 | # Put them in a list. The order is important so that we |
|
203 | 203 | # find things in the same order that Python finds them. |
|
204 | 204 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
205 | 205 | ('IPython internal', self.shell.internal_ns), |
|
206 | 206 | ('Python builtin', __builtin__.__dict__), |
|
207 | 207 | ('Alias', self.shell.alias_table), |
|
208 | 208 | ] |
|
209 | 209 | alias_ns = self.shell.alias_table |
|
210 | 210 | |
|
211 | 211 | # initialize results to 'null' |
|
212 | 212 | found = 0; obj = None; ospace = None; ds = None; |
|
213 | 213 | ismagic = 0; isalias = 0; parent = None |
|
214 | 214 | |
|
215 | 215 | # Look for the given name by splitting it in parts. If the head is |
|
216 | 216 | # found, then we look for all the remaining parts as members, and only |
|
217 | 217 | # declare success if we can find them all. |
|
218 | 218 | oname_parts = oname.split('.') |
|
219 | 219 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
220 | 220 | for nsname,ns in namespaces: |
|
221 | 221 | try: |
|
222 | 222 | obj = ns[oname_head] |
|
223 | 223 | except KeyError: |
|
224 | 224 | continue |
|
225 | 225 | else: |
|
226 | 226 | #print 'oname_rest:', oname_rest # dbg |
|
227 | 227 | for part in oname_rest: |
|
228 | 228 | try: |
|
229 | 229 | parent = obj |
|
230 | 230 | obj = getattr(obj,part) |
|
231 | 231 | except: |
|
232 | 232 | # Blanket except b/c some badly implemented objects |
|
233 | 233 | # allow __getattr__ to raise exceptions other than |
|
234 | 234 | # AttributeError, which then crashes IPython. |
|
235 | 235 | break |
|
236 | 236 | else: |
|
237 | 237 | # If we finish the for loop (no break), we got all members |
|
238 | 238 | found = 1 |
|
239 | 239 | ospace = nsname |
|
240 | 240 | if ns == alias_ns: |
|
241 | 241 | isalias = 1 |
|
242 | 242 | break # namespace loop |
|
243 | 243 | |
|
244 | 244 | # Try to see if it's magic |
|
245 | 245 | if not found: |
|
246 | 246 | if oname.startswith(self.shell.ESC_MAGIC): |
|
247 | 247 | oname = oname[1:] |
|
248 | 248 | obj = getattr(self,'magic_'+oname,None) |
|
249 | 249 | if obj is not None: |
|
250 | 250 | found = 1 |
|
251 | 251 | ospace = 'IPython internal' |
|
252 | 252 | ismagic = 1 |
|
253 | 253 | |
|
254 | 254 | # Last try: special-case some literals like '', [], {}, etc: |
|
255 | 255 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
256 | 256 | obj = eval(oname_head) |
|
257 | 257 | found = 1 |
|
258 | 258 | ospace = 'Interactive' |
|
259 | 259 | |
|
260 | 260 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
261 | 261 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
262 | 262 | |
|
263 | 263 | def arg_err(self,func): |
|
264 | 264 | """Print docstring if incorrect arguments were passed""" |
|
265 | 265 | print 'Error in arguments:' |
|
266 | 266 | print OInspect.getdoc(func) |
|
267 | 267 | |
|
268 | 268 | def format_latex(self,strng): |
|
269 | 269 | """Format a string for latex inclusion.""" |
|
270 | 270 | |
|
271 | 271 | # Characters that need to be escaped for latex: |
|
272 | 272 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
273 | 273 | # Magic command names as headers: |
|
274 | 274 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
275 | 275 | re.MULTILINE) |
|
276 | 276 | # Magic commands |
|
277 | 277 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
278 | 278 | re.MULTILINE) |
|
279 | 279 | # Paragraph continue |
|
280 | 280 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
281 | 281 | |
|
282 | 282 | # The "\n" symbol |
|
283 | 283 | newline_re = re.compile(r'\\n') |
|
284 | 284 | |
|
285 | 285 | # Now build the string for output: |
|
286 | 286 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
287 | 287 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
288 | 288 | strng) |
|
289 | 289 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
290 | 290 | strng = par_re.sub(r'\\\\',strng) |
|
291 | 291 | strng = escape_re.sub(r'\\\1',strng) |
|
292 | 292 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
293 | 293 | return strng |
|
294 | 294 | |
|
295 | 295 | def format_screen(self,strng): |
|
296 | 296 | """Format a string for screen printing. |
|
297 | 297 | |
|
298 | 298 | This removes some latex-type format codes.""" |
|
299 | 299 | # Paragraph continue |
|
300 | 300 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
301 | 301 | strng = par_re.sub('',strng) |
|
302 | 302 | return strng |
|
303 | 303 | |
|
304 | 304 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
305 | 305 | """Parse options passed to an argument string. |
|
306 | 306 | |
|
307 | 307 | The interface is similar to that of getopt(), but it returns back a |
|
308 | 308 | Struct with the options as keys and the stripped argument string still |
|
309 | 309 | as a string. |
|
310 | 310 | |
|
311 | 311 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
312 | 312 | This allows us to easily expand variables, glob files, quote |
|
313 | 313 | arguments, etc. |
|
314 | 314 | |
|
315 | 315 | Options: |
|
316 | 316 | -mode: default 'string'. If given as 'list', the argument string is |
|
317 | 317 | returned as a list (split on whitespace) instead of a string. |
|
318 | 318 | |
|
319 | 319 | -list_all: put all option values in lists. Normally only options |
|
320 | 320 | appearing more than once are put in a list. |
|
321 | 321 | |
|
322 | 322 | -posix (True): whether to split the input line in POSIX mode or not, |
|
323 | 323 | as per the conventions outlined in the shlex module from the |
|
324 | 324 | standard library.""" |
|
325 | 325 | |
|
326 | 326 | # inject default options at the beginning of the input line |
|
327 | 327 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
328 | 328 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
329 | 329 | |
|
330 | 330 | mode = kw.get('mode','string') |
|
331 | 331 | if mode not in ['string','list']: |
|
332 | 332 | raise ValueError,'incorrect mode given: %s' % mode |
|
333 | 333 | # Get options |
|
334 | 334 | list_all = kw.get('list_all',0) |
|
335 | 335 | posix = kw.get('posix',True) |
|
336 | 336 | |
|
337 | 337 | # Check if we have more than one argument to warrant extra processing: |
|
338 | 338 | odict = {} # Dictionary with options |
|
339 | 339 | args = arg_str.split() |
|
340 | 340 | if len(args) >= 1: |
|
341 | 341 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
342 | 342 | # need to look for options |
|
343 | 343 | argv = arg_split(arg_str,posix) |
|
344 | 344 | # Do regular option processing |
|
345 | 345 | try: |
|
346 | 346 | opts,args = getopt(argv,opt_str,*long_opts) |
|
347 | 347 | except GetoptError,e: |
|
348 | 348 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
349 | 349 | " ".join(long_opts))) |
|
350 | 350 | for o,a in opts: |
|
351 | 351 | if o.startswith('--'): |
|
352 | 352 | o = o[2:] |
|
353 | 353 | else: |
|
354 | 354 | o = o[1:] |
|
355 | 355 | try: |
|
356 | 356 | odict[o].append(a) |
|
357 | 357 | except AttributeError: |
|
358 | 358 | odict[o] = [odict[o],a] |
|
359 | 359 | except KeyError: |
|
360 | 360 | if list_all: |
|
361 | 361 | odict[o] = [a] |
|
362 | 362 | else: |
|
363 | 363 | odict[o] = a |
|
364 | 364 | |
|
365 | 365 | # Prepare opts,args for return |
|
366 | 366 | opts = Struct(odict) |
|
367 | 367 | if mode == 'string': |
|
368 | 368 | args = ' '.join(args) |
|
369 | 369 | |
|
370 | 370 | return opts,args |
|
371 | 371 | |
|
372 | 372 | #...................................................................... |
|
373 | 373 | # And now the actual magic functions |
|
374 | 374 | |
|
375 | 375 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
376 | 376 | def magic_lsmagic(self, parameter_s = ''): |
|
377 | 377 | """List currently available magic functions.""" |
|
378 | 378 | mesc = self.shell.ESC_MAGIC |
|
379 | 379 | print 'Available magic functions:\n'+mesc+\ |
|
380 | 380 | (' '+mesc).join(self.lsmagic()) |
|
381 |
print '\n' + Magic.auto_status[self.shell. |
|
|
381 | print '\n' + Magic.auto_status[self.shell.automagic] | |
|
382 | 382 | return None |
|
383 | 383 | |
|
384 | 384 | def magic_magic(self, parameter_s = ''): |
|
385 | 385 | """Print information about the magic function system. |
|
386 | 386 | |
|
387 | 387 | Supported formats: -latex, -brief, -rest |
|
388 | 388 | """ |
|
389 | 389 | |
|
390 | 390 | mode = '' |
|
391 | 391 | try: |
|
392 | 392 | if parameter_s.split()[0] == '-latex': |
|
393 | 393 | mode = 'latex' |
|
394 | 394 | if parameter_s.split()[0] == '-brief': |
|
395 | 395 | mode = 'brief' |
|
396 | 396 | if parameter_s.split()[0] == '-rest': |
|
397 | 397 | mode = 'rest' |
|
398 | 398 | rest_docs = [] |
|
399 | 399 | except: |
|
400 | 400 | pass |
|
401 | 401 | |
|
402 | 402 | magic_docs = [] |
|
403 | 403 | for fname in self.lsmagic(): |
|
404 | 404 | mname = 'magic_' + fname |
|
405 | 405 | for space in (Magic,self,self.__class__): |
|
406 | 406 | try: |
|
407 | 407 | fn = space.__dict__[mname] |
|
408 | 408 | except KeyError: |
|
409 | 409 | pass |
|
410 | 410 | else: |
|
411 | 411 | break |
|
412 | 412 | if mode == 'brief': |
|
413 | 413 | # only first line |
|
414 | 414 | if fn.__doc__: |
|
415 | 415 | fndoc = fn.__doc__.split('\n',1)[0] |
|
416 | 416 | else: |
|
417 | 417 | fndoc = 'No documentation' |
|
418 | 418 | else: |
|
419 | 419 | if fn.__doc__: |
|
420 | 420 | fndoc = fn.__doc__.rstrip() |
|
421 | 421 | else: |
|
422 | 422 | fndoc = 'No documentation' |
|
423 | 423 | |
|
424 | 424 | |
|
425 | 425 | if mode == 'rest': |
|
426 | 426 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
427 | 427 | fname,fndoc)) |
|
428 | 428 | |
|
429 | 429 | else: |
|
430 | 430 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
431 | 431 | fname,fndoc)) |
|
432 | 432 | |
|
433 | 433 | magic_docs = ''.join(magic_docs) |
|
434 | 434 | |
|
435 | 435 | if mode == 'rest': |
|
436 | 436 | return "".join(rest_docs) |
|
437 | 437 | |
|
438 | 438 | if mode == 'latex': |
|
439 | 439 | print self.format_latex(magic_docs) |
|
440 | 440 | return |
|
441 | 441 | else: |
|
442 | 442 | magic_docs = self.format_screen(magic_docs) |
|
443 | 443 | if mode == 'brief': |
|
444 | 444 | return magic_docs |
|
445 | 445 | |
|
446 | 446 | outmsg = """ |
|
447 | 447 | IPython's 'magic' functions |
|
448 | 448 | =========================== |
|
449 | 449 | |
|
450 | 450 | The magic function system provides a series of functions which allow you to |
|
451 | 451 | control the behavior of IPython itself, plus a lot of system-type |
|
452 | 452 | features. All these functions are prefixed with a % character, but parameters |
|
453 | 453 | are given without parentheses or quotes. |
|
454 | 454 | |
|
455 | 455 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
456 | 456 | %automagic function), you don't need to type in the % explicitly. By default, |
|
457 | 457 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
458 | 458 | |
|
459 | 459 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
460 | 460 | to 'mydir', if it exists. |
|
461 | 461 | |
|
462 | 462 | You can define your own magic functions to extend the system. See the supplied |
|
463 | 463 | ipythonrc and example-magic.py files for details (in your ipython |
|
464 | 464 | configuration directory, typically $HOME/.ipython/). |
|
465 | 465 | |
|
466 | 466 | You can also define your own aliased names for magic functions. In your |
|
467 | 467 | ipythonrc file, placing a line like: |
|
468 | 468 | |
|
469 | 469 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
470 | 470 | |
|
471 | 471 | will define %pf as a new name for %profile. |
|
472 | 472 | |
|
473 | 473 | You can also call magics in code using the ipmagic() function, which IPython |
|
474 | 474 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
475 | 475 | |
|
476 | 476 | For a list of the available magic functions, use %lsmagic. For a description |
|
477 | 477 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
478 | 478 | |
|
479 | 479 | Currently the magic system has the following functions:\n""" |
|
480 | 480 | |
|
481 | 481 | mesc = self.shell.ESC_MAGIC |
|
482 | 482 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
483 | 483 | "\n\n%s%s\n\n%s" % (outmsg, |
|
484 | 484 | magic_docs,mesc,mesc, |
|
485 | 485 | (' '+mesc).join(self.lsmagic()), |
|
486 |
Magic.auto_status[self.shell. |
|
|
486 | Magic.auto_status[self.shell.automagic] ) ) | |
|
487 | 487 | |
|
488 |
page(outmsg,screen_lines=self.shell. |
|
|
488 | page(outmsg,screen_lines=self.shell.screen_length) | |
|
489 | 489 | |
|
490 | 490 | |
|
491 | 491 | def magic_autoindent(self, parameter_s = ''): |
|
492 | 492 | """Toggle autoindent on/off (if available).""" |
|
493 | 493 | |
|
494 | 494 | self.shell.set_autoindent() |
|
495 | 495 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
496 | 496 | |
|
497 | 497 | |
|
498 | 498 | def magic_automagic(self, parameter_s = ''): |
|
499 | 499 | """Make magic functions callable without having to type the initial %. |
|
500 | 500 | |
|
501 | 501 | Without argumentsl toggles on/off (when off, you must call it as |
|
502 | 502 | %automagic, of course). With arguments it sets the value, and you can |
|
503 | 503 | use any of (case insensitive): |
|
504 | 504 | |
|
505 | 505 | - on,1,True: to activate |
|
506 | 506 | |
|
507 | 507 | - off,0,False: to deactivate. |
|
508 | 508 | |
|
509 | 509 | Note that magic functions have lowest priority, so if there's a |
|
510 | 510 | variable whose name collides with that of a magic fn, automagic won't |
|
511 | 511 | work for that function (you get the variable instead). However, if you |
|
512 | 512 | delete the variable (del var), the previously shadowed magic function |
|
513 | 513 | becomes visible to automagic again.""" |
|
514 | 514 | |
|
515 | rc = self.shell.rc | |
|
516 | 515 | arg = parameter_s.lower() |
|
517 | 516 | if parameter_s in ('on','1','true'): |
|
518 |
|
|
|
517 | self.shell.automagic = True | |
|
519 | 518 | elif parameter_s in ('off','0','false'): |
|
520 |
|
|
|
519 | self.shell.automagic = False | |
|
521 | 520 | else: |
|
522 |
|
|
|
523 |
print '\n' + Magic.auto_status[ |
|
|
521 | self.shell.automagic = not self.shell.automagic | |
|
522 | print '\n' + Magic.auto_status[self.shell.automagic] | |
|
524 | 523 | |
|
525 | 524 | @testdec.skip_doctest |
|
526 | 525 | def magic_autocall(self, parameter_s = ''): |
|
527 | 526 | """Make functions callable without having to type parentheses. |
|
528 | 527 | |
|
529 | 528 | Usage: |
|
530 | 529 | |
|
531 | 530 | %autocall [mode] |
|
532 | 531 | |
|
533 | 532 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
534 | 533 | value is toggled on and off (remembering the previous state). |
|
535 | 534 | |
|
536 | 535 | In more detail, these values mean: |
|
537 | 536 | |
|
538 | 537 | 0 -> fully disabled |
|
539 | 538 | |
|
540 | 539 | 1 -> active, but do not apply if there are no arguments on the line. |
|
541 | 540 | |
|
542 | 541 | In this mode, you get: |
|
543 | 542 | |
|
544 | 543 | In [1]: callable |
|
545 | 544 | Out[1]: <built-in function callable> |
|
546 | 545 | |
|
547 | 546 | In [2]: callable 'hello' |
|
548 | 547 | ------> callable('hello') |
|
549 | 548 | Out[2]: False |
|
550 | 549 | |
|
551 | 550 | 2 -> Active always. Even if no arguments are present, the callable |
|
552 | 551 | object is called: |
|
553 | 552 | |
|
554 | 553 | In [2]: float |
|
555 | 554 | ------> float() |
|
556 | 555 | Out[2]: 0.0 |
|
557 | 556 | |
|
558 | 557 | Note that even with autocall off, you can still use '/' at the start of |
|
559 | 558 | a line to treat the first argument on the command line as a function |
|
560 | 559 | and add parentheses to it: |
|
561 | 560 | |
|
562 | 561 | In [8]: /str 43 |
|
563 | 562 | ------> str(43) |
|
564 | 563 | Out[8]: '43' |
|
565 | 564 | |
|
566 | 565 | # all-random (note for auto-testing) |
|
567 | 566 | """ |
|
568 | 567 | |
|
569 | rc = self.shell.rc | |
|
570 | ||
|
571 | 568 | if parameter_s: |
|
572 | 569 | arg = int(parameter_s) |
|
573 | 570 | else: |
|
574 | 571 | arg = 'toggle' |
|
575 | 572 | |
|
576 | 573 | if not arg in (0,1,2,'toggle'): |
|
577 | 574 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
578 | 575 | return |
|
579 | 576 | |
|
580 | 577 | if arg in (0,1,2): |
|
581 |
|
|
|
578 | self.shell.autocall = arg | |
|
582 | 579 | else: # toggle |
|
583 |
if |
|
|
584 |
self._magic_state.autocall_save = |
|
|
585 |
|
|
|
580 | if self.shell.autocall: | |
|
581 | self._magic_state.autocall_save = self.shell.autocall | |
|
582 | self.shell.autocall = 0 | |
|
586 | 583 | else: |
|
587 | 584 | try: |
|
588 |
|
|
|
585 | self.shell.autocall = self._magic_state.autocall_save | |
|
589 | 586 | except AttributeError: |
|
590 |
|
|
|
587 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
|
591 | 588 | |
|
592 |
print "Automatic calling is:",['OFF','Smart','Full'][ |
|
|
589 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
|
593 | 590 | |
|
594 | 591 | def magic_system_verbose(self, parameter_s = ''): |
|
595 | 592 | """Set verbose printing of system calls. |
|
596 | 593 | |
|
597 | 594 | If called without an argument, act as a toggle""" |
|
598 | 595 | |
|
599 | 596 | if parameter_s: |
|
600 | 597 | val = bool(eval(parameter_s)) |
|
601 | 598 | else: |
|
602 | 599 | val = None |
|
603 | ||
|
604 |
self.shell. |
|
|
600 | ||
|
601 | if self.shell.system_verbose: | |
|
602 | self.shell.system_verbose = False | |
|
603 | else: | |
|
604 | self.shell.system_verbose = True | |
|
605 | 605 | print "System verbose printing is:",\ |
|
606 |
['OFF','ON'][self.shell. |
|
|
606 | ['OFF','ON'][self.shell.system_verbose] | |
|
607 | 607 | |
|
608 | 608 | |
|
609 | 609 | def magic_page(self, parameter_s=''): |
|
610 | 610 | """Pretty print the object and display it through a pager. |
|
611 | 611 | |
|
612 | 612 | %page [options] OBJECT |
|
613 | 613 | |
|
614 | 614 | If no object is given, use _ (last output). |
|
615 | 615 | |
|
616 | 616 | Options: |
|
617 | 617 | |
|
618 | 618 | -r: page str(object), don't pretty-print it.""" |
|
619 | 619 | |
|
620 | 620 | # After a function contributed by Olivier Aubert, slightly modified. |
|
621 | 621 | |
|
622 | 622 | # Process options/args |
|
623 | 623 | opts,args = self.parse_options(parameter_s,'r') |
|
624 | 624 | raw = 'r' in opts |
|
625 | 625 | |
|
626 | 626 | oname = args and args or '_' |
|
627 | 627 | info = self._ofind(oname) |
|
628 | 628 | if info['found']: |
|
629 | 629 | txt = (raw and str or pformat)( info['obj'] ) |
|
630 | 630 | page(txt) |
|
631 | 631 | else: |
|
632 | 632 | print 'Object `%s` not found' % oname |
|
633 | 633 | |
|
634 | 634 | def magic_profile(self, parameter_s=''): |
|
635 | 635 | """Print your currently active IPyhton profile.""" |
|
636 |
if self.shell. |
|
|
637 |
printpl('Current IPython profile: $self.shell. |
|
|
636 | if self.shell.profile: | |
|
637 | printpl('Current IPython profile: $self.shell.profile.') | |
|
638 | 638 | else: |
|
639 | 639 | print 'No profile active.' |
|
640 | 640 | |
|
641 | 641 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
642 | 642 | """Provide detailed information about an object. |
|
643 | 643 | |
|
644 | 644 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
645 | 645 | |
|
646 | 646 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
647 | 647 | |
|
648 | 648 | |
|
649 | 649 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
650 | 650 | detail_level = 0 |
|
651 | 651 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
652 | 652 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
653 | 653 | pinfo,qmark1,oname,qmark2 = \ |
|
654 | 654 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
655 | 655 | if pinfo or qmark1 or qmark2: |
|
656 | 656 | detail_level = 1 |
|
657 | 657 | if "*" in oname: |
|
658 | 658 | self.magic_psearch(oname) |
|
659 | 659 | else: |
|
660 | 660 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
661 | 661 | namespaces=namespaces) |
|
662 | 662 | |
|
663 | 663 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
664 | 664 | """Print the definition header for any callable object. |
|
665 | 665 | |
|
666 | 666 | If the object is a class, print the constructor information.""" |
|
667 | 667 | self._inspect('pdef',parameter_s, namespaces) |
|
668 | 668 | |
|
669 | 669 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
670 | 670 | """Print the docstring for an object. |
|
671 | 671 | |
|
672 | 672 | If the given object is a class, it will print both the class and the |
|
673 | 673 | constructor docstrings.""" |
|
674 | 674 | self._inspect('pdoc',parameter_s, namespaces) |
|
675 | 675 | |
|
676 | 676 | def magic_psource(self, parameter_s='', namespaces=None): |
|
677 | 677 | """Print (or run through pager) the source code for an object.""" |
|
678 | 678 | self._inspect('psource',parameter_s, namespaces) |
|
679 | 679 | |
|
680 | 680 | def magic_pfile(self, parameter_s=''): |
|
681 | 681 | """Print (or run through pager) the file where an object is defined. |
|
682 | 682 | |
|
683 | 683 | The file opens at the line where the object definition begins. IPython |
|
684 | 684 | will honor the environment variable PAGER if set, and otherwise will |
|
685 | 685 | do its best to print the file in a convenient form. |
|
686 | 686 | |
|
687 | 687 | If the given argument is not an object currently defined, IPython will |
|
688 | 688 | try to interpret it as a filename (automatically adding a .py extension |
|
689 | 689 | if needed). You can thus use %pfile as a syntax highlighting code |
|
690 | 690 | viewer.""" |
|
691 | 691 | |
|
692 | 692 | # first interpret argument as an object name |
|
693 | 693 | out = self._inspect('pfile',parameter_s) |
|
694 | 694 | # if not, try the input as a filename |
|
695 | 695 | if out == 'not found': |
|
696 | 696 | try: |
|
697 | 697 | filename = get_py_filename(parameter_s) |
|
698 | 698 | except IOError,msg: |
|
699 | 699 | print msg |
|
700 | 700 | return |
|
701 | 701 | page(self.shell.inspector.format(file(filename).read())) |
|
702 | 702 | |
|
703 | 703 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
704 | 704 | """Generic interface to the inspector system. |
|
705 | 705 | |
|
706 | 706 | This function is meant to be called by pdef, pdoc & friends.""" |
|
707 | 707 | |
|
708 | 708 | #oname = oname.strip() |
|
709 | 709 | #print '1- oname: <%r>' % oname # dbg |
|
710 | 710 | try: |
|
711 | 711 | oname = oname.strip().encode('ascii') |
|
712 | 712 | #print '2- oname: <%r>' % oname # dbg |
|
713 | 713 | except UnicodeEncodeError: |
|
714 | 714 | print 'Python identifiers can only contain ascii characters.' |
|
715 | 715 | return 'not found' |
|
716 | 716 | |
|
717 | 717 | info = Struct(self._ofind(oname, namespaces)) |
|
718 | 718 | |
|
719 | 719 | if info.found: |
|
720 | 720 | try: |
|
721 | 721 | IPython.utils.generics.inspect_object(info.obj) |
|
722 | 722 | return |
|
723 | 723 | except ipapi.TryNext: |
|
724 | 724 | pass |
|
725 | 725 | # Get the docstring of the class property if it exists. |
|
726 | 726 | path = oname.split('.') |
|
727 | 727 | root = '.'.join(path[:-1]) |
|
728 | 728 | if info.parent is not None: |
|
729 | 729 | try: |
|
730 | 730 | target = getattr(info.parent, '__class__') |
|
731 | 731 | # The object belongs to a class instance. |
|
732 | 732 | try: |
|
733 | 733 | target = getattr(target, path[-1]) |
|
734 | 734 | # The class defines the object. |
|
735 | 735 | if isinstance(target, property): |
|
736 | 736 | oname = root + '.__class__.' + path[-1] |
|
737 | 737 | info = Struct(self._ofind(oname)) |
|
738 | 738 | except AttributeError: pass |
|
739 | 739 | except AttributeError: pass |
|
740 | 740 | |
|
741 | 741 | pmethod = getattr(self.shell.inspector,meth) |
|
742 | 742 | formatter = info.ismagic and self.format_screen or None |
|
743 | 743 | if meth == 'pdoc': |
|
744 | 744 | pmethod(info.obj,oname,formatter) |
|
745 | 745 | elif meth == 'pinfo': |
|
746 | 746 | pmethod(info.obj,oname,formatter,info,**kw) |
|
747 | 747 | else: |
|
748 | 748 | pmethod(info.obj,oname) |
|
749 | 749 | else: |
|
750 | 750 | print 'Object `%s` not found.' % oname |
|
751 | 751 | return 'not found' # so callers can take other action |
|
752 | 752 | |
|
753 | 753 | def magic_psearch(self, parameter_s=''): |
|
754 | 754 | """Search for object in namespaces by wildcard. |
|
755 | 755 | |
|
756 | 756 | %psearch [options] PATTERN [OBJECT TYPE] |
|
757 | 757 | |
|
758 | 758 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
759 | 759 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
760 | 760 | rest of the command line must be unchanged (options come first), so |
|
761 | 761 | for example the following forms are equivalent |
|
762 | 762 | |
|
763 | 763 | %psearch -i a* function |
|
764 | 764 | -i a* function? |
|
765 | 765 | ?-i a* function |
|
766 | 766 | |
|
767 | 767 | Arguments: |
|
768 | 768 | |
|
769 | 769 | PATTERN |
|
770 | 770 | |
|
771 | 771 | where PATTERN is a string containing * as a wildcard similar to its |
|
772 | 772 | use in a shell. The pattern is matched in all namespaces on the |
|
773 | 773 | search path. By default objects starting with a single _ are not |
|
774 | 774 | matched, many IPython generated objects have a single |
|
775 | 775 | underscore. The default is case insensitive matching. Matching is |
|
776 | 776 | also done on the attributes of objects and not only on the objects |
|
777 | 777 | in a module. |
|
778 | 778 | |
|
779 | 779 | [OBJECT TYPE] |
|
780 | 780 | |
|
781 | 781 | Is the name of a python type from the types module. The name is |
|
782 | 782 | given in lowercase without the ending type, ex. StringType is |
|
783 | 783 | written string. By adding a type here only objects matching the |
|
784 | 784 | given type are matched. Using all here makes the pattern match all |
|
785 | 785 | types (this is the default). |
|
786 | 786 | |
|
787 | 787 | Options: |
|
788 | 788 | |
|
789 | 789 | -a: makes the pattern match even objects whose names start with a |
|
790 | 790 | single underscore. These names are normally ommitted from the |
|
791 | 791 | search. |
|
792 | 792 | |
|
793 | 793 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
794 | 794 | these options is given, the default is read from your ipythonrc |
|
795 | 795 | file. The option name which sets this value is |
|
796 | 796 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
797 | 797 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
798 | 798 | search. |
|
799 | 799 | |
|
800 | 800 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
801 | 801 | specifiy can be searched in any of the following namespaces: |
|
802 | 802 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
803 | 803 | 'builtin' and 'user' are the search defaults. Note that you should |
|
804 | 804 | not use quotes when specifying namespaces. |
|
805 | 805 | |
|
806 | 806 | 'Builtin' contains the python module builtin, 'user' contains all |
|
807 | 807 | user data, 'alias' only contain the shell aliases and no python |
|
808 | 808 | objects, 'internal' contains objects used by IPython. The |
|
809 | 809 | 'user_global' namespace is only used by embedded IPython instances, |
|
810 | 810 | and it contains module-level globals. You can add namespaces to the |
|
811 | 811 | search with -s or exclude them with -e (these options can be given |
|
812 | 812 | more than once). |
|
813 | 813 | |
|
814 | 814 | Examples: |
|
815 | 815 | |
|
816 | 816 | %psearch a* -> objects beginning with an a |
|
817 | 817 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
818 | 818 | %psearch a* function -> all functions beginning with an a |
|
819 | 819 | %psearch re.e* -> objects beginning with an e in module re |
|
820 | 820 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
821 | 821 | %psearch r*.* string -> all strings in modules beginning with r |
|
822 | 822 | |
|
823 | 823 | Case sensitve search: |
|
824 | 824 | |
|
825 | 825 | %psearch -c a* list all object beginning with lower case a |
|
826 | 826 | |
|
827 | 827 | Show objects beginning with a single _: |
|
828 | 828 | |
|
829 | 829 | %psearch -a _* list objects beginning with a single underscore""" |
|
830 | 830 | try: |
|
831 | 831 | parameter_s = parameter_s.encode('ascii') |
|
832 | 832 | except UnicodeEncodeError: |
|
833 | 833 | print 'Python identifiers can only contain ascii characters.' |
|
834 | 834 | return |
|
835 | 835 | |
|
836 | 836 | # default namespaces to be searched |
|
837 | 837 | def_search = ['user','builtin'] |
|
838 | 838 | |
|
839 | 839 | # Process options/args |
|
840 | 840 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
841 | 841 | opt = opts.get |
|
842 | 842 | shell = self.shell |
|
843 | 843 | psearch = shell.inspector.psearch |
|
844 | 844 | |
|
845 | 845 | # select case options |
|
846 | 846 | if opts.has_key('i'): |
|
847 | 847 | ignore_case = True |
|
848 | 848 | elif opts.has_key('c'): |
|
849 | 849 | ignore_case = False |
|
850 | 850 | else: |
|
851 |
ignore_case = not shell. |
|
|
851 | ignore_case = not shell.wildcards_case_sensitive | |
|
852 | 852 | |
|
853 | 853 | # Build list of namespaces to search from user options |
|
854 | 854 | def_search.extend(opt('s',[])) |
|
855 | 855 | ns_exclude = ns_exclude=opt('e',[]) |
|
856 | 856 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
857 | 857 | |
|
858 | 858 | # Call the actual search |
|
859 | 859 | try: |
|
860 | 860 | psearch(args,shell.ns_table,ns_search, |
|
861 | 861 | show_all=opt('a'),ignore_case=ignore_case) |
|
862 | 862 | except: |
|
863 | 863 | shell.showtraceback() |
|
864 | 864 | |
|
865 | 865 | def magic_who_ls(self, parameter_s=''): |
|
866 | 866 | """Return a sorted list of all interactive variables. |
|
867 | 867 | |
|
868 | 868 | If arguments are given, only variables of types matching these |
|
869 | 869 | arguments are returned.""" |
|
870 | 870 | |
|
871 | 871 | user_ns = self.shell.user_ns |
|
872 | 872 | internal_ns = self.shell.internal_ns |
|
873 | 873 | user_config_ns = self.shell.user_config_ns |
|
874 | 874 | out = [] |
|
875 | 875 | typelist = parameter_s.split() |
|
876 | 876 | |
|
877 | 877 | for i in user_ns: |
|
878 | 878 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
879 | 879 | and not (i in internal_ns or i in user_config_ns): |
|
880 | 880 | if typelist: |
|
881 | 881 | if type(user_ns[i]).__name__ in typelist: |
|
882 | 882 | out.append(i) |
|
883 | 883 | else: |
|
884 | 884 | out.append(i) |
|
885 | 885 | out.sort() |
|
886 | 886 | return out |
|
887 | 887 | |
|
888 | 888 | def magic_who(self, parameter_s=''): |
|
889 | 889 | """Print all interactive variables, with some minimal formatting. |
|
890 | 890 | |
|
891 | 891 | If any arguments are given, only variables whose type matches one of |
|
892 | 892 | these are printed. For example: |
|
893 | 893 | |
|
894 | 894 | %who function str |
|
895 | 895 | |
|
896 | 896 | will only list functions and strings, excluding all other types of |
|
897 | 897 | variables. To find the proper type names, simply use type(var) at a |
|
898 | 898 | command line to see how python prints type names. For example: |
|
899 | 899 | |
|
900 | 900 | In [1]: type('hello')\\ |
|
901 | 901 | Out[1]: <type 'str'> |
|
902 | 902 | |
|
903 | 903 | indicates that the type name for strings is 'str'. |
|
904 | 904 | |
|
905 | 905 | %who always excludes executed names loaded through your configuration |
|
906 | 906 | file and things which are internal to IPython. |
|
907 | 907 | |
|
908 | 908 | This is deliberate, as typically you may load many modules and the |
|
909 | 909 | purpose of %who is to show you only what you've manually defined.""" |
|
910 | 910 | |
|
911 | 911 | varlist = self.magic_who_ls(parameter_s) |
|
912 | 912 | if not varlist: |
|
913 | 913 | if parameter_s: |
|
914 | 914 | print 'No variables match your requested type.' |
|
915 | 915 | else: |
|
916 | 916 | print 'Interactive namespace is empty.' |
|
917 | 917 | return |
|
918 | 918 | |
|
919 | 919 | # if we have variables, move on... |
|
920 | 920 | count = 0 |
|
921 | 921 | for i in varlist: |
|
922 | 922 | print i+'\t', |
|
923 | 923 | count += 1 |
|
924 | 924 | if count > 8: |
|
925 | 925 | count = 0 |
|
926 | 926 | |
|
927 | 927 | |
|
928 | 928 | |
|
929 | 929 | def magic_whos(self, parameter_s=''): |
|
930 | 930 | """Like %who, but gives some extra information about each variable. |
|
931 | 931 | |
|
932 | 932 | The same type filtering of %who can be applied here. |
|
933 | 933 | |
|
934 | 934 | For all variables, the type is printed. Additionally it prints: |
|
935 | 935 | |
|
936 | 936 | - For {},[],(): their length. |
|
937 | 937 | |
|
938 | 938 | - For numpy and Numeric arrays, a summary with shape, number of |
|
939 | 939 | elements, typecode and size in memory. |
|
940 | 940 | |
|
941 | 941 | - Everything else: a string representation, snipping their middle if |
|
942 | 942 | too long.""" |
|
943 | 943 | |
|
944 | 944 | varnames = self.magic_who_ls(parameter_s) |
|
945 | 945 | if not varnames: |
|
946 | 946 | if parameter_s: |
|
947 | 947 | print 'No variables match your requested type.' |
|
948 | 948 | else: |
|
949 | 949 | print 'Interactive namespace is empty.' |
|
950 | 950 | return |
|
951 | 951 | |
|
952 | 952 | # if we have variables, move on... |
|
953 | 953 | |
|
954 | 954 | # for these types, show len() instead of data: |
|
955 | 955 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
956 | 956 | |
|
957 | 957 | # for numpy/Numeric arrays, display summary info |
|
958 | 958 | try: |
|
959 | 959 | import numpy |
|
960 | 960 | except ImportError: |
|
961 | 961 | ndarray_type = None |
|
962 | 962 | else: |
|
963 | 963 | ndarray_type = numpy.ndarray.__name__ |
|
964 | 964 | try: |
|
965 | 965 | import Numeric |
|
966 | 966 | except ImportError: |
|
967 | 967 | array_type = None |
|
968 | 968 | else: |
|
969 | 969 | array_type = Numeric.ArrayType.__name__ |
|
970 | 970 | |
|
971 | 971 | # Find all variable names and types so we can figure out column sizes |
|
972 | 972 | def get_vars(i): |
|
973 | 973 | return self.shell.user_ns[i] |
|
974 | 974 | |
|
975 | 975 | # some types are well known and can be shorter |
|
976 | 976 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
977 | 977 | def type_name(v): |
|
978 | 978 | tn = type(v).__name__ |
|
979 | 979 | return abbrevs.get(tn,tn) |
|
980 | 980 | |
|
981 | 981 | varlist = map(get_vars,varnames) |
|
982 | 982 | |
|
983 | 983 | typelist = [] |
|
984 | 984 | for vv in varlist: |
|
985 | 985 | tt = type_name(vv) |
|
986 | 986 | |
|
987 | 987 | if tt=='instance': |
|
988 | 988 | typelist.append( abbrevs.get(str(vv.__class__), |
|
989 | 989 | str(vv.__class__))) |
|
990 | 990 | else: |
|
991 | 991 | typelist.append(tt) |
|
992 | 992 | |
|
993 | 993 | # column labels and # of spaces as separator |
|
994 | 994 | varlabel = 'Variable' |
|
995 | 995 | typelabel = 'Type' |
|
996 | 996 | datalabel = 'Data/Info' |
|
997 | 997 | colsep = 3 |
|
998 | 998 | # variable format strings |
|
999 | 999 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1000 | 1000 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1001 | 1001 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1002 | 1002 | # find the size of the columns to format the output nicely |
|
1003 | 1003 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1004 | 1004 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1005 | 1005 | # table header |
|
1006 | 1006 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1007 | 1007 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1008 | 1008 | # and the table itself |
|
1009 | 1009 | kb = 1024 |
|
1010 | 1010 | Mb = 1048576 # kb**2 |
|
1011 | 1011 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1012 | 1012 | print itpl(vformat), |
|
1013 | 1013 | if vtype in seq_types: |
|
1014 | 1014 | print len(var) |
|
1015 | 1015 | elif vtype in [array_type,ndarray_type]: |
|
1016 | 1016 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1017 | 1017 | if vtype==ndarray_type: |
|
1018 | 1018 | # numpy |
|
1019 | 1019 | vsize = var.size |
|
1020 | 1020 | vbytes = vsize*var.itemsize |
|
1021 | 1021 | vdtype = var.dtype |
|
1022 | 1022 | else: |
|
1023 | 1023 | # Numeric |
|
1024 | 1024 | vsize = Numeric.size(var) |
|
1025 | 1025 | vbytes = vsize*var.itemsize() |
|
1026 | 1026 | vdtype = var.typecode() |
|
1027 | 1027 | |
|
1028 | 1028 | if vbytes < 100000: |
|
1029 | 1029 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1030 | 1030 | else: |
|
1031 | 1031 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1032 | 1032 | if vbytes < Mb: |
|
1033 | 1033 | print '(%s kb)' % (vbytes/kb,) |
|
1034 | 1034 | else: |
|
1035 | 1035 | print '(%s Mb)' % (vbytes/Mb,) |
|
1036 | 1036 | else: |
|
1037 | 1037 | try: |
|
1038 | 1038 | vstr = str(var) |
|
1039 | 1039 | except UnicodeEncodeError: |
|
1040 | 1040 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1041 | 1041 | 'backslashreplace') |
|
1042 | 1042 | vstr = vstr.replace('\n','\\n') |
|
1043 | 1043 | if len(vstr) < 50: |
|
1044 | 1044 | print vstr |
|
1045 | 1045 | else: |
|
1046 | 1046 | printpl(vfmt_short) |
|
1047 | 1047 | |
|
1048 | 1048 | def magic_reset(self, parameter_s=''): |
|
1049 | 1049 | """Resets the namespace by removing all names defined by the user. |
|
1050 | 1050 | |
|
1051 | 1051 | Input/Output history are left around in case you need them. |
|
1052 | 1052 | |
|
1053 | 1053 | Parameters |
|
1054 | 1054 | ---------- |
|
1055 | 1055 | -y : force reset without asking for confirmation. |
|
1056 | 1056 | |
|
1057 | 1057 | Examples |
|
1058 | 1058 | -------- |
|
1059 | 1059 | In [6]: a = 1 |
|
1060 | 1060 | |
|
1061 | 1061 | In [7]: a |
|
1062 | 1062 | Out[7]: 1 |
|
1063 | 1063 | |
|
1064 | 1064 | In [8]: 'a' in _ip.user_ns |
|
1065 | 1065 | Out[8]: True |
|
1066 | 1066 | |
|
1067 | 1067 | In [9]: %reset -f |
|
1068 | 1068 | |
|
1069 | 1069 | In [10]: 'a' in _ip.user_ns |
|
1070 | 1070 | Out[10]: False |
|
1071 | 1071 | """ |
|
1072 | 1072 | |
|
1073 | 1073 | if parameter_s == '-f': |
|
1074 | 1074 | ans = True |
|
1075 | 1075 | else: |
|
1076 | 1076 | ans = self.shell.ask_yes_no( |
|
1077 | 1077 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1078 | 1078 | if not ans: |
|
1079 | 1079 | print 'Nothing done.' |
|
1080 | 1080 | return |
|
1081 | 1081 | user_ns = self.shell.user_ns |
|
1082 | 1082 | for i in self.magic_who_ls(): |
|
1083 | 1083 | del(user_ns[i]) |
|
1084 | 1084 | |
|
1085 | 1085 | # Also flush the private list of module references kept for script |
|
1086 | 1086 | # execution protection |
|
1087 | 1087 | self.shell.clear_main_mod_cache() |
|
1088 | 1088 | |
|
1089 | 1089 | def magic_logstart(self,parameter_s=''): |
|
1090 | 1090 | """Start logging anywhere in a session. |
|
1091 | 1091 | |
|
1092 | 1092 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1093 | 1093 | |
|
1094 | 1094 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1095 | 1095 | current directory, in 'rotate' mode (see below). |
|
1096 | 1096 | |
|
1097 | 1097 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1098 | 1098 | history up to that point and then continues logging. |
|
1099 | 1099 | |
|
1100 | 1100 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1101 | 1101 | of (note that the modes are given unquoted):\\ |
|
1102 | 1102 | append: well, that says it.\\ |
|
1103 | 1103 | backup: rename (if exists) to name~ and start name.\\ |
|
1104 | 1104 | global: single logfile in your home dir, appended to.\\ |
|
1105 | 1105 | over : overwrite existing log.\\ |
|
1106 | 1106 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1107 | 1107 | |
|
1108 | 1108 | Options: |
|
1109 | 1109 | |
|
1110 | 1110 | -o: log also IPython's output. In this mode, all commands which |
|
1111 | 1111 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1112 | 1112 | their corresponding input line. The output lines are always |
|
1113 | 1113 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1114 | 1114 | Python code. |
|
1115 | 1115 | |
|
1116 | 1116 | Since this marker is always the same, filtering only the output from |
|
1117 | 1117 | a log is very easy, using for example a simple awk call: |
|
1118 | 1118 | |
|
1119 | 1119 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1120 | 1120 | |
|
1121 | 1121 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1122 | 1122 | input, so that user lines are logged in their final form, converted |
|
1123 | 1123 | into valid Python. For example, %Exit is logged as |
|
1124 | 1124 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1125 | 1125 | exactly as typed, with no transformations applied. |
|
1126 | 1126 | |
|
1127 | 1127 | -t: put timestamps before each input line logged (these are put in |
|
1128 | 1128 | comments).""" |
|
1129 | 1129 | |
|
1130 | 1130 | opts,par = self.parse_options(parameter_s,'ort') |
|
1131 | 1131 | log_output = 'o' in opts |
|
1132 | 1132 | log_raw_input = 'r' in opts |
|
1133 | 1133 | timestamp = 't' in opts |
|
1134 | 1134 | |
|
1135 | rc = self.shell.rc | |
|
1136 | 1135 | logger = self.shell.logger |
|
1137 | 1136 | |
|
1138 | 1137 | # if no args are given, the defaults set in the logger constructor by |
|
1139 | 1138 | # ipytohn remain valid |
|
1140 | 1139 | if par: |
|
1141 | 1140 | try: |
|
1142 | 1141 | logfname,logmode = par.split() |
|
1143 | 1142 | except: |
|
1144 | 1143 | logfname = par |
|
1145 | 1144 | logmode = 'backup' |
|
1146 | 1145 | else: |
|
1147 | 1146 | logfname = logger.logfname |
|
1148 | 1147 | logmode = logger.logmode |
|
1149 | 1148 | # put logfname into rc struct as if it had been called on the command |
|
1150 | 1149 | # line, so it ends up saved in the log header Save it in case we need |
|
1151 | 1150 | # to restore it... |
|
1152 |
old_logfile = |
|
|
1151 | old_logfile = self.shell.logfile | |
|
1153 | 1152 | if logfname: |
|
1154 | 1153 | logfname = os.path.expanduser(logfname) |
|
1155 |
|
|
|
1156 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
|
1154 | self.shell.logfile = logfname | |
|
1155 | # TODO: we need to re-think how logs with args/opts are replayed | |
|
1156 | # and tracked. | |
|
1157 | # loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
|
1158 | loghead = self.shell.loghead_tpl % ('','') | |
|
1157 | 1159 | try: |
|
1158 | 1160 | started = logger.logstart(logfname,loghead,logmode, |
|
1159 | 1161 | log_output,timestamp,log_raw_input) |
|
1160 | 1162 | except: |
|
1161 | 1163 | rc.opts.logfile = old_logfile |
|
1162 | 1164 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1163 | 1165 | else: |
|
1164 | 1166 | # log input history up to this point, optionally interleaving |
|
1165 | 1167 | # output if requested |
|
1166 | 1168 | |
|
1167 | 1169 | if timestamp: |
|
1168 | 1170 | # disable timestamping for the previous history, since we've |
|
1169 | 1171 | # lost those already (no time machine here). |
|
1170 | 1172 | logger.timestamp = False |
|
1171 | 1173 | |
|
1172 | 1174 | if log_raw_input: |
|
1173 | 1175 | input_hist = self.shell.input_hist_raw |
|
1174 | 1176 | else: |
|
1175 | 1177 | input_hist = self.shell.input_hist |
|
1176 | 1178 | |
|
1177 | 1179 | if log_output: |
|
1178 | 1180 | log_write = logger.log_write |
|
1179 | 1181 | output_hist = self.shell.output_hist |
|
1180 | 1182 | for n in range(1,len(input_hist)-1): |
|
1181 | 1183 | log_write(input_hist[n].rstrip()) |
|
1182 | 1184 | if n in output_hist: |
|
1183 | 1185 | log_write(repr(output_hist[n]),'output') |
|
1184 | 1186 | else: |
|
1185 | 1187 | logger.log_write(input_hist[1:]) |
|
1186 | 1188 | if timestamp: |
|
1187 | 1189 | # re-enable timestamping |
|
1188 | 1190 | logger.timestamp = True |
|
1189 | 1191 | |
|
1190 | 1192 | print ('Activating auto-logging. ' |
|
1191 | 1193 | 'Current session state plus future input saved.') |
|
1192 | 1194 | logger.logstate() |
|
1193 | 1195 | |
|
1194 | 1196 | def magic_logstop(self,parameter_s=''): |
|
1195 | 1197 | """Fully stop logging and close log file. |
|
1196 | 1198 | |
|
1197 | 1199 | In order to start logging again, a new %logstart call needs to be made, |
|
1198 | 1200 | possibly (though not necessarily) with a new filename, mode and other |
|
1199 | 1201 | options.""" |
|
1200 | 1202 | self.logger.logstop() |
|
1201 | 1203 | |
|
1202 | 1204 | def magic_logoff(self,parameter_s=''): |
|
1203 | 1205 | """Temporarily stop logging. |
|
1204 | 1206 | |
|
1205 | 1207 | You must have previously started logging.""" |
|
1206 | 1208 | self.shell.logger.switch_log(0) |
|
1207 | 1209 | |
|
1208 | 1210 | def magic_logon(self,parameter_s=''): |
|
1209 | 1211 | """Restart logging. |
|
1210 | 1212 | |
|
1211 | 1213 | This function is for restarting logging which you've temporarily |
|
1212 | 1214 | stopped with %logoff. For starting logging for the first time, you |
|
1213 | 1215 | must use the %logstart function, which allows you to specify an |
|
1214 | 1216 | optional log filename.""" |
|
1215 | 1217 | |
|
1216 | 1218 | self.shell.logger.switch_log(1) |
|
1217 | 1219 | |
|
1218 | 1220 | def magic_logstate(self,parameter_s=''): |
|
1219 | 1221 | """Print the status of the logging system.""" |
|
1220 | 1222 | |
|
1221 | 1223 | self.shell.logger.logstate() |
|
1222 | 1224 | |
|
1223 | 1225 | def magic_pdb(self, parameter_s=''): |
|
1224 | 1226 | """Control the automatic calling of the pdb interactive debugger. |
|
1225 | 1227 | |
|
1226 | 1228 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1227 | 1229 | argument it works as a toggle. |
|
1228 | 1230 | |
|
1229 | 1231 | When an exception is triggered, IPython can optionally call the |
|
1230 | 1232 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1231 | 1233 | this feature on and off. |
|
1232 | 1234 | |
|
1233 | 1235 | The initial state of this feature is set in your ipythonrc |
|
1234 | 1236 | configuration file (the variable is called 'pdb'). |
|
1235 | 1237 | |
|
1236 | 1238 | If you want to just activate the debugger AFTER an exception has fired, |
|
1237 | 1239 | without having to type '%pdb on' and rerunning your code, you can use |
|
1238 | 1240 | the %debug magic.""" |
|
1239 | 1241 | |
|
1240 | 1242 | par = parameter_s.strip().lower() |
|
1241 | 1243 | |
|
1242 | 1244 | if par: |
|
1243 | 1245 | try: |
|
1244 | 1246 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1245 | 1247 | except KeyError: |
|
1246 | 1248 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1247 | 1249 | 'or nothing for a toggle.') |
|
1248 | 1250 | return |
|
1249 | 1251 | else: |
|
1250 | 1252 | # toggle |
|
1251 | 1253 | new_pdb = not self.shell.call_pdb |
|
1252 | 1254 | |
|
1253 | 1255 | # set on the shell |
|
1254 | 1256 | self.shell.call_pdb = new_pdb |
|
1255 | 1257 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1256 | 1258 | |
|
1257 | 1259 | def magic_debug(self, parameter_s=''): |
|
1258 | 1260 | """Activate the interactive debugger in post-mortem mode. |
|
1259 | 1261 | |
|
1260 | 1262 | If an exception has just occurred, this lets you inspect its stack |
|
1261 | 1263 | frames interactively. Note that this will always work only on the last |
|
1262 | 1264 | traceback that occurred, so you must call this quickly after an |
|
1263 | 1265 | exception that you wish to inspect has fired, because if another one |
|
1264 | 1266 | occurs, it clobbers the previous one. |
|
1265 | 1267 | |
|
1266 | 1268 | If you want IPython to automatically do this on every exception, see |
|
1267 | 1269 | the %pdb magic for more details. |
|
1268 | 1270 | """ |
|
1269 | 1271 | |
|
1270 | 1272 | self.shell.debugger(force=True) |
|
1271 | 1273 | |
|
1272 | 1274 | @testdec.skip_doctest |
|
1273 | 1275 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1274 | 1276 | opts=None,arg_lst=None,prog_ns=None): |
|
1275 | 1277 | |
|
1276 | 1278 | """Run a statement through the python code profiler. |
|
1277 | 1279 | |
|
1278 | 1280 | Usage: |
|
1279 | 1281 | %prun [options] statement |
|
1280 | 1282 | |
|
1281 | 1283 | The given statement (which doesn't require quote marks) is run via the |
|
1282 | 1284 | python profiler in a manner similar to the profile.run() function. |
|
1283 | 1285 | Namespaces are internally managed to work correctly; profile.run |
|
1284 | 1286 | cannot be used in IPython because it makes certain assumptions about |
|
1285 | 1287 | namespaces which do not hold under IPython. |
|
1286 | 1288 | |
|
1287 | 1289 | Options: |
|
1288 | 1290 | |
|
1289 | 1291 | -l <limit>: you can place restrictions on what or how much of the |
|
1290 | 1292 | profile gets printed. The limit value can be: |
|
1291 | 1293 | |
|
1292 | 1294 | * A string: only information for function names containing this string |
|
1293 | 1295 | is printed. |
|
1294 | 1296 | |
|
1295 | 1297 | * An integer: only these many lines are printed. |
|
1296 | 1298 | |
|
1297 | 1299 | * A float (between 0 and 1): this fraction of the report is printed |
|
1298 | 1300 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1299 | 1301 | |
|
1300 | 1302 | You can combine several limits with repeated use of the option. For |
|
1301 | 1303 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1302 | 1304 | information about class constructors. |
|
1303 | 1305 | |
|
1304 | 1306 | -r: return the pstats.Stats object generated by the profiling. This |
|
1305 | 1307 | object has all the information about the profile in it, and you can |
|
1306 | 1308 | later use it for further analysis or in other functions. |
|
1307 | 1309 | |
|
1308 | 1310 | -s <key>: sort profile by given key. You can provide more than one key |
|
1309 | 1311 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1310 | 1312 | default sorting key is 'time'. |
|
1311 | 1313 | |
|
1312 | 1314 | The following is copied verbatim from the profile documentation |
|
1313 | 1315 | referenced below: |
|
1314 | 1316 | |
|
1315 | 1317 | When more than one key is provided, additional keys are used as |
|
1316 | 1318 | secondary criteria when the there is equality in all keys selected |
|
1317 | 1319 | before them. |
|
1318 | 1320 | |
|
1319 | 1321 | Abbreviations can be used for any key names, as long as the |
|
1320 | 1322 | abbreviation is unambiguous. The following are the keys currently |
|
1321 | 1323 | defined: |
|
1322 | 1324 | |
|
1323 | 1325 | Valid Arg Meaning |
|
1324 | 1326 | "calls" call count |
|
1325 | 1327 | "cumulative" cumulative time |
|
1326 | 1328 | "file" file name |
|
1327 | 1329 | "module" file name |
|
1328 | 1330 | "pcalls" primitive call count |
|
1329 | 1331 | "line" line number |
|
1330 | 1332 | "name" function name |
|
1331 | 1333 | "nfl" name/file/line |
|
1332 | 1334 | "stdname" standard name |
|
1333 | 1335 | "time" internal time |
|
1334 | 1336 | |
|
1335 | 1337 | Note that all sorts on statistics are in descending order (placing |
|
1336 | 1338 | most time consuming items first), where as name, file, and line number |
|
1337 | 1339 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1338 | 1340 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1339 | 1341 | sort of the name as printed, which means that the embedded line |
|
1340 | 1342 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1341 | 1343 | would (if the file names were the same) appear in the string order |
|
1342 | 1344 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1343 | 1345 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1344 | 1346 | sort_stats("name", "file", "line"). |
|
1345 | 1347 | |
|
1346 | 1348 | -T <filename>: save profile results as shown on screen to a text |
|
1347 | 1349 | file. The profile is still shown on screen. |
|
1348 | 1350 | |
|
1349 | 1351 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1350 | 1352 | filename. This data is in a format understod by the pstats module, and |
|
1351 | 1353 | is generated by a call to the dump_stats() method of profile |
|
1352 | 1354 | objects. The profile is still shown on screen. |
|
1353 | 1355 | |
|
1354 | 1356 | If you want to run complete programs under the profiler's control, use |
|
1355 | 1357 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1356 | 1358 | contains profiler specific options as described here. |
|
1357 | 1359 | |
|
1358 | 1360 | You can read the complete documentation for the profile module with:: |
|
1359 | 1361 | |
|
1360 | 1362 | In [1]: import profile; profile.help() |
|
1361 | 1363 | """ |
|
1362 | 1364 | |
|
1363 | 1365 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1364 | 1366 | # protect user quote marks |
|
1365 | 1367 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1366 | 1368 | |
|
1367 | 1369 | if user_mode: # regular user call |
|
1368 | 1370 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1369 | 1371 | list_all=1) |
|
1370 | 1372 | namespace = self.shell.user_ns |
|
1371 | 1373 | else: # called to run a program by %run -p |
|
1372 | 1374 | try: |
|
1373 | 1375 | filename = get_py_filename(arg_lst[0]) |
|
1374 | 1376 | except IOError,msg: |
|
1375 | 1377 | error(msg) |
|
1376 | 1378 | return |
|
1377 | 1379 | |
|
1378 | 1380 | arg_str = 'execfile(filename,prog_ns)' |
|
1379 | 1381 | namespace = locals() |
|
1380 | 1382 | |
|
1381 | 1383 | opts.merge(opts_def) |
|
1382 | 1384 | |
|
1383 | 1385 | prof = profile.Profile() |
|
1384 | 1386 | try: |
|
1385 | 1387 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1386 | 1388 | sys_exit = '' |
|
1387 | 1389 | except SystemExit: |
|
1388 | 1390 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1389 | 1391 | |
|
1390 | 1392 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1391 | 1393 | |
|
1392 | 1394 | lims = opts.l |
|
1393 | 1395 | if lims: |
|
1394 | 1396 | lims = [] # rebuild lims with ints/floats/strings |
|
1395 | 1397 | for lim in opts.l: |
|
1396 | 1398 | try: |
|
1397 | 1399 | lims.append(int(lim)) |
|
1398 | 1400 | except ValueError: |
|
1399 | 1401 | try: |
|
1400 | 1402 | lims.append(float(lim)) |
|
1401 | 1403 | except ValueError: |
|
1402 | 1404 | lims.append(lim) |
|
1403 | 1405 | |
|
1404 | 1406 | # Trap output. |
|
1405 | 1407 | stdout_trap = StringIO() |
|
1406 | 1408 | |
|
1407 | 1409 | if hasattr(stats,'stream'): |
|
1408 | 1410 | # In newer versions of python, the stats object has a 'stream' |
|
1409 | 1411 | # attribute to write into. |
|
1410 | 1412 | stats.stream = stdout_trap |
|
1411 | 1413 | stats.print_stats(*lims) |
|
1412 | 1414 | else: |
|
1413 | 1415 | # For older versions, we manually redirect stdout during printing |
|
1414 | 1416 | sys_stdout = sys.stdout |
|
1415 | 1417 | try: |
|
1416 | 1418 | sys.stdout = stdout_trap |
|
1417 | 1419 | stats.print_stats(*lims) |
|
1418 | 1420 | finally: |
|
1419 | 1421 | sys.stdout = sys_stdout |
|
1420 | 1422 | |
|
1421 | 1423 | output = stdout_trap.getvalue() |
|
1422 | 1424 | output = output.rstrip() |
|
1423 | 1425 | |
|
1424 |
page(output,screen_lines=self.shell. |
|
|
1426 | page(output,screen_lines=self.shell.screen_length) | |
|
1425 | 1427 | print sys_exit, |
|
1426 | 1428 | |
|
1427 | 1429 | dump_file = opts.D[0] |
|
1428 | 1430 | text_file = opts.T[0] |
|
1429 | 1431 | if dump_file: |
|
1430 | 1432 | prof.dump_stats(dump_file) |
|
1431 | 1433 | print '\n*** Profile stats marshalled to file',\ |
|
1432 | 1434 | `dump_file`+'.',sys_exit |
|
1433 | 1435 | if text_file: |
|
1434 | 1436 | pfile = file(text_file,'w') |
|
1435 | 1437 | pfile.write(output) |
|
1436 | 1438 | pfile.close() |
|
1437 | 1439 | print '\n*** Profile printout saved to text file',\ |
|
1438 | 1440 | `text_file`+'.',sys_exit |
|
1439 | 1441 | |
|
1440 | 1442 | if opts.has_key('r'): |
|
1441 | 1443 | return stats |
|
1442 | 1444 | else: |
|
1443 | 1445 | return None |
|
1444 | 1446 | |
|
1445 | 1447 | @testdec.skip_doctest |
|
1446 | 1448 | def magic_run(self, parameter_s ='',runner=None, |
|
1447 | 1449 | file_finder=get_py_filename): |
|
1448 | 1450 | """Run the named file inside IPython as a program. |
|
1449 | 1451 | |
|
1450 | 1452 | Usage:\\ |
|
1451 | 1453 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1452 | 1454 | |
|
1453 | 1455 | Parameters after the filename are passed as command-line arguments to |
|
1454 | 1456 | the program (put in sys.argv). Then, control returns to IPython's |
|
1455 | 1457 | prompt. |
|
1456 | 1458 | |
|
1457 | 1459 | This is similar to running at a system prompt:\\ |
|
1458 | 1460 | $ python file args\\ |
|
1459 | 1461 | but with the advantage of giving you IPython's tracebacks, and of |
|
1460 | 1462 | loading all variables into your interactive namespace for further use |
|
1461 | 1463 | (unless -p is used, see below). |
|
1462 | 1464 | |
|
1463 | 1465 | The file is executed in a namespace initially consisting only of |
|
1464 | 1466 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1465 | 1467 | sees its environment as if it were being run as a stand-alone program |
|
1466 | 1468 | (except for sharing global objects such as previously imported |
|
1467 | 1469 | modules). But after execution, the IPython interactive namespace gets |
|
1468 | 1470 | updated with all variables defined in the program (except for __name__ |
|
1469 | 1471 | and sys.argv). This allows for very convenient loading of code for |
|
1470 | 1472 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1471 | 1473 | |
|
1472 | 1474 | Options: |
|
1473 | 1475 | |
|
1474 | 1476 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1475 | 1477 | without extension (as python does under import). This allows running |
|
1476 | 1478 | scripts and reloading the definitions in them without calling code |
|
1477 | 1479 | protected by an ' if __name__ == "__main__" ' clause. |
|
1478 | 1480 | |
|
1479 | 1481 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1480 | 1482 | is useful if you are experimenting with code written in a text editor |
|
1481 | 1483 | which depends on variables defined interactively. |
|
1482 | 1484 | |
|
1483 | 1485 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1484 | 1486 | being run. This is particularly useful if IPython is being used to |
|
1485 | 1487 | run unittests, which always exit with a sys.exit() call. In such |
|
1486 | 1488 | cases you are interested in the output of the test results, not in |
|
1487 | 1489 | seeing a traceback of the unittest module. |
|
1488 | 1490 | |
|
1489 | 1491 | -t: print timing information at the end of the run. IPython will give |
|
1490 | 1492 | you an estimated CPU time consumption for your script, which under |
|
1491 | 1493 | Unix uses the resource module to avoid the wraparound problems of |
|
1492 | 1494 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1493 | 1495 | is also given (for Windows platforms this is reported as 0.0). |
|
1494 | 1496 | |
|
1495 | 1497 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1496 | 1498 | must be an integer indicating how many times you want the script to |
|
1497 | 1499 | run. The final timing report will include total and per run results. |
|
1498 | 1500 | |
|
1499 | 1501 | For example (testing the script uniq_stable.py): |
|
1500 | 1502 | |
|
1501 | 1503 | In [1]: run -t uniq_stable |
|
1502 | 1504 | |
|
1503 | 1505 | IPython CPU timings (estimated):\\ |
|
1504 | 1506 | User : 0.19597 s.\\ |
|
1505 | 1507 | System: 0.0 s.\\ |
|
1506 | 1508 | |
|
1507 | 1509 | In [2]: run -t -N5 uniq_stable |
|
1508 | 1510 | |
|
1509 | 1511 | IPython CPU timings (estimated):\\ |
|
1510 | 1512 | Total runs performed: 5\\ |
|
1511 | 1513 | Times : Total Per run\\ |
|
1512 | 1514 | User : 0.910862 s, 0.1821724 s.\\ |
|
1513 | 1515 | System: 0.0 s, 0.0 s. |
|
1514 | 1516 | |
|
1515 | 1517 | -d: run your program under the control of pdb, the Python debugger. |
|
1516 | 1518 | This allows you to execute your program step by step, watch variables, |
|
1517 | 1519 | etc. Internally, what IPython does is similar to calling: |
|
1518 | 1520 | |
|
1519 | 1521 | pdb.run('execfile("YOURFILENAME")') |
|
1520 | 1522 | |
|
1521 | 1523 | with a breakpoint set on line 1 of your file. You can change the line |
|
1522 | 1524 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1523 | 1525 | (where N must be an integer). For example: |
|
1524 | 1526 | |
|
1525 | 1527 | %run -d -b40 myscript |
|
1526 | 1528 | |
|
1527 | 1529 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1528 | 1530 | the first breakpoint must be set on a line which actually does |
|
1529 | 1531 | something (not a comment or docstring) for it to stop execution. |
|
1530 | 1532 | |
|
1531 | 1533 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1532 | 1534 | first enter 'c' (without qoutes) to start execution up to the first |
|
1533 | 1535 | breakpoint. |
|
1534 | 1536 | |
|
1535 | 1537 | Entering 'help' gives information about the use of the debugger. You |
|
1536 | 1538 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1537 | 1539 | at a prompt. |
|
1538 | 1540 | |
|
1539 | 1541 | -p: run program under the control of the Python profiler module (which |
|
1540 | 1542 | prints a detailed report of execution times, function calls, etc). |
|
1541 | 1543 | |
|
1542 | 1544 | You can pass other options after -p which affect the behavior of the |
|
1543 | 1545 | profiler itself. See the docs for %prun for details. |
|
1544 | 1546 | |
|
1545 | 1547 | In this mode, the program's variables do NOT propagate back to the |
|
1546 | 1548 | IPython interactive namespace (because they remain in the namespace |
|
1547 | 1549 | where the profiler executes them). |
|
1548 | 1550 | |
|
1549 | 1551 | Internally this triggers a call to %prun, see its documentation for |
|
1550 | 1552 | details on the options available specifically for profiling. |
|
1551 | 1553 | |
|
1552 | 1554 | There is one special usage for which the text above doesn't apply: |
|
1553 | 1555 | if the filename ends with .ipy, the file is run as ipython script, |
|
1554 | 1556 | just as if the commands were written on IPython prompt. |
|
1555 | 1557 | """ |
|
1556 | 1558 | |
|
1557 | 1559 | # get arguments and set sys.argv for program to be run. |
|
1558 | 1560 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1559 | 1561 | mode='list',list_all=1) |
|
1560 | 1562 | |
|
1561 | 1563 | try: |
|
1562 | 1564 | filename = file_finder(arg_lst[0]) |
|
1563 | 1565 | except IndexError: |
|
1564 | 1566 | warn('you must provide at least a filename.') |
|
1565 | 1567 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1566 | 1568 | return |
|
1567 | 1569 | except IOError,msg: |
|
1568 | 1570 | error(msg) |
|
1569 | 1571 | return |
|
1570 | 1572 | |
|
1571 | 1573 | if filename.lower().endswith('.ipy'): |
|
1572 | 1574 | self.api.runlines(open(filename).read()) |
|
1573 | 1575 | return |
|
1574 | 1576 | |
|
1575 | 1577 | # Control the response to exit() calls made by the script being run |
|
1576 | 1578 | exit_ignore = opts.has_key('e') |
|
1577 | 1579 | |
|
1578 | 1580 | # Make sure that the running script gets a proper sys.argv as if it |
|
1579 | 1581 | # were run from a system shell. |
|
1580 | 1582 | save_argv = sys.argv # save it for later restoring |
|
1581 | 1583 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1582 | 1584 | |
|
1583 | 1585 | if opts.has_key('i'): |
|
1584 | 1586 | # Run in user's interactive namespace |
|
1585 | 1587 | prog_ns = self.shell.user_ns |
|
1586 | 1588 | __name__save = self.shell.user_ns['__name__'] |
|
1587 | 1589 | prog_ns['__name__'] = '__main__' |
|
1588 | 1590 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1589 | 1591 | else: |
|
1590 | 1592 | # Run in a fresh, empty namespace |
|
1591 | 1593 | if opts.has_key('n'): |
|
1592 | 1594 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1593 | 1595 | else: |
|
1594 | 1596 | name = '__main__' |
|
1595 | 1597 | |
|
1596 | 1598 | main_mod = self.shell.new_main_mod() |
|
1597 | 1599 | prog_ns = main_mod.__dict__ |
|
1598 | 1600 | prog_ns['__name__'] = name |
|
1599 | 1601 | |
|
1600 | 1602 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1601 | 1603 | # set the __file__ global in the script's namespace |
|
1602 | 1604 | prog_ns['__file__'] = filename |
|
1603 | 1605 | |
|
1604 | 1606 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1605 | 1607 | # that, if we overwrite __main__, we replace it at the end |
|
1606 | 1608 | main_mod_name = prog_ns['__name__'] |
|
1607 | 1609 | |
|
1608 | 1610 | if main_mod_name == '__main__': |
|
1609 | 1611 | restore_main = sys.modules['__main__'] |
|
1610 | 1612 | else: |
|
1611 | 1613 | restore_main = False |
|
1612 | 1614 | |
|
1613 | 1615 | # This needs to be undone at the end to prevent holding references to |
|
1614 | 1616 | # every single object ever created. |
|
1615 | 1617 | sys.modules[main_mod_name] = main_mod |
|
1616 | 1618 | |
|
1617 | 1619 | stats = None |
|
1618 | 1620 | try: |
|
1619 | 1621 | self.shell.savehist() |
|
1620 | 1622 | |
|
1621 | 1623 | if opts.has_key('p'): |
|
1622 | 1624 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1623 | 1625 | else: |
|
1624 | 1626 | if opts.has_key('d'): |
|
1625 |
deb = debugger.Pdb(self.shell. |
|
|
1627 | deb = debugger.Pdb(self.shell.colors) | |
|
1626 | 1628 | # reset Breakpoint state, which is moronically kept |
|
1627 | 1629 | # in a class |
|
1628 | 1630 | bdb.Breakpoint.next = 1 |
|
1629 | 1631 | bdb.Breakpoint.bplist = {} |
|
1630 | 1632 | bdb.Breakpoint.bpbynumber = [None] |
|
1631 | 1633 | # Set an initial breakpoint to stop execution |
|
1632 | 1634 | maxtries = 10 |
|
1633 | 1635 | bp = int(opts.get('b',[1])[0]) |
|
1634 | 1636 | checkline = deb.checkline(filename,bp) |
|
1635 | 1637 | if not checkline: |
|
1636 | 1638 | for bp in range(bp+1,bp+maxtries+1): |
|
1637 | 1639 | if deb.checkline(filename,bp): |
|
1638 | 1640 | break |
|
1639 | 1641 | else: |
|
1640 | 1642 | msg = ("\nI failed to find a valid line to set " |
|
1641 | 1643 | "a breakpoint\n" |
|
1642 | 1644 | "after trying up to line: %s.\n" |
|
1643 | 1645 | "Please set a valid breakpoint manually " |
|
1644 | 1646 | "with the -b option." % bp) |
|
1645 | 1647 | error(msg) |
|
1646 | 1648 | return |
|
1647 | 1649 | # if we find a good linenumber, set the breakpoint |
|
1648 | 1650 | deb.do_break('%s:%s' % (filename,bp)) |
|
1649 | 1651 | # Start file run |
|
1650 | 1652 | print "NOTE: Enter 'c' at the", |
|
1651 | 1653 | print "%s prompt to start your script." % deb.prompt |
|
1652 | 1654 | try: |
|
1653 | 1655 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1654 | 1656 | |
|
1655 | 1657 | except: |
|
1656 | 1658 | etype, value, tb = sys.exc_info() |
|
1657 | 1659 | # Skip three frames in the traceback: the %run one, |
|
1658 | 1660 | # one inside bdb.py, and the command-line typed by the |
|
1659 | 1661 | # user (run by exec in pdb itself). |
|
1660 | 1662 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1661 | 1663 | else: |
|
1662 | 1664 | if runner is None: |
|
1663 | 1665 | runner = self.shell.safe_execfile |
|
1664 | 1666 | if opts.has_key('t'): |
|
1665 | 1667 | # timed execution |
|
1666 | 1668 | try: |
|
1667 | 1669 | nruns = int(opts['N'][0]) |
|
1668 | 1670 | if nruns < 1: |
|
1669 | 1671 | error('Number of runs must be >=1') |
|
1670 | 1672 | return |
|
1671 | 1673 | except (KeyError): |
|
1672 | 1674 | nruns = 1 |
|
1673 | 1675 | if nruns == 1: |
|
1674 | 1676 | t0 = clock2() |
|
1675 | 1677 | runner(filename,prog_ns,prog_ns, |
|
1676 | 1678 | exit_ignore=exit_ignore) |
|
1677 | 1679 | t1 = clock2() |
|
1678 | 1680 | t_usr = t1[0]-t0[0] |
|
1679 | 1681 | t_sys = t1[1]-t0[1] |
|
1680 | 1682 | print "\nIPython CPU timings (estimated):" |
|
1681 | 1683 | print " User : %10s s." % t_usr |
|
1682 | 1684 | print " System: %10s s." % t_sys |
|
1683 | 1685 | else: |
|
1684 | 1686 | runs = range(nruns) |
|
1685 | 1687 | t0 = clock2() |
|
1686 | 1688 | for nr in runs: |
|
1687 | 1689 | runner(filename,prog_ns,prog_ns, |
|
1688 | 1690 | exit_ignore=exit_ignore) |
|
1689 | 1691 | t1 = clock2() |
|
1690 | 1692 | t_usr = t1[0]-t0[0] |
|
1691 | 1693 | t_sys = t1[1]-t0[1] |
|
1692 | 1694 | print "\nIPython CPU timings (estimated):" |
|
1693 | 1695 | print "Total runs performed:",nruns |
|
1694 | 1696 | print " Times : %10s %10s" % ('Total','Per run') |
|
1695 | 1697 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1696 | 1698 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1697 | 1699 | |
|
1698 | 1700 | else: |
|
1699 | 1701 | # regular execution |
|
1700 | 1702 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1701 | 1703 | |
|
1702 | 1704 | if opts.has_key('i'): |
|
1703 | 1705 | self.shell.user_ns['__name__'] = __name__save |
|
1704 | 1706 | else: |
|
1705 | 1707 | # The shell MUST hold a reference to prog_ns so after %run |
|
1706 | 1708 | # exits, the python deletion mechanism doesn't zero it out |
|
1707 | 1709 | # (leaving dangling references). |
|
1708 | 1710 | self.shell.cache_main_mod(prog_ns,filename) |
|
1709 | 1711 | # update IPython interactive namespace |
|
1710 | 1712 | |
|
1711 | 1713 | # Some forms of read errors on the file may mean the |
|
1712 | 1714 | # __name__ key was never set; using pop we don't have to |
|
1713 | 1715 | # worry about a possible KeyError. |
|
1714 | 1716 | prog_ns.pop('__name__', None) |
|
1715 | 1717 | |
|
1716 | 1718 | self.shell.user_ns.update(prog_ns) |
|
1717 | 1719 | finally: |
|
1718 | 1720 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1719 | 1721 | # being a module to becoming a dict missing some key data after |
|
1720 | 1722 | # %run. As best I can see, this is NOT something IPython is doing |
|
1721 | 1723 | # at all, and similar problems have been reported before: |
|
1722 | 1724 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1723 | 1725 | # Since this seems to be done by the interpreter itself, the best |
|
1724 | 1726 | # we can do is to at least restore __builtins__ for the user on |
|
1725 | 1727 | # exit. |
|
1726 | 1728 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1727 | 1729 | |
|
1728 | 1730 | # Ensure key global structures are restored |
|
1729 | 1731 | sys.argv = save_argv |
|
1730 | 1732 | if restore_main: |
|
1731 | 1733 | sys.modules['__main__'] = restore_main |
|
1732 | 1734 | else: |
|
1733 | 1735 | # Remove from sys.modules the reference to main_mod we'd |
|
1734 | 1736 | # added. Otherwise it will trap references to objects |
|
1735 | 1737 | # contained therein. |
|
1736 | 1738 | del sys.modules[main_mod_name] |
|
1737 | 1739 | |
|
1738 | 1740 | self.shell.reloadhist() |
|
1739 | 1741 | |
|
1740 | 1742 | return stats |
|
1741 | 1743 | |
|
1742 | 1744 | def magic_runlog(self, parameter_s =''): |
|
1743 | 1745 | """Run files as logs. |
|
1744 | 1746 | |
|
1745 | 1747 | Usage:\\ |
|
1746 | 1748 | %runlog file1 file2 ... |
|
1747 | 1749 | |
|
1748 | 1750 | Run the named files (treating them as log files) in sequence inside |
|
1749 | 1751 | the interpreter, and return to the prompt. This is much slower than |
|
1750 | 1752 | %run because each line is executed in a try/except block, but it |
|
1751 | 1753 | allows running files with syntax errors in them. |
|
1752 | 1754 | |
|
1753 | 1755 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1754 | 1756 | you can typically use %run even for logs. This shorthand allows you to |
|
1755 | 1757 | force any file to be treated as a log file.""" |
|
1756 | 1758 | |
|
1757 | 1759 | for f in parameter_s.split(): |
|
1758 | 1760 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1759 | 1761 | self.shell.user_ns,islog=1) |
|
1760 | 1762 | |
|
1761 | 1763 | @testdec.skip_doctest |
|
1762 | 1764 | def magic_timeit(self, parameter_s =''): |
|
1763 | 1765 | """Time execution of a Python statement or expression |
|
1764 | 1766 | |
|
1765 | 1767 | Usage:\\ |
|
1766 | 1768 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1767 | 1769 | |
|
1768 | 1770 | Time execution of a Python statement or expression using the timeit |
|
1769 | 1771 | module. |
|
1770 | 1772 | |
|
1771 | 1773 | Options: |
|
1772 | 1774 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1773 | 1775 | is not given, a fitting value is chosen. |
|
1774 | 1776 | |
|
1775 | 1777 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1776 | 1778 | Default: 3 |
|
1777 | 1779 | |
|
1778 | 1780 | -t: use time.time to measure the time, which is the default on Unix. |
|
1779 | 1781 | This function measures wall time. |
|
1780 | 1782 | |
|
1781 | 1783 | -c: use time.clock to measure the time, which is the default on |
|
1782 | 1784 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1783 | 1785 | instead and returns the CPU user time. |
|
1784 | 1786 | |
|
1785 | 1787 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1786 | 1788 | Default: 3 |
|
1787 | 1789 | |
|
1788 | 1790 | |
|
1789 | 1791 | Examples: |
|
1790 | 1792 | |
|
1791 | 1793 | In [1]: %timeit pass |
|
1792 | 1794 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1793 | 1795 | |
|
1794 | 1796 | In [2]: u = None |
|
1795 | 1797 | |
|
1796 | 1798 | In [3]: %timeit u is None |
|
1797 | 1799 | 10000000 loops, best of 3: 184 ns per loop |
|
1798 | 1800 | |
|
1799 | 1801 | In [4]: %timeit -r 4 u == None |
|
1800 | 1802 | 1000000 loops, best of 4: 242 ns per loop |
|
1801 | 1803 | |
|
1802 | 1804 | In [5]: import time |
|
1803 | 1805 | |
|
1804 | 1806 | In [6]: %timeit -n1 time.sleep(2) |
|
1805 | 1807 | 1 loops, best of 3: 2 s per loop |
|
1806 | 1808 | |
|
1807 | 1809 | |
|
1808 | 1810 | The times reported by %timeit will be slightly higher than those |
|
1809 | 1811 | reported by the timeit.py script when variables are accessed. This is |
|
1810 | 1812 | due to the fact that %timeit executes the statement in the namespace |
|
1811 | 1813 | of the shell, compared with timeit.py, which uses a single setup |
|
1812 | 1814 | statement to import function or create variables. Generally, the bias |
|
1813 | 1815 | does not matter as long as results from timeit.py are not mixed with |
|
1814 | 1816 | those from %timeit.""" |
|
1815 | 1817 | |
|
1816 | 1818 | import timeit |
|
1817 | 1819 | import math |
|
1818 | 1820 | |
|
1819 | 1821 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1820 | 1822 | # certain terminals. Until we figure out a robust way of |
|
1821 | 1823 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1822 | 1824 | # microseconds. I am really NOT happy about disabling the proper |
|
1823 | 1825 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1824 | 1826 | # right solution for this is, I'm all ears... |
|
1825 | 1827 | # |
|
1826 | 1828 | # Note: using |
|
1827 | 1829 | # |
|
1828 | 1830 | # s = u'\xb5' |
|
1829 | 1831 | # s.encode(sys.getdefaultencoding()) |
|
1830 | 1832 | # |
|
1831 | 1833 | # is not sufficient, as I've seen terminals where that fails but |
|
1832 | 1834 | # print s |
|
1833 | 1835 | # |
|
1834 | 1836 | # succeeds |
|
1835 | 1837 | # |
|
1836 | 1838 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1837 | 1839 | |
|
1838 | 1840 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1839 | 1841 | units = [u"s", u"ms",u'us',"ns"] |
|
1840 | 1842 | |
|
1841 | 1843 | scaling = [1, 1e3, 1e6, 1e9] |
|
1842 | 1844 | |
|
1843 | 1845 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1844 | 1846 | posix=False) |
|
1845 | 1847 | if stmt == "": |
|
1846 | 1848 | return |
|
1847 | 1849 | timefunc = timeit.default_timer |
|
1848 | 1850 | number = int(getattr(opts, "n", 0)) |
|
1849 | 1851 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1850 | 1852 | precision = int(getattr(opts, "p", 3)) |
|
1851 | 1853 | if hasattr(opts, "t"): |
|
1852 | 1854 | timefunc = time.time |
|
1853 | 1855 | if hasattr(opts, "c"): |
|
1854 | 1856 | timefunc = clock |
|
1855 | 1857 | |
|
1856 | 1858 | timer = timeit.Timer(timer=timefunc) |
|
1857 | 1859 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1858 | 1860 | # but is there a better way to achieve that the code stmt has access |
|
1859 | 1861 | # to the shell namespace? |
|
1860 | 1862 | |
|
1861 | 1863 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1862 | 1864 | 'setup': "pass"} |
|
1863 | 1865 | # Track compilation time so it can be reported if too long |
|
1864 | 1866 | # Minimum time above which compilation time will be reported |
|
1865 | 1867 | tc_min = 0.1 |
|
1866 | 1868 | |
|
1867 | 1869 | t0 = clock() |
|
1868 | 1870 | code = compile(src, "<magic-timeit>", "exec") |
|
1869 | 1871 | tc = clock()-t0 |
|
1870 | 1872 | |
|
1871 | 1873 | ns = {} |
|
1872 | 1874 | exec code in self.shell.user_ns, ns |
|
1873 | 1875 | timer.inner = ns["inner"] |
|
1874 | 1876 | |
|
1875 | 1877 | if number == 0: |
|
1876 | 1878 | # determine number so that 0.2 <= total time < 2.0 |
|
1877 | 1879 | number = 1 |
|
1878 | 1880 | for i in range(1, 10): |
|
1879 | 1881 | if timer.timeit(number) >= 0.2: |
|
1880 | 1882 | break |
|
1881 | 1883 | number *= 10 |
|
1882 | 1884 | |
|
1883 | 1885 | best = min(timer.repeat(repeat, number)) / number |
|
1884 | 1886 | |
|
1885 | 1887 | if best > 0.0: |
|
1886 | 1888 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1887 | 1889 | else: |
|
1888 | 1890 | order = 3 |
|
1889 | 1891 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1890 | 1892 | precision, |
|
1891 | 1893 | best * scaling[order], |
|
1892 | 1894 | units[order]) |
|
1893 | 1895 | if tc > tc_min: |
|
1894 | 1896 | print "Compiler time: %.2f s" % tc |
|
1895 | 1897 | |
|
1896 | 1898 | @testdec.skip_doctest |
|
1897 | 1899 | def magic_time(self,parameter_s = ''): |
|
1898 | 1900 | """Time execution of a Python statement or expression. |
|
1899 | 1901 | |
|
1900 | 1902 | The CPU and wall clock times are printed, and the value of the |
|
1901 | 1903 | expression (if any) is returned. Note that under Win32, system time |
|
1902 | 1904 | is always reported as 0, since it can not be measured. |
|
1903 | 1905 | |
|
1904 | 1906 | This function provides very basic timing functionality. In Python |
|
1905 | 1907 | 2.3, the timeit module offers more control and sophistication, so this |
|
1906 | 1908 | could be rewritten to use it (patches welcome). |
|
1907 | 1909 | |
|
1908 | 1910 | Some examples: |
|
1909 | 1911 | |
|
1910 | 1912 | In [1]: time 2**128 |
|
1911 | 1913 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1912 | 1914 | Wall time: 0.00 |
|
1913 | 1915 | Out[1]: 340282366920938463463374607431768211456L |
|
1914 | 1916 | |
|
1915 | 1917 | In [2]: n = 1000000 |
|
1916 | 1918 | |
|
1917 | 1919 | In [3]: time sum(range(n)) |
|
1918 | 1920 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1919 | 1921 | Wall time: 1.37 |
|
1920 | 1922 | Out[3]: 499999500000L |
|
1921 | 1923 | |
|
1922 | 1924 | In [4]: time print 'hello world' |
|
1923 | 1925 | hello world |
|
1924 | 1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1925 | 1927 | Wall time: 0.00 |
|
1926 | 1928 | |
|
1927 | 1929 | Note that the time needed by Python to compile the given expression |
|
1928 | 1930 | will be reported if it is more than 0.1s. In this example, the |
|
1929 | 1931 | actual exponentiation is done by Python at compilation time, so while |
|
1930 | 1932 | the expression can take a noticeable amount of time to compute, that |
|
1931 | 1933 | time is purely due to the compilation: |
|
1932 | 1934 | |
|
1933 | 1935 | In [5]: time 3**9999; |
|
1934 | 1936 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1935 | 1937 | Wall time: 0.00 s |
|
1936 | 1938 | |
|
1937 | 1939 | In [6]: time 3**999999; |
|
1938 | 1940 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1939 | 1941 | Wall time: 0.00 s |
|
1940 | 1942 | Compiler : 0.78 s |
|
1941 | 1943 | """ |
|
1942 | 1944 | |
|
1943 | 1945 | # fail immediately if the given expression can't be compiled |
|
1944 | 1946 | |
|
1945 | 1947 | expr = self.shell.prefilter(parameter_s,False) |
|
1946 | 1948 | |
|
1947 | 1949 | # Minimum time above which compilation time will be reported |
|
1948 | 1950 | tc_min = 0.1 |
|
1949 | 1951 | |
|
1950 | 1952 | try: |
|
1951 | 1953 | mode = 'eval' |
|
1952 | 1954 | t0 = clock() |
|
1953 | 1955 | code = compile(expr,'<timed eval>',mode) |
|
1954 | 1956 | tc = clock()-t0 |
|
1955 | 1957 | except SyntaxError: |
|
1956 | 1958 | mode = 'exec' |
|
1957 | 1959 | t0 = clock() |
|
1958 | 1960 | code = compile(expr,'<timed exec>',mode) |
|
1959 | 1961 | tc = clock()-t0 |
|
1960 | 1962 | # skew measurement as little as possible |
|
1961 | 1963 | glob = self.shell.user_ns |
|
1962 | 1964 | clk = clock2 |
|
1963 | 1965 | wtime = time.time |
|
1964 | 1966 | # time execution |
|
1965 | 1967 | wall_st = wtime() |
|
1966 | 1968 | if mode=='eval': |
|
1967 | 1969 | st = clk() |
|
1968 | 1970 | out = eval(code,glob) |
|
1969 | 1971 | end = clk() |
|
1970 | 1972 | else: |
|
1971 | 1973 | st = clk() |
|
1972 | 1974 | exec code in glob |
|
1973 | 1975 | end = clk() |
|
1974 | 1976 | out = None |
|
1975 | 1977 | wall_end = wtime() |
|
1976 | 1978 | # Compute actual times and report |
|
1977 | 1979 | wall_time = wall_end-wall_st |
|
1978 | 1980 | cpu_user = end[0]-st[0] |
|
1979 | 1981 | cpu_sys = end[1]-st[1] |
|
1980 | 1982 | cpu_tot = cpu_user+cpu_sys |
|
1981 | 1983 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1982 | 1984 | (cpu_user,cpu_sys,cpu_tot) |
|
1983 | 1985 | print "Wall time: %.2f s" % wall_time |
|
1984 | 1986 | if tc > tc_min: |
|
1985 | 1987 | print "Compiler : %.2f s" % tc |
|
1986 | 1988 | return out |
|
1987 | 1989 | |
|
1988 | 1990 | @testdec.skip_doctest |
|
1989 | 1991 | def magic_macro(self,parameter_s = ''): |
|
1990 | 1992 | """Define a set of input lines as a macro for future re-execution. |
|
1991 | 1993 | |
|
1992 | 1994 | Usage:\\ |
|
1993 | 1995 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1994 | 1996 | |
|
1995 | 1997 | Options: |
|
1996 | 1998 | |
|
1997 | 1999 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1998 | 2000 | so that magics are loaded in their transformed version to valid |
|
1999 | 2001 | Python. If this option is given, the raw input as typed as the |
|
2000 | 2002 | command line is used instead. |
|
2001 | 2003 | |
|
2002 | 2004 | This will define a global variable called `name` which is a string |
|
2003 | 2005 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2004 | 2006 | above) from your input history into a single string. This variable |
|
2005 | 2007 | acts like an automatic function which re-executes those lines as if |
|
2006 | 2008 | you had typed them. You just type 'name' at the prompt and the code |
|
2007 | 2009 | executes. |
|
2008 | 2010 | |
|
2009 | 2011 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
2010 | 2012 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
2011 | 2013 | using the lines numbered 5,6 and 7. |
|
2012 | 2014 | |
|
2013 | 2015 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2014 | 2016 | notation, where N:M means numbers N through M-1. |
|
2015 | 2017 | |
|
2016 | 2018 | For example, if your history contains (%hist prints it): |
|
2017 | 2019 | |
|
2018 | 2020 | 44: x=1 |
|
2019 | 2021 | 45: y=3 |
|
2020 | 2022 | 46: z=x+y |
|
2021 | 2023 | 47: print x |
|
2022 | 2024 | 48: a=5 |
|
2023 | 2025 | 49: print 'x',x,'y',y |
|
2024 | 2026 | |
|
2025 | 2027 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2026 | 2028 | called my_macro with: |
|
2027 | 2029 | |
|
2028 | 2030 | In [55]: %macro my_macro 44-47 49 |
|
2029 | 2031 | |
|
2030 | 2032 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2031 | 2033 | in one pass. |
|
2032 | 2034 | |
|
2033 | 2035 | You don't need to give the line-numbers in order, and any given line |
|
2034 | 2036 | number can appear multiple times. You can assemble macros with any |
|
2035 | 2037 | lines from your input history in any order. |
|
2036 | 2038 | |
|
2037 | 2039 | The macro is a simple object which holds its value in an attribute, |
|
2038 | 2040 | but IPython's display system checks for macros and executes them as |
|
2039 | 2041 | code instead of printing them when you type their name. |
|
2040 | 2042 | |
|
2041 | 2043 | You can view a macro's contents by explicitly printing it with: |
|
2042 | 2044 | |
|
2043 | 2045 | 'print macro_name'. |
|
2044 | 2046 | |
|
2045 | 2047 | For one-off cases which DON'T contain magic function calls in them you |
|
2046 | 2048 | can obtain similar results by explicitly executing slices from your |
|
2047 | 2049 | input history with: |
|
2048 | 2050 | |
|
2049 | 2051 | In [60]: exec In[44:48]+In[49]""" |
|
2050 | 2052 | |
|
2051 | 2053 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2052 | 2054 | if not args: |
|
2053 | 2055 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2054 | 2056 | macs.sort() |
|
2055 | 2057 | return macs |
|
2056 | 2058 | if len(args) == 1: |
|
2057 | 2059 | raise UsageError( |
|
2058 | 2060 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2059 | 2061 | name,ranges = args[0], args[1:] |
|
2060 | 2062 | |
|
2061 | 2063 | #print 'rng',ranges # dbg |
|
2062 | 2064 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2063 | 2065 | macro = Macro(lines) |
|
2064 | 2066 | self.shell.user_ns.update({name:macro}) |
|
2065 | 2067 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2066 | 2068 | print 'Macro contents:' |
|
2067 | 2069 | print macro, |
|
2068 | 2070 | |
|
2069 | 2071 | def magic_save(self,parameter_s = ''): |
|
2070 | 2072 | """Save a set of lines to a given filename. |
|
2071 | 2073 | |
|
2072 | 2074 | Usage:\\ |
|
2073 | 2075 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2074 | 2076 | |
|
2075 | 2077 | Options: |
|
2076 | 2078 | |
|
2077 | 2079 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2078 | 2080 | so that magics are loaded in their transformed version to valid |
|
2079 | 2081 | Python. If this option is given, the raw input as typed as the |
|
2080 | 2082 | command line is used instead. |
|
2081 | 2083 | |
|
2082 | 2084 | This function uses the same syntax as %macro for line extraction, but |
|
2083 | 2085 | instead of creating a macro it saves the resulting string to the |
|
2084 | 2086 | filename you specify. |
|
2085 | 2087 | |
|
2086 | 2088 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2087 | 2089 | it asks for confirmation before overwriting existing files.""" |
|
2088 | 2090 | |
|
2089 | 2091 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2090 | 2092 | fname,ranges = args[0], args[1:] |
|
2091 | 2093 | if not fname.endswith('.py'): |
|
2092 | 2094 | fname += '.py' |
|
2093 | 2095 | if os.path.isfile(fname): |
|
2094 | 2096 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2095 | 2097 | if ans.lower() not in ['y','yes']: |
|
2096 | 2098 | print 'Operation cancelled.' |
|
2097 | 2099 | return |
|
2098 | 2100 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2099 | 2101 | f = file(fname,'w') |
|
2100 | 2102 | f.write(cmds) |
|
2101 | 2103 | f.close() |
|
2102 | 2104 | print 'The following commands were written to file `%s`:' % fname |
|
2103 | 2105 | print cmds |
|
2104 | 2106 | |
|
2105 | 2107 | def _edit_macro(self,mname,macro): |
|
2106 | 2108 | """open an editor with the macro data in a file""" |
|
2107 | 2109 | filename = self.shell.mktempfile(macro.value) |
|
2108 | 2110 | self.shell.hooks.editor(filename) |
|
2109 | 2111 | |
|
2110 | 2112 | # and make a new macro object, to replace the old one |
|
2111 | 2113 | mfile = open(filename) |
|
2112 | 2114 | mvalue = mfile.read() |
|
2113 | 2115 | mfile.close() |
|
2114 | 2116 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2115 | 2117 | |
|
2116 | 2118 | def magic_ed(self,parameter_s=''): |
|
2117 | 2119 | """Alias to %edit.""" |
|
2118 | 2120 | return self.magic_edit(parameter_s) |
|
2119 | 2121 | |
|
2120 | 2122 | @testdec.skip_doctest |
|
2121 | 2123 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2122 | 2124 | """Bring up an editor and execute the resulting code. |
|
2123 | 2125 | |
|
2124 | 2126 | Usage: |
|
2125 | 2127 | %edit [options] [args] |
|
2126 | 2128 | |
|
2127 | 2129 | %edit runs IPython's editor hook. The default version of this hook is |
|
2128 | 2130 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2129 | 2131 | environment variable $EDITOR. If this isn't found, it will default to |
|
2130 | 2132 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2131 | 2133 | docstring for how to change the editor hook. |
|
2132 | 2134 | |
|
2133 | 2135 | You can also set the value of this editor via the command line option |
|
2134 | 2136 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2135 | 2137 | specifically for IPython an editor different from your typical default |
|
2136 | 2138 | (and for Windows users who typically don't set environment variables). |
|
2137 | 2139 | |
|
2138 | 2140 | This command allows you to conveniently edit multi-line code right in |
|
2139 | 2141 | your IPython session. |
|
2140 | 2142 | |
|
2141 | 2143 | If called without arguments, %edit opens up an empty editor with a |
|
2142 | 2144 | temporary file and will execute the contents of this file when you |
|
2143 | 2145 | close it (don't forget to save it!). |
|
2144 | 2146 | |
|
2145 | 2147 | |
|
2146 | 2148 | Options: |
|
2147 | 2149 | |
|
2148 | 2150 | -n <number>: open the editor at a specified line number. By default, |
|
2149 | 2151 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2150 | 2152 | you can configure this by providing your own modified hook if your |
|
2151 | 2153 | favorite editor supports line-number specifications with a different |
|
2152 | 2154 | syntax. |
|
2153 | 2155 | |
|
2154 | 2156 | -p: this will call the editor with the same data as the previous time |
|
2155 | 2157 | it was used, regardless of how long ago (in your current session) it |
|
2156 | 2158 | was. |
|
2157 | 2159 | |
|
2158 | 2160 | -r: use 'raw' input. This option only applies to input taken from the |
|
2159 | 2161 | user's history. By default, the 'processed' history is used, so that |
|
2160 | 2162 | magics are loaded in their transformed version to valid Python. If |
|
2161 | 2163 | this option is given, the raw input as typed as the command line is |
|
2162 | 2164 | used instead. When you exit the editor, it will be executed by |
|
2163 | 2165 | IPython's own processor. |
|
2164 | 2166 | |
|
2165 | 2167 | -x: do not execute the edited code immediately upon exit. This is |
|
2166 | 2168 | mainly useful if you are editing programs which need to be called with |
|
2167 | 2169 | command line arguments, which you can then do using %run. |
|
2168 | 2170 | |
|
2169 | 2171 | |
|
2170 | 2172 | Arguments: |
|
2171 | 2173 | |
|
2172 | 2174 | If arguments are given, the following possibilites exist: |
|
2173 | 2175 | |
|
2174 | 2176 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2175 | 2177 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2176 | 2178 | loaded into the editor. The syntax is the same of the %macro command. |
|
2177 | 2179 | |
|
2178 | 2180 | - If the argument doesn't start with a number, it is evaluated as a |
|
2179 | 2181 | variable and its contents loaded into the editor. You can thus edit |
|
2180 | 2182 | any string which contains python code (including the result of |
|
2181 | 2183 | previous edits). |
|
2182 | 2184 | |
|
2183 | 2185 | - If the argument is the name of an object (other than a string), |
|
2184 | 2186 | IPython will try to locate the file where it was defined and open the |
|
2185 | 2187 | editor at the point where it is defined. You can use `%edit function` |
|
2186 | 2188 | to load an editor exactly at the point where 'function' is defined, |
|
2187 | 2189 | edit it and have the file be executed automatically. |
|
2188 | 2190 | |
|
2189 | 2191 | If the object is a macro (see %macro for details), this opens up your |
|
2190 | 2192 | specified editor with a temporary file containing the macro's data. |
|
2191 | 2193 | Upon exit, the macro is reloaded with the contents of the file. |
|
2192 | 2194 | |
|
2193 | 2195 | Note: opening at an exact line is only supported under Unix, and some |
|
2194 | 2196 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2195 | 2197 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2196 | 2198 | (X)Emacs, vi, jed, pico and joe all do. |
|
2197 | 2199 | |
|
2198 | 2200 | - If the argument is not found as a variable, IPython will look for a |
|
2199 | 2201 | file with that name (adding .py if necessary) and load it into the |
|
2200 | 2202 | editor. It will execute its contents with execfile() when you exit, |
|
2201 | 2203 | loading any code in the file into your interactive namespace. |
|
2202 | 2204 | |
|
2203 | 2205 | After executing your code, %edit will return as output the code you |
|
2204 | 2206 | typed in the editor (except when it was an existing file). This way |
|
2205 | 2207 | you can reload the code in further invocations of %edit as a variable, |
|
2206 | 2208 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2207 | 2209 | the output. |
|
2208 | 2210 | |
|
2209 | 2211 | Note that %edit is also available through the alias %ed. |
|
2210 | 2212 | |
|
2211 | 2213 | This is an example of creating a simple function inside the editor and |
|
2212 | 2214 | then modifying it. First, start up the editor: |
|
2213 | 2215 | |
|
2214 | 2216 | In [1]: ed |
|
2215 | 2217 | Editing... done. Executing edited code... |
|
2216 | 2218 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2217 | 2219 | |
|
2218 | 2220 | We can then call the function foo(): |
|
2219 | 2221 | |
|
2220 | 2222 | In [2]: foo() |
|
2221 | 2223 | foo() was defined in an editing session |
|
2222 | 2224 | |
|
2223 | 2225 | Now we edit foo. IPython automatically loads the editor with the |
|
2224 | 2226 | (temporary) file where foo() was previously defined: |
|
2225 | 2227 | |
|
2226 | 2228 | In [3]: ed foo |
|
2227 | 2229 | Editing... done. Executing edited code... |
|
2228 | 2230 | |
|
2229 | 2231 | And if we call foo() again we get the modified version: |
|
2230 | 2232 | |
|
2231 | 2233 | In [4]: foo() |
|
2232 | 2234 | foo() has now been changed! |
|
2233 | 2235 | |
|
2234 | 2236 | Here is an example of how to edit a code snippet successive |
|
2235 | 2237 | times. First we call the editor: |
|
2236 | 2238 | |
|
2237 | 2239 | In [5]: ed |
|
2238 | 2240 | Editing... done. Executing edited code... |
|
2239 | 2241 | hello |
|
2240 | 2242 | Out[5]: "print 'hello'n" |
|
2241 | 2243 | |
|
2242 | 2244 | Now we call it again with the previous output (stored in _): |
|
2243 | 2245 | |
|
2244 | 2246 | In [6]: ed _ |
|
2245 | 2247 | Editing... done. Executing edited code... |
|
2246 | 2248 | hello world |
|
2247 | 2249 | Out[6]: "print 'hello world'n" |
|
2248 | 2250 | |
|
2249 | 2251 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2250 | 2252 | |
|
2251 | 2253 | In [7]: ed _8 |
|
2252 | 2254 | Editing... done. Executing edited code... |
|
2253 | 2255 | hello again |
|
2254 | 2256 | Out[7]: "print 'hello again'n" |
|
2255 | 2257 | |
|
2256 | 2258 | |
|
2257 | 2259 | Changing the default editor hook: |
|
2258 | 2260 | |
|
2259 | 2261 | If you wish to write your own editor hook, you can put it in a |
|
2260 | 2262 | configuration file which you load at startup time. The default hook |
|
2261 | 2263 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2262 | 2264 | starting example for further modifications. That file also has |
|
2263 | 2265 | general instructions on how to set a new hook for use once you've |
|
2264 | 2266 | defined it.""" |
|
2265 | 2267 | |
|
2266 | 2268 | # FIXME: This function has become a convoluted mess. It needs a |
|
2267 | 2269 | # ground-up rewrite with clean, simple logic. |
|
2268 | 2270 | |
|
2269 | 2271 | def make_filename(arg): |
|
2270 | 2272 | "Make a filename from the given args" |
|
2271 | 2273 | try: |
|
2272 | 2274 | filename = get_py_filename(arg) |
|
2273 | 2275 | except IOError: |
|
2274 | 2276 | if args.endswith('.py'): |
|
2275 | 2277 | filename = arg |
|
2276 | 2278 | else: |
|
2277 | 2279 | filename = None |
|
2278 | 2280 | return filename |
|
2279 | 2281 | |
|
2280 | 2282 | # custom exceptions |
|
2281 | 2283 | class DataIsObject(Exception): pass |
|
2282 | 2284 | |
|
2283 | 2285 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2284 | 2286 | # Set a few locals from the options for convenience: |
|
2285 | 2287 | opts_p = opts.has_key('p') |
|
2286 | 2288 | opts_r = opts.has_key('r') |
|
2287 | 2289 | |
|
2288 | 2290 | # Default line number value |
|
2289 | 2291 | lineno = opts.get('n',None) |
|
2290 | 2292 | |
|
2291 | 2293 | if opts_p: |
|
2292 | 2294 | args = '_%s' % last_call[0] |
|
2293 | 2295 | if not self.shell.user_ns.has_key(args): |
|
2294 | 2296 | args = last_call[1] |
|
2295 | 2297 | |
|
2296 | 2298 | # use last_call to remember the state of the previous call, but don't |
|
2297 | 2299 | # let it be clobbered by successive '-p' calls. |
|
2298 | 2300 | try: |
|
2299 | 2301 | last_call[0] = self.shell.outputcache.prompt_count |
|
2300 | 2302 | if not opts_p: |
|
2301 | 2303 | last_call[1] = parameter_s |
|
2302 | 2304 | except: |
|
2303 | 2305 | pass |
|
2304 | 2306 | |
|
2305 | 2307 | # by default this is done with temp files, except when the given |
|
2306 | 2308 | # arg is a filename |
|
2307 | 2309 | use_temp = 1 |
|
2308 | 2310 | |
|
2309 | 2311 | if re.match(r'\d',args): |
|
2310 | 2312 | # Mode where user specifies ranges of lines, like in %macro. |
|
2311 | 2313 | # This means that you can't edit files whose names begin with |
|
2312 | 2314 | # numbers this way. Tough. |
|
2313 | 2315 | ranges = args.split() |
|
2314 | 2316 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2315 | 2317 | elif args.endswith('.py'): |
|
2316 | 2318 | filename = make_filename(args) |
|
2317 | 2319 | data = '' |
|
2318 | 2320 | use_temp = 0 |
|
2319 | 2321 | elif args: |
|
2320 | 2322 | try: |
|
2321 | 2323 | # Load the parameter given as a variable. If not a string, |
|
2322 | 2324 | # process it as an object instead (below) |
|
2323 | 2325 | |
|
2324 | 2326 | #print '*** args',args,'type',type(args) # dbg |
|
2325 | 2327 | data = eval(args,self.shell.user_ns) |
|
2326 | 2328 | if not type(data) in StringTypes: |
|
2327 | 2329 | raise DataIsObject |
|
2328 | 2330 | |
|
2329 | 2331 | except (NameError,SyntaxError): |
|
2330 | 2332 | # given argument is not a variable, try as a filename |
|
2331 | 2333 | filename = make_filename(args) |
|
2332 | 2334 | if filename is None: |
|
2333 | 2335 | warn("Argument given (%s) can't be found as a variable " |
|
2334 | 2336 | "or as a filename." % args) |
|
2335 | 2337 | return |
|
2336 | 2338 | |
|
2337 | 2339 | data = '' |
|
2338 | 2340 | use_temp = 0 |
|
2339 | 2341 | except DataIsObject: |
|
2340 | 2342 | |
|
2341 | 2343 | # macros have a special edit function |
|
2342 | 2344 | if isinstance(data,Macro): |
|
2343 | 2345 | self._edit_macro(args,data) |
|
2344 | 2346 | return |
|
2345 | 2347 | |
|
2346 | 2348 | # For objects, try to edit the file where they are defined |
|
2347 | 2349 | try: |
|
2348 | 2350 | filename = inspect.getabsfile(data) |
|
2349 | 2351 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2350 | 2352 | # class created by %edit? Try to find source |
|
2351 | 2353 | # by looking for method definitions instead, the |
|
2352 | 2354 | # __module__ in those classes is FakeModule. |
|
2353 | 2355 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2354 | 2356 | for attr in attrs: |
|
2355 | 2357 | if not inspect.ismethod(attr): |
|
2356 | 2358 | continue |
|
2357 | 2359 | filename = inspect.getabsfile(attr) |
|
2358 | 2360 | if filename and 'fakemodule' not in filename.lower(): |
|
2359 | 2361 | # change the attribute to be the edit target instead |
|
2360 | 2362 | data = attr |
|
2361 | 2363 | break |
|
2362 | 2364 | |
|
2363 | 2365 | datafile = 1 |
|
2364 | 2366 | except TypeError: |
|
2365 | 2367 | filename = make_filename(args) |
|
2366 | 2368 | datafile = 1 |
|
2367 | 2369 | warn('Could not find file where `%s` is defined.\n' |
|
2368 | 2370 | 'Opening a file named `%s`' % (args,filename)) |
|
2369 | 2371 | # Now, make sure we can actually read the source (if it was in |
|
2370 | 2372 | # a temp file it's gone by now). |
|
2371 | 2373 | if datafile: |
|
2372 | 2374 | try: |
|
2373 | 2375 | if lineno is None: |
|
2374 | 2376 | lineno = inspect.getsourcelines(data)[1] |
|
2375 | 2377 | except IOError: |
|
2376 | 2378 | filename = make_filename(args) |
|
2377 | 2379 | if filename is None: |
|
2378 | 2380 | warn('The file `%s` where `%s` was defined cannot ' |
|
2379 | 2381 | 'be read.' % (filename,data)) |
|
2380 | 2382 | return |
|
2381 | 2383 | use_temp = 0 |
|
2382 | 2384 | else: |
|
2383 | 2385 | data = '' |
|
2384 | 2386 | |
|
2385 | 2387 | if use_temp: |
|
2386 | 2388 | filename = self.shell.mktempfile(data) |
|
2387 | 2389 | print 'IPython will make a temporary file named:',filename |
|
2388 | 2390 | |
|
2389 | 2391 | # do actual editing here |
|
2390 | 2392 | print 'Editing...', |
|
2391 | 2393 | sys.stdout.flush() |
|
2392 | 2394 | try: |
|
2393 | 2395 | self.shell.hooks.editor(filename,lineno) |
|
2394 | 2396 | except ipapi.TryNext: |
|
2395 | 2397 | warn('Could not open editor') |
|
2396 | 2398 | return |
|
2397 | 2399 | |
|
2398 | 2400 | # XXX TODO: should this be generalized for all string vars? |
|
2399 | 2401 | # For now, this is special-cased to blocks created by cpaste |
|
2400 | 2402 | if args.strip() == 'pasted_block': |
|
2401 | 2403 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2402 | 2404 | |
|
2403 | 2405 | if opts.has_key('x'): # -x prevents actual execution |
|
2404 | 2406 | |
|
2405 | 2407 | else: |
|
2406 | 2408 | print 'done. Executing edited code...' |
|
2407 | 2409 | if opts_r: |
|
2408 | 2410 | self.shell.runlines(file_read(filename)) |
|
2409 | 2411 | else: |
|
2410 | 2412 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2411 | 2413 | self.shell.user_ns) |
|
2412 | 2414 | |
|
2413 | 2415 | |
|
2414 | 2416 | if use_temp: |
|
2415 | 2417 | try: |
|
2416 | 2418 | return open(filename).read() |
|
2417 | 2419 | except IOError,msg: |
|
2418 | 2420 | if msg.filename == filename: |
|
2419 | 2421 | warn('File not found. Did you forget to save?') |
|
2420 | 2422 | return |
|
2421 | 2423 | else: |
|
2422 | 2424 | self.shell.showtraceback() |
|
2423 | 2425 | |
|
2424 | 2426 | def magic_xmode(self,parameter_s = ''): |
|
2425 | 2427 | """Switch modes for the exception handlers. |
|
2426 | 2428 | |
|
2427 | 2429 | Valid modes: Plain, Context and Verbose. |
|
2428 | 2430 | |
|
2429 | 2431 | If called without arguments, acts as a toggle.""" |
|
2430 | 2432 | |
|
2431 | 2433 | def xmode_switch_err(name): |
|
2432 | 2434 | warn('Error changing %s exception modes.\n%s' % |
|
2433 | 2435 | (name,sys.exc_info()[1])) |
|
2434 | 2436 | |
|
2435 | 2437 | shell = self.shell |
|
2436 | 2438 | new_mode = parameter_s.strip().capitalize() |
|
2437 | 2439 | try: |
|
2438 | 2440 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2439 | 2441 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2440 | 2442 | except: |
|
2441 | 2443 | xmode_switch_err('user') |
|
2442 | 2444 | |
|
2443 | 2445 | # threaded shells use a special handler in sys.excepthook |
|
2444 | 2446 | if shell.isthreaded: |
|
2445 | 2447 | try: |
|
2446 | 2448 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2447 | 2449 | except: |
|
2448 | 2450 | xmode_switch_err('threaded') |
|
2449 | 2451 | |
|
2450 | 2452 | def magic_colors(self,parameter_s = ''): |
|
2451 | 2453 | """Switch color scheme for prompts, info system and exception handlers. |
|
2452 | 2454 | |
|
2453 | 2455 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2454 | 2456 | |
|
2455 | 2457 | Color scheme names are not case-sensitive.""" |
|
2456 | 2458 | |
|
2457 | 2459 | def color_switch_err(name): |
|
2458 | 2460 | warn('Error changing %s color schemes.\n%s' % |
|
2459 | 2461 | (name,sys.exc_info()[1])) |
|
2460 | 2462 | |
|
2461 | 2463 | |
|
2462 | 2464 | new_scheme = parameter_s.strip() |
|
2463 | 2465 | if not new_scheme: |
|
2464 | 2466 | raise UsageError( |
|
2465 | 2467 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2466 | 2468 | return |
|
2467 | 2469 | # local shortcut |
|
2468 | 2470 | shell = self.shell |
|
2469 | 2471 | |
|
2470 | 2472 | import IPython.utils.rlineimpl as readline |
|
2471 | 2473 | |
|
2472 | 2474 | if not readline.have_readline and sys.platform == "win32": |
|
2473 | 2475 | msg = """\ |
|
2474 | 2476 | Proper color support under MS Windows requires the pyreadline library. |
|
2475 | 2477 | You can find it at: |
|
2476 | 2478 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2477 | 2479 | Gary's readline needs the ctypes module, from: |
|
2478 | 2480 | http://starship.python.net/crew/theller/ctypes |
|
2479 | 2481 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2480 | 2482 | |
|
2481 | 2483 | Defaulting color scheme to 'NoColor'""" |
|
2482 | 2484 | new_scheme = 'NoColor' |
|
2483 | 2485 | warn(msg) |
|
2484 | 2486 | |
|
2485 | 2487 | # readline option is 0 |
|
2486 | 2488 | if not shell.has_readline: |
|
2487 | 2489 | new_scheme = 'NoColor' |
|
2488 | 2490 | |
|
2489 | 2491 | # Set prompt colors |
|
2490 | 2492 | try: |
|
2491 | 2493 | shell.outputcache.set_colors(new_scheme) |
|
2492 | 2494 | except: |
|
2493 | 2495 | color_switch_err('prompt') |
|
2494 | 2496 | else: |
|
2495 |
shell |
|
|
2497 | shell.colors = \ | |
|
2496 | 2498 | shell.outputcache.color_table.active_scheme_name |
|
2497 | 2499 | # Set exception colors |
|
2498 | 2500 | try: |
|
2499 | 2501 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2500 | 2502 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2501 | 2503 | except: |
|
2502 | 2504 | color_switch_err('exception') |
|
2503 | 2505 | |
|
2504 | 2506 | # threaded shells use a verbose traceback in sys.excepthook |
|
2505 | 2507 | if shell.isthreaded: |
|
2506 | 2508 | try: |
|
2507 | 2509 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2508 | 2510 | except: |
|
2509 | 2511 | color_switch_err('system exception handler') |
|
2510 | 2512 | |
|
2511 | 2513 | # Set info (for 'object?') colors |
|
2512 |
if shell. |
|
|
2514 | if shell.color_info: | |
|
2513 | 2515 | try: |
|
2514 | 2516 | shell.inspector.set_active_scheme(new_scheme) |
|
2515 | 2517 | except: |
|
2516 | 2518 | color_switch_err('object inspector') |
|
2517 | 2519 | else: |
|
2518 | 2520 | shell.inspector.set_active_scheme('NoColor') |
|
2519 | 2521 | |
|
2520 | 2522 | def magic_color_info(self,parameter_s = ''): |
|
2521 | 2523 | """Toggle color_info. |
|
2522 | 2524 | |
|
2523 | 2525 | The color_info configuration parameter controls whether colors are |
|
2524 | 2526 | used for displaying object details (by things like %psource, %pfile or |
|
2525 | 2527 | the '?' system). This function toggles this value with each call. |
|
2526 | 2528 | |
|
2527 | 2529 | Note that unless you have a fairly recent pager (less works better |
|
2528 | 2530 | than more) in your system, using colored object information displays |
|
2529 | 2531 | will not work properly. Test it and see.""" |
|
2530 | 2532 | |
|
2531 |
self.shell |
|
|
2532 |
self.magic_colors(self.shell. |
|
|
2533 | self.shell.color_info = 1 - self.shell.color_info | |
|
2534 | self.magic_colors(self.shell.colors) | |
|
2533 | 2535 | print 'Object introspection functions have now coloring:', |
|
2534 |
print ['OFF','ON'][self.shell. |
|
|
2536 | print ['OFF','ON'][self.shell.color_info] | |
|
2535 | 2537 | |
|
2536 | 2538 | def magic_Pprint(self, parameter_s=''): |
|
2537 | 2539 | """Toggle pretty printing on/off.""" |
|
2538 | 2540 | |
|
2539 |
self.shell |
|
|
2541 | self.shell.pprint = 1 - self.shell.pprint | |
|
2540 | 2542 | print 'Pretty printing has been turned', \ |
|
2541 |
['OFF','ON'][self.shell. |
|
|
2543 | ['OFF','ON'][self.shell.pprint] | |
|
2542 | 2544 | |
|
2543 | 2545 | def magic_exit(self, parameter_s=''): |
|
2544 | 2546 | """Exit IPython, confirming if configured to do so. |
|
2545 | 2547 | |
|
2546 | 2548 | You can configure whether IPython asks for confirmation upon exit by |
|
2547 | 2549 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2548 | 2550 | |
|
2549 | 2551 | self.shell.exit() |
|
2550 | 2552 | |
|
2551 | 2553 | def magic_quit(self, parameter_s=''): |
|
2552 | 2554 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2553 | 2555 | |
|
2554 | 2556 | self.shell.exit() |
|
2555 | 2557 | |
|
2556 | 2558 | def magic_Exit(self, parameter_s=''): |
|
2557 | 2559 | """Exit IPython without confirmation.""" |
|
2558 | 2560 | |
|
2559 | 2561 | self.shell.ask_exit() |
|
2560 | 2562 | |
|
2561 | 2563 | #...................................................................... |
|
2562 | 2564 | # Functions to implement unix shell-type things |
|
2563 | 2565 | |
|
2564 | 2566 | @testdec.skip_doctest |
|
2565 | 2567 | def magic_alias(self, parameter_s = ''): |
|
2566 | 2568 | """Define an alias for a system command. |
|
2567 | 2569 | |
|
2568 | 2570 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2569 | 2571 | |
|
2570 | 2572 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2571 | 2573 | params' (from your underlying operating system). |
|
2572 | 2574 | |
|
2573 | 2575 | Aliases have lower precedence than magic functions and Python normal |
|
2574 | 2576 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2575 | 2577 | alias can not be executed until 'del foo' removes the Python variable. |
|
2576 | 2578 | |
|
2577 | 2579 | You can use the %l specifier in an alias definition to represent the |
|
2578 | 2580 | whole line when the alias is called. For example: |
|
2579 | 2581 | |
|
2580 | 2582 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2581 | 2583 | In [3]: all hello world |
|
2582 | 2584 | Input in brackets: <hello world> |
|
2583 | 2585 | |
|
2584 | 2586 | You can also define aliases with parameters using %s specifiers (one |
|
2585 | 2587 | per parameter): |
|
2586 | 2588 | |
|
2587 | 2589 | In [1]: alias parts echo first %s second %s |
|
2588 | 2590 | In [2]: %parts A B |
|
2589 | 2591 | first A second B |
|
2590 | 2592 | In [3]: %parts A |
|
2591 | 2593 | Incorrect number of arguments: 2 expected. |
|
2592 | 2594 | parts is an alias to: 'echo first %s second %s' |
|
2593 | 2595 | |
|
2594 | 2596 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2595 | 2597 | the other in your aliases. |
|
2596 | 2598 | |
|
2597 | 2599 | Aliases expand Python variables just like system calls using ! or !! |
|
2598 | 2600 | do: all expressions prefixed with '$' get expanded. For details of |
|
2599 | 2601 | the semantic rules, see PEP-215: |
|
2600 | 2602 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2601 | 2603 | IPython for variable expansion. If you want to access a true shell |
|
2602 | 2604 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2603 | 2605 | |
|
2604 | 2606 | In [6]: alias show echo |
|
2605 | 2607 | In [7]: PATH='A Python string' |
|
2606 | 2608 | In [8]: show $PATH |
|
2607 | 2609 | A Python string |
|
2608 | 2610 | In [9]: show $$PATH |
|
2609 | 2611 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2610 | 2612 | |
|
2611 | 2613 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2612 | 2614 | and %rehashx functions, which automatically create aliases for the |
|
2613 | 2615 | contents of your $PATH. |
|
2614 | 2616 | |
|
2615 | 2617 | If called with no parameters, %alias prints the current alias table.""" |
|
2616 | 2618 | |
|
2617 | 2619 | par = parameter_s.strip() |
|
2618 | 2620 | if not par: |
|
2619 | 2621 | stored = self.db.get('stored_aliases', {} ) |
|
2620 | 2622 | atab = self.shell.alias_table |
|
2621 | 2623 | aliases = atab.keys() |
|
2622 | 2624 | aliases.sort() |
|
2623 | 2625 | res = [] |
|
2624 | 2626 | showlast = [] |
|
2625 | 2627 | for alias in aliases: |
|
2626 | 2628 | special = False |
|
2627 | 2629 | try: |
|
2628 | 2630 | tgt = atab[alias][1] |
|
2629 | 2631 | except (TypeError, AttributeError): |
|
2630 | 2632 | # unsubscriptable? probably a callable |
|
2631 | 2633 | tgt = atab[alias] |
|
2632 | 2634 | special = True |
|
2633 | 2635 | # 'interesting' aliases |
|
2634 | 2636 | if (alias in stored or |
|
2635 | 2637 | special or |
|
2636 | 2638 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2637 | 2639 | ' ' in tgt): |
|
2638 | 2640 | showlast.append((alias, tgt)) |
|
2639 | 2641 | else: |
|
2640 | 2642 | res.append((alias, tgt )) |
|
2641 | 2643 | |
|
2642 | 2644 | # show most interesting aliases last |
|
2643 | 2645 | res.extend(showlast) |
|
2644 | 2646 | print "Total number of aliases:",len(aliases) |
|
2645 | 2647 | return res |
|
2646 | 2648 | try: |
|
2647 | 2649 | alias,cmd = par.split(None,1) |
|
2648 | 2650 | except: |
|
2649 | 2651 | print oinspect.getdoc(self.magic_alias) |
|
2650 | 2652 | else: |
|
2651 | 2653 | nargs = cmd.count('%s') |
|
2652 | 2654 | if nargs>0 and cmd.find('%l')>=0: |
|
2653 | 2655 | error('The %s and %l specifiers are mutually exclusive ' |
|
2654 | 2656 | 'in alias definitions.') |
|
2655 | 2657 | else: # all looks OK |
|
2656 | 2658 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2657 | 2659 | self.shell.alias_table_validate(verbose=0) |
|
2658 | 2660 | # end magic_alias |
|
2659 | 2661 | |
|
2660 | 2662 | def magic_unalias(self, parameter_s = ''): |
|
2661 | 2663 | """Remove an alias""" |
|
2662 | 2664 | |
|
2663 | 2665 | aname = parameter_s.strip() |
|
2664 | 2666 | if aname in self.shell.alias_table: |
|
2665 | 2667 | del self.shell.alias_table[aname] |
|
2666 | 2668 | stored = self.db.get('stored_aliases', {} ) |
|
2667 | 2669 | if aname in stored: |
|
2668 | 2670 | print "Removing %stored alias",aname |
|
2669 | 2671 | del stored[aname] |
|
2670 | 2672 | self.db['stored_aliases'] = stored |
|
2671 | 2673 | |
|
2672 | 2674 | |
|
2673 | 2675 | def magic_rehashx(self, parameter_s = ''): |
|
2674 | 2676 | """Update the alias table with all executable files in $PATH. |
|
2675 | 2677 | |
|
2676 | 2678 | This version explicitly checks that every entry in $PATH is a file |
|
2677 | 2679 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2678 | 2680 | |
|
2679 | 2681 | Under Windows, it checks executability as a match agains a |
|
2680 | 2682 | '|'-separated string of extensions, stored in the IPython config |
|
2681 | 2683 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2682 | 2684 | |
|
2683 | 2685 | This function also resets the root module cache of module completer, |
|
2684 | 2686 | used on slow filesystems. |
|
2685 | 2687 | """ |
|
2686 | 2688 | |
|
2687 | 2689 | |
|
2688 | 2690 | ip = self.api |
|
2689 | 2691 | |
|
2690 | 2692 | # for the benefit of module completer in ipy_completers.py |
|
2691 | 2693 | del ip.db['rootmodules'] |
|
2692 | 2694 | |
|
2693 | 2695 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2694 | 2696 | os.environ.get('PATH','').split(os.pathsep)] |
|
2695 | 2697 | path = filter(os.path.isdir,path) |
|
2696 | 2698 | |
|
2697 | 2699 | alias_table = self.shell.alias_table |
|
2698 | 2700 | syscmdlist = [] |
|
2699 | 2701 | if os.name == 'posix': |
|
2700 | 2702 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2701 | 2703 | os.access(fname,os.X_OK) |
|
2702 | 2704 | else: |
|
2703 | 2705 | |
|
2704 | 2706 | try: |
|
2705 | 2707 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2706 | 2708 | except KeyError: |
|
2707 | 2709 | winext = 'exe|com|bat|py' |
|
2708 | 2710 | if 'py' not in winext: |
|
2709 | 2711 | winext += '|py' |
|
2710 | 2712 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2711 | 2713 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2712 | 2714 | savedir = os.getcwd() |
|
2713 | 2715 | try: |
|
2714 | 2716 | # write the whole loop for posix/Windows so we don't have an if in |
|
2715 | 2717 | # the innermost part |
|
2716 | 2718 | if os.name == 'posix': |
|
2717 | 2719 | for pdir in path: |
|
2718 | 2720 | os.chdir(pdir) |
|
2719 | 2721 | for ff in os.listdir(pdir): |
|
2720 | 2722 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2721 | 2723 | # each entry in the alias table must be (N,name), |
|
2722 | 2724 | # where N is the number of positional arguments of the |
|
2723 | 2725 | # alias. |
|
2724 | 2726 | # Dots will be removed from alias names, since ipython |
|
2725 | 2727 | # assumes names with dots to be python code |
|
2726 | 2728 | alias_table[ff.replace('.','')] = (0,ff) |
|
2727 | 2729 | syscmdlist.append(ff) |
|
2728 | 2730 | else: |
|
2729 | 2731 | for pdir in path: |
|
2730 | 2732 | os.chdir(pdir) |
|
2731 | 2733 | for ff in os.listdir(pdir): |
|
2732 | 2734 | base, ext = os.path.splitext(ff) |
|
2733 | 2735 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2734 | 2736 | if ext.lower() == '.exe': |
|
2735 | 2737 | ff = base |
|
2736 | 2738 | alias_table[base.lower().replace('.','')] = (0,ff) |
|
2737 | 2739 | syscmdlist.append(ff) |
|
2738 | 2740 | # Make sure the alias table doesn't contain keywords or builtins |
|
2739 | 2741 | self.shell.alias_table_validate() |
|
2740 | 2742 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2741 | 2743 | # modified aliases since %rehashx will probably clobber them |
|
2742 | 2744 | |
|
2743 | 2745 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2744 | 2746 | # we'll probably get better versions |
|
2745 | 2747 | # self.shell.init_auto_alias() |
|
2746 | 2748 | db = ip.db |
|
2747 | 2749 | db['syscmdlist'] = syscmdlist |
|
2748 | 2750 | finally: |
|
2749 | 2751 | os.chdir(savedir) |
|
2750 | 2752 | |
|
2751 | 2753 | def magic_pwd(self, parameter_s = ''): |
|
2752 | 2754 | """Return the current working directory path.""" |
|
2753 | 2755 | return os.getcwd() |
|
2754 | 2756 | |
|
2755 | 2757 | def magic_cd(self, parameter_s=''): |
|
2756 | 2758 | """Change the current working directory. |
|
2757 | 2759 | |
|
2758 | 2760 | This command automatically maintains an internal list of directories |
|
2759 | 2761 | you visit during your IPython session, in the variable _dh. The |
|
2760 | 2762 | command %dhist shows this history nicely formatted. You can also |
|
2761 | 2763 | do 'cd -<tab>' to see directory history conveniently. |
|
2762 | 2764 | |
|
2763 | 2765 | Usage: |
|
2764 | 2766 | |
|
2765 | 2767 | cd 'dir': changes to directory 'dir'. |
|
2766 | 2768 | |
|
2767 | 2769 | cd -: changes to the last visited directory. |
|
2768 | 2770 | |
|
2769 | 2771 | cd -<n>: changes to the n-th directory in the directory history. |
|
2770 | 2772 | |
|
2771 | 2773 | cd --foo: change to directory that matches 'foo' in history |
|
2772 | 2774 | |
|
2773 | 2775 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2774 | 2776 | (note: cd <bookmark_name> is enough if there is no |
|
2775 | 2777 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2776 | 2778 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2777 | 2779 | |
|
2778 | 2780 | Options: |
|
2779 | 2781 | |
|
2780 | 2782 | -q: quiet. Do not print the working directory after the cd command is |
|
2781 | 2783 | executed. By default IPython's cd command does print this directory, |
|
2782 | 2784 | since the default prompts do not display path information. |
|
2783 | 2785 | |
|
2784 | 2786 | Note that !cd doesn't work for this purpose because the shell where |
|
2785 | 2787 | !command runs is immediately discarded after executing 'command'.""" |
|
2786 | 2788 | |
|
2787 | 2789 | parameter_s = parameter_s.strip() |
|
2788 | 2790 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2789 | 2791 | |
|
2790 | 2792 | oldcwd = os.getcwd() |
|
2791 | 2793 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2792 | 2794 | # jump in directory history by number |
|
2793 | 2795 | if numcd: |
|
2794 | 2796 | nn = int(numcd.group(2)) |
|
2795 | 2797 | try: |
|
2796 | 2798 | ps = self.shell.user_ns['_dh'][nn] |
|
2797 | 2799 | except IndexError: |
|
2798 | 2800 | print 'The requested directory does not exist in history.' |
|
2799 | 2801 | return |
|
2800 | 2802 | else: |
|
2801 | 2803 | opts = {} |
|
2802 | 2804 | elif parameter_s.startswith('--'): |
|
2803 | 2805 | ps = None |
|
2804 | 2806 | fallback = None |
|
2805 | 2807 | pat = parameter_s[2:] |
|
2806 | 2808 | dh = self.shell.user_ns['_dh'] |
|
2807 | 2809 | # first search only by basename (last component) |
|
2808 | 2810 | for ent in reversed(dh): |
|
2809 | 2811 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2810 | 2812 | ps = ent |
|
2811 | 2813 | break |
|
2812 | 2814 | |
|
2813 | 2815 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2814 | 2816 | fallback = ent |
|
2815 | 2817 | |
|
2816 | 2818 | # if we have no last part match, pick the first full path match |
|
2817 | 2819 | if ps is None: |
|
2818 | 2820 | ps = fallback |
|
2819 | 2821 | |
|
2820 | 2822 | if ps is None: |
|
2821 | 2823 | print "No matching entry in directory history" |
|
2822 | 2824 | return |
|
2823 | 2825 | else: |
|
2824 | 2826 | opts = {} |
|
2825 | 2827 | |
|
2826 | 2828 | |
|
2827 | 2829 | else: |
|
2828 | 2830 | #turn all non-space-escaping backslashes to slashes, |
|
2829 | 2831 | # for c:\windows\directory\names\ |
|
2830 | 2832 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2831 | 2833 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2832 | 2834 | # jump to previous |
|
2833 | 2835 | if ps == '-': |
|
2834 | 2836 | try: |
|
2835 | 2837 | ps = self.shell.user_ns['_dh'][-2] |
|
2836 | 2838 | except IndexError: |
|
2837 | 2839 | raise UsageError('%cd -: No previous directory to change to.') |
|
2838 | 2840 | # jump to bookmark if needed |
|
2839 | 2841 | else: |
|
2840 | 2842 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2841 | 2843 | bkms = self.db.get('bookmarks', {}) |
|
2842 | 2844 | |
|
2843 | 2845 | if bkms.has_key(ps): |
|
2844 | 2846 | target = bkms[ps] |
|
2845 | 2847 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2846 | 2848 | ps = target |
|
2847 | 2849 | else: |
|
2848 | 2850 | if opts.has_key('b'): |
|
2849 | 2851 | raise UsageError("Bookmark '%s' not found. " |
|
2850 | 2852 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2851 | 2853 | |
|
2852 | 2854 | # at this point ps should point to the target dir |
|
2853 | 2855 | if ps: |
|
2854 | 2856 | try: |
|
2855 | 2857 | os.chdir(os.path.expanduser(ps)) |
|
2856 |
if self.shell. |
|
|
2857 |
#print 'set term title:',self.shell. |
|
|
2858 | if self.shell.term_title: | |
|
2859 | #print 'set term title:',self.shell.term_title # dbg | |
|
2858 | 2860 | platutils.set_term_title('IPy ' + abbrev_cwd()) |
|
2859 | 2861 | except OSError: |
|
2860 | 2862 | print sys.exc_info()[1] |
|
2861 | 2863 | else: |
|
2862 | 2864 | cwd = os.getcwd() |
|
2863 | 2865 | dhist = self.shell.user_ns['_dh'] |
|
2864 | 2866 | if oldcwd != cwd: |
|
2865 | 2867 | dhist.append(cwd) |
|
2866 | 2868 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2867 | 2869 | |
|
2868 | 2870 | else: |
|
2869 | 2871 | os.chdir(self.shell.home_dir) |
|
2870 |
if self.shell. |
|
|
2872 | if self.shell.term_title: | |
|
2871 | 2873 | platutils.set_term_title("IPy ~") |
|
2872 | 2874 | cwd = os.getcwd() |
|
2873 | 2875 | dhist = self.shell.user_ns['_dh'] |
|
2874 | 2876 | |
|
2875 | 2877 | if oldcwd != cwd: |
|
2876 | 2878 | dhist.append(cwd) |
|
2877 | 2879 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2878 | 2880 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2879 | 2881 | print self.shell.user_ns['_dh'][-1] |
|
2880 | 2882 | |
|
2881 | 2883 | |
|
2882 | 2884 | def magic_env(self, parameter_s=''): |
|
2883 | 2885 | """List environment variables.""" |
|
2884 | 2886 | |
|
2885 | 2887 | return os.environ.data |
|
2886 | 2888 | |
|
2887 | 2889 | def magic_pushd(self, parameter_s=''): |
|
2888 | 2890 | """Place the current dir on stack and change directory. |
|
2889 | 2891 | |
|
2890 | 2892 | Usage:\\ |
|
2891 | 2893 | %pushd ['dirname'] |
|
2892 | 2894 | """ |
|
2893 | 2895 | |
|
2894 | 2896 | dir_s = self.shell.dir_stack |
|
2895 | 2897 | tgt = os.path.expanduser(parameter_s) |
|
2896 | 2898 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2897 | 2899 | if tgt: |
|
2898 | 2900 | self.magic_cd(parameter_s) |
|
2899 | 2901 | dir_s.insert(0,cwd) |
|
2900 | 2902 | return self.magic_dirs() |
|
2901 | 2903 | |
|
2902 | 2904 | def magic_popd(self, parameter_s=''): |
|
2903 | 2905 | """Change to directory popped off the top of the stack. |
|
2904 | 2906 | """ |
|
2905 | 2907 | if not self.shell.dir_stack: |
|
2906 | 2908 | raise UsageError("%popd on empty stack") |
|
2907 | 2909 | top = self.shell.dir_stack.pop(0) |
|
2908 | 2910 | self.magic_cd(top) |
|
2909 | 2911 | print "popd ->",top |
|
2910 | 2912 | |
|
2911 | 2913 | def magic_dirs(self, parameter_s=''): |
|
2912 | 2914 | """Return the current directory stack.""" |
|
2913 | 2915 | |
|
2914 | 2916 | return self.shell.dir_stack |
|
2915 | 2917 | |
|
2916 | 2918 | def magic_dhist(self, parameter_s=''): |
|
2917 | 2919 | """Print your history of visited directories. |
|
2918 | 2920 | |
|
2919 | 2921 | %dhist -> print full history\\ |
|
2920 | 2922 | %dhist n -> print last n entries only\\ |
|
2921 | 2923 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2922 | 2924 | |
|
2923 | 2925 | This history is automatically maintained by the %cd command, and |
|
2924 | 2926 | always available as the global list variable _dh. You can use %cd -<n> |
|
2925 | 2927 | to go to directory number <n>. |
|
2926 | 2928 | |
|
2927 | 2929 | Note that most of time, you should view directory history by entering |
|
2928 | 2930 | cd -<TAB>. |
|
2929 | 2931 | |
|
2930 | 2932 | """ |
|
2931 | 2933 | |
|
2932 | 2934 | dh = self.shell.user_ns['_dh'] |
|
2933 | 2935 | if parameter_s: |
|
2934 | 2936 | try: |
|
2935 | 2937 | args = map(int,parameter_s.split()) |
|
2936 | 2938 | except: |
|
2937 | 2939 | self.arg_err(Magic.magic_dhist) |
|
2938 | 2940 | return |
|
2939 | 2941 | if len(args) == 1: |
|
2940 | 2942 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2941 | 2943 | elif len(args) == 2: |
|
2942 | 2944 | ini,fin = args |
|
2943 | 2945 | else: |
|
2944 | 2946 | self.arg_err(Magic.magic_dhist) |
|
2945 | 2947 | return |
|
2946 | 2948 | else: |
|
2947 | 2949 | ini,fin = 0,len(dh) |
|
2948 | 2950 | nlprint(dh, |
|
2949 | 2951 | header = 'Directory history (kept in _dh)', |
|
2950 | 2952 | start=ini,stop=fin) |
|
2951 | 2953 | |
|
2952 | 2954 | @testdec.skip_doctest |
|
2953 | 2955 | def magic_sc(self, parameter_s=''): |
|
2954 | 2956 | """Shell capture - execute a shell command and capture its output. |
|
2955 | 2957 | |
|
2956 | 2958 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2957 | 2959 | |
|
2958 | 2960 | You should use the form 'var = !command' instead. Example: |
|
2959 | 2961 | |
|
2960 | 2962 | "%sc -l myfiles = ls ~" should now be written as |
|
2961 | 2963 | |
|
2962 | 2964 | "myfiles = !ls ~" |
|
2963 | 2965 | |
|
2964 | 2966 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2965 | 2967 | below. |
|
2966 | 2968 | |
|
2967 | 2969 | -- |
|
2968 | 2970 | %sc [options] varname=command |
|
2969 | 2971 | |
|
2970 | 2972 | IPython will run the given command using commands.getoutput(), and |
|
2971 | 2973 | will then update the user's interactive namespace with a variable |
|
2972 | 2974 | called varname, containing the value of the call. Your command can |
|
2973 | 2975 | contain shell wildcards, pipes, etc. |
|
2974 | 2976 | |
|
2975 | 2977 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2976 | 2978 | supply must follow Python's standard conventions for valid names. |
|
2977 | 2979 | |
|
2978 | 2980 | (A special format without variable name exists for internal use) |
|
2979 | 2981 | |
|
2980 | 2982 | Options: |
|
2981 | 2983 | |
|
2982 | 2984 | -l: list output. Split the output on newlines into a list before |
|
2983 | 2985 | assigning it to the given variable. By default the output is stored |
|
2984 | 2986 | as a single string. |
|
2985 | 2987 | |
|
2986 | 2988 | -v: verbose. Print the contents of the variable. |
|
2987 | 2989 | |
|
2988 | 2990 | In most cases you should not need to split as a list, because the |
|
2989 | 2991 | returned value is a special type of string which can automatically |
|
2990 | 2992 | provide its contents either as a list (split on newlines) or as a |
|
2991 | 2993 | space-separated string. These are convenient, respectively, either |
|
2992 | 2994 | for sequential processing or to be passed to a shell command. |
|
2993 | 2995 | |
|
2994 | 2996 | For example: |
|
2995 | 2997 | |
|
2996 | 2998 | # all-random |
|
2997 | 2999 | |
|
2998 | 3000 | # Capture into variable a |
|
2999 | 3001 | In [1]: sc a=ls *py |
|
3000 | 3002 | |
|
3001 | 3003 | # a is a string with embedded newlines |
|
3002 | 3004 | In [2]: a |
|
3003 | 3005 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3004 | 3006 | |
|
3005 | 3007 | # which can be seen as a list: |
|
3006 | 3008 | In [3]: a.l |
|
3007 | 3009 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3008 | 3010 | |
|
3009 | 3011 | # or as a whitespace-separated string: |
|
3010 | 3012 | In [4]: a.s |
|
3011 | 3013 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3012 | 3014 | |
|
3013 | 3015 | # a.s is useful to pass as a single command line: |
|
3014 | 3016 | In [5]: !wc -l $a.s |
|
3015 | 3017 | 146 setup.py |
|
3016 | 3018 | 130 win32_manual_post_install.py |
|
3017 | 3019 | 276 total |
|
3018 | 3020 | |
|
3019 | 3021 | # while the list form is useful to loop over: |
|
3020 | 3022 | In [6]: for f in a.l: |
|
3021 | 3023 | ...: !wc -l $f |
|
3022 | 3024 | ...: |
|
3023 | 3025 | 146 setup.py |
|
3024 | 3026 | 130 win32_manual_post_install.py |
|
3025 | 3027 | |
|
3026 | 3028 | Similiarly, the lists returned by the -l option are also special, in |
|
3027 | 3029 | the sense that you can equally invoke the .s attribute on them to |
|
3028 | 3030 | automatically get a whitespace-separated string from their contents: |
|
3029 | 3031 | |
|
3030 | 3032 | In [7]: sc -l b=ls *py |
|
3031 | 3033 | |
|
3032 | 3034 | In [8]: b |
|
3033 | 3035 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3034 | 3036 | |
|
3035 | 3037 | In [9]: b.s |
|
3036 | 3038 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3037 | 3039 | |
|
3038 | 3040 | In summary, both the lists and strings used for ouptut capture have |
|
3039 | 3041 | the following special attributes: |
|
3040 | 3042 | |
|
3041 | 3043 | .l (or .list) : value as list. |
|
3042 | 3044 | .n (or .nlstr): value as newline-separated string. |
|
3043 | 3045 | .s (or .spstr): value as space-separated string. |
|
3044 | 3046 | """ |
|
3045 | 3047 | |
|
3046 | 3048 | opts,args = self.parse_options(parameter_s,'lv') |
|
3047 | 3049 | # Try to get a variable name and command to run |
|
3048 | 3050 | try: |
|
3049 | 3051 | # the variable name must be obtained from the parse_options |
|
3050 | 3052 | # output, which uses shlex.split to strip options out. |
|
3051 | 3053 | var,_ = args.split('=',1) |
|
3052 | 3054 | var = var.strip() |
|
3053 | 3055 | # But the the command has to be extracted from the original input |
|
3054 | 3056 | # parameter_s, not on what parse_options returns, to avoid the |
|
3055 | 3057 | # quote stripping which shlex.split performs on it. |
|
3056 | 3058 | _,cmd = parameter_s.split('=',1) |
|
3057 | 3059 | except ValueError: |
|
3058 | 3060 | var,cmd = '','' |
|
3059 | 3061 | # If all looks ok, proceed |
|
3060 | 3062 | out,err = self.shell.getoutputerror(cmd) |
|
3061 | 3063 | if err: |
|
3062 | 3064 | print >> Term.cerr,err |
|
3063 | 3065 | if opts.has_key('l'): |
|
3064 | 3066 | out = SList(out.split('\n')) |
|
3065 | 3067 | else: |
|
3066 | 3068 | out = LSString(out) |
|
3067 | 3069 | if opts.has_key('v'): |
|
3068 | 3070 | print '%s ==\n%s' % (var,pformat(out)) |
|
3069 | 3071 | if var: |
|
3070 | 3072 | self.shell.user_ns.update({var:out}) |
|
3071 | 3073 | else: |
|
3072 | 3074 | return out |
|
3073 | 3075 | |
|
3074 | 3076 | def magic_sx(self, parameter_s=''): |
|
3075 | 3077 | """Shell execute - run a shell command and capture its output. |
|
3076 | 3078 | |
|
3077 | 3079 | %sx command |
|
3078 | 3080 | |
|
3079 | 3081 | IPython will run the given command using commands.getoutput(), and |
|
3080 | 3082 | return the result formatted as a list (split on '\\n'). Since the |
|
3081 | 3083 | output is _returned_, it will be stored in ipython's regular output |
|
3082 | 3084 | cache Out[N] and in the '_N' automatic variables. |
|
3083 | 3085 | |
|
3084 | 3086 | Notes: |
|
3085 | 3087 | |
|
3086 | 3088 | 1) If an input line begins with '!!', then %sx is automatically |
|
3087 | 3089 | invoked. That is, while: |
|
3088 | 3090 | !ls |
|
3089 | 3091 | causes ipython to simply issue system('ls'), typing |
|
3090 | 3092 | !!ls |
|
3091 | 3093 | is a shorthand equivalent to: |
|
3092 | 3094 | %sx ls |
|
3093 | 3095 | |
|
3094 | 3096 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3095 | 3097 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3096 | 3098 | to process line-oriented shell output via further python commands. |
|
3097 | 3099 | %sc is meant to provide much finer control, but requires more |
|
3098 | 3100 | typing. |
|
3099 | 3101 | |
|
3100 | 3102 | 3) Just like %sc -l, this is a list with special attributes: |
|
3101 | 3103 | |
|
3102 | 3104 | .l (or .list) : value as list. |
|
3103 | 3105 | .n (or .nlstr): value as newline-separated string. |
|
3104 | 3106 | .s (or .spstr): value as whitespace-separated string. |
|
3105 | 3107 | |
|
3106 | 3108 | This is very useful when trying to use such lists as arguments to |
|
3107 | 3109 | system commands.""" |
|
3108 | 3110 | |
|
3109 | 3111 | if parameter_s: |
|
3110 | 3112 | out,err = self.shell.getoutputerror(parameter_s) |
|
3111 | 3113 | if err: |
|
3112 | 3114 | print >> Term.cerr,err |
|
3113 | 3115 | return SList(out.split('\n')) |
|
3114 | 3116 | |
|
3115 | 3117 | def magic_bg(self, parameter_s=''): |
|
3116 | 3118 | """Run a job in the background, in a separate thread. |
|
3117 | 3119 | |
|
3118 | 3120 | For example, |
|
3119 | 3121 | |
|
3120 | 3122 | %bg myfunc(x,y,z=1) |
|
3121 | 3123 | |
|
3122 | 3124 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3123 | 3125 | execution starts, a message will be printed indicating the job |
|
3124 | 3126 | number. If your job number is 5, you can use |
|
3125 | 3127 | |
|
3126 | 3128 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3127 | 3129 | |
|
3128 | 3130 | to assign this result to variable 'myvar'. |
|
3129 | 3131 | |
|
3130 | 3132 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3131 | 3133 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3132 | 3134 | its attributes. All attributes not starting with an underscore are |
|
3133 | 3135 | meant for public use. |
|
3134 | 3136 | |
|
3135 | 3137 | In particular, look at the jobs.new() method, which is used to create |
|
3136 | 3138 | new jobs. This magic %bg function is just a convenience wrapper |
|
3137 | 3139 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3138 | 3140 | new job with an explicit function object and arguments, you must call |
|
3139 | 3141 | jobs.new() directly. |
|
3140 | 3142 | |
|
3141 | 3143 | The jobs.new docstring also describes in detail several important |
|
3142 | 3144 | caveats associated with a thread-based model for background job |
|
3143 | 3145 | execution. Type jobs.new? for details. |
|
3144 | 3146 | |
|
3145 | 3147 | You can check the status of all jobs with jobs.status(). |
|
3146 | 3148 | |
|
3147 | 3149 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3148 | 3150 | If you ever declare a variable named 'jobs', you will shadow this |
|
3149 | 3151 | name. You can either delete your global jobs variable to regain |
|
3150 | 3152 | access to the job manager, or make a new name and assign it manually |
|
3151 | 3153 | to the manager (stored in IPython's namespace). For example, to |
|
3152 | 3154 | assign the job manager to the Jobs name, use: |
|
3153 | 3155 | |
|
3154 | 3156 | Jobs = __builtins__.jobs""" |
|
3155 | 3157 | |
|
3156 | 3158 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3157 | 3159 | |
|
3158 | 3160 | def magic_r(self, parameter_s=''): |
|
3159 | 3161 | """Repeat previous input. |
|
3160 | 3162 | |
|
3161 | 3163 | Note: Consider using the more powerfull %rep instead! |
|
3162 | 3164 | |
|
3163 | 3165 | If given an argument, repeats the previous command which starts with |
|
3164 | 3166 | the same string, otherwise it just repeats the previous input. |
|
3165 | 3167 | |
|
3166 | 3168 | Shell escaped commands (with ! as first character) are not recognized |
|
3167 | 3169 | by this system, only pure python code and magic commands. |
|
3168 | 3170 | """ |
|
3169 | 3171 | |
|
3170 | 3172 | start = parameter_s.strip() |
|
3171 | 3173 | esc_magic = self.shell.ESC_MAGIC |
|
3172 | 3174 | # Identify magic commands even if automagic is on (which means |
|
3173 | 3175 | # the in-memory version is different from that typed by the user). |
|
3174 |
if self.shell. |
|
|
3176 | if self.shell.automagic: | |
|
3175 | 3177 | start_magic = esc_magic+start |
|
3176 | 3178 | else: |
|
3177 | 3179 | start_magic = start |
|
3178 | 3180 | # Look through the input history in reverse |
|
3179 | 3181 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3180 | 3182 | input = self.shell.input_hist[n] |
|
3181 | 3183 | # skip plain 'r' lines so we don't recurse to infinity |
|
3182 | 3184 | if input != '_ip.magic("r")\n' and \ |
|
3183 | 3185 | (input.startswith(start) or input.startswith(start_magic)): |
|
3184 | 3186 | #print 'match',`input` # dbg |
|
3185 | 3187 | print 'Executing:',input, |
|
3186 | 3188 | self.shell.runlines(input) |
|
3187 | 3189 | return |
|
3188 | 3190 | print 'No previous input matching `%s` found.' % start |
|
3189 | 3191 | |
|
3190 | 3192 | |
|
3191 | 3193 | def magic_bookmark(self, parameter_s=''): |
|
3192 | 3194 | """Manage IPython's bookmark system. |
|
3193 | 3195 | |
|
3194 | 3196 | %bookmark <name> - set bookmark to current dir |
|
3195 | 3197 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3196 | 3198 | %bookmark -l - list all bookmarks |
|
3197 | 3199 | %bookmark -d <name> - remove bookmark |
|
3198 | 3200 | %bookmark -r - remove all bookmarks |
|
3199 | 3201 | |
|
3200 | 3202 | You can later on access a bookmarked folder with: |
|
3201 | 3203 | %cd -b <name> |
|
3202 | 3204 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3203 | 3205 | there is such a bookmark defined. |
|
3204 | 3206 | |
|
3205 | 3207 | Your bookmarks persist through IPython sessions, but they are |
|
3206 | 3208 | associated with each profile.""" |
|
3207 | 3209 | |
|
3208 | 3210 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3209 | 3211 | if len(args) > 2: |
|
3210 | 3212 | raise UsageError("%bookmark: too many arguments") |
|
3211 | 3213 | |
|
3212 | 3214 | bkms = self.db.get('bookmarks',{}) |
|
3213 | 3215 | |
|
3214 | 3216 | if opts.has_key('d'): |
|
3215 | 3217 | try: |
|
3216 | 3218 | todel = args[0] |
|
3217 | 3219 | except IndexError: |
|
3218 | 3220 | raise UsageError( |
|
3219 | 3221 | "%bookmark -d: must provide a bookmark to delete") |
|
3220 | 3222 | else: |
|
3221 | 3223 | try: |
|
3222 | 3224 | del bkms[todel] |
|
3223 | 3225 | except KeyError: |
|
3224 | 3226 | raise UsageError( |
|
3225 | 3227 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3226 | 3228 | |
|
3227 | 3229 | elif opts.has_key('r'): |
|
3228 | 3230 | bkms = {} |
|
3229 | 3231 | elif opts.has_key('l'): |
|
3230 | 3232 | bks = bkms.keys() |
|
3231 | 3233 | bks.sort() |
|
3232 | 3234 | if bks: |
|
3233 | 3235 | size = max(map(len,bks)) |
|
3234 | 3236 | else: |
|
3235 | 3237 | size = 0 |
|
3236 | 3238 | fmt = '%-'+str(size)+'s -> %s' |
|
3237 | 3239 | print 'Current bookmarks:' |
|
3238 | 3240 | for bk in bks: |
|
3239 | 3241 | print fmt % (bk,bkms[bk]) |
|
3240 | 3242 | else: |
|
3241 | 3243 | if not args: |
|
3242 | 3244 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3243 | 3245 | elif len(args)==1: |
|
3244 | 3246 | bkms[args[0]] = os.getcwd() |
|
3245 | 3247 | elif len(args)==2: |
|
3246 | 3248 | bkms[args[0]] = args[1] |
|
3247 | 3249 | self.db['bookmarks'] = bkms |
|
3248 | 3250 | |
|
3249 | 3251 | def magic_pycat(self, parameter_s=''): |
|
3250 | 3252 | """Show a syntax-highlighted file through a pager. |
|
3251 | 3253 | |
|
3252 | 3254 | This magic is similar to the cat utility, but it will assume the file |
|
3253 | 3255 | to be Python source and will show it with syntax highlighting. """ |
|
3254 | 3256 | |
|
3255 | 3257 | try: |
|
3256 | 3258 | filename = get_py_filename(parameter_s) |
|
3257 | 3259 | cont = file_read(filename) |
|
3258 | 3260 | except IOError: |
|
3259 | 3261 | try: |
|
3260 | 3262 | cont = eval(parameter_s,self.user_ns) |
|
3261 | 3263 | except NameError: |
|
3262 | 3264 | cont = None |
|
3263 | 3265 | if cont is None: |
|
3264 | 3266 | print "Error: no such file or variable" |
|
3265 | 3267 | return |
|
3266 | 3268 | |
|
3267 | 3269 | page(self.shell.pycolorize(cont), |
|
3268 |
screen_lines=self.shell. |
|
|
3270 | screen_lines=self.shell.screen_length) | |
|
3269 | 3271 | |
|
3270 | 3272 | def _rerun_pasted(self): |
|
3271 | 3273 | """ Rerun a previously pasted command. |
|
3272 | 3274 | """ |
|
3273 | 3275 | b = self.user_ns.get('pasted_block', None) |
|
3274 | 3276 | if b is None: |
|
3275 | 3277 | raise UsageError('No previous pasted block available') |
|
3276 | 3278 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3277 | 3279 | exec b in self.user_ns |
|
3278 | 3280 | |
|
3279 | 3281 | def _get_pasted_lines(self, sentinel): |
|
3280 | 3282 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3281 | 3283 | """ |
|
3282 | 3284 | from IPython.core import iplib |
|
3283 | 3285 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3284 | 3286 | while True: |
|
3285 | 3287 | l = iplib.raw_input_original(':') |
|
3286 | 3288 | if l == sentinel: |
|
3287 | 3289 | return |
|
3288 | 3290 | else: |
|
3289 | 3291 | yield l |
|
3290 | 3292 | |
|
3291 | 3293 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3292 | 3294 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3293 | 3295 | code. |
|
3294 | 3296 | """ |
|
3295 | 3297 | # Regular expressions that declare text we strip from the input: |
|
3296 | 3298 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3297 | 3299 | r'^\s*(\s?>)+', # Python input prompt |
|
3298 | 3300 | r'^\s*\.{3,}', # Continuation prompts |
|
3299 | 3301 | r'^\++', |
|
3300 | 3302 | ] |
|
3301 | 3303 | |
|
3302 | 3304 | strip_from_start = map(re.compile,strip_re) |
|
3303 | 3305 | |
|
3304 | 3306 | lines = [] |
|
3305 | 3307 | for l in raw_lines: |
|
3306 | 3308 | for pat in strip_from_start: |
|
3307 | 3309 | l = pat.sub('',l) |
|
3308 | 3310 | lines.append(l) |
|
3309 | 3311 | |
|
3310 | 3312 | block = "\n".join(lines) + '\n' |
|
3311 | 3313 | #print "block:\n",block |
|
3312 | 3314 | return block |
|
3313 | 3315 | |
|
3314 | 3316 | def _execute_block(self, block, par): |
|
3315 | 3317 | """ Execute a block, or store it in a variable, per the user's request. |
|
3316 | 3318 | """ |
|
3317 | 3319 | if not par: |
|
3318 | 3320 | b = textwrap.dedent(block) |
|
3319 | 3321 | self.user_ns['pasted_block'] = b |
|
3320 | 3322 | exec b in self.user_ns |
|
3321 | 3323 | else: |
|
3322 | 3324 | self.user_ns[par] = SList(block.splitlines()) |
|
3323 | 3325 | print "Block assigned to '%s'" % par |
|
3324 | 3326 | |
|
3325 | 3327 | def magic_cpaste(self, parameter_s=''): |
|
3326 | 3328 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3327 | 3329 | |
|
3328 | 3330 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3329 | 3331 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3330 | 3332 | is the new sentinel for this operation) |
|
3331 | 3333 | |
|
3332 | 3334 | The block is dedented prior to execution to enable execution of method |
|
3333 | 3335 | definitions. '>' and '+' characters at the beginning of a line are |
|
3334 | 3336 | ignored, to allow pasting directly from e-mails, diff files and |
|
3335 | 3337 | doctests (the '...' continuation prompt is also stripped). The |
|
3336 | 3338 | executed block is also assigned to variable named 'pasted_block' for |
|
3337 | 3339 | later editing with '%edit pasted_block'. |
|
3338 | 3340 | |
|
3339 | 3341 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3340 | 3342 | This assigns the pasted block to variable 'foo' as string, without |
|
3341 | 3343 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3342 | 3344 | |
|
3343 | 3345 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3344 | 3346 | |
|
3345 | 3347 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3346 | 3348 | Just press enter and type -- (and press enter again) and the block |
|
3347 | 3349 | will be what was just pasted. |
|
3348 | 3350 | |
|
3349 | 3351 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3350 | 3352 | |
|
3351 | 3353 | See also |
|
3352 | 3354 | -------- |
|
3353 | 3355 | paste: automatically pull code from clipboard. |
|
3354 | 3356 | """ |
|
3355 | 3357 | |
|
3356 | 3358 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3357 | 3359 | par = args.strip() |
|
3358 | 3360 | if opts.has_key('r'): |
|
3359 | 3361 | self._rerun_pasted() |
|
3360 | 3362 | return |
|
3361 | 3363 | |
|
3362 | 3364 | sentinel = opts.get('s','--') |
|
3363 | 3365 | |
|
3364 | 3366 | block = self._strip_pasted_lines_for_code( |
|
3365 | 3367 | self._get_pasted_lines(sentinel)) |
|
3366 | 3368 | |
|
3367 | 3369 | self._execute_block(block, par) |
|
3368 | 3370 | |
|
3369 | 3371 | def magic_paste(self, parameter_s=''): |
|
3370 | 3372 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3371 | 3373 | |
|
3372 | 3374 | The text is pulled directly from the clipboard without user |
|
3373 | 3375 | intervention and printed back on the screen before execution (unless |
|
3374 | 3376 | the -q flag is given to force quiet mode). |
|
3375 | 3377 | |
|
3376 | 3378 | The block is dedented prior to execution to enable execution of method |
|
3377 | 3379 | definitions. '>' and '+' characters at the beginning of a line are |
|
3378 | 3380 | ignored, to allow pasting directly from e-mails, diff files and |
|
3379 | 3381 | doctests (the '...' continuation prompt is also stripped). The |
|
3380 | 3382 | executed block is also assigned to variable named 'pasted_block' for |
|
3381 | 3383 | later editing with '%edit pasted_block'. |
|
3382 | 3384 | |
|
3383 | 3385 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3384 | 3386 | This assigns the pasted block to variable 'foo' as string, without |
|
3385 | 3387 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3386 | 3388 | |
|
3387 | 3389 | Options |
|
3388 | 3390 | ------- |
|
3389 | 3391 | |
|
3390 | 3392 | -r: re-executes the block previously entered by cpaste. |
|
3391 | 3393 | |
|
3392 | 3394 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3393 | 3395 | |
|
3394 | 3396 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3395 | 3397 | |
|
3396 | 3398 | See also |
|
3397 | 3399 | -------- |
|
3398 | 3400 | cpaste: manually paste code into terminal until you mark its end. |
|
3399 | 3401 | """ |
|
3400 | 3402 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3401 | 3403 | par = args.strip() |
|
3402 | 3404 | if opts.has_key('r'): |
|
3403 | 3405 | self._rerun_pasted() |
|
3404 | 3406 | return |
|
3405 | 3407 | |
|
3406 | 3408 | text = self.shell.hooks.clipboard_get() |
|
3407 | 3409 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3408 | 3410 | |
|
3409 | 3411 | # By default, echo back to terminal unless quiet mode is requested |
|
3410 | 3412 | if not opts.has_key('q'): |
|
3411 | 3413 | write = self.shell.write |
|
3412 | 3414 | write(block) |
|
3413 | 3415 | if not block.endswith('\n'): |
|
3414 | 3416 | write('\n') |
|
3415 | 3417 | write("## -- End pasted text --\n") |
|
3416 | 3418 | |
|
3417 | 3419 | self._execute_block(block, par) |
|
3418 | 3420 | |
|
3419 | 3421 | def magic_quickref(self,arg): |
|
3420 | 3422 | """ Show a quick reference sheet """ |
|
3421 | 3423 | import IPython.core.usage |
|
3422 | 3424 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3423 | 3425 | |
|
3424 | 3426 | page(qr) |
|
3425 | 3427 | |
|
3426 | 3428 | def magic_upgrade(self,arg): |
|
3427 | 3429 | """ Upgrade your IPython installation |
|
3428 | 3430 | |
|
3429 | 3431 | This will copy the config files that don't yet exist in your |
|
3430 | 3432 | ipython dir from the system config dir. Use this after upgrading |
|
3431 | 3433 | IPython if you don't wish to delete your .ipython dir. |
|
3432 | 3434 | |
|
3433 | 3435 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3434 | 3436 | new users) |
|
3435 | 3437 | |
|
3436 | 3438 | """ |
|
3437 | 3439 | ip = self.getapi() |
|
3438 | 3440 | ipinstallation = path(IPython.__file__).dirname() |
|
3439 | 3441 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') |
|
3440 | 3442 | src_config = ipinstallation / 'config' / 'userconfig' |
|
3441 |
userdir = path(ip.options. |
|
|
3443 | userdir = path(ip.options.IPYTHONDIR) | |
|
3442 | 3444 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3443 | 3445 | print ">",cmd |
|
3444 | 3446 | shell(cmd) |
|
3445 | 3447 | if arg == '-nolegacy': |
|
3446 | 3448 | legacy = userdir.files('ipythonrc*') |
|
3447 | 3449 | print "Nuking legacy files:",legacy |
|
3448 | 3450 | |
|
3449 | 3451 | [p.remove() for p in legacy] |
|
3450 | 3452 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3451 | 3453 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3452 | 3454 | |
|
3453 | 3455 | |
|
3454 | 3456 | def magic_doctest_mode(self,parameter_s=''): |
|
3455 | 3457 | """Toggle doctest mode on and off. |
|
3456 | 3458 | |
|
3457 | 3459 | This mode allows you to toggle the prompt behavior between normal |
|
3458 | 3460 | IPython prompts and ones that are as similar to the default IPython |
|
3459 | 3461 | interpreter as possible. |
|
3460 | 3462 | |
|
3461 | 3463 | It also supports the pasting of code snippets that have leading '>>>' |
|
3462 | 3464 | and '...' prompts in them. This means that you can paste doctests from |
|
3463 | 3465 | files or docstrings (even if they have leading whitespace), and the |
|
3464 | 3466 | code will execute correctly. You can then use '%history -tn' to see |
|
3465 | 3467 | the translated history without line numbers; this will give you the |
|
3466 | 3468 | input after removal of all the leading prompts and whitespace, which |
|
3467 | 3469 | can be pasted back into an editor. |
|
3468 | 3470 | |
|
3469 | 3471 | With these features, you can switch into this mode easily whenever you |
|
3470 | 3472 | need to do testing and changes to doctests, without having to leave |
|
3471 | 3473 | your existing IPython session. |
|
3472 | 3474 | """ |
|
3473 | 3475 | |
|
3474 | 3476 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3475 | 3477 | from IPython.extensions import InterpreterPasteInput as ipaste |
|
3476 | 3478 | from IPython.utils.ipstruct import Struct |
|
3477 | 3479 | |
|
3478 | 3480 | # Shorthands |
|
3479 | 3481 | shell = self.shell |
|
3480 | 3482 | oc = shell.outputcache |
|
3481 | rc = shell.rc | |
|
3482 | 3483 | meta = shell.meta |
|
3483 | 3484 | # dstore is a data store kept in the instance metadata bag to track any |
|
3484 | 3485 | # changes we make, so we can undo them later. |
|
3485 | 3486 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3486 | 3487 | save_dstore = dstore.setdefault |
|
3487 | 3488 | |
|
3488 | 3489 | # save a few values we'll need to recover later |
|
3489 | 3490 | mode = save_dstore('mode',False) |
|
3490 |
save_dstore('rc_pprint', |
|
|
3491 | save_dstore('rc_pprint',shell.pprint) | |
|
3491 | 3492 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3492 |
save_dstore('rc_separate_out', |
|
|
3493 |
save_dstore('rc_separate_out2', |
|
|
3494 |
save_dstore('rc_prompts_pad_left', |
|
|
3495 |
save_dstore('rc_separate_in', |
|
|
3493 | save_dstore('rc_separate_out',shell.separate_out) | |
|
3494 | save_dstore('rc_separate_out2',shell.separate_out2) | |
|
3495 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
|
3496 | save_dstore('rc_separate_in',shell.separate_in) | |
|
3496 | 3497 | |
|
3497 | 3498 | if mode == False: |
|
3498 | 3499 | # turn on |
|
3499 | 3500 | ipaste.activate_prefilter() |
|
3500 | 3501 | |
|
3501 | 3502 | oc.prompt1.p_template = '>>> ' |
|
3502 | 3503 | oc.prompt2.p_template = '... ' |
|
3503 | 3504 | oc.prompt_out.p_template = '' |
|
3504 | 3505 | |
|
3505 | 3506 | # Prompt separators like plain python |
|
3506 | 3507 | oc.input_sep = oc.prompt1.sep = '' |
|
3507 | 3508 | oc.output_sep = '' |
|
3508 | 3509 | oc.output_sep2 = '' |
|
3509 | 3510 | |
|
3510 | 3511 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3511 | 3512 | oc.prompt_out.pad_left = False |
|
3512 | 3513 | |
|
3513 |
|
|
|
3514 | shell.pprint = False | |
|
3514 | 3515 | |
|
3515 | 3516 | shell.magic_xmode('Plain') |
|
3516 | 3517 | |
|
3517 | 3518 | else: |
|
3518 | 3519 | # turn off |
|
3519 | 3520 | ipaste.deactivate_prefilter() |
|
3520 | 3521 | |
|
3521 |
oc.prompt1.p_template = |
|
|
3522 |
oc.prompt2.p_template = |
|
|
3523 |
oc.prompt_out.p_template = |
|
|
3522 | oc.prompt1.p_template = shell.prompt_in1 | |
|
3523 | oc.prompt2.p_template = shell.prompt_in2 | |
|
3524 | oc.prompt_out.p_template = shell.prompt_out | |
|
3524 | 3525 | |
|
3525 | 3526 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3526 | 3527 | |
|
3527 | 3528 | oc.output_sep = dstore.rc_separate_out |
|
3528 | 3529 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3529 | 3530 | |
|
3530 | 3531 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3531 | 3532 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3532 | 3533 | |
|
3533 | 3534 | rc.pprint = dstore.rc_pprint |
|
3534 | 3535 | |
|
3535 | 3536 | shell.magic_xmode(dstore.xmode) |
|
3536 | 3537 | |
|
3537 | 3538 | # Store new mode and inform |
|
3538 | 3539 | dstore.mode = bool(1-int(mode)) |
|
3539 | 3540 | print 'Doctest mode is:', |
|
3540 | 3541 | print ['OFF','ON'][dstore.mode] |
|
3541 | 3542 | |
|
3542 | 3543 | def magic_gui(self, parameter_s=''): |
|
3543 | 3544 | """Enable or disable IPython GUI event loop integration. |
|
3544 | 3545 | |
|
3545 | 3546 | %gui [-a] [GUINAME] |
|
3546 | 3547 | |
|
3547 | 3548 | This magic replaces IPython's threaded shells that were activated |
|
3548 | 3549 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3549 | 3550 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3550 | 3551 | interrupts should work without any problems. The following toolkits |
|
3551 | 3552 | are supports: wxPython, PyQt4, PyGTK, and Tk:: |
|
3552 | 3553 | |
|
3553 | 3554 | %gui wx # enable wxPython event loop integration |
|
3554 | 3555 | %gui qt4 # enable PyQt4 event loop integration |
|
3555 | 3556 | %gui gtk # enable PyGTK event loop integration |
|
3556 | 3557 | %gui tk # enable Tk event loop integration |
|
3557 | 3558 | %gui # disable all event loop integration |
|
3558 | 3559 | |
|
3559 | 3560 | WARNING: after any of these has been called you can simply create |
|
3560 | 3561 | an application object, but DO NOT start the event loop yourself, as |
|
3561 | 3562 | we have already handled that. |
|
3562 | 3563 | |
|
3563 | 3564 | If you want us to create an appropriate application object add the |
|
3564 | 3565 | "-a" flag to your command:: |
|
3565 | 3566 | |
|
3566 | 3567 | %gui -a wx |
|
3567 | 3568 | |
|
3568 | 3569 | This is highly recommended for most users. |
|
3569 | 3570 | """ |
|
3570 | 3571 | from IPython.lib import inputhook |
|
3571 | 3572 | if "-a" in parameter_s: |
|
3572 | 3573 | app = True |
|
3573 | 3574 | else: |
|
3574 | 3575 | app = False |
|
3575 | 3576 | if not parameter_s: |
|
3576 | 3577 | inputhook.clear_inputhook() |
|
3577 | 3578 | elif 'wx' in parameter_s: |
|
3578 | 3579 | return inputhook.enable_wx(app) |
|
3579 | 3580 | elif 'qt4' in parameter_s: |
|
3580 | 3581 | return inputhook.enable_qt4(app) |
|
3581 | 3582 | elif 'gtk' in parameter_s: |
|
3582 | 3583 | return inputhook.enable_gtk(app) |
|
3583 | 3584 | elif 'tk' in parameter_s: |
|
3584 | 3585 | return inputhook.enable_tk(app) |
|
3585 | 3586 | |
|
3586 | 3587 | |
|
3587 | 3588 | # end Magic |
@@ -1,320 +1,320 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Classes and functions for prefiltering (transforming) a line of user input. |
|
4 | 4 | This module is responsible, primarily, for breaking the line up into useful |
|
5 | 5 | pieces and triggering the appropriate handlers in iplib to do the actual |
|
6 | 6 | transforming work. |
|
7 | 7 | """ |
|
8 | 8 | __docformat__ = "restructuredtext en" |
|
9 | 9 | |
|
10 | 10 | import re |
|
11 | 11 | from IPython.core import ipapi |
|
12 | 12 | |
|
13 | 13 | class LineInfo(object): |
|
14 | 14 | """A single line of input and associated info. |
|
15 | 15 | |
|
16 | 16 | Includes the following as properties: |
|
17 | 17 | |
|
18 | 18 | line |
|
19 | 19 | The original, raw line |
|
20 | 20 | |
|
21 | 21 | continue_prompt |
|
22 | 22 | Is this line a continuation in a sequence of multiline input? |
|
23 | 23 | |
|
24 | 24 | pre |
|
25 | 25 | The initial esc character or whitespace. |
|
26 | 26 | |
|
27 | 27 | preChar |
|
28 | 28 | The escape character(s) in pre or the empty string if there isn't one. |
|
29 | 29 | Note that '!!' is a possible value for preChar. Otherwise it will |
|
30 | 30 | always be a single character. |
|
31 | 31 | |
|
32 | 32 | preWhitespace |
|
33 | 33 | The leading whitespace from pre if it exists. If there is a preChar, |
|
34 | 34 | this is just ''. |
|
35 | 35 | |
|
36 | 36 | iFun |
|
37 | 37 | The 'function part', which is basically the maximal initial sequence |
|
38 | 38 | of valid python identifiers and the '.' character. This is what is |
|
39 | 39 | checked for alias and magic transformations, used for auto-calling, |
|
40 | 40 | etc. |
|
41 | 41 | |
|
42 | 42 | theRest |
|
43 | 43 | Everything else on the line. |
|
44 | 44 | """ |
|
45 | 45 | def __init__(self, line, continue_prompt): |
|
46 | 46 | self.line = line |
|
47 | 47 | self.continue_prompt = continue_prompt |
|
48 | 48 | self.pre, self.iFun, self.theRest = splitUserInput(line) |
|
49 | 49 | |
|
50 | 50 | self.preChar = self.pre.strip() |
|
51 | 51 | if self.preChar: |
|
52 | 52 | self.preWhitespace = '' # No whitespace allowd before esc chars |
|
53 | 53 | else: |
|
54 | 54 | self.preWhitespace = self.pre |
|
55 | 55 | |
|
56 | 56 | self._oinfo = None |
|
57 | 57 | |
|
58 | 58 | def ofind(self, ip): |
|
59 | 59 | """Do a full, attribute-walking lookup of the iFun in the various |
|
60 | 60 | namespaces for the given IPython InteractiveShell instance. |
|
61 | 61 | |
|
62 | 62 | Return a dict with keys: found,obj,ospace,ismagic |
|
63 | 63 | |
|
64 | 64 | Note: can cause state changes because of calling getattr, but should |
|
65 | 65 | only be run if autocall is on and if the line hasn't matched any |
|
66 | 66 | other, less dangerous handlers. |
|
67 | 67 | |
|
68 | 68 | Does cache the results of the call, so can be called multiple times |
|
69 | 69 | without worrying about *further* damaging state. |
|
70 | 70 | """ |
|
71 | 71 | if not self._oinfo: |
|
72 | 72 | self._oinfo = ip._ofind(self.iFun) |
|
73 | 73 | return self._oinfo |
|
74 | 74 | def __str__(self): |
|
75 | 75 | return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest) |
|
76 | 76 | |
|
77 | 77 | def splitUserInput(line, pattern=None): |
|
78 | 78 | """Split user input into pre-char/whitespace, function part and rest. |
|
79 | 79 | |
|
80 | 80 | Mostly internal to this module, but also used by iplib.expand_aliases, |
|
81 | 81 | which passes in a shell pattern. |
|
82 | 82 | """ |
|
83 | 83 | # It seems to me that the shell splitting should be a separate method. |
|
84 | 84 | |
|
85 | 85 | if not pattern: |
|
86 | 86 | pattern = line_split |
|
87 | 87 | match = pattern.match(line) |
|
88 | 88 | if not match: |
|
89 | 89 | #print "match failed for line '%s'" % line |
|
90 | 90 | try: |
|
91 | 91 | iFun,theRest = line.split(None,1) |
|
92 | 92 | except ValueError: |
|
93 | 93 | #print "split failed for line '%s'" % line |
|
94 | 94 | iFun,theRest = line,'' |
|
95 | 95 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
96 | 96 | else: |
|
97 | 97 | pre,iFun,theRest = match.groups() |
|
98 | 98 | |
|
99 | 99 | # iFun has to be a valid python identifier, so it better be only pure |
|
100 | 100 | # ascii, no unicode: |
|
101 | 101 | try: |
|
102 | 102 | iFun = iFun.encode('ascii') |
|
103 | 103 | except UnicodeEncodeError: |
|
104 | 104 | theRest = iFun + u' ' + theRest |
|
105 | 105 | iFun = u'' |
|
106 | 106 | |
|
107 | 107 | #print 'line:<%s>' % line # dbg |
|
108 | 108 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
109 | 109 | return pre,iFun.strip(),theRest.lstrip() |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | # RegExp for splitting line contents into pre-char//first word-method//rest. |
|
113 | 113 | # For clarity, each group in on one line. |
|
114 | 114 | |
|
115 | 115 | # WARNING: update the regexp if the escapes in iplib are changed, as they |
|
116 | 116 | # are hardwired in. |
|
117 | 117 | |
|
118 | 118 | # Although it's not solely driven by the regex, note that: |
|
119 | 119 | # ,;/% only trigger if they are the first character on the line |
|
120 | 120 | # ! and !! trigger if they are first char(s) *or* follow an indent |
|
121 | 121 | # ? triggers as first or last char. |
|
122 | 122 | |
|
123 | 123 | # The three parts of the regex are: |
|
124 | 124 | # 1) pre: pre_char *or* initial whitespace |
|
125 | 125 | # 2) iFun: first word/method (mix of \w and '.') |
|
126 | 126 | # 3) theRest: rest of line (separated from iFun by space if non-empty) |
|
127 | 127 | line_split = re.compile(r'^([,;/%?]|!!?|\s*)' |
|
128 | 128 | r'\s*([\w\.]+)' |
|
129 | 129 | r'(\s+.*$|$)') |
|
130 | 130 | |
|
131 | 131 | shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)') |
|
132 | 132 | |
|
133 | 133 | def prefilter(line_info, ip): |
|
134 | 134 | """Call one of the passed-in InteractiveShell's handler preprocessors, |
|
135 | 135 | depending on the form of the line. Return the results, which must be a |
|
136 | 136 | value, even if it's a blank ('').""" |
|
137 | 137 | # Note: the order of these checks does matter. |
|
138 | 138 | for check in [ checkEmacs, |
|
139 | 139 | checkShellEscape, |
|
140 | 140 | checkIPyAutocall, |
|
141 | 141 | checkMultiLineMagic, |
|
142 | 142 | checkEscChars, |
|
143 | 143 | checkAssignment, |
|
144 | 144 | checkAutomagic, |
|
145 | 145 | checkAlias, |
|
146 | 146 | checkPythonOps, |
|
147 | 147 | checkAutocall, |
|
148 | 148 | ]: |
|
149 | 149 | handler = check(line_info, ip) |
|
150 | 150 | if handler: |
|
151 | 151 | return handler(line_info) |
|
152 | 152 | |
|
153 | 153 | return ip.handle_normal(line_info) |
|
154 | 154 | |
|
155 | 155 | # Handler checks |
|
156 | 156 | # |
|
157 | 157 | # All have the same interface: they take a LineInfo object and a ref to the |
|
158 | 158 | # iplib.InteractiveShell object. They check the line to see if a particular |
|
159 | 159 | # handler should be called, and return either a handler or None. The |
|
160 | 160 | # handlers which they return are *bound* methods of the InteractiveShell |
|
161 | 161 | # object. |
|
162 | 162 | # |
|
163 | 163 | # In general, these checks should only take responsibility for their 'own' |
|
164 | 164 | # handler. If it doesn't get triggered, they should just return None and |
|
165 | 165 | # let the rest of the check sequence run. |
|
166 | 166 | |
|
167 | 167 | def checkShellEscape(l_info,ip): |
|
168 | 168 | if l_info.line.lstrip().startswith(ip.ESC_SHELL): |
|
169 | 169 | return ip.handle_shell_escape |
|
170 | 170 | |
|
171 | 171 | def checkEmacs(l_info,ip): |
|
172 | 172 | "Emacs ipython-mode tags certain input lines." |
|
173 | 173 | if l_info.line.endswith('# PYTHON-MODE'): |
|
174 | 174 | return ip.handle_emacs |
|
175 | 175 | else: |
|
176 | 176 | return None |
|
177 | 177 | |
|
178 | 178 | def checkIPyAutocall(l_info,ip): |
|
179 | 179 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
180 | 180 | obj = ip.user_ns.get(l_info.iFun, None) |
|
181 | 181 | if isinstance(obj, ipapi.IPyAutocall): |
|
182 | 182 | obj.set_ip(ip.api) |
|
183 | 183 | return ip.handle_auto |
|
184 | 184 | else: |
|
185 | 185 | return None |
|
186 | 186 | |
|
187 | 187 | |
|
188 | 188 | def checkMultiLineMagic(l_info,ip): |
|
189 | 189 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
190 | 190 | # Note that this one of the only places we check the first character of |
|
191 | 191 | # iFun and *not* the preChar. Also note that the below test matches |
|
192 | 192 | # both ! and !!. |
|
193 | 193 | if l_info.continue_prompt \ |
|
194 |
and ip. |
|
|
194 | and ip.multi_line_specials: | |
|
195 | 195 | if l_info.iFun.startswith(ip.ESC_MAGIC): |
|
196 | 196 | return ip.handle_magic |
|
197 | 197 | else: |
|
198 | 198 | return None |
|
199 | 199 | |
|
200 | 200 | def checkEscChars(l_info,ip): |
|
201 | 201 | """Check for escape character and return either a handler to handle it, |
|
202 | 202 | or None if there is no escape char.""" |
|
203 | 203 | if l_info.line[-1] == ip.ESC_HELP \ |
|
204 | 204 | and l_info.preChar != ip.ESC_SHELL \ |
|
205 | 205 | and l_info.preChar != ip.ESC_SH_CAP: |
|
206 | 206 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
207 | 207 | # because a ? can be a vaild final char in a shell cmd |
|
208 | 208 | return ip.handle_help |
|
209 | 209 | elif l_info.preChar in ip.esc_handlers: |
|
210 | 210 | return ip.esc_handlers[l_info.preChar] |
|
211 | 211 | else: |
|
212 | 212 | return None |
|
213 | 213 | |
|
214 | 214 | |
|
215 | 215 | def checkAssignment(l_info,ip): |
|
216 | 216 | """Check to see if user is assigning to a var for the first time, in |
|
217 | 217 | which case we want to avoid any sort of automagic / autocall games. |
|
218 | 218 | |
|
219 | 219 | This allows users to assign to either alias or magic names true python |
|
220 | 220 | variables (the magic/alias systems always take second seat to true |
|
221 | 221 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
222 | 222 | if l_info.theRest and l_info.theRest[0] in '=,': |
|
223 | 223 | return ip.handle_normal |
|
224 | 224 | else: |
|
225 | 225 | return None |
|
226 | 226 | |
|
227 | 227 | |
|
228 | 228 | def checkAutomagic(l_info,ip): |
|
229 | 229 | """If the iFun is magic, and automagic is on, run it. Note: normal, |
|
230 | 230 | non-auto magic would already have been triggered via '%' in |
|
231 | 231 | check_esc_chars. This just checks for automagic. Also, before |
|
232 | 232 | triggering the magic handler, make sure that there is nothing in the |
|
233 | 233 | user namespace which could shadow it.""" |
|
234 |
if not ip |
|
|
234 | if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun): | |
|
235 | 235 | return None |
|
236 | 236 | |
|
237 | 237 | # We have a likely magic method. Make sure we should actually call it. |
|
238 |
if l_info.continue_prompt and not ip. |
|
|
238 | if l_info.continue_prompt and not ip.multi_line_specials: | |
|
239 | 239 | return None |
|
240 | 240 | |
|
241 | 241 | head = l_info.iFun.split('.',1)[0] |
|
242 | 242 | if isShadowed(head,ip): |
|
243 | 243 | return None |
|
244 | 244 | |
|
245 | 245 | return ip.handle_magic |
|
246 | 246 | |
|
247 | 247 | |
|
248 | 248 | def checkAlias(l_info,ip): |
|
249 | 249 | "Check if the initital identifier on the line is an alias." |
|
250 | 250 | # Note: aliases can not contain '.' |
|
251 | 251 | head = l_info.iFun.split('.',1)[0] |
|
252 | 252 | |
|
253 | 253 | if l_info.iFun not in ip.alias_table \ |
|
254 | 254 | or head not in ip.alias_table \ |
|
255 | 255 | or isShadowed(head,ip): |
|
256 | 256 | return None |
|
257 | 257 | |
|
258 | 258 | return ip.handle_alias |
|
259 | 259 | |
|
260 | 260 | |
|
261 | 261 | def checkPythonOps(l_info,ip): |
|
262 | 262 | """If the 'rest' of the line begins with a function call or pretty much |
|
263 | 263 | any python operator, we should simply execute the line (regardless of |
|
264 | 264 | whether or not there's a possible autocall expansion). This avoids |
|
265 | 265 | spurious (and very confusing) geattr() accesses.""" |
|
266 | 266 | if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|': |
|
267 | 267 | return ip.handle_normal |
|
268 | 268 | else: |
|
269 | 269 | return None |
|
270 | 270 | |
|
271 | 271 | |
|
272 | 272 | def checkAutocall(l_info,ip): |
|
273 | 273 | "Check if the initial word/function is callable and autocall is on." |
|
274 |
if not ip. |
|
|
274 | if not ip.autocall: | |
|
275 | 275 | return None |
|
276 | 276 | |
|
277 | 277 | oinfo = l_info.ofind(ip) # This can mutate state via getattr |
|
278 | 278 | if not oinfo['found']: |
|
279 | 279 | return None |
|
280 | 280 | |
|
281 | 281 | if callable(oinfo['obj']) \ |
|
282 | 282 | and (not re_exclude_auto.match(l_info.theRest)) \ |
|
283 | 283 | and re_fun_name.match(l_info.iFun): |
|
284 | 284 | #print 'going auto' # dbg |
|
285 | 285 | return ip.handle_auto |
|
286 | 286 | else: |
|
287 | 287 | #print 'was callable?', callable(l_info.oinfo['obj']) # dbg |
|
288 | 288 | return None |
|
289 | 289 | |
|
290 | 290 | # RegExp to identify potential function names |
|
291 | 291 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
292 | 292 | |
|
293 | 293 | # RegExp to exclude strings with this start from autocalling. In |
|
294 | 294 | # particular, all binary operators should be excluded, so that if foo is |
|
295 | 295 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
296 | 296 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
297 | 297 | # routine explicitely does so, to catch direct calls and rebindings of |
|
298 | 298 | # existing names. |
|
299 | 299 | |
|
300 | 300 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
301 | 301 | # it affects the rest of the group in square brackets. |
|
302 | 302 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
303 | 303 | r'|^is |^not |^in |^and |^or ') |
|
304 | 304 | |
|
305 | 305 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
306 | 306 | # (experimental). For this to work, the line_split regexp would need |
|
307 | 307 | # to be modified so it wouldn't break things at '['. That line is |
|
308 | 308 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
309 | 309 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
310 | 310 | |
|
311 | 311 | # Handler Check Utilities |
|
312 | 312 | def isShadowed(identifier,ip): |
|
313 | 313 | """Is the given identifier defined in one of the namespaces which shadow |
|
314 | 314 | the alias and magic namespaces? Note that an identifier is different |
|
315 | 315 | than iFun, because it can not contain a '.' character.""" |
|
316 | 316 | # This is much safer than calling ofind, which can change state |
|
317 | 317 | return (identifier in ip.user_ns \ |
|
318 | 318 | or identifier in ip.internal_ns \ |
|
319 | 319 | or identifier in ip.ns_table['builtin']) |
|
320 | 320 |
@@ -1,274 +1,274 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """IPython Shell classes. |
|
4 | 4 | |
|
5 | 5 | Originally, this module was horribly complicated because of the need to |
|
6 | 6 | use threads to integrate with GUI toolkit event loops. Now, we are using |
|
7 | 7 | the :mod:`IPython.lib.inputhook`, which is based on PyOS_InputHook. This |
|
8 | 8 | dramatically simplifies this logic and allow 3rd party packages (such as |
|
9 | 9 | matplotlib) to handle these things by themselves. |
|
10 | 10 | |
|
11 | 11 | This new approach also allows projects like matplotlib to work interactively |
|
12 | 12 | in the standard python shell. |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | import sys |
|
27 | 27 | |
|
28 | 28 | from IPython.core import ultratb |
|
29 | 29 | from IPython.core import ipapi |
|
30 | 30 | from IPython.utils.genutils import ask_yes_no |
|
31 | 31 | from IPython.core.iplib import InteractiveShell |
|
32 | 32 | from IPython.core.ipmaker import make_IPython |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Code |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | class IPShell: |
|
40 | 40 | """Create an IPython instance. |
|
41 | 41 | |
|
42 | 42 | This calls the factory :func:`make_IPython`, which creates a configured |
|
43 | 43 | :class:`InteractiveShell` object, and presents the result as a simple |
|
44 | 44 | class with a :meth:`mainloop` method. |
|
45 | 45 | """ |
|
46 | 46 | |
|
47 | 47 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, |
|
48 | 48 | debug=1, shell_class=InteractiveShell): |
|
49 | 49 | self.IP = make_IPython(argv, user_ns=user_ns, |
|
50 | 50 | user_global_ns=user_global_ns, |
|
51 | 51 | debug=debug, shell_class=shell_class) |
|
52 | 52 | |
|
53 | 53 | def mainloop(self,sys_exit=0,banner=None): |
|
54 | 54 | self.IP.mainloop(banner) |
|
55 | 55 | if sys_exit: |
|
56 | 56 | sys.exit() |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | # This is an additional magic that is exposed in embedded shells. |
|
60 | 60 | def kill_embedded(self,parameter_s=''): |
|
61 | 61 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
62 | 62 | |
|
63 | 63 | This function (after asking for confirmation) sets an internal flag so that |
|
64 | 64 | an embedded IPython will never activate again. This is useful to |
|
65 | 65 | permanently disable a shell that is being called inside a loop: once you've |
|
66 | 66 | figured out what you needed from it, you may then kill it and the program |
|
67 | 67 | will then continue to run without the interactive shell interfering again. |
|
68 | 68 | """ |
|
69 | 69 | |
|
70 | 70 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
71 | 71 | "(y/n)? [y/N] ",'n') |
|
72 | 72 | if kill: |
|
73 | 73 | self.shell.embedded_active = False |
|
74 | 74 | print "This embedded IPython will not reactivate anymore once you exit." |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | class IPShellEmbed: |
|
78 | 78 | """Allow embedding an IPython shell into a running program. |
|
79 | 79 | |
|
80 | 80 | Instances of this class are callable, with the __call__ method being an |
|
81 | 81 | alias to the embed() method of an InteractiveShell instance. |
|
82 | 82 | |
|
83 | 83 | Usage (see also the example-embed.py file for a running example):: |
|
84 | 84 | |
|
85 | 85 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) |
|
86 | 86 | |
|
87 | 87 | * argv: list containing valid command-line options for IPython, as they |
|
88 | 88 | would appear in sys.argv[1:]. |
|
89 | 89 | |
|
90 | 90 | For example, the following command-line options:: |
|
91 | 91 | |
|
92 | 92 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG |
|
93 | 93 | |
|
94 | 94 | would be passed in the argv list as:: |
|
95 | 95 | |
|
96 | 96 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] |
|
97 | 97 | |
|
98 | 98 | * banner: string which gets printed every time the interpreter starts. |
|
99 | 99 | |
|
100 | 100 | * exit_msg: string which gets printed every time the interpreter exits. |
|
101 | 101 | |
|
102 | 102 | * rc_override: a dict or Struct of configuration options such as those |
|
103 | 103 | used by IPython. These options are read from your ~/.ipython/ipythonrc |
|
104 | 104 | file when the Shell object is created. Passing an explicit rc_override |
|
105 | 105 | dict with any options you want allows you to override those values at |
|
106 | 106 | creation time without having to modify the file. This way you can create |
|
107 | 107 | embeddable instances configured in any way you want without editing any |
|
108 | 108 | global files (thus keeping your interactive IPython configuration |
|
109 | 109 | unchanged). |
|
110 | 110 | |
|
111 | 111 | Then the ipshell instance can be called anywhere inside your code:: |
|
112 | 112 | |
|
113 | 113 | ipshell(header='') -> Opens up an IPython shell. |
|
114 | 114 | |
|
115 | 115 | * header: string printed by the IPython shell upon startup. This can let |
|
116 | 116 | you know where in your code you are when dropping into the shell. Note |
|
117 | 117 | that 'banner' gets prepended to all calls, so header is used for |
|
118 | 118 | location-specific information. |
|
119 | 119 | |
|
120 | 120 | For more details, see the __call__ method below. |
|
121 | 121 | |
|
122 | 122 | When the IPython shell is exited with Ctrl-D, normal program execution |
|
123 | 123 | resumes. |
|
124 | 124 | |
|
125 | 125 | This functionality was inspired by a posting on comp.lang.python by cmkl |
|
126 | 126 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and |
|
127 | 127 | by the IDL stop/continue commands. |
|
128 | 128 | """ |
|
129 | 129 | |
|
130 | 130 | def __init__(self, argv=None, banner='', exit_msg=None, |
|
131 | 131 | rc_override=None, user_ns=None): |
|
132 | 132 | """Note that argv here is a string, NOT a list.""" |
|
133 | 133 | |
|
134 | 134 | self.set_banner(banner) |
|
135 | 135 | self.set_exit_msg(exit_msg) |
|
136 | 136 | self.set_dummy_mode(0) |
|
137 | 137 | |
|
138 | 138 | # sys.displayhook is a global, we need to save the user's original |
|
139 | 139 | # Don't rely on __displayhook__, as the user may have changed that. |
|
140 | 140 | self.sys_displayhook_ori = sys.displayhook |
|
141 | 141 | |
|
142 | 142 | # save readline completer status |
|
143 | 143 | try: |
|
144 | 144 | #print 'Save completer',sys.ipcompleter # dbg |
|
145 | 145 | self.sys_ipcompleter_ori = sys.ipcompleter |
|
146 | 146 | except: |
|
147 | 147 | pass # not nested with IPython |
|
148 | 148 | |
|
149 | 149 | self.IP = make_IPython(argv,rc_override=rc_override, |
|
150 | 150 | embedded=True, |
|
151 | 151 | user_ns=user_ns) |
|
152 | 152 | |
|
153 | 153 | ip = ipapi.IPApi(self.IP) |
|
154 | 154 | ip.expose_magic("kill_embedded",kill_embedded) |
|
155 | 155 | |
|
156 | 156 | # copy our own displayhook also |
|
157 | 157 | self.sys_displayhook_embed = sys.displayhook |
|
158 | 158 | # and leave the system's display hook clean |
|
159 | 159 | sys.displayhook = self.sys_displayhook_ori |
|
160 | 160 | # don't use the ipython crash handler so that user exceptions aren't |
|
161 | 161 | # trapped |
|
162 |
sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP. |
|
|
163 |
mode = self.IP. |
|
|
164 |
call_pdb = self.IP. |
|
|
162 | sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.colors, | |
|
163 | mode = self.IP.xmode, | |
|
164 | call_pdb = self.IP.pdb) | |
|
165 | 165 | self.restore_system_completer() |
|
166 | 166 | |
|
167 | 167 | def restore_system_completer(self): |
|
168 | 168 | """Restores the readline completer which was in place. |
|
169 | 169 | |
|
170 | 170 | This allows embedded IPython within IPython not to disrupt the |
|
171 | 171 | parent's completion. |
|
172 | 172 | """ |
|
173 | 173 | |
|
174 | 174 | try: |
|
175 | 175 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) |
|
176 | 176 | sys.ipcompleter = self.sys_ipcompleter_ori |
|
177 | 177 | except: |
|
178 | 178 | pass |
|
179 | 179 | |
|
180 | 180 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None): |
|
181 | 181 | """Activate the interactive interpreter. |
|
182 | 182 | |
|
183 | 183 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
184 | 184 | the interpreter shell with the given local and global namespaces, and |
|
185 | 185 | optionally print a header string at startup. |
|
186 | 186 | |
|
187 | 187 | The shell can be globally activated/deactivated using the |
|
188 | 188 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
189 | 189 | for debugging globally. |
|
190 | 190 | |
|
191 | 191 | However, *each* time you call the shell you can override the current |
|
192 | 192 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
193 | 193 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
194 | 194 | can still have a specific call work by making it as IPShell(dummy=0). |
|
195 | 195 | |
|
196 | 196 | The optional keyword parameter dummy controls whether the call |
|
197 | 197 | actually does anything. |
|
198 | 198 | """ |
|
199 | 199 | |
|
200 | 200 | # If the user has turned it off, go away |
|
201 | 201 | if not self.IP.embedded_active: |
|
202 | 202 | return |
|
203 | 203 | |
|
204 | 204 | # Normal exits from interactive mode set this flag, so the shell can't |
|
205 | 205 | # re-enter (it checks this variable at the start of interactive mode). |
|
206 | 206 | self.IP.exit_now = False |
|
207 | 207 | |
|
208 | 208 | # Allow the dummy parameter to override the global __dummy_mode |
|
209 | 209 | if dummy or (dummy != 0 and self.__dummy_mode): |
|
210 | 210 | return |
|
211 | 211 | |
|
212 | 212 | # Set global subsystems (display,completions) to our values |
|
213 | 213 | sys.displayhook = self.sys_displayhook_embed |
|
214 | 214 | if self.IP.has_readline: |
|
215 | 215 | self.IP.set_completer() |
|
216 | 216 | |
|
217 | 217 | if self.banner and header: |
|
218 | 218 | format = '%s\n%s\n' |
|
219 | 219 | else: |
|
220 | 220 | format = '%s%s\n' |
|
221 | 221 | banner = format % (self.banner,header) |
|
222 | 222 | |
|
223 | 223 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
224 | 224 | # our call and get the original caller's namespaces. |
|
225 | 225 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) |
|
226 | 226 | |
|
227 | 227 | if self.exit_msg: |
|
228 | 228 | print self.exit_msg |
|
229 | 229 | |
|
230 | 230 | # Restore global systems (display, completion) |
|
231 | 231 | sys.displayhook = self.sys_displayhook_ori |
|
232 | 232 | self.restore_system_completer() |
|
233 | 233 | |
|
234 | 234 | def set_dummy_mode(self, dummy): |
|
235 | 235 | """Sets the embeddable shell's dummy mode parameter. |
|
236 | 236 | |
|
237 | 237 | set_dummy_mode(dummy): dummy = 0 or 1. |
|
238 | 238 | |
|
239 | 239 | This parameter is persistent and makes calls to the embeddable shell |
|
240 | 240 | silently return without performing any action. This allows you to |
|
241 | 241 | globally activate or deactivate a shell you're using with a single call. |
|
242 | 242 | |
|
243 | 243 | If you need to manually""" |
|
244 | 244 | |
|
245 | 245 | if dummy not in [0,1,False,True]: |
|
246 | 246 | raise ValueError,'dummy parameter must be boolean' |
|
247 | 247 | self.__dummy_mode = dummy |
|
248 | 248 | |
|
249 | 249 | def get_dummy_mode(self): |
|
250 | 250 | """Return the current value of the dummy mode parameter. |
|
251 | 251 | """ |
|
252 | 252 | return self.__dummy_mode |
|
253 | 253 | |
|
254 | 254 | def set_banner(self, banner): |
|
255 | 255 | """Sets the global banner. |
|
256 | 256 | |
|
257 | 257 | This banner gets prepended to every header printed when the shell |
|
258 | 258 | instance is called.""" |
|
259 | 259 | |
|
260 | 260 | self.banner = banner |
|
261 | 261 | |
|
262 | 262 | def set_exit_msg(self, exit_msg): |
|
263 | 263 | """Sets the global exit_msg. |
|
264 | 264 | |
|
265 | 265 | This exit message gets printed upon exiting every time the embedded |
|
266 | 266 | shell is called. It is None by default. """ |
|
267 | 267 | |
|
268 | 268 | self.exit_msg = exit_msg |
|
269 | 269 | |
|
270 | 270 | # This is the one which should be called by external code. |
|
271 | 271 | def start(user_ns = None): |
|
272 | 272 | """Return a running shell instance of :class:`IPShell`.""" |
|
273 | 273 | return IPShell(user_ns = user_ns) |
|
274 | 274 |
@@ -1,81 +1,82 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 | # Globals |
|
21 | 22 | #----------------------------------------------------------------------------- |
|
22 | 23 | |
|
23 | 24 | # Useful global ipapi object and main IPython one. Unfortunately we have a |
|
24 | 25 | # long precedent of carrying the 'ipapi' global object which is injected into |
|
25 | 26 | # the system namespace as _ip, but that keeps a pointer to the actual IPython |
|
26 | 27 | # InteractiveShell instance, which is named IP. Since in testing we do need |
|
27 | 28 | # access to the real thing (we want to probe beyond what ipapi exposes), make |
|
28 | 29 | # here a global reference to each. In general, things that are exposed by the |
|
29 | 30 | # ipapi instance should be read from there, but we also will often need to use |
|
30 | 31 | # the actual IPython one. |
|
31 | 32 | |
|
32 | 33 | # Get the public instance of IPython, and if it's None, make one so we can use |
|
33 | 34 | # it for testing |
|
34 | 35 | ip = ipapi.get() |
|
35 | 36 | if ip is None: |
|
36 | 37 | # IPython not running yet, make one from the testing machinery for |
|
37 | 38 | # consistency when the test suite is being run via iptest |
|
38 | 39 | from IPython.testing.plugin import ipdoctest |
|
39 | 40 | ip = ipapi.get() |
|
40 | 41 | |
|
41 | 42 | IP = ip.IP # This is the actual IPython shell 'raw' object. |
|
42 | 43 | |
|
43 | 44 | #----------------------------------------------------------------------------- |
|
44 | 45 | # Test functions |
|
45 | 46 | #----------------------------------------------------------------------------- |
|
46 | 47 | |
|
47 | 48 | def test_reset(): |
|
48 | 49 | """reset must clear most namespaces.""" |
|
49 | 50 | IP.reset() # first, it should run without error |
|
50 | 51 | # Then, check that most namespaces end up empty |
|
51 | 52 | for ns in IP.ns_refs_table: |
|
52 | 53 | if ns is IP.user_ns: |
|
53 | 54 | # The user namespace is reset with some data, so we can't check for |
|
54 | 55 | # it being empty |
|
55 | 56 | continue |
|
56 | 57 | nt.assert_equals(len(ns),0) |
|
57 | 58 | |
|
58 | 59 | |
|
59 | 60 | # make sure that user_setup can be run re-entrantly in 'install' mode. |
|
60 | 61 | def test_user_setup(): |
|
61 | 62 | # use a lambda to pass kwargs to the generator |
|
62 |
user_setup = lambda a,k: |
|
|
63 | user_setup = lambda a,k: user_setup(*a,**k) | |
|
63 | 64 | kw = dict(mode='install', interactive=False) |
|
64 | 65 | |
|
65 | 66 | # Call the user setup and verify that the directory exists |
|
66 |
yield user_setup, (ip.options. |
|
|
67 |
yield os.path.isdir, ip.options. |
|
|
67 | yield user_setup, (ip.options.IPYTHONDIR,''), kw | |
|
68 | yield os.path.isdir, ip.options.IPYTHONDIR | |
|
68 | 69 | |
|
69 | 70 | # Now repeat the operation with a non-existent directory. Check both that |
|
70 | 71 | # the call succeeds and that the directory is created. |
|
71 | 72 | tmpdir = tempfile.mktemp(prefix='ipython-test-') |
|
72 | 73 | # Use a try with an empty except because try/finally doesn't work with a |
|
73 | 74 | # yield in Python 2.4. |
|
74 | 75 | try: |
|
75 | 76 | yield user_setup, (tmpdir,''), kw |
|
76 | 77 | yield os.path.isdir, tmpdir |
|
77 | 78 | except: |
|
78 | 79 | pass |
|
79 | 80 | # Clean up the temp dir once done |
|
80 | 81 | shutil.rmtree(tmpdir) |
|
81 | 82 | No newline at end of file |
@@ -1,1063 +1,1063 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | ultratb.py -- Spice up your tracebacks! |
|
4 | 4 | |
|
5 | 5 | * ColorTB |
|
6 | 6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
7 | 7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
8 | 8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
9 | 9 | text editor. |
|
10 | 10 | |
|
11 | 11 | Installation instructions for ColorTB: |
|
12 | 12 | import sys,ultratb |
|
13 | 13 | sys.excepthook = ultratb.ColorTB() |
|
14 | 14 | |
|
15 | 15 | * VerboseTB |
|
16 | 16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
17 | 17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
18 | 18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
19 | 19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
20 | 20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
21 | 21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
22 | 22 | Give it a shot--you'll love it or you'll hate it. |
|
23 | 23 | |
|
24 | 24 | Note: |
|
25 | 25 | |
|
26 | 26 | The Verbose mode prints the variables currently visible where the exception |
|
27 | 27 | happened (shortening their strings if too long). This can potentially be |
|
28 | 28 | very slow, if you happen to have a huge data structure whose string |
|
29 | 29 | representation is complex to compute. Your computer may appear to freeze for |
|
30 | 30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
31 | 31 | with Ctrl-C (maybe hitting it more than once). |
|
32 | 32 | |
|
33 | 33 | If you encounter this kind of situation often, you may want to use the |
|
34 | 34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
35 | 35 | variables (but otherwise includes the information and context given by |
|
36 | 36 | Verbose). |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | Installation instructions for ColorTB: |
|
40 | 40 | import sys,ultratb |
|
41 | 41 | sys.excepthook = ultratb.VerboseTB() |
|
42 | 42 | |
|
43 | 43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
44 | 44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
45 | 45 | |
|
46 | 46 | * Color schemes |
|
47 | 47 | The colors are defined in the class TBTools through the use of the |
|
48 | 48 | ColorSchemeTable class. Currently the following exist: |
|
49 | 49 | |
|
50 | 50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
51 | 51 | escapes are just dummy blank strings). |
|
52 | 52 | |
|
53 | 53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
54 | 54 | or very dark background). |
|
55 | 55 | |
|
56 | 56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
57 | 57 | in light background terminals. |
|
58 | 58 | |
|
59 | 59 | You can implement other color schemes easily, the syntax is fairly |
|
60 | 60 | self-explanatory. Please send back new schemes you develop to the author for |
|
61 | 61 | possible inclusion in future releases. |
|
62 | 62 | """ |
|
63 | 63 | |
|
64 | 64 | #***************************************************************************** |
|
65 | 65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
66 | 66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
67 | 67 | # |
|
68 | 68 | # Distributed under the terms of the BSD License. The full license is in |
|
69 | 69 | # the file COPYING, distributed as part of this software. |
|
70 | 70 | #***************************************************************************** |
|
71 | 71 | |
|
72 | 72 | # Required modules |
|
73 | 73 | import inspect |
|
74 | 74 | import keyword |
|
75 | 75 | import linecache |
|
76 | 76 | import os |
|
77 | 77 | import pydoc |
|
78 | 78 | import re |
|
79 | 79 | import string |
|
80 | 80 | import sys |
|
81 | 81 | import time |
|
82 | 82 | import tokenize |
|
83 | 83 | import traceback |
|
84 | 84 | import types |
|
85 | 85 | |
|
86 | 86 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
87 | 87 | from inspect import getsourcefile, getfile, getmodule,\ |
|
88 | 88 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | # IPython's own modules |
|
92 | 92 | # Modified pdb which doesn't damage IPython's readline handling |
|
93 | 93 | from IPython.utils import PyColorize |
|
94 | 94 | from IPython.core import debugger, ipapi |
|
95 | 95 | from IPython.utils.ipstruct import Struct |
|
96 | 96 | from IPython.core.excolors import exception_colors |
|
97 | 97 | from IPython.utils.genutils import Term,uniq_stable,error,info |
|
98 | 98 | |
|
99 | 99 | # Globals |
|
100 | 100 | # amount of space to put line numbers before verbose tracebacks |
|
101 | 101 | INDENT_SIZE = 8 |
|
102 | 102 | |
|
103 | 103 | # Default color scheme. This is used, for example, by the traceback |
|
104 | 104 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
105 | 105 | # value is used, but havinga module global makes this functionality available |
|
106 | 106 | # to users of ultratb who are NOT running inside ipython. |
|
107 | 107 | DEFAULT_SCHEME = 'NoColor' |
|
108 | 108 | |
|
109 | 109 | #--------------------------------------------------------------------------- |
|
110 | 110 | # Code begins |
|
111 | 111 | |
|
112 | 112 | # Utility functions |
|
113 | 113 | def inspect_error(): |
|
114 | 114 | """Print a message about internal inspect errors. |
|
115 | 115 | |
|
116 | 116 | These are unfortunately quite common.""" |
|
117 | 117 | |
|
118 | 118 | error('Internal Python error in the inspect module.\n' |
|
119 | 119 | 'Below is the traceback from this internal error.\n') |
|
120 | 120 | |
|
121 | 121 | |
|
122 | 122 | def findsource(object): |
|
123 | 123 | """Return the entire source file and starting line number for an object. |
|
124 | 124 | |
|
125 | 125 | The argument may be a module, class, method, function, traceback, frame, |
|
126 | 126 | or code object. The source code is returned as a list of all the lines |
|
127 | 127 | in the file and the line number indexes a line in that list. An IOError |
|
128 | 128 | is raised if the source code cannot be retrieved. |
|
129 | 129 | |
|
130 | 130 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
131 | 131 | |
|
132 | 132 | file = getsourcefile(object) or getfile(object) |
|
133 | 133 | # If the object is a frame, then trying to get the globals dict from its |
|
134 | 134 | # module won't work. Instead, the frame object itself has the globals |
|
135 | 135 | # dictionary. |
|
136 | 136 | globals_dict = None |
|
137 | 137 | if inspect.isframe(object): |
|
138 | 138 | # XXX: can this ever be false? |
|
139 | 139 | globals_dict = object.f_globals |
|
140 | 140 | else: |
|
141 | 141 | module = getmodule(object, file) |
|
142 | 142 | if module: |
|
143 | 143 | globals_dict = module.__dict__ |
|
144 | 144 | lines = linecache.getlines(file, globals_dict) |
|
145 | 145 | if not lines: |
|
146 | 146 | raise IOError('could not get source code') |
|
147 | 147 | |
|
148 | 148 | if ismodule(object): |
|
149 | 149 | return lines, 0 |
|
150 | 150 | |
|
151 | 151 | if isclass(object): |
|
152 | 152 | name = object.__name__ |
|
153 | 153 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
154 | 154 | # make some effort to find the best matching class definition: |
|
155 | 155 | # use the one with the least indentation, which is the one |
|
156 | 156 | # that's most probably not inside a function definition. |
|
157 | 157 | candidates = [] |
|
158 | 158 | for i in range(len(lines)): |
|
159 | 159 | match = pat.match(lines[i]) |
|
160 | 160 | if match: |
|
161 | 161 | # if it's at toplevel, it's already the best one |
|
162 | 162 | if lines[i][0] == 'c': |
|
163 | 163 | return lines, i |
|
164 | 164 | # else add whitespace to candidate list |
|
165 | 165 | candidates.append((match.group(1), i)) |
|
166 | 166 | if candidates: |
|
167 | 167 | # this will sort by whitespace, and by line number, |
|
168 | 168 | # less whitespace first |
|
169 | 169 | candidates.sort() |
|
170 | 170 | return lines, candidates[0][1] |
|
171 | 171 | else: |
|
172 | 172 | raise IOError('could not find class definition') |
|
173 | 173 | |
|
174 | 174 | if ismethod(object): |
|
175 | 175 | object = object.im_func |
|
176 | 176 | if isfunction(object): |
|
177 | 177 | object = object.func_code |
|
178 | 178 | if istraceback(object): |
|
179 | 179 | object = object.tb_frame |
|
180 | 180 | if isframe(object): |
|
181 | 181 | object = object.f_code |
|
182 | 182 | if iscode(object): |
|
183 | 183 | if not hasattr(object, 'co_firstlineno'): |
|
184 | 184 | raise IOError('could not find function definition') |
|
185 | 185 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
186 | 186 | pmatch = pat.match |
|
187 | 187 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
188 | 188 | # the length of lines, which causes an error. Safeguard against that. |
|
189 | 189 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
190 | 190 | while lnum > 0: |
|
191 | 191 | if pmatch(lines[lnum]): break |
|
192 | 192 | lnum -= 1 |
|
193 | 193 | |
|
194 | 194 | return lines, lnum |
|
195 | 195 | raise IOError('could not find code object') |
|
196 | 196 | |
|
197 | 197 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
198 | 198 | if sys.version_info[:2] >= (2,5): |
|
199 | 199 | inspect.findsource = findsource |
|
200 | 200 | |
|
201 | 201 | def fix_frame_records_filenames(records): |
|
202 | 202 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
203 | 203 | |
|
204 | 204 | Particularly, modules loaded from within zip files have useless filenames |
|
205 | 205 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
206 | 206 | """ |
|
207 | 207 | fixed_records = [] |
|
208 | 208 | for frame, filename, line_no, func_name, lines, index in records: |
|
209 | 209 | # Look inside the frame's globals dictionary for __file__, which should |
|
210 | 210 | # be better. |
|
211 | 211 | better_fn = frame.f_globals.get('__file__', None) |
|
212 | 212 | if isinstance(better_fn, str): |
|
213 | 213 | # Check the type just in case someone did something weird with |
|
214 | 214 | # __file__. It might also be None if the error occurred during |
|
215 | 215 | # import. |
|
216 | 216 | filename = better_fn |
|
217 | 217 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
218 | 218 | return fixed_records |
|
219 | 219 | |
|
220 | 220 | |
|
221 | 221 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
222 | 222 | import linecache |
|
223 | 223 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
224 | 224 | |
|
225 | 225 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
226 | 226 | |
|
227 | 227 | # If the error is at the console, don't build any context, since it would |
|
228 | 228 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
229 | 229 | # console) |
|
230 | 230 | rec_check = records[tb_offset:] |
|
231 | 231 | try: |
|
232 | 232 | rname = rec_check[0][1] |
|
233 | 233 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
234 | 234 | return rec_check |
|
235 | 235 | except IndexError: |
|
236 | 236 | pass |
|
237 | 237 | |
|
238 | 238 | aux = traceback.extract_tb(etb) |
|
239 | 239 | assert len(records) == len(aux) |
|
240 | 240 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
241 | 241 | maybeStart = lnum-1 - context//2 |
|
242 | 242 | start = max(maybeStart, 0) |
|
243 | 243 | end = start + context |
|
244 | 244 | lines = linecache.getlines(file)[start:end] |
|
245 | 245 | # pad with empty lines if necessary |
|
246 | 246 | if maybeStart < 0: |
|
247 | 247 | lines = (['\n'] * -maybeStart) + lines |
|
248 | 248 | if len(lines) < context: |
|
249 | 249 | lines += ['\n'] * (context - len(lines)) |
|
250 | 250 | buf = list(records[i]) |
|
251 | 251 | buf[LNUM_POS] = lnum |
|
252 | 252 | buf[INDEX_POS] = lnum - 1 - start |
|
253 | 253 | buf[LINES_POS] = lines |
|
254 | 254 | records[i] = tuple(buf) |
|
255 | 255 | return records[tb_offset:] |
|
256 | 256 | |
|
257 | 257 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
258 | 258 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
259 | 259 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
260 | 260 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
261 | 261 | |
|
262 | 262 | _parser = PyColorize.Parser() |
|
263 | 263 | |
|
264 | 264 | def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
265 | 265 | numbers_width = INDENT_SIZE - 1 |
|
266 | 266 | res = [] |
|
267 | 267 | i = lnum - index |
|
268 | 268 | |
|
269 | 269 | # This lets us get fully syntax-highlighted tracebacks. |
|
270 | 270 | if scheme is None: |
|
271 | 271 | ipinst = ipapi.get() |
|
272 | 272 | if ipinst is not None: |
|
273 |
scheme = ipinst.IP. |
|
|
273 | scheme = ipinst.IP.colors | |
|
274 | 274 | else: |
|
275 | 275 | scheme = DEFAULT_SCHEME |
|
276 | 276 | |
|
277 | 277 | _line_format = _parser.format2 |
|
278 | 278 | |
|
279 | 279 | for line in lines: |
|
280 | 280 | new_line, err = _line_format(line,'str',scheme) |
|
281 | 281 | if not err: line = new_line |
|
282 | 282 | |
|
283 | 283 | if i == lnum: |
|
284 | 284 | # This is the line with the error |
|
285 | 285 | pad = numbers_width - len(str(i)) |
|
286 | 286 | if pad >= 3: |
|
287 | 287 | marker = '-'*(pad-3) + '-> ' |
|
288 | 288 | elif pad == 2: |
|
289 | 289 | marker = '> ' |
|
290 | 290 | elif pad == 1: |
|
291 | 291 | marker = '>' |
|
292 | 292 | else: |
|
293 | 293 | marker = '' |
|
294 | 294 | num = marker + str(i) |
|
295 | 295 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
296 | 296 | Colors.line, line, Colors.Normal) |
|
297 | 297 | else: |
|
298 | 298 | num = '%*s' % (numbers_width,i) |
|
299 | 299 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
300 | 300 | Colors.Normal, line) |
|
301 | 301 | |
|
302 | 302 | res.append(line) |
|
303 | 303 | if lvals and i == lnum: |
|
304 | 304 | res.append(lvals + '\n') |
|
305 | 305 | i = i + 1 |
|
306 | 306 | return res |
|
307 | 307 | |
|
308 | 308 | |
|
309 | 309 | #--------------------------------------------------------------------------- |
|
310 | 310 | # Module classes |
|
311 | 311 | class TBTools: |
|
312 | 312 | """Basic tools used by all traceback printer classes.""" |
|
313 | 313 | |
|
314 | 314 | def __init__(self,color_scheme = 'NoColor',call_pdb=False): |
|
315 | 315 | # Whether to call the interactive pdb debugger after printing |
|
316 | 316 | # tracebacks or not |
|
317 | 317 | self.call_pdb = call_pdb |
|
318 | 318 | |
|
319 | 319 | # Create color table |
|
320 | 320 | self.color_scheme_table = exception_colors() |
|
321 | 321 | |
|
322 | 322 | self.set_colors(color_scheme) |
|
323 | 323 | self.old_scheme = color_scheme # save initial value for toggles |
|
324 | 324 | |
|
325 | 325 | if call_pdb: |
|
326 | 326 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
327 | 327 | else: |
|
328 | 328 | self.pdb = None |
|
329 | 329 | |
|
330 | 330 | def set_colors(self,*args,**kw): |
|
331 | 331 | """Shorthand access to the color table scheme selector method.""" |
|
332 | 332 | |
|
333 | 333 | # Set own color table |
|
334 | 334 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
335 | 335 | # for convenience, set Colors to the active scheme |
|
336 | 336 | self.Colors = self.color_scheme_table.active_colors |
|
337 | 337 | # Also set colors of debugger |
|
338 | 338 | if hasattr(self,'pdb') and self.pdb is not None: |
|
339 | 339 | self.pdb.set_colors(*args,**kw) |
|
340 | 340 | |
|
341 | 341 | def color_toggle(self): |
|
342 | 342 | """Toggle between the currently active color scheme and NoColor.""" |
|
343 | 343 | |
|
344 | 344 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
345 | 345 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
346 | 346 | self.Colors = self.color_scheme_table.active_colors |
|
347 | 347 | else: |
|
348 | 348 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
349 | 349 | self.color_scheme_table.set_active_scheme('NoColor') |
|
350 | 350 | self.Colors = self.color_scheme_table.active_colors |
|
351 | 351 | |
|
352 | 352 | #--------------------------------------------------------------------------- |
|
353 | 353 | class ListTB(TBTools): |
|
354 | 354 | """Print traceback information from a traceback list, with optional color. |
|
355 | 355 | |
|
356 | 356 | Calling: requires 3 arguments: |
|
357 | 357 | (etype, evalue, elist) |
|
358 | 358 | as would be obtained by: |
|
359 | 359 | etype, evalue, tb = sys.exc_info() |
|
360 | 360 | if tb: |
|
361 | 361 | elist = traceback.extract_tb(tb) |
|
362 | 362 | else: |
|
363 | 363 | elist = None |
|
364 | 364 | |
|
365 | 365 | It can thus be used by programs which need to process the traceback before |
|
366 | 366 | printing (such as console replacements based on the code module from the |
|
367 | 367 | standard library). |
|
368 | 368 | |
|
369 | 369 | Because they are meant to be called without a full traceback (only a |
|
370 | 370 | list), instances of this class can't call the interactive pdb debugger.""" |
|
371 | 371 | |
|
372 | 372 | def __init__(self,color_scheme = 'NoColor'): |
|
373 | 373 | TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0) |
|
374 | 374 | |
|
375 | 375 | def __call__(self, etype, value, elist): |
|
376 | 376 | Term.cout.flush() |
|
377 | 377 | print >> Term.cerr, self.text(etype,value,elist) |
|
378 | 378 | Term.cerr.flush() |
|
379 | 379 | |
|
380 | 380 | def text(self,etype, value, elist,context=5): |
|
381 | 381 | """Return a color formatted string with the traceback info.""" |
|
382 | 382 | |
|
383 | 383 | Colors = self.Colors |
|
384 | 384 | out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)] |
|
385 | 385 | if elist: |
|
386 | 386 | out_string.append('Traceback %s(most recent call last)%s:' % \ |
|
387 | 387 | (Colors.normalEm, Colors.Normal) + '\n') |
|
388 | 388 | out_string.extend(self._format_list(elist)) |
|
389 | 389 | lines = self._format_exception_only(etype, value) |
|
390 | 390 | for line in lines[:-1]: |
|
391 | 391 | out_string.append(" "+line) |
|
392 | 392 | out_string.append(lines[-1]) |
|
393 | 393 | return ''.join(out_string) |
|
394 | 394 | |
|
395 | 395 | def _format_list(self, extracted_list): |
|
396 | 396 | """Format a list of traceback entry tuples for printing. |
|
397 | 397 | |
|
398 | 398 | Given a list of tuples as returned by extract_tb() or |
|
399 | 399 | extract_stack(), return a list of strings ready for printing. |
|
400 | 400 | Each string in the resulting list corresponds to the item with the |
|
401 | 401 | same index in the argument list. Each string ends in a newline; |
|
402 | 402 | the strings may contain internal newlines as well, for those items |
|
403 | 403 | whose source text line is not None. |
|
404 | 404 | |
|
405 | 405 | Lifted almost verbatim from traceback.py |
|
406 | 406 | """ |
|
407 | 407 | |
|
408 | 408 | Colors = self.Colors |
|
409 | 409 | list = [] |
|
410 | 410 | for filename, lineno, name, line in extracted_list[:-1]: |
|
411 | 411 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
412 | 412 | (Colors.filename, filename, Colors.Normal, |
|
413 | 413 | Colors.lineno, lineno, Colors.Normal, |
|
414 | 414 | Colors.name, name, Colors.Normal) |
|
415 | 415 | if line: |
|
416 | 416 | item = item + ' %s\n' % line.strip() |
|
417 | 417 | list.append(item) |
|
418 | 418 | # Emphasize the last entry |
|
419 | 419 | filename, lineno, name, line = extracted_list[-1] |
|
420 | 420 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
421 | 421 | (Colors.normalEm, |
|
422 | 422 | Colors.filenameEm, filename, Colors.normalEm, |
|
423 | 423 | Colors.linenoEm, lineno, Colors.normalEm, |
|
424 | 424 | Colors.nameEm, name, Colors.normalEm, |
|
425 | 425 | Colors.Normal) |
|
426 | 426 | if line: |
|
427 | 427 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), |
|
428 | 428 | Colors.Normal) |
|
429 | 429 | list.append(item) |
|
430 | 430 | return list |
|
431 | 431 | |
|
432 | 432 | def _format_exception_only(self, etype, value): |
|
433 | 433 | """Format the exception part of a traceback. |
|
434 | 434 | |
|
435 | 435 | The arguments are the exception type and value such as given by |
|
436 | 436 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
437 | 437 | in a newline. Normally, the list contains a single string; however, |
|
438 | 438 | for SyntaxError exceptions, it contains several lines that (when |
|
439 | 439 | printed) display detailed information about where the syntax error |
|
440 | 440 | occurred. The message indicating which exception occurred is the |
|
441 | 441 | always last string in the list. |
|
442 | 442 | |
|
443 | 443 | Also lifted nearly verbatim from traceback.py |
|
444 | 444 | """ |
|
445 | 445 | |
|
446 | 446 | have_filedata = False |
|
447 | 447 | Colors = self.Colors |
|
448 | 448 | list = [] |
|
449 | 449 | try: |
|
450 | 450 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
451 | 451 | except AttributeError: |
|
452 | 452 | stype = etype # String exceptions don't get special coloring |
|
453 | 453 | if value is None: |
|
454 | 454 | list.append( str(stype) + '\n') |
|
455 | 455 | else: |
|
456 | 456 | if etype is SyntaxError: |
|
457 | 457 | try: |
|
458 | 458 | msg, (filename, lineno, offset, line) = value |
|
459 | 459 | except: |
|
460 | 460 | have_filedata = False |
|
461 | 461 | else: |
|
462 | 462 | have_filedata = True |
|
463 | 463 | #print 'filename is',filename # dbg |
|
464 | 464 | if not filename: filename = "<string>" |
|
465 | 465 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
466 | 466 | (Colors.normalEm, |
|
467 | 467 | Colors.filenameEm, filename, Colors.normalEm, |
|
468 | 468 | Colors.linenoEm, lineno, Colors.Normal )) |
|
469 | 469 | if line is not None: |
|
470 | 470 | i = 0 |
|
471 | 471 | while i < len(line) and line[i].isspace(): |
|
472 | 472 | i = i+1 |
|
473 | 473 | list.append('%s %s%s\n' % (Colors.line, |
|
474 | 474 | line.strip(), |
|
475 | 475 | Colors.Normal)) |
|
476 | 476 | if offset is not None: |
|
477 | 477 | s = ' ' |
|
478 | 478 | for c in line[i:offset-1]: |
|
479 | 479 | if c.isspace(): |
|
480 | 480 | s = s + c |
|
481 | 481 | else: |
|
482 | 482 | s = s + ' ' |
|
483 | 483 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
484 | 484 | Colors.Normal) ) |
|
485 | 485 | value = msg |
|
486 | 486 | s = self._some_str(value) |
|
487 | 487 | if s: |
|
488 | 488 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
489 | 489 | Colors.Normal, s)) |
|
490 | 490 | else: |
|
491 | 491 | list.append('%s\n' % str(stype)) |
|
492 | 492 | |
|
493 | 493 | # vds:>> |
|
494 | 494 | if have_filedata: |
|
495 | 495 | ipinst = ipapi.get() |
|
496 | 496 | if ipinst is not None: |
|
497 | 497 | ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0) |
|
498 | 498 | # vds:<< |
|
499 | 499 | |
|
500 | 500 | return list |
|
501 | 501 | |
|
502 | 502 | def _some_str(self, value): |
|
503 | 503 | # Lifted from traceback.py |
|
504 | 504 | try: |
|
505 | 505 | return str(value) |
|
506 | 506 | except: |
|
507 | 507 | return '<unprintable %s object>' % type(value).__name__ |
|
508 | 508 | |
|
509 | 509 | #---------------------------------------------------------------------------- |
|
510 | 510 | class VerboseTB(TBTools): |
|
511 | 511 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
512 | 512 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
513 | 513 | |
|
514 | 514 | Modified version which optionally strips the topmost entries from the |
|
515 | 515 | traceback, to be used with alternate interpreters (because their own code |
|
516 | 516 | would appear in the traceback).""" |
|
517 | 517 | |
|
518 | 518 | def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0, |
|
519 | 519 | call_pdb = 0, include_vars=1): |
|
520 | 520 | """Specify traceback offset, headers and color scheme. |
|
521 | 521 | |
|
522 | 522 | Define how many frames to drop from the tracebacks. Calling it with |
|
523 | 523 | tb_offset=1 allows use of this handler in interpreters which will have |
|
524 | 524 | their own code at the top of the traceback (VerboseTB will first |
|
525 | 525 | remove that frame before printing the traceback info).""" |
|
526 | 526 | TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb) |
|
527 | 527 | self.tb_offset = tb_offset |
|
528 | 528 | self.long_header = long_header |
|
529 | 529 | self.include_vars = include_vars |
|
530 | 530 | |
|
531 | 531 | def text(self, etype, evalue, etb, context=5): |
|
532 | 532 | """Return a nice text document describing the traceback.""" |
|
533 | 533 | |
|
534 | 534 | # some locals |
|
535 | 535 | try: |
|
536 | 536 | etype = etype.__name__ |
|
537 | 537 | except AttributeError: |
|
538 | 538 | pass |
|
539 | 539 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
540 | 540 | ColorsNormal = Colors.Normal # used a lot |
|
541 | 541 | col_scheme = self.color_scheme_table.active_scheme_name |
|
542 | 542 | indent = ' '*INDENT_SIZE |
|
543 | 543 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
544 | 544 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
545 | 545 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
546 | 546 | |
|
547 | 547 | # some internal-use functions |
|
548 | 548 | def text_repr(value): |
|
549 | 549 | """Hopefully pretty robust repr equivalent.""" |
|
550 | 550 | # this is pretty horrible but should always return *something* |
|
551 | 551 | try: |
|
552 | 552 | return pydoc.text.repr(value) |
|
553 | 553 | except KeyboardInterrupt: |
|
554 | 554 | raise |
|
555 | 555 | except: |
|
556 | 556 | try: |
|
557 | 557 | return repr(value) |
|
558 | 558 | except KeyboardInterrupt: |
|
559 | 559 | raise |
|
560 | 560 | except: |
|
561 | 561 | try: |
|
562 | 562 | # all still in an except block so we catch |
|
563 | 563 | # getattr raising |
|
564 | 564 | name = getattr(value, '__name__', None) |
|
565 | 565 | if name: |
|
566 | 566 | # ick, recursion |
|
567 | 567 | return text_repr(name) |
|
568 | 568 | klass = getattr(value, '__class__', None) |
|
569 | 569 | if klass: |
|
570 | 570 | return '%s instance' % text_repr(klass) |
|
571 | 571 | except KeyboardInterrupt: |
|
572 | 572 | raise |
|
573 | 573 | except: |
|
574 | 574 | return 'UNRECOVERABLE REPR FAILURE' |
|
575 | 575 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
576 | 576 | def nullrepr(value, repr=text_repr): return '' |
|
577 | 577 | |
|
578 | 578 | # meat of the code begins |
|
579 | 579 | try: |
|
580 | 580 | etype = etype.__name__ |
|
581 | 581 | except AttributeError: |
|
582 | 582 | pass |
|
583 | 583 | |
|
584 | 584 | if self.long_header: |
|
585 | 585 | # Header with the exception type, python version, and date |
|
586 | 586 | pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable |
|
587 | 587 | date = time.ctime(time.time()) |
|
588 | 588 | |
|
589 | 589 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
590 | 590 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
591 | 591 | pyver, string.rjust(date, 75) ) |
|
592 | 592 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
593 | 593 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
594 | 594 | else: |
|
595 | 595 | # Simplified header |
|
596 | 596 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
597 | 597 | string.rjust('Traceback (most recent call last)', |
|
598 | 598 | 75 - len(str(etype)) ) ) |
|
599 | 599 | frames = [] |
|
600 | 600 | # Flush cache before calling inspect. This helps alleviate some of the |
|
601 | 601 | # problems with python 2.3's inspect.py. |
|
602 | 602 | linecache.checkcache() |
|
603 | 603 | # Drop topmost frames if requested |
|
604 | 604 | try: |
|
605 | 605 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
606 | 606 | # problems, but it generates empty tracebacks for console errors |
|
607 | 607 | # (5 blanks lines) where none should be returned. |
|
608 | 608 | #records = inspect.getinnerframes(etb, context)[self.tb_offset:] |
|
609 | 609 | #print 'python records:', records # dbg |
|
610 | 610 | records = _fixed_getinnerframes(etb, context,self.tb_offset) |
|
611 | 611 | #print 'alex records:', records # dbg |
|
612 | 612 | except: |
|
613 | 613 | |
|
614 | 614 | # FIXME: I've been getting many crash reports from python 2.3 |
|
615 | 615 | # users, traceable to inspect.py. If I can find a small test-case |
|
616 | 616 | # to reproduce this, I should either write a better workaround or |
|
617 | 617 | # file a bug report against inspect (if that's the real problem). |
|
618 | 618 | # So far, I haven't been able to find an isolated example to |
|
619 | 619 | # reproduce the problem. |
|
620 | 620 | inspect_error() |
|
621 | 621 | traceback.print_exc(file=Term.cerr) |
|
622 | 622 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
623 | 623 | return '' |
|
624 | 624 | |
|
625 | 625 | # build some color string templates outside these nested loops |
|
626 | 626 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
627 | 627 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
628 | 628 | ColorsNormal) |
|
629 | 629 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
630 | 630 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
631 | 631 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
632 | 632 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
633 | 633 | Colors.vName, ColorsNormal) |
|
634 | 634 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
635 | 635 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
636 | 636 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
637 | 637 | ColorsNormal) |
|
638 | 638 | |
|
639 | 639 | # now, loop over all records printing context and info |
|
640 | 640 | abspath = os.path.abspath |
|
641 | 641 | for frame, file, lnum, func, lines, index in records: |
|
642 | 642 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
643 | 643 | try: |
|
644 | 644 | file = file and abspath(file) or '?' |
|
645 | 645 | except OSError: |
|
646 | 646 | # if file is '<console>' or something not in the filesystem, |
|
647 | 647 | # the abspath call will throw an OSError. Just ignore it and |
|
648 | 648 | # keep the original file string. |
|
649 | 649 | pass |
|
650 | 650 | link = tpl_link % file |
|
651 | 651 | try: |
|
652 | 652 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
653 | 653 | except: |
|
654 | 654 | # This can happen due to a bug in python2.3. We should be |
|
655 | 655 | # able to remove this try/except when 2.4 becomes a |
|
656 | 656 | # requirement. Bug details at http://python.org/sf/1005466 |
|
657 | 657 | inspect_error() |
|
658 | 658 | traceback.print_exc(file=Term.cerr) |
|
659 | 659 | info("\nIPython's exception reporting continues...\n") |
|
660 | 660 | |
|
661 | 661 | if func == '?': |
|
662 | 662 | call = '' |
|
663 | 663 | else: |
|
664 | 664 | # Decide whether to include variable details or not |
|
665 | 665 | var_repr = self.include_vars and eqrepr or nullrepr |
|
666 | 666 | try: |
|
667 | 667 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
668 | 668 | varargs, varkw, |
|
669 | 669 | locals,formatvalue=var_repr)) |
|
670 | 670 | except KeyError: |
|
671 | 671 | # Very odd crash from inspect.formatargvalues(). The |
|
672 | 672 | # scenario under which it appeared was a call to |
|
673 | 673 | # view(array,scale) in NumTut.view.view(), where scale had |
|
674 | 674 | # been defined as a scalar (it should be a tuple). Somehow |
|
675 | 675 | # inspect messes up resolving the argument list of view() |
|
676 | 676 | # and barfs out. At some point I should dig into this one |
|
677 | 677 | # and file a bug report about it. |
|
678 | 678 | inspect_error() |
|
679 | 679 | traceback.print_exc(file=Term.cerr) |
|
680 | 680 | info("\nIPython's exception reporting continues...\n") |
|
681 | 681 | call = tpl_call_fail % func |
|
682 | 682 | |
|
683 | 683 | # Initialize a list of names on the current line, which the |
|
684 | 684 | # tokenizer below will populate. |
|
685 | 685 | names = [] |
|
686 | 686 | |
|
687 | 687 | def tokeneater(token_type, token, start, end, line): |
|
688 | 688 | """Stateful tokeneater which builds dotted names. |
|
689 | 689 | |
|
690 | 690 | The list of names it appends to (from the enclosing scope) can |
|
691 | 691 | contain repeated composite names. This is unavoidable, since |
|
692 | 692 | there is no way to disambguate partial dotted structures until |
|
693 | 693 | the full list is known. The caller is responsible for pruning |
|
694 | 694 | the final list of duplicates before using it.""" |
|
695 | 695 | |
|
696 | 696 | # build composite names |
|
697 | 697 | if token == '.': |
|
698 | 698 | try: |
|
699 | 699 | names[-1] += '.' |
|
700 | 700 | # store state so the next token is added for x.y.z names |
|
701 | 701 | tokeneater.name_cont = True |
|
702 | 702 | return |
|
703 | 703 | except IndexError: |
|
704 | 704 | pass |
|
705 | 705 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
706 | 706 | if tokeneater.name_cont: |
|
707 | 707 | # Dotted names |
|
708 | 708 | names[-1] += token |
|
709 | 709 | tokeneater.name_cont = False |
|
710 | 710 | else: |
|
711 | 711 | # Regular new names. We append everything, the caller |
|
712 | 712 | # will be responsible for pruning the list later. It's |
|
713 | 713 | # very tricky to try to prune as we go, b/c composite |
|
714 | 714 | # names can fool us. The pruning at the end is easy |
|
715 | 715 | # to do (or the caller can print a list with repeated |
|
716 | 716 | # names if so desired. |
|
717 | 717 | names.append(token) |
|
718 | 718 | elif token_type == tokenize.NEWLINE: |
|
719 | 719 | raise IndexError |
|
720 | 720 | # we need to store a bit of state in the tokenizer to build |
|
721 | 721 | # dotted names |
|
722 | 722 | tokeneater.name_cont = False |
|
723 | 723 | |
|
724 | 724 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
725 | 725 | line = getline(file, lnum[0]) |
|
726 | 726 | lnum[0] += 1 |
|
727 | 727 | return line |
|
728 | 728 | |
|
729 | 729 | # Build the list of names on this line of code where the exception |
|
730 | 730 | # occurred. |
|
731 | 731 | try: |
|
732 | 732 | # This builds the names list in-place by capturing it from the |
|
733 | 733 | # enclosing scope. |
|
734 | 734 | tokenize.tokenize(linereader, tokeneater) |
|
735 | 735 | except IndexError: |
|
736 | 736 | # signals exit of tokenizer |
|
737 | 737 | pass |
|
738 | 738 | except tokenize.TokenError,msg: |
|
739 | 739 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
740 | 740 | "The following traceback may be corrupted or invalid\n" |
|
741 | 741 | "The error message is: %s\n" % msg) |
|
742 | 742 | error(_m) |
|
743 | 743 | |
|
744 | 744 | # prune names list of duplicates, but keep the right order |
|
745 | 745 | unique_names = uniq_stable(names) |
|
746 | 746 | |
|
747 | 747 | # Start loop over vars |
|
748 | 748 | lvals = [] |
|
749 | 749 | if self.include_vars: |
|
750 | 750 | for name_full in unique_names: |
|
751 | 751 | name_base = name_full.split('.',1)[0] |
|
752 | 752 | if name_base in frame.f_code.co_varnames: |
|
753 | 753 | if locals.has_key(name_base): |
|
754 | 754 | try: |
|
755 | 755 | value = repr(eval(name_full,locals)) |
|
756 | 756 | except: |
|
757 | 757 | value = undefined |
|
758 | 758 | else: |
|
759 | 759 | value = undefined |
|
760 | 760 | name = tpl_local_var % name_full |
|
761 | 761 | else: |
|
762 | 762 | if frame.f_globals.has_key(name_base): |
|
763 | 763 | try: |
|
764 | 764 | value = repr(eval(name_full,frame.f_globals)) |
|
765 | 765 | except: |
|
766 | 766 | value = undefined |
|
767 | 767 | else: |
|
768 | 768 | value = undefined |
|
769 | 769 | name = tpl_global_var % name_full |
|
770 | 770 | lvals.append(tpl_name_val % (name,value)) |
|
771 | 771 | if lvals: |
|
772 | 772 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
773 | 773 | else: |
|
774 | 774 | lvals = '' |
|
775 | 775 | |
|
776 | 776 | level = '%s %s\n' % (link,call) |
|
777 | 777 | |
|
778 | 778 | if index is None: |
|
779 | 779 | frames.append(level) |
|
780 | 780 | else: |
|
781 | 781 | frames.append('%s%s' % (level,''.join( |
|
782 | 782 | _formatTracebackLines(lnum,index,lines,Colors,lvals, |
|
783 | 783 | col_scheme)))) |
|
784 | 784 | |
|
785 | 785 | # Get (safely) a string form of the exception info |
|
786 | 786 | try: |
|
787 | 787 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
788 | 788 | except: |
|
789 | 789 | # User exception is improperly defined. |
|
790 | 790 | etype,evalue = str,sys.exc_info()[:2] |
|
791 | 791 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
792 | 792 | # ... and format it |
|
793 | 793 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
794 | 794 | ColorsNormal, evalue_str)] |
|
795 | 795 | if type(evalue) is types.InstanceType: |
|
796 | 796 | try: |
|
797 | 797 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
798 | 798 | except: |
|
799 | 799 | # Every now and then, an object with funny inernals blows up |
|
800 | 800 | # when dir() is called on it. We do the best we can to report |
|
801 | 801 | # the problem and continue |
|
802 | 802 | _m = '%sException reporting error (object with broken dir())%s:' |
|
803 | 803 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
804 | 804 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
805 | 805 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
806 | 806 | ColorsNormal, evalue_str)) |
|
807 | 807 | names = [] |
|
808 | 808 | for name in names: |
|
809 | 809 | value = text_repr(getattr(evalue, name)) |
|
810 | 810 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
811 | 811 | |
|
812 | 812 | # vds: >> |
|
813 | 813 | if records: |
|
814 | 814 | filepath, lnum = records[-1][1:3] |
|
815 | 815 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
816 | 816 | filepath = os.path.abspath(filepath) |
|
817 | 817 | ipinst = ipapi.get() |
|
818 | 818 | if ipinst is not None: |
|
819 | 819 | ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
820 | 820 | # vds: << |
|
821 | 821 | |
|
822 | 822 | # return all our info assembled as a single string |
|
823 | 823 | return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
824 | 824 | |
|
825 | 825 | def debugger(self,force=False): |
|
826 | 826 | """Call up the pdb debugger if desired, always clean up the tb |
|
827 | 827 | reference. |
|
828 | 828 | |
|
829 | 829 | Keywords: |
|
830 | 830 | |
|
831 | 831 | - force(False): by default, this routine checks the instance call_pdb |
|
832 | 832 | flag and does not actually invoke the debugger if the flag is false. |
|
833 | 833 | The 'force' option forces the debugger to activate even if the flag |
|
834 | 834 | is false. |
|
835 | 835 | |
|
836 | 836 | If the call_pdb flag is set, the pdb interactive debugger is |
|
837 | 837 | invoked. In all cases, the self.tb reference to the current traceback |
|
838 | 838 | is deleted to prevent lingering references which hamper memory |
|
839 | 839 | management. |
|
840 | 840 | |
|
841 | 841 | Note that each call to pdb() does an 'import readline', so if your app |
|
842 | 842 | requires a special setup for the readline completers, you'll have to |
|
843 | 843 | fix that by hand after invoking the exception handler.""" |
|
844 | 844 | |
|
845 | 845 | if force or self.call_pdb: |
|
846 | 846 | if self.pdb is None: |
|
847 | 847 | self.pdb = debugger.Pdb( |
|
848 | 848 | self.color_scheme_table.active_scheme_name) |
|
849 | 849 | # the system displayhook may have changed, restore the original |
|
850 | 850 | # for pdb |
|
851 | 851 | dhook = sys.displayhook |
|
852 | 852 | sys.displayhook = sys.__displayhook__ |
|
853 | 853 | self.pdb.reset() |
|
854 | 854 | # Find the right frame so we don't pop up inside ipython itself |
|
855 | 855 | if hasattr(self,'tb'): |
|
856 | 856 | etb = self.tb |
|
857 | 857 | else: |
|
858 | 858 | etb = self.tb = sys.last_traceback |
|
859 | 859 | while self.tb.tb_next is not None: |
|
860 | 860 | self.tb = self.tb.tb_next |
|
861 | 861 | try: |
|
862 | 862 | if etb and etb.tb_next: |
|
863 | 863 | etb = etb.tb_next |
|
864 | 864 | self.pdb.botframe = etb.tb_frame |
|
865 | 865 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
866 | 866 | finally: |
|
867 | 867 | sys.displayhook = dhook |
|
868 | 868 | |
|
869 | 869 | if hasattr(self,'tb'): |
|
870 | 870 | del self.tb |
|
871 | 871 | |
|
872 | 872 | def handler(self, info=None): |
|
873 | 873 | (etype, evalue, etb) = info or sys.exc_info() |
|
874 | 874 | self.tb = etb |
|
875 | 875 | Term.cout.flush() |
|
876 | 876 | print >> Term.cerr, self.text(etype, evalue, etb) |
|
877 | 877 | Term.cerr.flush() |
|
878 | 878 | |
|
879 | 879 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
880 | 880 | # out the right info on its own. |
|
881 | 881 | def __call__(self, etype=None, evalue=None, etb=None): |
|
882 | 882 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
883 | 883 | if etb is None: |
|
884 | 884 | self.handler() |
|
885 | 885 | else: |
|
886 | 886 | self.handler((etype, evalue, etb)) |
|
887 | 887 | try: |
|
888 | 888 | self.debugger() |
|
889 | 889 | except KeyboardInterrupt: |
|
890 | 890 | print "\nKeyboardInterrupt" |
|
891 | 891 | |
|
892 | 892 | #---------------------------------------------------------------------------- |
|
893 | 893 | class FormattedTB(VerboseTB,ListTB): |
|
894 | 894 | """Subclass ListTB but allow calling with a traceback. |
|
895 | 895 | |
|
896 | 896 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
897 | 897 | |
|
898 | 898 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
899 | 899 | |
|
900 | 900 | Allows a tb_offset to be specified. This is useful for situations where |
|
901 | 901 | one needs to remove a number of topmost frames from the traceback (such as |
|
902 | 902 | occurs with python programs that themselves execute other python code, |
|
903 | 903 | like Python shells). """ |
|
904 | 904 | |
|
905 | 905 | def __init__(self, mode = 'Plain', color_scheme='Linux', |
|
906 | 906 | tb_offset = 0,long_header=0,call_pdb=0,include_vars=0): |
|
907 | 907 | |
|
908 | 908 | # NEVER change the order of this list. Put new modes at the end: |
|
909 | 909 | self.valid_modes = ['Plain','Context','Verbose'] |
|
910 | 910 | self.verbose_modes = self.valid_modes[1:3] |
|
911 | 911 | |
|
912 | 912 | VerboseTB.__init__(self,color_scheme,tb_offset,long_header, |
|
913 | 913 | call_pdb=call_pdb,include_vars=include_vars) |
|
914 | 914 | self.set_mode(mode) |
|
915 | 915 | |
|
916 | 916 | def _extract_tb(self,tb): |
|
917 | 917 | if tb: |
|
918 | 918 | return traceback.extract_tb(tb) |
|
919 | 919 | else: |
|
920 | 920 | return None |
|
921 | 921 | |
|
922 | 922 | def text(self, etype, value, tb,context=5,mode=None): |
|
923 | 923 | """Return formatted traceback. |
|
924 | 924 | |
|
925 | 925 | If the optional mode parameter is given, it overrides the current |
|
926 | 926 | mode.""" |
|
927 | 927 | |
|
928 | 928 | if mode is None: |
|
929 | 929 | mode = self.mode |
|
930 | 930 | if mode in self.verbose_modes: |
|
931 | 931 | # verbose modes need a full traceback |
|
932 | 932 | return VerboseTB.text(self,etype, value, tb,context=5) |
|
933 | 933 | else: |
|
934 | 934 | # We must check the source cache because otherwise we can print |
|
935 | 935 | # out-of-date source code. |
|
936 | 936 | linecache.checkcache() |
|
937 | 937 | # Now we can extract and format the exception |
|
938 | 938 | elist = self._extract_tb(tb) |
|
939 | 939 | if len(elist) > self.tb_offset: |
|
940 | 940 | del elist[:self.tb_offset] |
|
941 | 941 | return ListTB.text(self,etype,value,elist) |
|
942 | 942 | |
|
943 | 943 | def set_mode(self,mode=None): |
|
944 | 944 | """Switch to the desired mode. |
|
945 | 945 | |
|
946 | 946 | If mode is not specified, cycles through the available modes.""" |
|
947 | 947 | |
|
948 | 948 | if not mode: |
|
949 | 949 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
950 | 950 | len(self.valid_modes) |
|
951 | 951 | self.mode = self.valid_modes[new_idx] |
|
952 | 952 | elif mode not in self.valid_modes: |
|
953 | 953 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ |
|
954 | 954 | 'Valid modes: '+str(self.valid_modes) |
|
955 | 955 | else: |
|
956 | 956 | self.mode = mode |
|
957 | 957 | # include variable details only in 'Verbose' mode |
|
958 | 958 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
959 | 959 | |
|
960 | 960 | # some convenient shorcuts |
|
961 | 961 | def plain(self): |
|
962 | 962 | self.set_mode(self.valid_modes[0]) |
|
963 | 963 | |
|
964 | 964 | def context(self): |
|
965 | 965 | self.set_mode(self.valid_modes[1]) |
|
966 | 966 | |
|
967 | 967 | def verbose(self): |
|
968 | 968 | self.set_mode(self.valid_modes[2]) |
|
969 | 969 | |
|
970 | 970 | #---------------------------------------------------------------------------- |
|
971 | 971 | class AutoFormattedTB(FormattedTB): |
|
972 | 972 | """A traceback printer which can be called on the fly. |
|
973 | 973 | |
|
974 | 974 | It will find out about exceptions by itself. |
|
975 | 975 | |
|
976 | 976 | A brief example: |
|
977 | 977 | |
|
978 | 978 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
979 | 979 | try: |
|
980 | 980 | ... |
|
981 | 981 | except: |
|
982 | 982 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
983 | 983 | """ |
|
984 | 984 | def __call__(self,etype=None,evalue=None,etb=None, |
|
985 | 985 | out=None,tb_offset=None): |
|
986 | 986 | """Print out a formatted exception traceback. |
|
987 | 987 | |
|
988 | 988 | Optional arguments: |
|
989 | 989 | - out: an open file-like object to direct output to. |
|
990 | 990 | |
|
991 | 991 | - tb_offset: the number of frames to skip over in the stack, on a |
|
992 | 992 | per-call basis (this overrides temporarily the instance's tb_offset |
|
993 | 993 | given at initialization time. """ |
|
994 | 994 | |
|
995 | 995 | if out is None: |
|
996 | 996 | out = Term.cerr |
|
997 | 997 | Term.cout.flush() |
|
998 | 998 | if tb_offset is not None: |
|
999 | 999 | tb_offset, self.tb_offset = self.tb_offset, tb_offset |
|
1000 | 1000 | print >> out, self.text(etype, evalue, etb) |
|
1001 | 1001 | self.tb_offset = tb_offset |
|
1002 | 1002 | else: |
|
1003 | 1003 | print >> out, self.text(etype, evalue, etb) |
|
1004 | 1004 | out.flush() |
|
1005 | 1005 | try: |
|
1006 | 1006 | self.debugger() |
|
1007 | 1007 | except KeyboardInterrupt: |
|
1008 | 1008 | print "\nKeyboardInterrupt" |
|
1009 | 1009 | |
|
1010 | 1010 | def text(self,etype=None,value=None,tb=None,context=5,mode=None): |
|
1011 | 1011 | if etype is None: |
|
1012 | 1012 | etype,value,tb = sys.exc_info() |
|
1013 | 1013 | self.tb = tb |
|
1014 | 1014 | return FormattedTB.text(self,etype,value,tb,context=5,mode=mode) |
|
1015 | 1015 | |
|
1016 | 1016 | #--------------------------------------------------------------------------- |
|
1017 | 1017 | # A simple class to preserve Nathan's original functionality. |
|
1018 | 1018 | class ColorTB(FormattedTB): |
|
1019 | 1019 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1020 | 1020 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1021 | 1021 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1022 | 1022 | call_pdb=call_pdb) |
|
1023 | 1023 | |
|
1024 | 1024 | #---------------------------------------------------------------------------- |
|
1025 | 1025 | # module testing (minimal) |
|
1026 | 1026 | if __name__ == "__main__": |
|
1027 | 1027 | def spam(c, (d, e)): |
|
1028 | 1028 | x = c + d |
|
1029 | 1029 | y = c * d |
|
1030 | 1030 | foo(x, y) |
|
1031 | 1031 | |
|
1032 | 1032 | def foo(a, b, bar=1): |
|
1033 | 1033 | eggs(a, b + bar) |
|
1034 | 1034 | |
|
1035 | 1035 | def eggs(f, g, z=globals()): |
|
1036 | 1036 | h = f + g |
|
1037 | 1037 | i = f - g |
|
1038 | 1038 | return h / i |
|
1039 | 1039 | |
|
1040 | 1040 | print '' |
|
1041 | 1041 | print '*** Before ***' |
|
1042 | 1042 | try: |
|
1043 | 1043 | print spam(1, (2, 3)) |
|
1044 | 1044 | except: |
|
1045 | 1045 | traceback.print_exc() |
|
1046 | 1046 | print '' |
|
1047 | 1047 | |
|
1048 | 1048 | handler = ColorTB() |
|
1049 | 1049 | print '*** ColorTB ***' |
|
1050 | 1050 | try: |
|
1051 | 1051 | print spam(1, (2, 3)) |
|
1052 | 1052 | except: |
|
1053 | 1053 | apply(handler, sys.exc_info() ) |
|
1054 | 1054 | print '' |
|
1055 | 1055 | |
|
1056 | 1056 | handler = VerboseTB() |
|
1057 | 1057 | print '*** VerboseTB ***' |
|
1058 | 1058 | try: |
|
1059 | 1059 | print spam(1, (2, 3)) |
|
1060 | 1060 | except: |
|
1061 | 1061 | apply(handler, sys.exc_info() ) |
|
1062 | 1062 | print '' |
|
1063 | 1063 |
@@ -1,558 +1,586 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 | import sys | |
|
10 | from IPython.core import release | |
|
11 | ||
|
9 | 12 | __doc__ = """ |
|
10 | 13 | IPython -- An enhanced Interactive Python |
|
11 | 14 | ========================================= |
|
12 | 15 | |
|
13 | 16 | A Python shell with automatic history (input and output), dynamic object |
|
14 | 17 | introspection, easier configuration, command completion, access to the system |
|
15 | 18 | shell and more. |
|
16 | 19 | |
|
17 | 20 | IPython can also be embedded in running programs. See EMBEDDING below. |
|
18 | 21 | |
|
19 | 22 | |
|
20 | 23 | USAGE |
|
21 | 24 | ipython [options] files |
|
22 | 25 | |
|
23 | 26 | If invoked with no options, it executes all the files listed in |
|
24 | 27 | sequence and drops you into the interpreter while still acknowledging |
|
25 | 28 | any options you may have set in your ipythonrc file. This behavior is |
|
26 | 29 | different from standard Python, which when called as python -i will |
|
27 | 30 | only execute one file and will ignore your configuration setup. |
|
28 | 31 | |
|
29 | 32 | Please note that some of the configuration options are not available at |
|
30 | 33 | the command line, simply because they are not practical here. Look into |
|
31 | 34 | your ipythonrc configuration file for details on those. This file |
|
32 | 35 | typically installed in the $HOME/.ipython directory. |
|
33 | 36 | |
|
34 | 37 | For Windows users, $HOME resolves to C:\\Documents and |
|
35 | 38 | Settings\\YourUserName in most instances, and _ipython is used instead |
|
36 | 39 | of .ipython, since some Win32 programs have problems with dotted names |
|
37 | 40 | in directories. |
|
38 | 41 | |
|
39 | 42 | In the rest of this text, we will refer to this directory as |
|
40 | 43 | IPYTHONDIR. |
|
41 | 44 | |
|
42 | 45 | REGULAR OPTIONS |
|
43 | 46 | After the above threading options have been given, regular options can |
|
44 | 47 | follow in any order. All options can be abbreviated to their shortest |
|
45 | 48 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
46 | 49 | used. Some options have an alternate short form, indicated after a |. |
|
47 | 50 | |
|
48 | 51 | Most options can also be set from your ipythonrc configuration file. |
|
49 | 52 | See the provided examples for assistance. Options given on the comman- |
|
50 | 53 | dline override the values set in the ipythonrc file. |
|
51 | 54 | |
|
52 | 55 | All options with a [no] prepended can be specified in negated form |
|
53 | 56 | (using -nooption instead of -option) to turn the feature off. |
|
54 | 57 | |
|
55 | 58 | -h, --help |
|
56 | 59 | Show summary of options. |
|
57 | 60 | |
|
58 | 61 | -autocall <val> |
|
59 | 62 | Make IPython automatically call any callable object even if you |
|
60 | 63 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
61 | 64 | 'str(43)' automatically. The value can be '0' to disable the |
|
62 | 65 | feature, '1' for 'smart' autocall, where it is not applied if |
|
63 | 66 | there are no more arguments on the line, and '2' for 'full' |
|
64 | 67 | autocall, where all callable objects are automatically called |
|
65 | 68 | (even if no arguments are present). The default is '1'. |
|
66 | 69 | |
|
67 | 70 | -[no]autoindent |
|
68 | 71 | Turn automatic indentation on/off. |
|
69 | 72 | |
|
70 | 73 | -[no]automagic |
|
71 | 74 | Make magic commands automatic (without needing their first char- |
|
72 | 75 | acter to be %). Type %magic at the IPython prompt for more |
|
73 | 76 | information. |
|
74 | 77 | |
|
75 | 78 | -[no]autoedit_syntax |
|
76 | 79 | When a syntax error occurs after editing a file, automatically |
|
77 | 80 | open the file to the trouble causing line for convenient fixing. |
|
78 | 81 | |
|
79 | 82 | -[no]banner |
|
80 | 83 | Print the intial information banner (default on). |
|
81 | 84 | |
|
82 | 85 | -c <command> |
|
83 | 86 | Execute the given command string, and set sys.argv to ['c']. |
|
84 | 87 | This is similar to the -c option in the normal Python inter- |
|
85 | 88 | preter. |
|
86 | 89 | |
|
87 | 90 | -cache_size|cs <n> |
|
88 | 91 | Size of the output cache (maximum number of entries to hold in |
|
89 | 92 | memory). The default is 1000, you can change it permanently in |
|
90 | 93 | your config file. Setting it to 0 completely disables the |
|
91 | 94 | caching system, and the minimum value accepted is 20 (if you |
|
92 | 95 | provide a value less than 20, it is reset to 0 and a warning is |
|
93 | 96 | issued). This limit is defined because otherwise you'll spend |
|
94 | 97 | more time re-flushing a too small cache than working. |
|
95 | 98 | |
|
96 | 99 | -classic|cl |
|
97 | 100 | Gives IPython a similar feel to the classic Python prompt. |
|
98 | 101 | |
|
99 | 102 | -colors <scheme> |
|
100 | 103 | Color scheme for prompts and exception reporting. Currently |
|
101 | 104 | implemented: NoColor, Linux, and LightBG. |
|
102 | 105 | |
|
103 | 106 | -[no]color_info |
|
104 | 107 | IPython can display information about objects via a set of func- |
|
105 | 108 | tions, and optionally can use colors for this, syntax highlight- |
|
106 | 109 | ing source code and various other elements. However, because |
|
107 | 110 | this information is passed through a pager (like 'less') and |
|
108 | 111 | many pagers get confused with color codes, this option is off by |
|
109 | 112 | default. You can test it and turn it on permanently in your |
|
110 | 113 | ipythonrc file if it works for you. As a reference, the 'less' |
|
111 | 114 | pager supplied with Mandrake 8.2 works ok, but that in RedHat |
|
112 | 115 | 7.2 doesn't. |
|
113 | 116 | |
|
114 | 117 | Test it and turn it on permanently if it works with your system. |
|
115 | 118 | The magic function @color_info allows you to toggle this inter- |
|
116 | 119 | actively for testing. |
|
117 | 120 | |
|
118 | 121 | -[no]confirm_exit |
|
119 | 122 | Set to confirm when you try to exit IPython with an EOF (Con- |
|
120 | 123 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the |
|
121 | 124 | magic functions @Exit or @Quit you can force a direct exit, |
|
122 | 125 | bypassing any confirmation. |
|
123 | 126 | |
|
124 | 127 | -[no]debug |
|
125 | 128 | Show information about the loading process. Very useful to pin |
|
126 | 129 | down problems with your configuration files or to get details |
|
127 | 130 | about session restores. |
|
128 | 131 | |
|
129 | 132 | -[no]deep_reload |
|
130 | 133 | IPython can use the deep_reload module which reloads changes in |
|
131 | 134 | modules recursively (it replaces the reload() function, so you |
|
132 | 135 | don't need to change anything to use it). deep_reload() forces a |
|
133 | 136 | full reload of modules whose code may have changed, which the |
|
134 | 137 | default reload() function does not. |
|
135 | 138 | |
|
136 | 139 | When deep_reload is off, IPython will use the normal reload(), |
|
137 | 140 | but deep_reload will still be available as dreload(). This fea- |
|
138 | 141 | ture is off by default [which means that you have both normal |
|
139 | 142 | reload() and dreload()]. |
|
140 | 143 | |
|
141 | 144 | -editor <name> |
|
142 | 145 | Which editor to use with the @edit command. By default, IPython |
|
143 | 146 | will honor your EDITOR environment variable (if not set, vi is |
|
144 | 147 | the Unix default and notepad the Windows one). Since this editor |
|
145 | 148 | is invoked on the fly by IPython and is meant for editing small |
|
146 | 149 | code snippets, you may want to use a small, lightweight editor |
|
147 | 150 | here (in case your default EDITOR is something like Emacs). |
|
148 | 151 | |
|
149 | 152 | -ipythondir <name> |
|
150 | 153 | The name of your IPython configuration directory IPYTHONDIR. |
|
151 | 154 | This can also be specified through the environment variable |
|
152 | 155 | IPYTHONDIR. |
|
153 | 156 | |
|
154 | 157 | -log|l Generate a log file of all input. The file is named |
|
155 | 158 | ipython_log.py in your current directory (which prevents logs |
|
156 | 159 | from multiple IPython sessions from trampling each other). You |
|
157 | 160 | can use this to later restore a session by loading your logfile |
|
158 | 161 | as a file to be executed with option -logplay (see below). |
|
159 | 162 | |
|
160 | 163 | -logfile|lf |
|
161 | 164 | Specify the name of your logfile. |
|
162 | 165 | |
|
163 | 166 | -logplay|lp |
|
164 | 167 | Replay a previous log. For restoring a session as close as pos- |
|
165 | 168 | sible to the state you left it in, use this option (don't just |
|
166 | 169 | run the logfile). With -logplay, IPython will try to reconstruct |
|
167 | 170 | the previous working environment in full, not just execute the |
|
168 | 171 | commands in the logfile. |
|
169 | 172 | When a session is restored, logging is automatically turned on |
|
170 | 173 | again with the name of the logfile it was invoked with (it is |
|
171 | 174 | read from the log header). So once you've turned logging on for |
|
172 | 175 | a session, you can quit IPython and reload it as many times as |
|
173 | 176 | you want and it will continue to log its history and restore |
|
174 | 177 | from the beginning every time. |
|
175 | 178 | |
|
176 | 179 | Caveats: there are limitations in this option. The history vari- |
|
177 | 180 | ables _i*,_* and _dh don't get restored properly. In the future |
|
178 | 181 | we will try to implement full session saving by writing and |
|
179 | 182 | retrieving a failed because of inherent limitations of Python's |
|
180 | 183 | Pickle module, so this may have to wait. |
|
181 | 184 | |
|
182 | 185 | -[no]messages |
|
183 | 186 | Print messages which IPython collects about its startup process |
|
184 | 187 | (default on). |
|
185 | 188 | |
|
186 | 189 | -[no]pdb |
|
187 | 190 | Automatically call the pdb debugger after every uncaught excep- |
|
188 | 191 | tion. If you are used to debugging using pdb, this puts you |
|
189 | 192 | automatically inside of it after any call (either in IPython or |
|
190 | 193 | in code called by it) which triggers an exception which goes |
|
191 | 194 | uncaught. |
|
192 | 195 | |
|
193 | 196 | -[no]pprint |
|
194 | 197 | IPython can optionally use the pprint (pretty printer) module |
|
195 | 198 | for displaying results. pprint tends to give a nicer display of |
|
196 | 199 | nested data structures. If you like it, you can turn it on per- |
|
197 | 200 | manently in your config file (default off). |
|
198 | 201 | |
|
199 | 202 | -profile|p <name> |
|
200 | 203 | Assume that your config file is ipythonrc-<name> (looks in cur- |
|
201 | 204 | rent dir first, then in IPYTHONDIR). This is a quick way to keep |
|
202 | 205 | and load multiple config files for different tasks, especially |
|
203 | 206 | if you use the include option of config files. You can keep a |
|
204 | 207 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' |
|
205 | 208 | which include this one and load extra things for particular |
|
206 | 209 | tasks. For example: |
|
207 | 210 | |
|
208 | 211 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. |
|
209 | 212 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- |
|
210 | 213 | related modules. |
|
211 | 214 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and |
|
212 | 215 | plotting modules. |
|
213 | 216 | |
|
214 | 217 | Since it is possible to create an endless loop by having circu- |
|
215 | 218 | lar file inclusions, IPython will stop if it reaches 15 recur- |
|
216 | 219 | sive inclusions. |
|
217 | 220 | |
|
218 | 221 | -prompt_in1|pi1 <string> |
|
219 | 222 | Specify the string used for input prompts. Note that if you are |
|
220 | 223 | using numbered prompts, the number is represented with a '\#' in |
|
221 | 224 | the string. Don't forget to quote strings with spaces embedded |
|
222 | 225 | in them. Default: 'In [\#]: '. |
|
223 | 226 | |
|
224 | 227 | Most bash-like escapes can be used to customize IPython's |
|
225 | 228 | prompts, as well as a few additional ones which are IPython-spe- |
|
226 | 229 | cific. All valid prompt escapes are described in detail in the |
|
227 | 230 | Customization section of the IPython HTML/PDF manual. |
|
228 | 231 | |
|
229 | 232 | -prompt_in2|pi2 <string> |
|
230 | 233 | Similar to the previous option, but used for the continuation |
|
231 | 234 | prompts. The special sequence '\D' is similar to '\#', but with |
|
232 | 235 | all digits replaced dots (so you can have your continuation |
|
233 | 236 | prompt aligned with your input prompt). Default: ' .\D.: ' |
|
234 | 237 | (note three spaces at the start for alignment with 'In [\#]'). |
|
235 | 238 | |
|
236 | 239 | -prompt_out|po <string> |
|
237 | 240 | String used for output prompts, also uses numbers like |
|
238 | 241 | prompt_in1. Default: 'Out[\#]:'. |
|
239 | 242 | |
|
240 | 243 | -quick Start in bare bones mode (no config file loaded). |
|
241 | 244 | |
|
242 | 245 | -rcfile <name> |
|
243 | 246 | Name of your IPython resource configuration file. normally |
|
244 | 247 | IPython loads ipythonrc (from current directory) or |
|
245 | 248 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, |
|
246 | 249 | IPython starts with a bare bones configuration (no modules |
|
247 | 250 | loaded at all). |
|
248 | 251 | |
|
249 | 252 | -[no]readline |
|
250 | 253 | Use the readline library, which is needed to support name com- |
|
251 | 254 | pletion and command history, among other things. It is enabled |
|
252 | 255 | by default, but may cause problems for users of X/Emacs in |
|
253 | 256 | Python comint or shell buffers. |
|
254 | 257 | |
|
255 | 258 | Note that emacs 'eterm' buffers (opened with M-x term) support |
|
256 | 259 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
257 | 260 | shell and C-c !) buffers do not. |
|
258 | 261 | |
|
259 | 262 | -screen_length|sl <n> |
|
260 | 263 | Number of lines of your screen. This is used to control print- |
|
261 | 264 | ing of very long strings. Strings longer than this number of |
|
262 | 265 | lines will be sent through a pager instead of directly printed. |
|
263 | 266 | |
|
264 | 267 | The default value for this is 0, which means IPython will auto- |
|
265 | 268 | detect your screen size every time it needs to print certain |
|
266 | 269 | potentially long strings (this doesn't change the behavior of |
|
267 | 270 | the 'print' keyword, it's only triggered internally). If for |
|
268 | 271 | some reason this isn't working well (it needs curses support), |
|
269 | 272 | specify it yourself. Otherwise don't change the default. |
|
270 | 273 | |
|
271 | 274 | -separate_in|si <string> |
|
272 | 275 | Separator before input prompts. Default '0. |
|
273 | 276 | |
|
274 | 277 | -separate_out|so <string> |
|
275 | 278 | Separator before output prompts. Default: 0 (nothing). |
|
276 | 279 | |
|
277 | 280 | -separate_out2|so2 <string> |
|
278 | 281 | Separator after output prompts. Default: 0 (nothing). |
|
279 | 282 | |
|
280 | 283 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. |
|
281 | 284 | Simply removes all input/output separators. |
|
282 | 285 | |
|
283 | 286 | -upgrade |
|
284 | 287 | Allows you to upgrade your IPYTHONDIR configuration when you |
|
285 | 288 | install a new version of IPython. Since new versions may |
|
286 | 289 | include new command lines options or example files, this copies |
|
287 | 290 | updated ipythonrc-type files. However, it backs up (with a .old |
|
288 | 291 | extension) all files which it overwrites so that you can merge |
|
289 | 292 | back any custimizations you might have in your personal files. |
|
290 | 293 | |
|
291 | 294 | -Version |
|
292 | 295 | Print version information and exit. |
|
293 | 296 | |
|
294 | 297 | -wxversion <string> |
|
295 | 298 | Select a specific version of wxPython (used in conjunction with |
|
296 | 299 | -wthread). Requires the wxversion module, part of recent |
|
297 | 300 | wxPython distributions. |
|
298 | 301 | |
|
299 | 302 | -xmode <modename> |
|
300 | 303 | Mode for exception reporting. The valid modes are Plain, Con- |
|
301 | 304 | text, and Verbose. |
|
302 | 305 | |
|
303 | 306 | - Plain: similar to python's normal traceback printing. |
|
304 | 307 | |
|
305 | 308 | - Context: prints 5 lines of context source code around each |
|
306 | 309 | line in the traceback. |
|
307 | 310 | |
|
308 | 311 | - Verbose: similar to Context, but additionally prints the vari- |
|
309 | 312 | ables currently visible where the exception happened (shortening |
|
310 | 313 | their strings if too long). This can potentially be very slow, |
|
311 | 314 | if you happen to have a huge data structure whose string repre- |
|
312 | 315 | sentation is complex to compute. Your computer may appear to |
|
313 | 316 | freeze for a while with cpu usage at 100%. If this occurs, you |
|
314 | 317 | can cancel the traceback with Ctrl-C (maybe hitting it more than |
|
315 | 318 | once). |
|
316 | 319 | |
|
317 | 320 | |
|
318 | 321 | EMBEDDING |
|
319 | 322 | It is possible to start an IPython instance inside your own Python pro- |
|
320 | 323 | grams. In the documentation example files there are some illustrations |
|
321 | 324 | on how to do this. |
|
322 | 325 | |
|
323 | 326 | This feature allows you to evalutate dynamically the state of your |
|
324 | 327 | code, operate with your variables, analyze them, etc. Note however |
|
325 | 328 | that any changes you make to values while in the shell do NOT propagate |
|
326 | 329 | back to the running code, so it is safe to modify your values because |
|
327 | 330 | you won't break your code in bizarre ways by doing so. |
|
328 | 331 | """ |
|
329 | 332 | |
|
330 | 333 | cmd_line_usage = __doc__ |
|
331 | 334 | |
|
332 | 335 | #--------------------------------------------------------------------------- |
|
333 | 336 | interactive_usage = """ |
|
334 | 337 | IPython -- An enhanced Interactive Python |
|
335 | 338 | ========================================= |
|
336 | 339 | |
|
337 | 340 | IPython offers a combination of convenient shell features, special commands |
|
338 | 341 | and a history mechanism for both input (command history) and output (results |
|
339 | 342 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
340 | 343 | replacement for the standard Python interpreter, while offering vastly |
|
341 | 344 | improved functionality and flexibility. |
|
342 | 345 | |
|
343 | 346 | At your system command line, type 'ipython -help' to see the command line |
|
344 | 347 | options available. This document only describes interactive features. |
|
345 | 348 | |
|
346 | 349 | Warning: IPython relies on the existence of a global variable called __IP which |
|
347 | 350 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
348 | 351 | will quickly occur. |
|
349 | 352 | |
|
350 | 353 | MAIN FEATURES |
|
351 | 354 | |
|
352 | 355 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
353 | 356 | available with access to object docstrings and the Python manuals. Simply |
|
354 | 357 | type 'help' (no quotes) to access it. |
|
355 | 358 | |
|
356 | 359 | * Magic commands: type %magic for information on the magic subsystem. |
|
357 | 360 | |
|
358 | 361 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
359 | 362 | |
|
360 | 363 | * Dynamic object information: |
|
361 | 364 | |
|
362 | 365 | Typing ?word or word? prints detailed information about an object. If |
|
363 | 366 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
364 | 367 | snipped in the center for brevity. |
|
365 | 368 | |
|
366 | 369 | Typing ??word or word?? gives access to the full information without |
|
367 | 370 | snipping long strings. Long strings are sent to the screen through the less |
|
368 | 371 | pager if longer than the screen, printed otherwise. |
|
369 | 372 | |
|
370 | 373 | The ?/?? system gives access to the full source code for any object (if |
|
371 | 374 | available), shows function prototypes and other useful information. |
|
372 | 375 | |
|
373 | 376 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
374 | 377 | quotes, and without % if you have automagic on). |
|
375 | 378 | |
|
376 | 379 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
377 | 380 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
378 | 381 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
379 | 382 | similarly. |
|
380 | 383 | |
|
381 | 384 | * Completion in the local namespace, by typing TAB at the prompt. |
|
382 | 385 | |
|
383 | 386 | At any time, hitting tab will complete any available python commands or |
|
384 | 387 | variable names, and show you a list of the possible completions if there's |
|
385 | 388 | no unambiguous one. It will also complete filenames in the current directory. |
|
386 | 389 | |
|
387 | 390 | This feature requires the readline and rlcomplete modules, so it won't work |
|
388 | 391 | if your Python lacks readline support (such as under Windows). |
|
389 | 392 | |
|
390 | 393 | * Search previous command history in two ways (also requires readline): |
|
391 | 394 | |
|
392 | 395 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
393 | 396 | search through only the history items that match what you've typed so |
|
394 | 397 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
395 | 398 | normal arrow keys. |
|
396 | 399 | |
|
397 | 400 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
398 | 401 | your history for lines that match what you've typed so far, completing as |
|
399 | 402 | much as it can. |
|
400 | 403 | |
|
401 | 404 | * Persistent command history across sessions (readline required). |
|
402 | 405 | |
|
403 | 406 | * Logging of input with the ability to save and restore a working session. |
|
404 | 407 | |
|
405 | 408 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
406 | 409 | |
|
407 | 410 | * The reload command does a 'deep' reload of a module: changes made to the |
|
408 | 411 | module since you imported will actually be available without having to exit. |
|
409 | 412 | |
|
410 | 413 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
411 | 414 | xcolor functions for details (just type %magic). |
|
412 | 415 | |
|
413 | 416 | * Input caching system: |
|
414 | 417 | |
|
415 | 418 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
416 | 419 | input is saved and can be retrieved as variables (besides the usual arrow |
|
417 | 420 | key recall). |
|
418 | 421 | |
|
419 | 422 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
420 | 423 | _i: stores previous input. |
|
421 | 424 | _ii: next previous. |
|
422 | 425 | _iii: next-next previous. |
|
423 | 426 | _ih : a list of all input _ih[n] is the input from line n. |
|
424 | 427 | |
|
425 | 428 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
426 | 429 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
427 | 430 | |
|
428 | 431 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
429 | 432 | |
|
430 | 433 | You can create macros which contain multiple input lines from this history, |
|
431 | 434 | for later re-execution, with the %macro function. |
|
432 | 435 | |
|
433 | 436 | The history function %hist allows you to see any part of your input history |
|
434 | 437 | by printing a range of the _i variables. Note that inputs which contain |
|
435 | 438 | magic functions (%) appear in the history with a prepended comment. This is |
|
436 | 439 | because they aren't really valid Python code, so you can't exec them. |
|
437 | 440 | |
|
438 | 441 | * Output caching system: |
|
439 | 442 | |
|
440 | 443 | For output that is returned from actions, a system similar to the input |
|
441 | 444 | cache exists but using _ instead of _i. Only actions that produce a result |
|
442 | 445 | (NOT assignments, for example) are cached. If you are familiar with |
|
443 | 446 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
444 | 447 | variables. |
|
445 | 448 | |
|
446 | 449 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
447 | 450 | _ (one underscore): previous output. |
|
448 | 451 | __ (two underscores): next previous. |
|
449 | 452 | ___ (three underscores): next-next previous. |
|
450 | 453 | |
|
451 | 454 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
452 | 455 | counter), such that the result of output <n> is always available as _<n>. |
|
453 | 456 | |
|
454 | 457 | Finally, a global dictionary named _oh exists with entries for all lines |
|
455 | 458 | which generated output. |
|
456 | 459 | |
|
457 | 460 | * Directory history: |
|
458 | 461 | |
|
459 | 462 | Your history of visited directories is kept in the global list _dh, and the |
|
460 | 463 | magic %cd command can be used to go to any entry in that list. |
|
461 | 464 | |
|
462 | 465 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
463 | 466 | |
|
464 | 467 | 1. Auto-parentheses |
|
465 | 468 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
466 | 469 | this (notice the commas between the arguments): |
|
467 | 470 | >>> callable_ob arg1, arg2, arg3 |
|
468 | 471 | and the input will be translated to this: |
|
469 | 472 | --> callable_ob(arg1, arg2, arg3) |
|
470 | 473 | You can force auto-parentheses by using '/' as the first character |
|
471 | 474 | of a line. For example: |
|
472 | 475 | >>> /globals # becomes 'globals()' |
|
473 | 476 | Note that the '/' MUST be the first character on the line! This |
|
474 | 477 | won't work: |
|
475 | 478 | >>> print /globals # syntax error |
|
476 | 479 | |
|
477 | 480 | In most cases the automatic algorithm should work, so you should |
|
478 | 481 | rarely need to explicitly invoke /. One notable exception is if you |
|
479 | 482 | are trying to call a function with a list of tuples as arguments (the |
|
480 | 483 | parenthesis will confuse IPython): |
|
481 | 484 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
482 | 485 | but this will work: |
|
483 | 486 | In [2]: /zip (1,2,3),(4,5,6) |
|
484 | 487 | ------> zip ((1,2,3),(4,5,6)) |
|
485 | 488 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
486 | 489 | |
|
487 | 490 | IPython tells you that it has altered your command line by |
|
488 | 491 | displaying the new command line preceded by -->. e.g.: |
|
489 | 492 | In [18]: callable list |
|
490 | 493 | -------> callable (list) |
|
491 | 494 | |
|
492 | 495 | 2. Auto-Quoting |
|
493 | 496 | You can force auto-quoting of a function's arguments by using ',' as |
|
494 | 497 | the first character of a line. For example: |
|
495 | 498 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
496 | 499 | |
|
497 | 500 | If you use ';' instead, the whole argument is quoted as a single |
|
498 | 501 | string (while ',' splits on whitespace): |
|
499 | 502 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
500 | 503 | >>> ;my_function a b c # becomes my_function("a b c") |
|
501 | 504 | |
|
502 | 505 | Note that the ',' MUST be the first character on the line! This |
|
503 | 506 | won't work: |
|
504 | 507 | >>> x = ,my_function /home/me # syntax error |
|
505 | 508 | """ |
|
506 | 509 | |
|
510 | interactive_usage_min = """\ | |
|
511 | An enhanced console for Python. | |
|
512 | Some of its features are: | |
|
513 | - Readline support if the readline library is present. | |
|
514 | - Tab completion in the local namespace. | |
|
515 | - Logging of input, see command-line options. | |
|
516 | - System shell escape via ! , eg !ls. | |
|
517 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
|
518 | - Keeps track of locally defined variables via %who, %whos. | |
|
519 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
|
520 | """ | |
|
521 | ||
|
507 | 522 | quick_reference = r""" |
|
508 | 523 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
509 | 524 | ================================================================ |
|
510 | 525 | |
|
511 | 526 | obj?, obj?? : Get help, or more help for object (also works as |
|
512 | 527 | ?obj, ??obj). |
|
513 | 528 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
514 | 529 | %magic : Information about IPython's 'magic' % functions. |
|
515 | 530 | |
|
516 | 531 | Magic functions are prefixed by %, and typically take their arguments without |
|
517 | 532 | parentheses, quotes or even commas for convenience. |
|
518 | 533 | |
|
519 | 534 | Example magic function calls: |
|
520 | 535 | |
|
521 | 536 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
522 | 537 | alias d ls -F : Works if 'alias' not a python name |
|
523 | 538 | alist = %alias : Get list of aliases to 'alist' |
|
524 | 539 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
525 | 540 | %cd?? : See help AND source for magic %cd |
|
526 | 541 | |
|
527 | 542 | System commands: |
|
528 | 543 | |
|
529 | 544 | !cp a.txt b/ : System command escape, calls os.system() |
|
530 | 545 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
531 | 546 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
532 | 547 | files = !ls /usr : Capture sytem command output |
|
533 | 548 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
534 | 549 | |
|
535 | 550 | History: |
|
536 | 551 | |
|
537 | 552 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
538 | 553 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
539 | 554 | exec _i81 : Execute input history line #81 again |
|
540 | 555 | %rep 81 : Edit input history line #81 |
|
541 | 556 | _, __, ___ : previous, next previous, next next previous output |
|
542 | 557 | _dh : Directory history |
|
543 | 558 | _oh : Output history |
|
544 | 559 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
545 | 560 | |
|
546 | 561 | Autocall: |
|
547 | 562 | |
|
548 | 563 | f 1,2 : f(1,2) |
|
549 | 564 | /f 1,2 : f(1,2) (forced autoparen) |
|
550 | 565 | ,f 1 2 : f("1","2") |
|
551 | 566 | ;f 1 2 : f("1 2") |
|
552 | 567 | |
|
553 | 568 | Remember: TAB completion works in many contexts, not just file names |
|
554 | 569 | or python names. |
|
555 | 570 | |
|
556 | 571 | The following magic functions are currently available: |
|
557 | 572 | |
|
558 | 573 | """ |
|
574 | ||
|
575 | quick_guide = """\ | |
|
576 | ? -> Introduction and overview of IPython's features. | |
|
577 | %quickref -> Quick reference. | |
|
578 | help -> Python's own help system. | |
|
579 | object? -> Details about 'object'. ?object also works, ?? prints more.""" | |
|
580 | ||
|
581 | banner_parts = [ | |
|
582 | 'Python %s' % (sys.version.split('\n')[0],), | |
|
583 | 'Type "copyright", "credits" or "license" for more information.\n', | |
|
584 | 'IPython %s -- An enhanced Interactive Python.' % (release.version,), | |
|
585 | quick_guide | |
|
586 | ] |
@@ -1,245 +1,245 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 | ip = ipapi.get() |
|
20 | 20 | |
|
21 | 21 | import shutil,os,shlex |
|
22 | 22 | from IPython.external import mglob |
|
23 | 23 | from IPython.external.path import path |
|
24 | 24 | from IPython.core.ipapi import UsageError |
|
25 | 25 | import IPython.utils.generics |
|
26 | 26 | |
|
27 | 27 | def parse_args(args): |
|
28 | 28 | """ Given arg string 'CMD files... target', return ([files], target) """ |
|
29 | 29 | |
|
30 | 30 | tup = args.split(None, 1) |
|
31 | 31 | if len(tup) == 1: |
|
32 | 32 | raise UsageError("Expected arguments for " + tup[0]) |
|
33 | 33 | |
|
34 | 34 | tup2 = shlex.split(tup[1]) |
|
35 | 35 | |
|
36 | 36 | flist, trg = mglob.expand(tup2[0:-1]), tup2[-1] |
|
37 | 37 | if not flist: |
|
38 | 38 | raise UsageError("No files found:" + str(tup2[0:-1])) |
|
39 | 39 | return flist, trg |
|
40 | 40 | |
|
41 | 41 | def icp(ip,arg): |
|
42 | 42 | """ icp files... targetdir |
|
43 | 43 | |
|
44 | 44 | Copy all files to target, creating dirs for target if necessary |
|
45 | 45 | |
|
46 | 46 | icp srcdir dstdir |
|
47 | 47 | |
|
48 | 48 | Copy srcdir to distdir |
|
49 | 49 | |
|
50 | 50 | """ |
|
51 | 51 | import distutils.dir_util |
|
52 | 52 | |
|
53 | 53 | fs, targetdir = parse_args(arg) |
|
54 | 54 | if not os.path.isdir(targetdir) and len(fs) > 1: |
|
55 | 55 | distutils.dir_util.mkpath(targetdir,verbose =1) |
|
56 | 56 | for f in fs: |
|
57 | 57 | if os.path.isdir(f): |
|
58 | 58 | shutil.copytree(f, targetdir) |
|
59 | 59 | else: |
|
60 | 60 | shutil.copy2(f,targetdir) |
|
61 | 61 | return fs |
|
62 | 62 | ip.defalias("icp",icp) |
|
63 | 63 | |
|
64 | 64 | def imv(ip,arg): |
|
65 | 65 | """ imv src tgt |
|
66 | 66 | |
|
67 | 67 | Move source to target. |
|
68 | 68 | """ |
|
69 | 69 | |
|
70 | 70 | fs, target = parse_args(arg) |
|
71 | 71 | if len(fs) > 1: |
|
72 | 72 | assert os.path.isdir(target) |
|
73 | 73 | for f in fs: |
|
74 | 74 | shutil.move(f, target) |
|
75 | 75 | return fs |
|
76 | 76 | ip.defalias("imv",imv) |
|
77 | 77 | |
|
78 | 78 | def irm(ip,arg): |
|
79 | 79 | """ irm path[s]... |
|
80 | 80 | |
|
81 | 81 | Remove file[s] or dir[s] path. Dirs are deleted recursively. |
|
82 | 82 | """ |
|
83 | 83 | try: |
|
84 | 84 | paths = mglob.expand(arg.split(None,1)[1]) |
|
85 | 85 | except IndexError: |
|
86 | 86 | raise UsageError("%irm paths...") |
|
87 | 87 | import distutils.dir_util |
|
88 | 88 | for p in paths: |
|
89 | 89 | print "rm",p |
|
90 | 90 | if os.path.isdir(p): |
|
91 | 91 | distutils.dir_util.remove_tree(p, verbose = 1) |
|
92 | 92 | else: |
|
93 | 93 | os.remove(p) |
|
94 | 94 | |
|
95 | 95 | ip.defalias("irm",irm) |
|
96 | 96 | |
|
97 | 97 | def imkdir(ip,arg): |
|
98 | 98 | """ imkdir path |
|
99 | 99 | |
|
100 | 100 | Creates dir path, and all dirs on the road |
|
101 | 101 | """ |
|
102 | 102 | import distutils.dir_util |
|
103 | 103 | targetdir = arg.split(None,1)[1] |
|
104 | 104 | distutils.dir_util.mkpath(targetdir,verbose =1) |
|
105 | 105 | |
|
106 | 106 | ip.defalias("imkdir",imkdir) |
|
107 | 107 | |
|
108 | 108 | def igrep(ip,arg): |
|
109 | 109 | """ igrep PAT files... |
|
110 | 110 | |
|
111 | 111 | Very dumb file scan, case-insensitive. |
|
112 | 112 | |
|
113 | 113 | e.g. |
|
114 | 114 | |
|
115 | 115 | igrep "test this" rec:*.py |
|
116 | 116 | |
|
117 | 117 | """ |
|
118 | 118 | elems = shlex.split(arg) |
|
119 | 119 | dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:]) |
|
120 | 120 | res = [] |
|
121 | 121 | for f in fs: |
|
122 | 122 | found = False |
|
123 | 123 | for l in open(f): |
|
124 | 124 | if pat.lower() in l.lower(): |
|
125 | 125 | if not found: |
|
126 | 126 | print "[[",f,"]]" |
|
127 | 127 | found = True |
|
128 | 128 | res.append(f) |
|
129 | 129 | print l.rstrip() |
|
130 | 130 | return res |
|
131 | 131 | |
|
132 | 132 | ip.defalias("igrep",igrep) |
|
133 | 133 | |
|
134 | 134 | def collect(ip,arg): |
|
135 | 135 | """ collect foo/a.txt rec:bar=*.py |
|
136 | 136 | |
|
137 | 137 | Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar, |
|
138 | 138 | likewise |
|
139 | 139 | |
|
140 | 140 | Without args, try to open ~/_ipython/collect dir (in win32 at least). |
|
141 | 141 | """ |
|
142 | 142 | from IPython.external.path import path |
|
143 |
basedir = path(ip.options. |
|
|
143 | basedir = path(ip.options.IPYTHONDIR + '/collect') | |
|
144 | 144 | try: |
|
145 | 145 | fs = mglob.expand(arg.split(None,1)[1]) |
|
146 | 146 | except IndexError: |
|
147 | 147 | os.startfile(basedir) |
|
148 | 148 | return |
|
149 | 149 | for f in fs: |
|
150 | 150 | f = path(f) |
|
151 | 151 | trg = basedir / f.splitdrive()[1].lstrip('/\\') |
|
152 | 152 | if f.isdir(): |
|
153 | 153 | print "mkdir",trg |
|
154 | 154 | trg.makedirs() |
|
155 | 155 | continue |
|
156 | 156 | dname = trg.dirname() |
|
157 | 157 | if not dname.isdir(): |
|
158 | 158 | dname.makedirs() |
|
159 | 159 | print f,"=>",trg |
|
160 | 160 | shutil.copy2(f,trg) |
|
161 | 161 | |
|
162 | 162 | ip.defalias("collect",collect) |
|
163 | 163 | |
|
164 | 164 | def inote(ip,arg): |
|
165 | 165 | """ inote Hello world |
|
166 | 166 | |
|
167 | 167 | Adds timestamp and Hello world to ~/_ipython/notes.txt |
|
168 | 168 | |
|
169 | 169 | Without args, opens notes.txt for editing. |
|
170 | 170 | """ |
|
171 | 171 | import time |
|
172 |
fname = ip.options. |
|
|
172 | fname = ip.options.IPYTHONDIR + '/notes.txt' | |
|
173 | 173 | |
|
174 | 174 | try: |
|
175 | 175 | entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n' |
|
176 | 176 | f= open(fname, 'a').write(entry) |
|
177 | 177 | except IndexError: |
|
178 | 178 | ip.IP.hooks.editor(fname) |
|
179 | 179 | |
|
180 | 180 | ip.defalias("inote",inote) |
|
181 | 181 | |
|
182 | 182 | def pathobj_mangle(p): |
|
183 | 183 | return p.replace(' ', '__').replace('.','DOT') |
|
184 | 184 | def pathobj_unmangle(s): |
|
185 | 185 | return s.replace('__',' ').replace('DOT','.') |
|
186 | 186 | |
|
187 | 187 | |
|
188 | 188 | |
|
189 | 189 | class PathObj(path): |
|
190 | 190 | def __init__(self,p): |
|
191 | 191 | self.path = p |
|
192 | 192 | if p != '.': |
|
193 | 193 | self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)] |
|
194 | 194 | else: |
|
195 | 195 | self.ents = None |
|
196 | 196 | def __complete__(self): |
|
197 | 197 | if self.path != '.': |
|
198 | 198 | return self.ents |
|
199 | 199 | self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')] |
|
200 | 200 | return self.ents |
|
201 | 201 | def __getattr__(self,name): |
|
202 | 202 | if name in self.ents: |
|
203 | 203 | if self.path.endswith('/'): |
|
204 | 204 | sep = '' |
|
205 | 205 | else: |
|
206 | 206 | sep = '/' |
|
207 | 207 | |
|
208 | 208 | tgt = self.path + sep + pathobj_unmangle(name) |
|
209 | 209 | #print "tgt",tgt |
|
210 | 210 | if os.path.isdir(tgt): |
|
211 | 211 | return PathObj(tgt) |
|
212 | 212 | if os.path.isfile(tgt): |
|
213 | 213 | return path(tgt) |
|
214 | 214 | |
|
215 | 215 | raise AttributeError, name # <<< DON'T FORGET THIS LINE !! |
|
216 | 216 | def __str__(self): |
|
217 | 217 | return self.path |
|
218 | 218 | |
|
219 | 219 | def __repr__(self): |
|
220 | 220 | return "<PathObj to %s>" % self.path |
|
221 | 221 | |
|
222 | 222 | def __call__(self): |
|
223 | 223 | print "cd:",self.path |
|
224 | 224 | os.chdir(self.path) |
|
225 | 225 | |
|
226 | 226 | def complete_pathobj(obj, prev_completions): |
|
227 | 227 | if hasattr(obj,'__complete__'): |
|
228 | 228 | res = obj.__complete__() |
|
229 | 229 | if res: |
|
230 | 230 | return res |
|
231 | 231 | # just return normal attributes of 'path' object if the dir is empty |
|
232 | 232 | raise ipapi.TryNext |
|
233 | 233 | |
|
234 | 234 | complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj) |
|
235 | 235 | |
|
236 | 236 | def test_pathobj(): |
|
237 | 237 | #p = PathObj('c:/prj') |
|
238 | 238 | #p2 = p.cgi |
|
239 | 239 | #print p,p2 |
|
240 | 240 | rootdir = PathObj("/") |
|
241 | 241 | startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs") |
|
242 | 242 | cwd = PathObj('.') |
|
243 | 243 | ip.to_user_ns("rootdir startmenu cwd") |
|
244 | 244 | |
|
245 | 245 | #test_pathobj() No newline at end of file |
@@ -1,31 +1,31 b'' | |||
|
1 | 1 | import inspect |
|
2 | 2 | from IPython.core import ipapi |
|
3 | 3 | from IPython.utils.genutils import arg_split |
|
4 | 4 | ip = ipapi.get() |
|
5 | 5 | |
|
6 | 6 | from IPython.core import debugger |
|
7 | 7 | |
|
8 | 8 | def call_pydb(self, args): |
|
9 | 9 | """Invoke pydb with the supplied parameters.""" |
|
10 | 10 | try: |
|
11 | 11 | import pydb |
|
12 | 12 | except ImportError: |
|
13 | 13 | raise ImportError("pydb doesn't seem to be installed.") |
|
14 | 14 | |
|
15 | 15 | if not hasattr(pydb.pydb, "runv"): |
|
16 | 16 | raise ImportError("You need pydb version 1.19 or later installed.") |
|
17 | 17 | |
|
18 | 18 | argl = arg_split(args) |
|
19 | 19 | # print argl # dbg |
|
20 | 20 | if len(inspect.getargspec(pydb.runv)[0]) == 2: |
|
21 |
pdb = debugger.Pdb(color_scheme=self. |
|
|
21 | pdb = debugger.Pdb(color_scheme=self.colors) | |
|
22 | 22 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )() |
|
23 | 23 | else: |
|
24 | 24 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )() |
|
25 | 25 | |
|
26 | 26 | |
|
27 | 27 | ip.expose_magic("pydb",call_pydb) |
|
28 | 28 | |
|
29 | 29 | |
|
30 | 30 | |
|
31 | 31 |
|
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: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now