##// END OF EJS Templates
Massive, crazy refactoring of everything....
Brian Granger -
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 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """A factory for creating configuration objects.
3 """A factory for creating configuration objects.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19
19
20 from IPython.external import argparse
20 from IPython.external import argparse
21 from IPython.utils.ipstruct import Struct
21 from IPython.utils.ipstruct import Struct
22 from IPython.utils.genutils import filefind
22 from IPython.utils.genutils import filefind
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 class ConfigLoaderError(Exception):
29 class ConfigLoaderError(Exception):
30 pass
30 pass
31
31
32
32
33 class ConfigLoader(object):
33 class ConfigLoader(object):
34 """A object for loading configurations from just about anywhere.
34 """A object for loading configurations from just about anywhere.
35
35
36 The resulting configuration is packaged as a :class:`Struct`.
36 The resulting configuration is packaged as a :class:`Struct`.
37
37
38 Notes
38 Notes
39 -----
39 -----
40 A :class:`ConfigLoader` does one thing: load a config from a source
40 A :class:`ConfigLoader` does one thing: load a config from a source
41 (file, command line arguments) and returns the data as a :class:`Struct`.
41 (file, command line arguments) and returns the data as a :class:`Struct`.
42 There are lots of things that :class:`ConfigLoader` does not do. It does
42 There are lots of things that :class:`ConfigLoader` does not do. It does
43 not implement complex logic for finding config files. It does not handle
43 not implement complex logic for finding config files. It does not handle
44 default values or merge multiple configs. These things need to be
44 default values or merge multiple configs. These things need to be
45 handled elsewhere.
45 handled elsewhere.
46 """
46 """
47
47
48 def __init__(self):
48 def __init__(self):
49 """A base class for config loaders.
49 """A base class for config loaders.
50
50
51 Examples
51 Examples
52 --------
52 --------
53
53
54 >>> cl = ConfigLoader()
54 >>> cl = ConfigLoader()
55 >>> config = cl.load_config()
55 >>> config = cl.load_config()
56 >>> config
56 >>> config
57 {}
57 {}
58 """
58 """
59 self.clear()
59 self.clear()
60
60
61 def clear(self):
61 def clear(self):
62 self.config = Struct()
62 self.config = Struct()
63
63
64 def load_config(self):
64 def load_config(self):
65 """Load a config from somewhere, return a Struct.
65 """Load a config from somewhere, return a Struct.
66
66
67 Usually, this will cause self.config to be set and then returned.
67 Usually, this will cause self.config to be set and then returned.
68 """
68 """
69 return self.config
69 return self.config
70
70
71
71
72 class FileConfigLoader(ConfigLoader):
72 class FileConfigLoader(ConfigLoader):
73 """A base class for file based configurations.
73 """A base class for file based configurations.
74
74
75 As we add more file based config loaders, the common logic should go
75 As we add more file based config loaders, the common logic should go
76 here.
76 here.
77 """
77 """
78 pass
78 pass
79
79
80
80
81 class PyFileConfigLoader(FileConfigLoader):
81 class PyFileConfigLoader(FileConfigLoader):
82 """A config loader for pure python files.
82 """A config loader for pure python files.
83
83
84 This calls execfile on a plain python file and looks for attributes
84 This calls execfile on a plain python file and looks for attributes
85 that are all caps. These attribute are added to the config Struct.
85 that are all caps. These attribute are added to the config Struct.
86 """
86 """
87
87
88 def __init__(self, filename, path=None):
88 def __init__(self, filename, path=None):
89 """Build a config loader for a filename and path.
89 """Build a config loader for a filename and path.
90
90
91 Parameters
91 Parameters
92 ----------
92 ----------
93 filename : str
93 filename : str
94 The file name of the config file.
94 The file name of the config file.
95 path : str, list, tuple
95 path : str, list, tuple
96 The path to search for the config file on, or a sequence of
96 The path to search for the config file on, or a sequence of
97 paths to try in order.
97 paths to try in order.
98 """
98 """
99 super(PyFileConfigLoader, self).__init__()
99 super(PyFileConfigLoader, self).__init__()
100 self.filename = filename
100 self.filename = filename
101 self.path = path
101 self.path = path
102 self.full_filename = ''
102 self.full_filename = ''
103 self.data = None
103 self.data = None
104
104
105 def load_config(self):
105 def load_config(self):
106 """Load the config from a file and return it as a Struct."""
106 """Load the config from a file and return it as a Struct."""
107 self._find_file()
107 self._find_file()
108 self._read_file_as_dict()
108 self._read_file_as_dict()
109 self._convert_to_struct()
109 self._convert_to_struct()
110 return self.config
110 return self.config
111
111
112 def _find_file(self):
112 def _find_file(self):
113 """Try to find the file by searching the paths."""
113 """Try to find the file by searching the paths."""
114 self.full_filename = filefind(self.filename, self.path)
114 self.full_filename = filefind(self.filename, self.path)
115
115
116 def _read_file_as_dict(self):
116 def _read_file_as_dict(self):
117 self.data = {}
117 self.data = {}
118 execfile(self.full_filename, self.data)
118 execfile(self.full_filename, self.data)
119
119
120 def _convert_to_struct(self):
120 def _convert_to_struct(self):
121 if self.data is None:
121 if self.data is None:
122 ConfigLoaderError('self.data does not exist')
122 ConfigLoaderError('self.data does not exist')
123 for k, v in self.data.iteritems():
123 for k, v in self.data.iteritems():
124 if k == k.upper():
124 if k == k.upper():
125 self.config[k] = v
125 self.config[k] = v
126
126
127
127
128 class CommandLineConfigLoader(ConfigLoader):
128 class CommandLineConfigLoader(ConfigLoader):
129 """A config loader for command line arguments.
129 """A config loader for command line arguments.
130
130
131 As we add more command line based loaders, the common logic should go
131 As we add more command line based loaders, the common logic should go
132 here.
132 here.
133 """
133 """
134
134
135
135
136 class NoDefault(object): pass
136 class NoDefault(object): pass
137 NoDefault = NoDefault()
137 NoDefault = NoDefault()
138
138
139 class ArgParseConfigLoader(CommandLineConfigLoader):
139 class ArgParseConfigLoader(CommandLineConfigLoader):
140
140
141 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
141 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
142 arguments = ()
142 arguments = ()
143
143
144 def __init__(self, *args, **kw):
144 def __init__(self, *args, **kw):
145 """Create a config loader for use with argparse.
145 """Create a config loader for use with argparse.
146
146
147 The args and kwargs arguments here are passed onto the constructor
147 The args and kwargs arguments here are passed onto the constructor
148 of :class:`argparse.ArgumentParser`.
148 of :class:`argparse.ArgumentParser`.
149 """
149 """
150 super(CommandLineConfigLoader, self).__init__()
150 super(CommandLineConfigLoader, self).__init__()
151 self.args = args
151 self.args = args
152 self.kw = kw
152 self.kw = kw
153
153
154 def load_config(self, args=None):
154 def load_config(self, args=None):
155 """Parse command line arguments and return as a Struct."""
155 """Parse command line arguments and return as a Struct."""
156 self._create_parser()
156 self._create_parser()
157 self._parse_args(args)
157 self._parse_args(args)
158 self._convert_to_struct()
158 self._convert_to_struct()
159 return self.config
159 return self.config
160
160
161 def _create_parser(self):
161 def _create_parser(self):
162 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
162 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
163 self._add_arguments()
163 self._add_arguments()
164 self._add_other_arguments()
164 self._add_other_arguments()
165
165
166 def _add_other_arguments():
166 def _add_other_arguments(self):
167 pass
167 pass
168
168
169 def _add_arguments(self):
169 def _add_arguments(self):
170 for argument in self.arguments:
170 for argument in self.arguments:
171 if not argument[1].has_key('default'):
171 if not argument[1].has_key('default'):
172 argument[1]['default'] = NoDefault
172 argument[1]['default'] = NoDefault
173 self.parser.add_argument(*argument[0],**argument[1])
173 self.parser.add_argument(*argument[0],**argument[1])
174
174
175 def _parse_args(self, args=None):
175 def _parse_args(self, args=None):
176 """self.parser->self.parsed_data"""
176 """self.parser->self.parsed_data"""
177 if args is None:
177 if args is None:
178 self.parsed_data = self.parser.parse_args()
178 self.parsed_data = self.parser.parse_args()
179 else:
179 else:
180 self.parsed_data = self.parser.parse_args(args)
180 self.parsed_data = self.parser.parse_args(args)
181
181
182 def _convert_to_struct(self):
182 def _convert_to_struct(self):
183 """self.parsed_data->self.config"""
183 """self.parsed_data->self.config"""
184 self.config = Struct()
184 self.config = Struct()
185 for k, v in vars(self.parsed_data).items():
185 for k, v in vars(self.parsed_data).items():
186 if v is not NoDefault:
186 if v is not NoDefault:
187 setattr(self.config, k, v)
187 setattr(self.config, k, v)
188
188
189 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
189 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
190
190
191 def _add_other_arguments(self):
191 def _add_other_arguments(self):
192 self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str,
192 self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str,
193 help='set to override default location of IPYTHONDIR',
193 help='set to override default location of IPYTHONDIR',
194 default=NoDefault)
194 default=NoDefault)
195 self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str,
195 self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str,
196 help='the string name of the ipython profile to be used',
196 help='the string name of the ipython profile to be used',
197 default=None)
197 default=None)
198 self.parser.add_argument('--debug',dest="DEBUG",action='store_true',
198 self.parser.add_argument('--debug',dest="DEBUG",action='store_true',
199 help='debug the application startup process',
199 help='debug the application startup process',
200 default=NoDefault)
200 default=NoDefault)
@@ -1,639 +1,639 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 __getattr__ hook is found. Since it is the responsibility of the
34 __getattr__ hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47
47
48 """
48 """
49
49
50 #*****************************************************************************
50 #*****************************************************************************
51 #
51 #
52 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # module which is part of the standard Python distribution, I assume that the
53 # module which is part of the standard Python distribution, I assume that the
54 # proper procedure is to maintain its copyright as belonging to the Python
54 # proper procedure is to maintain its copyright as belonging to the Python
55 # Software Foundation (in addition to my own, for all new code).
55 # Software Foundation (in addition to my own, for all new code).
56 #
56 #
57 # Copyright (C) 2001 Python Software Foundation, www.python.org
57 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 import __builtin__
65 import __builtin__
66 import __main__
66 import __main__
67 import glob
67 import glob
68 import keyword
68 import keyword
69 import os
69 import os
70 import re
70 import re
71 import shlex
71 import shlex
72 import sys
72 import sys
73 import IPython.utils.rlineimpl as readline
73 import IPython.utils.rlineimpl as readline
74 import itertools
74 import itertools
75 from IPython.utils.ipstruct import Struct
75 from IPython.utils.ipstruct import Struct
76 from IPython.core import ipapi
76 from IPython.core import ipapi
77 from IPython.utils import generics
77 from IPython.utils import generics
78 import types
78 import types
79
79
80 # Python 2.4 offers sets as a builtin
80 # Python 2.4 offers sets as a builtin
81 try:
81 try:
82 set()
82 set()
83 except NameError:
83 except NameError:
84 from sets import Set as set
84 from sets import Set as set
85
85
86 from IPython.utils.genutils import debugx, dir2
86 from IPython.utils.genutils import debugx, dir2
87
87
88 __all__ = ['Completer','IPCompleter']
88 __all__ = ['Completer','IPCompleter']
89
89
90 class Completer:
90 class Completer:
91 def __init__(self,namespace=None,global_namespace=None):
91 def __init__(self,namespace=None,global_namespace=None):
92 """Create a new completer for the command line.
92 """Create a new completer for the command line.
93
93
94 Completer([namespace,global_namespace]) -> completer instance.
94 Completer([namespace,global_namespace]) -> completer instance.
95
95
96 If unspecified, the default namespace where completions are performed
96 If unspecified, the default namespace where completions are performed
97 is __main__ (technically, __main__.__dict__). Namespaces should be
97 is __main__ (technically, __main__.__dict__). Namespaces should be
98 given as dictionaries.
98 given as dictionaries.
99
99
100 An optional second namespace can be given. This allows the completer
100 An optional second namespace can be given. This allows the completer
101 to handle cases where both the local and global scopes need to be
101 to handle cases where both the local and global scopes need to be
102 distinguished.
102 distinguished.
103
103
104 Completer instances should be used as the completion mechanism of
104 Completer instances should be used as the completion mechanism of
105 readline via the set_completer() call:
105 readline via the set_completer() call:
106
106
107 readline.set_completer(Completer(my_namespace).complete)
107 readline.set_completer(Completer(my_namespace).complete)
108 """
108 """
109
109
110 # Don't bind to namespace quite yet, but flag whether the user wants a
110 # Don't bind to namespace quite yet, but flag whether the user wants a
111 # specific namespace or to use __main__.__dict__. This will allow us
111 # specific namespace or to use __main__.__dict__. This will allow us
112 # to bind to __main__.__dict__ at completion time, not now.
112 # to bind to __main__.__dict__ at completion time, not now.
113 if namespace is None:
113 if namespace is None:
114 self.use_main_ns = 1
114 self.use_main_ns = 1
115 else:
115 else:
116 self.use_main_ns = 0
116 self.use_main_ns = 0
117 self.namespace = namespace
117 self.namespace = namespace
118
118
119 # The global namespace, if given, can be bound directly
119 # The global namespace, if given, can be bound directly
120 if global_namespace is None:
120 if global_namespace is None:
121 self.global_namespace = {}
121 self.global_namespace = {}
122 else:
122 else:
123 self.global_namespace = global_namespace
123 self.global_namespace = global_namespace
124
124
125 def complete(self, text, state):
125 def complete(self, text, state):
126 """Return the next possible completion for 'text'.
126 """Return the next possible completion for 'text'.
127
127
128 This is called successively with state == 0, 1, 2, ... until it
128 This is called successively with state == 0, 1, 2, ... until it
129 returns None. The completion should begin with 'text'.
129 returns None. The completion should begin with 'text'.
130
130
131 """
131 """
132 if self.use_main_ns:
132 if self.use_main_ns:
133 self.namespace = __main__.__dict__
133 self.namespace = __main__.__dict__
134
134
135 if state == 0:
135 if state == 0:
136 if "." in text:
136 if "." in text:
137 self.matches = self.attr_matches(text)
137 self.matches = self.attr_matches(text)
138 else:
138 else:
139 self.matches = self.global_matches(text)
139 self.matches = self.global_matches(text)
140 try:
140 try:
141 return self.matches[state]
141 return self.matches[state]
142 except IndexError:
142 except IndexError:
143 return None
143 return None
144
144
145 def global_matches(self, text):
145 def global_matches(self, text):
146 """Compute matches when text is a simple name.
146 """Compute matches when text is a simple name.
147
147
148 Return a list of all keywords, built-in functions and names currently
148 Return a list of all keywords, built-in functions and names currently
149 defined in self.namespace or self.global_namespace that match.
149 defined in self.namespace or self.global_namespace that match.
150
150
151 """
151 """
152 matches = []
152 matches = []
153 match_append = matches.append
153 match_append = matches.append
154 n = len(text)
154 n = len(text)
155 for lst in [keyword.kwlist,
155 for lst in [keyword.kwlist,
156 __builtin__.__dict__.keys(),
156 __builtin__.__dict__.keys(),
157 self.namespace.keys(),
157 self.namespace.keys(),
158 self.global_namespace.keys()]:
158 self.global_namespace.keys()]:
159 for word in lst:
159 for word in lst:
160 if word[:n] == text and word != "__builtins__":
160 if word[:n] == text and word != "__builtins__":
161 match_append(word)
161 match_append(word)
162 return matches
162 return matches
163
163
164 def attr_matches(self, text):
164 def attr_matches(self, text):
165 """Compute matches when text contains a dot.
165 """Compute matches when text contains a dot.
166
166
167 Assuming the text is of the form NAME.NAME....[NAME], and is
167 Assuming the text is of the form NAME.NAME....[NAME], and is
168 evaluatable in self.namespace or self.global_namespace, it will be
168 evaluatable in self.namespace or self.global_namespace, it will be
169 evaluated and its attributes (as revealed by dir()) are used as
169 evaluated and its attributes (as revealed by dir()) are used as
170 possible completions. (For class instances, class members are are
170 possible completions. (For class instances, class members are are
171 also considered.)
171 also considered.)
172
172
173 WARNING: this can still invoke arbitrary C code, if an object
173 WARNING: this can still invoke arbitrary C code, if an object
174 with a __getattr__ hook is evaluated.
174 with a __getattr__ hook is evaluated.
175
175
176 """
176 """
177 import re
177 import re
178
178
179 # Another option, seems to work great. Catches things like ''.<tab>
179 # Another option, seems to work great. Catches things like ''.<tab>
180 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
180 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
181
181
182 if not m:
182 if not m:
183 return []
183 return []
184
184
185 expr, attr = m.group(1, 3)
185 expr, attr = m.group(1, 3)
186 try:
186 try:
187 obj = eval(expr, self.namespace)
187 obj = eval(expr, self.namespace)
188 except:
188 except:
189 try:
189 try:
190 obj = eval(expr, self.global_namespace)
190 obj = eval(expr, self.global_namespace)
191 except:
191 except:
192 return []
192 return []
193
193
194 words = dir2(obj)
194 words = dir2(obj)
195
195
196 try:
196 try:
197 words = generics.complete_object(obj, words)
197 words = generics.complete_object(obj, words)
198 except ipapi.TryNext:
198 except ipapi.TryNext:
199 pass
199 pass
200 # Build match list to return
200 # Build match list to return
201 n = len(attr)
201 n = len(attr)
202 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
202 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
203 return res
203 return res
204
204
205 class IPCompleter(Completer):
205 class IPCompleter(Completer):
206 """Extension of the completer class with IPython-specific features"""
206 """Extension of the completer class with IPython-specific features"""
207
207
208 def __init__(self,shell,namespace=None,global_namespace=None,
208 def __init__(self,shell,namespace=None,global_namespace=None,
209 omit__names=0,alias_table=None):
209 omit__names=0,alias_table=None):
210 """IPCompleter() -> completer
210 """IPCompleter() -> completer
211
211
212 Return a completer object suitable for use by the readline library
212 Return a completer object suitable for use by the readline library
213 via readline.set_completer().
213 via readline.set_completer().
214
214
215 Inputs:
215 Inputs:
216
216
217 - shell: a pointer to the ipython shell itself. This is needed
217 - shell: a pointer to the ipython shell itself. This is needed
218 because this completer knows about magic functions, and those can
218 because this completer knows about magic functions, and those can
219 only be accessed via the ipython instance.
219 only be accessed via the ipython instance.
220
220
221 - namespace: an optional dict where completions are performed.
221 - namespace: an optional dict where completions are performed.
222
222
223 - global_namespace: secondary optional dict for completions, to
223 - global_namespace: secondary optional dict for completions, to
224 handle cases (such as IPython embedded inside functions) where
224 handle cases (such as IPython embedded inside functions) where
225 both Python scopes are visible.
225 both Python scopes are visible.
226
226
227 - The optional omit__names parameter sets the completer to omit the
227 - The optional omit__names parameter sets the completer to omit the
228 'magic' names (__magicname__) for python objects unless the text
228 'magic' names (__magicname__) for python objects unless the text
229 to be completed explicitly starts with one or more underscores.
229 to be completed explicitly starts with one or more underscores.
230
230
231 - If alias_table is supplied, it should be a dictionary of aliases
231 - If alias_table is supplied, it should be a dictionary of aliases
232 to complete. """
232 to complete. """
233
233
234 Completer.__init__(self,namespace,global_namespace)
234 Completer.__init__(self,namespace,global_namespace)
235 self.magic_prefix = shell.name+'.magic_'
235 self.magic_prefix = shell.name+'.magic_'
236 self.magic_escape = shell.ESC_MAGIC
236 self.magic_escape = shell.ESC_MAGIC
237 self.readline = readline
237 self.readline = readline
238 delims = self.readline.get_completer_delims()
238 delims = self.readline.get_completer_delims()
239 delims = delims.replace(self.magic_escape,'')
239 delims = delims.replace(self.magic_escape,'')
240 self.readline.set_completer_delims(delims)
240 self.readline.set_completer_delims(delims)
241 self.get_line_buffer = self.readline.get_line_buffer
241 self.get_line_buffer = self.readline.get_line_buffer
242 self.get_endidx = self.readline.get_endidx
242 self.get_endidx = self.readline.get_endidx
243 self.omit__names = omit__names
243 self.omit__names = omit__names
244 self.merge_completions = shell.rc.readline_merge_completions
244 self.merge_completions = shell.readline_merge_completions
245 if alias_table is None:
245 if alias_table is None:
246 alias_table = {}
246 alias_table = {}
247 self.alias_table = alias_table
247 self.alias_table = alias_table
248 # Regexp to split filenames with spaces in them
248 # Regexp to split filenames with spaces in them
249 self.space_name_re = re.compile(r'([^\\] )')
249 self.space_name_re = re.compile(r'([^\\] )')
250 # Hold a local ref. to glob.glob for speed
250 # Hold a local ref. to glob.glob for speed
251 self.glob = glob.glob
251 self.glob = glob.glob
252
252
253 # Determine if we are running on 'dumb' terminals, like (X)Emacs
253 # Determine if we are running on 'dumb' terminals, like (X)Emacs
254 # buffers, to avoid completion problems.
254 # buffers, to avoid completion problems.
255 term = os.environ.get('TERM','xterm')
255 term = os.environ.get('TERM','xterm')
256 self.dumb_terminal = term in ['dumb','emacs']
256 self.dumb_terminal = term in ['dumb','emacs']
257
257
258 # Special handling of backslashes needed in win32 platforms
258 # Special handling of backslashes needed in win32 platforms
259 if sys.platform == "win32":
259 if sys.platform == "win32":
260 self.clean_glob = self._clean_glob_win32
260 self.clean_glob = self._clean_glob_win32
261 else:
261 else:
262 self.clean_glob = self._clean_glob
262 self.clean_glob = self._clean_glob
263 self.matchers = [self.python_matches,
263 self.matchers = [self.python_matches,
264 self.file_matches,
264 self.file_matches,
265 self.alias_matches,
265 self.alias_matches,
266 self.python_func_kw_matches]
266 self.python_func_kw_matches]
267
267
268
268
269 # Code contributed by Alex Schmolck, for ipython/emacs integration
269 # Code contributed by Alex Schmolck, for ipython/emacs integration
270 def all_completions(self, text):
270 def all_completions(self, text):
271 """Return all possible completions for the benefit of emacs."""
271 """Return all possible completions for the benefit of emacs."""
272
272
273 completions = []
273 completions = []
274 comp_append = completions.append
274 comp_append = completions.append
275 try:
275 try:
276 for i in xrange(sys.maxint):
276 for i in xrange(sys.maxint):
277 res = self.complete(text, i)
277 res = self.complete(text, i)
278
278
279 if not res: break
279 if not res: break
280
280
281 comp_append(res)
281 comp_append(res)
282 #XXX workaround for ``notDefined.<tab>``
282 #XXX workaround for ``notDefined.<tab>``
283 except NameError:
283 except NameError:
284 pass
284 pass
285 return completions
285 return completions
286 # /end Alex Schmolck code.
286 # /end Alex Schmolck code.
287
287
288 def _clean_glob(self,text):
288 def _clean_glob(self,text):
289 return self.glob("%s*" % text)
289 return self.glob("%s*" % text)
290
290
291 def _clean_glob_win32(self,text):
291 def _clean_glob_win32(self,text):
292 return [f.replace("\\","/")
292 return [f.replace("\\","/")
293 for f in self.glob("%s*" % text)]
293 for f in self.glob("%s*" % text)]
294
294
295 def file_matches(self, text):
295 def file_matches(self, text):
296 """Match filenames, expanding ~USER type strings.
296 """Match filenames, expanding ~USER type strings.
297
297
298 Most of the seemingly convoluted logic in this completer is an
298 Most of the seemingly convoluted logic in this completer is an
299 attempt to handle filenames with spaces in them. And yet it's not
299 attempt to handle filenames with spaces in them. And yet it's not
300 quite perfect, because Python's readline doesn't expose all of the
300 quite perfect, because Python's readline doesn't expose all of the
301 GNU readline details needed for this to be done correctly.
301 GNU readline details needed for this to be done correctly.
302
302
303 For a filename with a space in it, the printed completions will be
303 For a filename with a space in it, the printed completions will be
304 only the parts after what's already been typed (instead of the
304 only the parts after what's already been typed (instead of the
305 full completions, as is normally done). I don't think with the
305 full completions, as is normally done). I don't think with the
306 current (as of Python 2.3) Python readline it's possible to do
306 current (as of Python 2.3) Python readline it's possible to do
307 better."""
307 better."""
308
308
309 #print 'Completer->file_matches: <%s>' % text # dbg
309 #print 'Completer->file_matches: <%s>' % text # dbg
310
310
311 # chars that require escaping with backslash - i.e. chars
311 # chars that require escaping with backslash - i.e. chars
312 # that readline treats incorrectly as delimiters, but we
312 # that readline treats incorrectly as delimiters, but we
313 # don't want to treat as delimiters in filename matching
313 # don't want to treat as delimiters in filename matching
314 # when escaped with backslash
314 # when escaped with backslash
315
315
316 if sys.platform == 'win32':
316 if sys.platform == 'win32':
317 protectables = ' '
317 protectables = ' '
318 else:
318 else:
319 protectables = ' ()'
319 protectables = ' ()'
320
320
321 if text.startswith('!'):
321 if text.startswith('!'):
322 text = text[1:]
322 text = text[1:]
323 text_prefix = '!'
323 text_prefix = '!'
324 else:
324 else:
325 text_prefix = ''
325 text_prefix = ''
326
326
327 def protect_filename(s):
327 def protect_filename(s):
328 return "".join([(ch in protectables and '\\' + ch or ch)
328 return "".join([(ch in protectables and '\\' + ch or ch)
329 for ch in s])
329 for ch in s])
330
330
331 def single_dir_expand(matches):
331 def single_dir_expand(matches):
332 "Recursively expand match lists containing a single dir."
332 "Recursively expand match lists containing a single dir."
333
333
334 if len(matches) == 1 and os.path.isdir(matches[0]):
334 if len(matches) == 1 and os.path.isdir(matches[0]):
335 # Takes care of links to directories also. Use '/'
335 # Takes care of links to directories also. Use '/'
336 # explicitly, even under Windows, so that name completions
336 # explicitly, even under Windows, so that name completions
337 # don't end up escaped.
337 # don't end up escaped.
338 d = matches[0]
338 d = matches[0]
339 if d[-1] in ['/','\\']:
339 if d[-1] in ['/','\\']:
340 d = d[:-1]
340 d = d[:-1]
341
341
342 subdirs = os.listdir(d)
342 subdirs = os.listdir(d)
343 if subdirs:
343 if subdirs:
344 matches = [ (d + '/' + p) for p in subdirs]
344 matches = [ (d + '/' + p) for p in subdirs]
345 return single_dir_expand(matches)
345 return single_dir_expand(matches)
346 else:
346 else:
347 return matches
347 return matches
348 else:
348 else:
349 return matches
349 return matches
350
350
351 lbuf = self.lbuf
351 lbuf = self.lbuf
352 open_quotes = 0 # track strings with open quotes
352 open_quotes = 0 # track strings with open quotes
353 try:
353 try:
354 lsplit = shlex.split(lbuf)[-1]
354 lsplit = shlex.split(lbuf)[-1]
355 except ValueError:
355 except ValueError:
356 # typically an unmatched ", or backslash without escaped char.
356 # typically an unmatched ", or backslash without escaped char.
357 if lbuf.count('"')==1:
357 if lbuf.count('"')==1:
358 open_quotes = 1
358 open_quotes = 1
359 lsplit = lbuf.split('"')[-1]
359 lsplit = lbuf.split('"')[-1]
360 elif lbuf.count("'")==1:
360 elif lbuf.count("'")==1:
361 open_quotes = 1
361 open_quotes = 1
362 lsplit = lbuf.split("'")[-1]
362 lsplit = lbuf.split("'")[-1]
363 else:
363 else:
364 return []
364 return []
365 except IndexError:
365 except IndexError:
366 # tab pressed on empty line
366 # tab pressed on empty line
367 lsplit = ""
367 lsplit = ""
368
368
369 if lsplit != protect_filename(lsplit):
369 if lsplit != protect_filename(lsplit):
370 # if protectables are found, do matching on the whole escaped
370 # if protectables are found, do matching on the whole escaped
371 # name
371 # name
372 has_protectables = 1
372 has_protectables = 1
373 text0,text = text,lsplit
373 text0,text = text,lsplit
374 else:
374 else:
375 has_protectables = 0
375 has_protectables = 0
376 text = os.path.expanduser(text)
376 text = os.path.expanduser(text)
377
377
378 if text == "":
378 if text == "":
379 return [text_prefix + protect_filename(f) for f in self.glob("*")]
379 return [text_prefix + protect_filename(f) for f in self.glob("*")]
380
380
381 m0 = self.clean_glob(text.replace('\\',''))
381 m0 = self.clean_glob(text.replace('\\',''))
382 if has_protectables:
382 if has_protectables:
383 # If we had protectables, we need to revert our changes to the
383 # If we had protectables, we need to revert our changes to the
384 # beginning of filename so that we don't double-write the part
384 # beginning of filename so that we don't double-write the part
385 # of the filename we have so far
385 # of the filename we have so far
386 len_lsplit = len(lsplit)
386 len_lsplit = len(lsplit)
387 matches = [text_prefix + text0 +
387 matches = [text_prefix + text0 +
388 protect_filename(f[len_lsplit:]) for f in m0]
388 protect_filename(f[len_lsplit:]) for f in m0]
389 else:
389 else:
390 if open_quotes:
390 if open_quotes:
391 # if we have a string with an open quote, we don't need to
391 # if we have a string with an open quote, we don't need to
392 # protect the names at all (and we _shouldn't_, as it
392 # protect the names at all (and we _shouldn't_, as it
393 # would cause bugs when the filesystem call is made).
393 # would cause bugs when the filesystem call is made).
394 matches = m0
394 matches = m0
395 else:
395 else:
396 matches = [text_prefix +
396 matches = [text_prefix +
397 protect_filename(f) for f in m0]
397 protect_filename(f) for f in m0]
398
398
399 #print 'mm',matches # dbg
399 #print 'mm',matches # dbg
400 return single_dir_expand(matches)
400 return single_dir_expand(matches)
401
401
402 def alias_matches(self, text):
402 def alias_matches(self, text):
403 """Match internal system aliases"""
403 """Match internal system aliases"""
404 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
404 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
405
405
406 # if we are not in the first 'item', alias matching
406 # if we are not in the first 'item', alias matching
407 # doesn't make sense - unless we are starting with 'sudo' command.
407 # doesn't make sense - unless we are starting with 'sudo' command.
408 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
408 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
409 return []
409 return []
410 text = os.path.expanduser(text)
410 text = os.path.expanduser(text)
411 aliases = self.alias_table.keys()
411 aliases = self.alias_table.keys()
412 if text == "":
412 if text == "":
413 return aliases
413 return aliases
414 else:
414 else:
415 return [alias for alias in aliases if alias.startswith(text)]
415 return [alias for alias in aliases if alias.startswith(text)]
416
416
417 def python_matches(self,text):
417 def python_matches(self,text):
418 """Match attributes or global python names"""
418 """Match attributes or global python names"""
419
419
420 #print 'Completer->python_matches, txt=<%s>' % text # dbg
420 #print 'Completer->python_matches, txt=<%s>' % text # dbg
421 if "." in text:
421 if "." in text:
422 try:
422 try:
423 matches = self.attr_matches(text)
423 matches = self.attr_matches(text)
424 if text.endswith('.') and self.omit__names:
424 if text.endswith('.') and self.omit__names:
425 if self.omit__names == 1:
425 if self.omit__names == 1:
426 # true if txt is _not_ a __ name, false otherwise:
426 # true if txt is _not_ a __ name, false otherwise:
427 no__name = (lambda txt:
427 no__name = (lambda txt:
428 re.match(r'.*\.__.*?__',txt) is None)
428 re.match(r'.*\.__.*?__',txt) is None)
429 else:
429 else:
430 # true if txt is _not_ a _ name, false otherwise:
430 # true if txt is _not_ a _ name, false otherwise:
431 no__name = (lambda txt:
431 no__name = (lambda txt:
432 re.match(r'.*\._.*?',txt) is None)
432 re.match(r'.*\._.*?',txt) is None)
433 matches = filter(no__name, matches)
433 matches = filter(no__name, matches)
434 except NameError:
434 except NameError:
435 # catches <undefined attributes>.<tab>
435 # catches <undefined attributes>.<tab>
436 matches = []
436 matches = []
437 else:
437 else:
438 matches = self.global_matches(text)
438 matches = self.global_matches(text)
439 # this is so completion finds magics when automagic is on:
439 # this is so completion finds magics when automagic is on:
440 if (matches == [] and
440 if (matches == [] and
441 not text.startswith(os.sep) and
441 not text.startswith(os.sep) and
442 not ' ' in self.lbuf):
442 not ' ' in self.lbuf):
443 matches = self.attr_matches(self.magic_prefix+text)
443 matches = self.attr_matches(self.magic_prefix+text)
444 return matches
444 return matches
445
445
446 def _default_arguments(self, obj):
446 def _default_arguments(self, obj):
447 """Return the list of default arguments of obj if it is callable,
447 """Return the list of default arguments of obj if it is callable,
448 or empty list otherwise."""
448 or empty list otherwise."""
449
449
450 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
450 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
451 # for classes, check for __init__,__new__
451 # for classes, check for __init__,__new__
452 if inspect.isclass(obj):
452 if inspect.isclass(obj):
453 obj = (getattr(obj,'__init__',None) or
453 obj = (getattr(obj,'__init__',None) or
454 getattr(obj,'__new__',None))
454 getattr(obj,'__new__',None))
455 # for all others, check if they are __call__able
455 # for all others, check if they are __call__able
456 elif hasattr(obj, '__call__'):
456 elif hasattr(obj, '__call__'):
457 obj = obj.__call__
457 obj = obj.__call__
458 # XXX: is there a way to handle the builtins ?
458 # XXX: is there a way to handle the builtins ?
459 try:
459 try:
460 args,_,_1,defaults = inspect.getargspec(obj)
460 args,_,_1,defaults = inspect.getargspec(obj)
461 if defaults:
461 if defaults:
462 return args[-len(defaults):]
462 return args[-len(defaults):]
463 except TypeError: pass
463 except TypeError: pass
464 return []
464 return []
465
465
466 def python_func_kw_matches(self,text):
466 def python_func_kw_matches(self,text):
467 """Match named parameters (kwargs) of the last open function"""
467 """Match named parameters (kwargs) of the last open function"""
468
468
469 if "." in text: # a parameter cannot be dotted
469 if "." in text: # a parameter cannot be dotted
470 return []
470 return []
471 try: regexp = self.__funcParamsRegex
471 try: regexp = self.__funcParamsRegex
472 except AttributeError:
472 except AttributeError:
473 regexp = self.__funcParamsRegex = re.compile(r'''
473 regexp = self.__funcParamsRegex = re.compile(r'''
474 '.*?' | # single quoted strings or
474 '.*?' | # single quoted strings or
475 ".*?" | # double quoted strings or
475 ".*?" | # double quoted strings or
476 \w+ | # identifier
476 \w+ | # identifier
477 \S # other characters
477 \S # other characters
478 ''', re.VERBOSE | re.DOTALL)
478 ''', re.VERBOSE | re.DOTALL)
479 # 1. find the nearest identifier that comes before an unclosed
479 # 1. find the nearest identifier that comes before an unclosed
480 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
480 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
481 tokens = regexp.findall(self.get_line_buffer())
481 tokens = regexp.findall(self.get_line_buffer())
482 tokens.reverse()
482 tokens.reverse()
483 iterTokens = iter(tokens); openPar = 0
483 iterTokens = iter(tokens); openPar = 0
484 for token in iterTokens:
484 for token in iterTokens:
485 if token == ')':
485 if token == ')':
486 openPar -= 1
486 openPar -= 1
487 elif token == '(':
487 elif token == '(':
488 openPar += 1
488 openPar += 1
489 if openPar > 0:
489 if openPar > 0:
490 # found the last unclosed parenthesis
490 # found the last unclosed parenthesis
491 break
491 break
492 else:
492 else:
493 return []
493 return []
494 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
494 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
495 ids = []
495 ids = []
496 isId = re.compile(r'\w+$').match
496 isId = re.compile(r'\w+$').match
497 while True:
497 while True:
498 try:
498 try:
499 ids.append(iterTokens.next())
499 ids.append(iterTokens.next())
500 if not isId(ids[-1]):
500 if not isId(ids[-1]):
501 ids.pop(); break
501 ids.pop(); break
502 if not iterTokens.next() == '.':
502 if not iterTokens.next() == '.':
503 break
503 break
504 except StopIteration:
504 except StopIteration:
505 break
505 break
506 # lookup the candidate callable matches either using global_matches
506 # lookup the candidate callable matches either using global_matches
507 # or attr_matches for dotted names
507 # or attr_matches for dotted names
508 if len(ids) == 1:
508 if len(ids) == 1:
509 callableMatches = self.global_matches(ids[0])
509 callableMatches = self.global_matches(ids[0])
510 else:
510 else:
511 callableMatches = self.attr_matches('.'.join(ids[::-1]))
511 callableMatches = self.attr_matches('.'.join(ids[::-1]))
512 argMatches = []
512 argMatches = []
513 for callableMatch in callableMatches:
513 for callableMatch in callableMatches:
514 try: namedArgs = self._default_arguments(eval(callableMatch,
514 try: namedArgs = self._default_arguments(eval(callableMatch,
515 self.namespace))
515 self.namespace))
516 except: continue
516 except: continue
517 for namedArg in namedArgs:
517 for namedArg in namedArgs:
518 if namedArg.startswith(text):
518 if namedArg.startswith(text):
519 argMatches.append("%s=" %namedArg)
519 argMatches.append("%s=" %namedArg)
520 return argMatches
520 return argMatches
521
521
522 def dispatch_custom_completer(self,text):
522 def dispatch_custom_completer(self,text):
523 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
523 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
524 line = self.full_lbuf
524 line = self.full_lbuf
525 if not line.strip():
525 if not line.strip():
526 return None
526 return None
527
527
528 event = Struct()
528 event = Struct()
529 event.line = line
529 event.line = line
530 event.symbol = text
530 event.symbol = text
531 cmd = line.split(None,1)[0]
531 cmd = line.split(None,1)[0]
532 event.command = cmd
532 event.command = cmd
533 #print "\ncustom:{%s]\n" % event # dbg
533 #print "\ncustom:{%s]\n" % event # dbg
534
534
535 # for foo etc, try also to find completer for %foo
535 # for foo etc, try also to find completer for %foo
536 if not cmd.startswith(self.magic_escape):
536 if not cmd.startswith(self.magic_escape):
537 try_magic = self.custom_completers.s_matches(
537 try_magic = self.custom_completers.s_matches(
538 self.magic_escape + cmd)
538 self.magic_escape + cmd)
539 else:
539 else:
540 try_magic = []
540 try_magic = []
541
541
542
542
543 for c in itertools.chain(
543 for c in itertools.chain(
544 self.custom_completers.s_matches(cmd),
544 self.custom_completers.s_matches(cmd),
545 try_magic,
545 try_magic,
546 self.custom_completers.flat_matches(self.lbuf)):
546 self.custom_completers.flat_matches(self.lbuf)):
547 #print "try",c # dbg
547 #print "try",c # dbg
548 try:
548 try:
549 res = c(event)
549 res = c(event)
550 # first, try case sensitive match
550 # first, try case sensitive match
551 withcase = [r for r in res if r.startswith(text)]
551 withcase = [r for r in res if r.startswith(text)]
552 if withcase:
552 if withcase:
553 return withcase
553 return withcase
554 # if none, then case insensitive ones are ok too
554 # if none, then case insensitive ones are ok too
555 return [r for r in res if r.lower().startswith(text.lower())]
555 return [r for r in res if r.lower().startswith(text.lower())]
556 except ipapi.TryNext:
556 except ipapi.TryNext:
557 pass
557 pass
558
558
559 return None
559 return None
560
560
561 def complete(self, text, state,line_buffer=None):
561 def complete(self, text, state,line_buffer=None):
562 """Return the next possible completion for 'text'.
562 """Return the next possible completion for 'text'.
563
563
564 This is called successively with state == 0, 1, 2, ... until it
564 This is called successively with state == 0, 1, 2, ... until it
565 returns None. The completion should begin with 'text'.
565 returns None. The completion should begin with 'text'.
566
566
567 :Keywords:
567 :Keywords:
568 - line_buffer: string
568 - line_buffer: string
569 If not given, the completer attempts to obtain the current line buffer
569 If not given, the completer attempts to obtain the current line buffer
570 via readline. This keyword allows clients which are requesting for
570 via readline. This keyword allows clients which are requesting for
571 text completions in non-readline contexts to inform the completer of
571 text completions in non-readline contexts to inform the completer of
572 the entire text.
572 the entire text.
573 """
573 """
574
574
575 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
575 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
576
576
577 # if there is only a tab on a line with only whitespace, instead
577 # if there is only a tab on a line with only whitespace, instead
578 # of the mostly useless 'do you want to see all million
578 # of the mostly useless 'do you want to see all million
579 # completions' message, just do the right thing and give the user
579 # completions' message, just do the right thing and give the user
580 # his tab! Incidentally, this enables pasting of tabbed text from
580 # his tab! Incidentally, this enables pasting of tabbed text from
581 # an editor (as long as autoindent is off).
581 # an editor (as long as autoindent is off).
582
582
583 # It should be noted that at least pyreadline still shows
583 # It should be noted that at least pyreadline still shows
584 # file completions - is there a way around it?
584 # file completions - is there a way around it?
585
585
586 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
586 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
587 # don't interfere with their own tab-completion mechanism.
587 # don't interfere with their own tab-completion mechanism.
588 if line_buffer is None:
588 if line_buffer is None:
589 self.full_lbuf = self.get_line_buffer()
589 self.full_lbuf = self.get_line_buffer()
590 else:
590 else:
591 self.full_lbuf = line_buffer
591 self.full_lbuf = line_buffer
592
592
593 if not (self.dumb_terminal or self.full_lbuf.strip()):
593 if not (self.dumb_terminal or self.full_lbuf.strip()):
594 self.readline.insert_text('\t')
594 self.readline.insert_text('\t')
595 return None
595 return None
596
596
597 magic_escape = self.magic_escape
597 magic_escape = self.magic_escape
598 magic_prefix = self.magic_prefix
598 magic_prefix = self.magic_prefix
599
599
600 self.lbuf = self.full_lbuf[:self.get_endidx()]
600 self.lbuf = self.full_lbuf[:self.get_endidx()]
601
601
602 try:
602 try:
603 if text.startswith(magic_escape):
603 if text.startswith(magic_escape):
604 text = text.replace(magic_escape,magic_prefix)
604 text = text.replace(magic_escape,magic_prefix)
605 elif text.startswith('~'):
605 elif text.startswith('~'):
606 text = os.path.expanduser(text)
606 text = os.path.expanduser(text)
607 if state == 0:
607 if state == 0:
608 custom_res = self.dispatch_custom_completer(text)
608 custom_res = self.dispatch_custom_completer(text)
609 if custom_res is not None:
609 if custom_res is not None:
610 # did custom completers produce something?
610 # did custom completers produce something?
611 self.matches = custom_res
611 self.matches = custom_res
612 else:
612 else:
613 # Extend the list of completions with the results of each
613 # Extend the list of completions with the results of each
614 # matcher, so we return results to the user from all
614 # matcher, so we return results to the user from all
615 # namespaces.
615 # namespaces.
616 if self.merge_completions:
616 if self.merge_completions:
617 self.matches = []
617 self.matches = []
618 for matcher in self.matchers:
618 for matcher in self.matchers:
619 self.matches.extend(matcher(text))
619 self.matches.extend(matcher(text))
620 else:
620 else:
621 for matcher in self.matchers:
621 for matcher in self.matchers:
622 self.matches = matcher(text)
622 self.matches = matcher(text)
623 if self.matches:
623 if self.matches:
624 break
624 break
625 def uniq(alist):
625 def uniq(alist):
626 set = {}
626 set = {}
627 return [set.setdefault(e,e) for e in alist if e not in set]
627 return [set.setdefault(e,e) for e in alist if e not in set]
628 self.matches = uniq(self.matches)
628 self.matches = uniq(self.matches)
629 try:
629 try:
630 ret = self.matches[state].replace(magic_prefix,magic_escape)
630 ret = self.matches[state].replace(magic_prefix,magic_escape)
631 return ret
631 return ret
632 except IndexError:
632 except IndexError:
633 return None
633 return None
634 except:
634 except:
635 #from IPython.core.ultratb import AutoFormattedTB; # dbg
635 #from IPython.core.ultratb import AutoFormattedTB; # dbg
636 #tb=AutoFormattedTB('Verbose');tb() #dbg
636 #tb=AutoFormattedTB('Verbose');tb() #dbg
637
637
638 # If completion fails, don't annoy the user.
638 # If completion fails, don't annoy the user.
639 return None
639 return None
@@ -1,229 +1,229 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4
4
5 Authors
5 Authors
6 -------
6 -------
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 #****************************************************************************
18 #****************************************************************************
19 # Required modules
19 # Required modules
20
20
21 # From the standard library
21 # From the standard library
22 import os
22 import os
23 import sys
23 import sys
24 from pprint import pformat
24 from pprint import pformat
25
25
26 # Our own
26 # Our own
27 from IPython.core import release
27 from IPython.core import release
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.external.Itpl import itpl
29 from IPython.external.Itpl import itpl
30
30
31 from IPython.utils.genutils import *
31 from IPython.utils.genutils import *
32
32
33 #****************************************************************************
33 #****************************************************************************
34 class CrashHandler:
34 class CrashHandler:
35 """Customizable crash handlers for IPython-based systems.
35 """Customizable crash handlers for IPython-based systems.
36
36
37 Instances of this class provide a __call__ method which can be used as a
37 Instances of this class provide a __call__ method which can be used as a
38 sys.excepthook, i.e., the __call__ signature is:
38 sys.excepthook, i.e., the __call__ signature is:
39
39
40 def __call__(self,etype, evalue, etb)
40 def __call__(self,etype, evalue, etb)
41
41
42 """
42 """
43
43
44 def __init__(self,IP,app_name,contact_name,contact_email,
44 def __init__(self,IP,app_name,contact_name,contact_email,
45 bug_tracker,crash_report_fname,
45 bug_tracker,crash_report_fname,
46 show_crash_traceback=True):
46 show_crash_traceback=True):
47 """New crash handler.
47 """New crash handler.
48
48
49 Inputs:
49 Inputs:
50
50
51 - IP: a running IPython instance, which will be queried at crash time
51 - IP: a running IPython instance, which will be queried at crash time
52 for internal information.
52 for internal information.
53
53
54 - app_name: a string containing the name of your application.
54 - app_name: a string containing the name of your application.
55
55
56 - contact_name: a string with the name of the person to contact.
56 - contact_name: a string with the name of the person to contact.
57
57
58 - contact_email: a string with the email address of the contact.
58 - contact_email: a string with the email address of the contact.
59
59
60 - bug_tracker: a string with the URL for your project's bug tracker.
60 - bug_tracker: a string with the URL for your project's bug tracker.
61
61
62 - crash_report_fname: a string with the filename for the crash report
62 - crash_report_fname: a string with the filename for the crash report
63 to be saved in. These reports are left in the ipython user directory
63 to be saved in. These reports are left in the ipython user directory
64 as determined by the running IPython instance.
64 as determined by the running IPython instance.
65
65
66 Optional inputs:
66 Optional inputs:
67
67
68 - show_crash_traceback(True): if false, don't print the crash
68 - show_crash_traceback(True): if false, don't print the crash
69 traceback on stderr, only generate the on-disk report
69 traceback on stderr, only generate the on-disk report
70
70
71
71
72 Non-argument instance attributes:
72 Non-argument instance attributes:
73
73
74 These instances contain some non-argument attributes which allow for
74 These instances contain some non-argument attributes which allow for
75 further customization of the crash handler's behavior. Please see the
75 further customization of the crash handler's behavior. Please see the
76 source for further details.
76 source for further details.
77 """
77 """
78
78
79 # apply args into instance
79 # apply args into instance
80 self.IP = IP # IPython instance
80 self.IP = IP # IPython instance
81 self.app_name = app_name
81 self.app_name = app_name
82 self.contact_name = contact_name
82 self.contact_name = contact_name
83 self.contact_email = contact_email
83 self.contact_email = contact_email
84 self.bug_tracker = bug_tracker
84 self.bug_tracker = bug_tracker
85 self.crash_report_fname = crash_report_fname
85 self.crash_report_fname = crash_report_fname
86 self.show_crash_traceback = show_crash_traceback
86 self.show_crash_traceback = show_crash_traceback
87
87
88 # Hardcoded defaults, which can be overridden either by subclasses or
88 # Hardcoded defaults, which can be overridden either by subclasses or
89 # at runtime for the instance.
89 # at runtime for the instance.
90
90
91 # Template for the user message. Subclasses which completely override
91 # Template for the user message. Subclasses which completely override
92 # this, or user apps, can modify it to suit their tastes. It gets
92 # this, or user apps, can modify it to suit their tastes. It gets
93 # expanded using itpl, so calls of the kind $self.foo are valid.
93 # expanded using itpl, so calls of the kind $self.foo are valid.
94 self.user_message_template = """
94 self.user_message_template = """
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
96
96
97 A crash report was automatically generated with the following information:
97 A crash report was automatically generated with the following information:
98 - A verbatim copy of the crash traceback.
98 - A verbatim copy of the crash traceback.
99 - A copy of your input history during this session.
99 - A copy of your input history during this session.
100 - Data on your current $self.app_name configuration.
100 - Data on your current $self.app_name configuration.
101
101
102 It was left in the file named:
102 It was left in the file named:
103 \t'$self.crash_report_fname'
103 \t'$self.crash_report_fname'
104 If you can email this file to the developers, the information in it will help
104 If you can email this file to the developers, the information in it will help
105 them in understanding and correcting the problem.
105 them in understanding and correcting the problem.
106
106
107 You can mail it to: $self.contact_name at $self.contact_email
107 You can mail it to: $self.contact_name at $self.contact_email
108 with the subject '$self.app_name Crash Report'.
108 with the subject '$self.app_name Crash Report'.
109
109
110 If you want to do it now, the following command will work (under Unix):
110 If you want to do it now, the following command will work (under Unix):
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
112
112
113 To ensure accurate tracking of this issue, please file a report about it at:
113 To ensure accurate tracking of this issue, please file a report about it at:
114 $self.bug_tracker
114 $self.bug_tracker
115 """
115 """
116
116
117 def __call__(self,etype, evalue, etb):
117 def __call__(self,etype, evalue, etb):
118 """Handle an exception, call for compatible with sys.excepthook"""
118 """Handle an exception, call for compatible with sys.excepthook"""
119
119
120 # Report tracebacks shouldn't use color in general (safer for users)
120 # Report tracebacks shouldn't use color in general (safer for users)
121 color_scheme = 'NoColor'
121 color_scheme = 'NoColor'
122
122
123 # Use this ONLY for developer debugging (keep commented out for release)
123 # Use this ONLY for developer debugging (keep commented out for release)
124 #color_scheme = 'Linux' # dbg
124 #color_scheme = 'Linux' # dbg
125
125
126 try:
126 try:
127 rptdir = self.IP.rc.ipythondir
127 rptdir = self.IP.config.IPYTHONDIR
128 except:
128 except:
129 rptdir = os.getcwd()
129 rptdir = os.getcwd()
130 if not os.path.isdir(rptdir):
130 if not os.path.isdir(rptdir):
131 rptdir = os.getcwd()
131 rptdir = os.getcwd()
132 report_name = os.path.join(rptdir,self.crash_report_fname)
132 report_name = os.path.join(rptdir,self.crash_report_fname)
133 # write the report filename into the instance dict so it can get
133 # write the report filename into the instance dict so it can get
134 # properly expanded out in the user message template
134 # properly expanded out in the user message template
135 self.crash_report_fname = report_name
135 self.crash_report_fname = report_name
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
137 long_header=1)
137 long_header=1)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
139
140 # print traceback to screen
140 # print traceback to screen
141 if self.show_crash_traceback:
141 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
142 print >> sys.stderr, traceback
143
143
144 # and generate a complete report on disk
144 # and generate a complete report on disk
145 try:
145 try:
146 report = open(report_name,'w')
146 report = open(report_name,'w')
147 except:
147 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
148 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
149 return
150
150
151 # Inform user on stderr of what happened
151 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
153 print >> sys.stderr, msg
153 print >> sys.stderr, msg
154
154
155 # Construct report on disk
155 # Construct report on disk
156 report.write(self.make_report(traceback))
156 report.write(self.make_report(traceback))
157 report.close()
157 report.close()
158 raw_input("Press enter to exit:")
158 raw_input("Press enter to exit:")
159
159
160 def make_report(self,traceback):
160 def make_report(self,traceback):
161 """Return a string containing a crash report."""
161 """Return a string containing a crash report."""
162
162
163 sec_sep = '\n\n'+'*'*75+'\n\n'
163 sec_sep = '\n\n'+'*'*75+'\n\n'
164
164
165 report = []
165 report = []
166 rpt_add = report.append
166 rpt_add = report.append
167
167
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
169 rpt_add('IPython version: %s \n\n' % release.version)
169 rpt_add('IPython version: %s \n\n' % release.version)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 (os.name,sys.platform) )
172 (os.name,sys.platform) )
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.rc.dict()))
174 rpt_add(pformat(self.IP.dict()))
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 try:
176 try:
177 rpt_add(sec_sep+"History of session input:")
177 rpt_add(sec_sep+"History of session input:")
178 for line in self.IP.user_ns['_ih']:
178 for line in self.IP.user_ns['_ih']:
179 rpt_add(line)
179 rpt_add(line)
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
181 rpt_add(self.IP._last_input_line+'\n')
181 rpt_add(self.IP._last_input_line+'\n')
182 except:
182 except:
183 pass
183 pass
184
184
185 return ''.join(report)
185 return ''.join(report)
186
186
187 class IPythonCrashHandler(CrashHandler):
187 class IPythonCrashHandler(CrashHandler):
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
189
189
190 def __init__(self,IP):
190 def __init__(self,IP):
191
191
192 # Set here which of the IPython authors should be listed as contact
192 # Set here which of the IPython authors should be listed as contact
193 AUTHOR_CONTACT = 'Fernando'
193 AUTHOR_CONTACT = 'Fernando'
194
194
195 # Set argument defaults
195 # Set argument defaults
196 app_name = 'IPython'
196 app_name = 'IPython'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
199 crash_report_fname = 'IPython_crash_report.txt'
199 crash_report_fname = 'IPython_crash_report.txt'
200 # Call parent constructor
200 # Call parent constructor
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
202 bug_tracker,crash_report_fname)
202 bug_tracker,crash_report_fname)
203
203
204 def make_report(self,traceback):
204 def make_report(self,traceback):
205 """Return a string containing a crash report."""
205 """Return a string containing a crash report."""
206
206
207 sec_sep = '\n\n'+'*'*75+'\n\n'
207 sec_sep = '\n\n'+'*'*75+'\n\n'
208
208
209 report = []
209 report = []
210 rpt_add = report.append
210 rpt_add = report.append
211
211
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
213 rpt_add('IPython version: %s \n\n' % release.version)
213 rpt_add('IPython version: %s \n\n' % release.version)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 (os.name,sys.platform) )
216 (os.name,sys.platform) )
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 rpt_add(pformat(self.IP.rc.dict()))
218 rpt_add(pformat(self.IP.dict()))
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 try:
220 try:
221 rpt_add(sec_sep+"History of session input:")
221 rpt_add(sec_sep+"History of session input:")
222 for line in self.IP.user_ns['_ih']:
222 for line in self.IP.user_ns['_ih']:
223 rpt_add(line)
223 rpt_add(line)
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
225 rpt_add(self.IP._last_input_line+'\n')
225 rpt_add(self.IP._last_input_line+'\n')
226 except:
226 except:
227 pass
227 pass
228
228
229 return ''.join(report)
229 return ''.join(report)
@@ -1,266 +1,266 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29 raise ipapi.TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython.core import ipapi
44 from IPython.core import ipapi
45
45
46 import os, bisect
46 import os, bisect
47 import sys
47 import sys
48 from IPython.utils.genutils import Term, shell
48 from IPython.utils.genutils import Term, shell
49 from pprint import PrettyPrinter
49 from pprint import PrettyPrinter
50
50
51 # List here all the default hooks. For now it's just the editor functions
51 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
52 # but over time we'll move here all the public API for user-accessible things.
53 # vds: >>
53 # vds: >>
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
56 'generate_prompt', 'generate_output_prompt','shell_hook',
56 'generate_prompt', 'generate_output_prompt','shell_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
58 'clipboard_get']
58 'clipboard_get']
59 # vds: <<
59 # vds: <<
60
60
61 pformat = PrettyPrinter().pformat
61 pformat = PrettyPrinter().pformat
62
62
63 def editor(self,filename, linenum=None):
63 def editor(self,filename, linenum=None):
64 """Open the default editor at the given filename and linenumber.
64 """Open the default editor at the given filename and linenumber.
65
65
66 This is IPython's default editor hook, you can use it as an example to
66 This is IPython's default editor hook, you can use it as an example to
67 write your own modified one. To set your own editor function as the
67 write your own modified one. To set your own editor function as the
68 new editor hook, call ip.set_hook('editor',yourfunc)."""
68 new editor hook, call ip.set_hook('editor',yourfunc)."""
69
69
70 # IPython configures a default editor at startup by reading $EDITOR from
70 # IPython configures a default editor at startup by reading $EDITOR from
71 # the environment, and falling back on vi (unix) or notepad (win32).
71 # the environment, and falling back on vi (unix) or notepad (win32).
72 editor = self.rc.editor
72 editor = self.editor
73
73
74 # marker for at which line to open the file (for existing objects)
74 # marker for at which line to open the file (for existing objects)
75 if linenum is None or editor=='notepad':
75 if linenum is None or editor=='notepad':
76 linemark = ''
76 linemark = ''
77 else:
77 else:
78 linemark = '+%d' % int(linenum)
78 linemark = '+%d' % int(linenum)
79
79
80 # Enclose in quotes if necessary and legal
80 # Enclose in quotes if necessary and legal
81 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
81 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
82 editor = '"%s"' % editor
82 editor = '"%s"' % editor
83
83
84 # Call the actual editor
84 # Call the actual editor
85 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
85 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
86 raise ipapi.TryNext()
86 raise ipapi.TryNext()
87
87
88 import tempfile
88 import tempfile
89 def fix_error_editor(self,filename,linenum,column,msg):
89 def fix_error_editor(self,filename,linenum,column,msg):
90 """Open the editor at the given filename, linenumber, column and
90 """Open the editor at the given filename, linenumber, column and
91 show an error message. This is used for correcting syntax errors.
91 show an error message. This is used for correcting syntax errors.
92 The current implementation only has special support for the VIM editor,
92 The current implementation only has special support for the VIM editor,
93 and falls back on the 'editor' hook if VIM is not used.
93 and falls back on the 'editor' hook if VIM is not used.
94
94
95 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
95 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
96 """
96 """
97 def vim_quickfix_file():
97 def vim_quickfix_file():
98 t = tempfile.NamedTemporaryFile()
98 t = tempfile.NamedTemporaryFile()
99 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
99 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
100 t.flush()
100 t.flush()
101 return t
101 return t
102 if os.path.basename(self.rc.editor) != 'vim':
102 if os.path.basename(self.editor) != 'vim':
103 self.hooks.editor(filename,linenum)
103 self.hooks.editor(filename,linenum)
104 return
104 return
105 t = vim_quickfix_file()
105 t = vim_quickfix_file()
106 try:
106 try:
107 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
107 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
108 raise ipapi.TryNext()
108 raise ipapi.TryNext()
109 finally:
109 finally:
110 t.close()
110 t.close()
111
111
112 # vds: >>
112 # vds: >>
113 def synchronize_with_editor(self, filename, linenum, column):
113 def synchronize_with_editor(self, filename, linenum, column):
114 pass
114 pass
115 # vds: <<
115 # vds: <<
116
116
117 class CommandChainDispatcher:
117 class CommandChainDispatcher:
118 """ Dispatch calls to a chain of commands until some func can handle it
118 """ Dispatch calls to a chain of commands until some func can handle it
119
119
120 Usage: instantiate, execute "add" to add commands (with optional
120 Usage: instantiate, execute "add" to add commands (with optional
121 priority), execute normally via f() calling mechanism.
121 priority), execute normally via f() calling mechanism.
122
122
123 """
123 """
124 def __init__(self,commands=None):
124 def __init__(self,commands=None):
125 if commands is None:
125 if commands is None:
126 self.chain = []
126 self.chain = []
127 else:
127 else:
128 self.chain = commands
128 self.chain = commands
129
129
130
130
131 def __call__(self,*args, **kw):
131 def __call__(self,*args, **kw):
132 """ Command chain is called just like normal func.
132 """ Command chain is called just like normal func.
133
133
134 This will call all funcs in chain with the same args as were given to this
134 This will call all funcs in chain with the same args as were given to this
135 function, and return the result of first func that didn't raise
135 function, and return the result of first func that didn't raise
136 TryNext """
136 TryNext """
137
137
138 for prio,cmd in self.chain:
138 for prio,cmd in self.chain:
139 #print "prio",prio,"cmd",cmd #dbg
139 #print "prio",prio,"cmd",cmd #dbg
140 try:
140 try:
141 ret = cmd(*args, **kw)
141 ret = cmd(*args, **kw)
142 return ret
142 return ret
143 except ipapi.TryNext, exc:
143 except ipapi.TryNext, exc:
144 if exc.args or exc.kwargs:
144 if exc.args or exc.kwargs:
145 args = exc.args
145 args = exc.args
146 kw = exc.kwargs
146 kw = exc.kwargs
147 # if no function will accept it, raise TryNext up to the caller
147 # if no function will accept it, raise TryNext up to the caller
148 raise ipapi.TryNext
148 raise ipapi.TryNext
149
149
150 def __str__(self):
150 def __str__(self):
151 return str(self.chain)
151 return str(self.chain)
152
152
153 def add(self, func, priority=0):
153 def add(self, func, priority=0):
154 """ Add a func to the cmd chain with given priority """
154 """ Add a func to the cmd chain with given priority """
155 bisect.insort(self.chain,(priority,func))
155 bisect.insort(self.chain,(priority,func))
156
156
157 def __iter__(self):
157 def __iter__(self):
158 """ Return all objects in chain.
158 """ Return all objects in chain.
159
159
160 Handy if the objects are not callable.
160 Handy if the objects are not callable.
161 """
161 """
162 return iter(self.chain)
162 return iter(self.chain)
163
163
164 def result_display(self,arg):
164 def result_display(self,arg):
165 """ Default display hook.
165 """ Default display hook.
166
166
167 Called for displaying the result to the user.
167 Called for displaying the result to the user.
168 """
168 """
169
169
170 if self.rc.pprint:
170 if self.pprint:
171 out = pformat(arg)
171 out = pformat(arg)
172 if '\n' in out:
172 if '\n' in out:
173 # So that multi-line strings line up with the left column of
173 # So that multi-line strings line up with the left column of
174 # the screen, instead of having the output prompt mess up
174 # the screen, instead of having the output prompt mess up
175 # their first line.
175 # their first line.
176 Term.cout.write('\n')
176 Term.cout.write('\n')
177 print >>Term.cout, out
177 print >>Term.cout, out
178 else:
178 else:
179 # By default, the interactive prompt uses repr() to display results,
179 # By default, the interactive prompt uses repr() to display results,
180 # so we should honor this. Users who'd rather use a different
180 # so we should honor this. Users who'd rather use a different
181 # mechanism can easily override this hook.
181 # mechanism can easily override this hook.
182 print >>Term.cout, repr(arg)
182 print >>Term.cout, repr(arg)
183 # the default display hook doesn't manipulate the value to put in history
183 # the default display hook doesn't manipulate the value to put in history
184 return None
184 return None
185
185
186 def input_prefilter(self,line):
186 def input_prefilter(self,line):
187 """ Default input prefilter
187 """ Default input prefilter
188
188
189 This returns the line as unchanged, so that the interpreter
189 This returns the line as unchanged, so that the interpreter
190 knows that nothing was done and proceeds with "classic" prefiltering
190 knows that nothing was done and proceeds with "classic" prefiltering
191 (%magics, !shell commands etc.).
191 (%magics, !shell commands etc.).
192
192
193 Note that leading whitespace is not passed to this hook. Prefilter
193 Note that leading whitespace is not passed to this hook. Prefilter
194 can't alter indentation.
194 can't alter indentation.
195
195
196 """
196 """
197 #print "attempt to rewrite",line #dbg
197 #print "attempt to rewrite",line #dbg
198 return line
198 return line
199
199
200 def shutdown_hook(self):
200 def shutdown_hook(self):
201 """ default shutdown hook
201 """ default shutdown hook
202
202
203 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
203 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
204 """
204 """
205
205
206 #print "default shutdown hook ok" # dbg
206 #print "default shutdown hook ok" # dbg
207 return
207 return
208
208
209 def late_startup_hook(self):
209 def late_startup_hook(self):
210 """ Executed after ipython has been constructed and configured
210 """ Executed after ipython has been constructed and configured
211
211
212 """
212 """
213 #print "default startup hook ok" # dbg
213 #print "default startup hook ok" # dbg
214
214
215 def generate_prompt(self, is_continuation):
215 def generate_prompt(self, is_continuation):
216 """ calculate and return a string with the prompt to display """
216 """ calculate and return a string with the prompt to display """
217 ip = self.api
217 ip = self.api
218 if is_continuation:
218 if is_continuation:
219 return str(ip.IP.outputcache.prompt2)
219 return str(ip.IP.outputcache.prompt2)
220 return str(ip.IP.outputcache.prompt1)
220 return str(ip.IP.outputcache.prompt1)
221
221
222 def generate_output_prompt(self):
222 def generate_output_prompt(self):
223 ip = self.api
223 ip = self.api
224 return str(ip.IP.outputcache.prompt_out)
224 return str(ip.IP.outputcache.prompt_out)
225
225
226 def shell_hook(self,cmd):
226 def shell_hook(self,cmd):
227 """ Run system/shell command a'la os.system() """
227 """ Run system/shell command a'la os.system() """
228
228
229 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
229 shell(cmd, header=self.system_header, verbose=self.system_verbose)
230
230
231 def show_in_pager(self,s):
231 def show_in_pager(self,s):
232 """ Run a string through pager """
232 """ Run a string through pager """
233 # raising TryNext here will use the default paging functionality
233 # raising TryNext here will use the default paging functionality
234 raise ipapi.TryNext
234 raise ipapi.TryNext
235
235
236 def pre_prompt_hook(self):
236 def pre_prompt_hook(self):
237 """ Run before displaying the next prompt
237 """ Run before displaying the next prompt
238
238
239 Use this e.g. to display output from asynchronous operations (in order
239 Use this e.g. to display output from asynchronous operations (in order
240 to not mess up text entry)
240 to not mess up text entry)
241 """
241 """
242
242
243 return None
243 return None
244
244
245 def pre_runcode_hook(self):
245 def pre_runcode_hook(self):
246 """ Executed before running the (prefiltered) code in IPython """
246 """ Executed before running the (prefiltered) code in IPython """
247 return None
247 return None
248
248
249 def clipboard_get(self):
249 def clipboard_get(self):
250 """ Get text from the clipboard.
250 """ Get text from the clipboard.
251 """
251 """
252 from IPython.lib.clipboard import (
252 from IPython.lib.clipboard import (
253 osx_clipboard_get, tkinter_clipboard_get,
253 osx_clipboard_get, tkinter_clipboard_get,
254 win32_clipboard_get
254 win32_clipboard_get
255 )
255 )
256 if sys.platform == 'win32':
256 if sys.platform == 'win32':
257 chain = [win32_clipboard_get, tkinter_clipboard_get]
257 chain = [win32_clipboard_get, tkinter_clipboard_get]
258 elif sys.platform == 'darwin':
258 elif sys.platform == 'darwin':
259 chain = [osx_clipboard_get, tkinter_clipboard_get]
259 chain = [osx_clipboard_get, tkinter_clipboard_get]
260 else:
260 else:
261 chain = [tkinter_clipboard_get]
261 chain = [tkinter_clipboard_get]
262 dispatcher = CommandChainDispatcher()
262 dispatcher = CommandChainDispatcher()
263 for func in chain:
263 for func in chain:
264 dispatcher.add(func)
264 dispatcher.add(func)
265 text = dispatcher()
265 text = dispatcher()
266 return text
266 return text
@@ -1,685 +1,684 b''
1 """IPython customization API
1 """IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 from IPython.core import ipapi
27 from IPython.core import ipapi
28 ip = ipapi.get()
28 ip = ipapi.get()
29
29
30 def ankka_f(self, arg):
30 def ankka_f(self, arg):
31 print 'Ankka',self,'says uppercase:',arg.upper()
31 print 'Ankka',self,'says uppercase:',arg.upper()
32
32
33 ip.expose_magic('ankka',ankka_f)
33 ip.expose_magic('ankka',ankka_f)
34
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
37 ip.system('pwd')
38
38
39 ip.ex('import re')
39 ip.ex('import re')
40 ip.ex('''
40 ip.ex('''
41 def funcci(a,b):
41 def funcci(a,b):
42 print a+b
42 print a+b
43 print funcci(3,4)
43 print funcci(3,4)
44 ''')
44 ''')
45 ip.ex('funcci(348,9)')
45 ip.ex('funcci(348,9)')
46
46
47 def jed_editor(self,filename, linenum=None):
47 def jed_editor(self,filename, linenum=None):
48 print 'Calling my own editor, jed ... via hook!'
48 print 'Calling my own editor, jed ... via hook!'
49 import os
49 import os
50 if linenum is None: linenum = 0
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
51 os.system('jed +%d %s' % (linenum, filename))
52 print 'exiting jed'
52 print 'exiting jed'
53
53
54 ip.set_hook('editor',jed_editor)
54 ip.set_hook('editor',jed_editor)
55
55
56 o = ip.options
56 o = ip.options
57 o.autocall = 2 # FULL autocall mode
57 o.autocall = 2 # FULL autocall mode
58
58
59 print 'done!'
59 print 'done!'
60 """
60 """
61
61
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63 # Modules and globals
63 # Modules and globals
64
64
65 # stdlib imports
65 # stdlib imports
66 import __builtin__
66 import __builtin__
67 import sys
67 import sys
68
68
69 # contains the most recently instantiated IPApi
69 # contains the most recently instantiated IPApi
70 _RECENT_IP = None
70 _RECENT_IP = None
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Code begins
73 # Code begins
74
74
75 class TryNext(Exception):
75 class TryNext(Exception):
76 """Try next hook exception.
76 """Try next hook exception.
77
77
78 Raise this in your hook function to indicate that the next hook handler
78 Raise this in your hook function to indicate that the next hook handler
79 should be used to handle the operation. If you pass arguments to the
79 should be used to handle the operation. If you pass arguments to the
80 constructor those arguments will be used by the next hook instead of the
80 constructor those arguments will be used by the next hook instead of the
81 original ones.
81 original ones.
82 """
82 """
83
83
84 def __init__(self, *args, **kwargs):
84 def __init__(self, *args, **kwargs):
85 self.args = args
85 self.args = args
86 self.kwargs = kwargs
86 self.kwargs = kwargs
87
87
88
88
89 class UsageError(Exception):
89 class UsageError(Exception):
90 """ Error in magic function arguments, etc.
90 """ Error in magic function arguments, etc.
91
91
92 Something that probably won't warrant a full traceback, but should
92 Something that probably won't warrant a full traceback, but should
93 nevertheless interrupt a macro / batch file.
93 nevertheless interrupt a macro / batch file.
94 """
94 """
95
95
96
96
97 class IPyAutocall:
97 class IPyAutocall:
98 """ Instances of this class are always autocalled
98 """ Instances of this class are always autocalled
99
99
100 This happens regardless of 'autocall' variable state. Use this to
100 This happens regardless of 'autocall' variable state. Use this to
101 develop macro-like mechanisms.
101 develop macro-like mechanisms.
102 """
102 """
103
103
104 def set_ip(self,ip):
104 def set_ip(self,ip):
105 """ Will be used to set _ip point to current ipython instance b/f call
105 """ Will be used to set _ip point to current ipython instance b/f call
106
106
107 Override this method if you don't want this to happen.
107 Override this method if you don't want this to happen.
108
108
109 """
109 """
110 self._ip = ip
110 self._ip = ip
111
111
112
112
113 class IPythonNotRunning:
113 class IPythonNotRunning:
114 """Dummy do-nothing class.
114 """Dummy do-nothing class.
115
115
116 Instances of this class return a dummy attribute on all accesses, which
116 Instances of this class return a dummy attribute on all accesses, which
117 can be called and warns. This makes it easier to write scripts which use
117 can be called and warns. This makes it easier to write scripts which use
118 the ipapi.get() object for informational purposes to operate both with and
118 the ipapi.get() object for informational purposes to operate both with and
119 without ipython. Obviously code which uses the ipython object for
119 without ipython. Obviously code which uses the ipython object for
120 computations will not work, but this allows a wider range of code to
120 computations will not work, but this allows a wider range of code to
121 transparently work whether ipython is being used or not."""
121 transparently work whether ipython is being used or not."""
122
122
123 def __init__(self,warn=True):
123 def __init__(self,warn=True):
124 if warn:
124 if warn:
125 self.dummy = self._dummy_warn
125 self.dummy = self._dummy_warn
126 else:
126 else:
127 self.dummy = self._dummy_silent
127 self.dummy = self._dummy_silent
128
128
129 def __str__(self):
129 def __str__(self):
130 return "<IPythonNotRunning>"
130 return "<IPythonNotRunning>"
131
131
132 __repr__ = __str__
132 __repr__ = __str__
133
133
134 def __getattr__(self,name):
134 def __getattr__(self,name):
135 return self.dummy
135 return self.dummy
136
136
137 def _dummy_warn(self,*args,**kw):
137 def _dummy_warn(self,*args,**kw):
138 """Dummy function, which doesn't do anything but warn."""
138 """Dummy function, which doesn't do anything but warn."""
139
139
140 print ("IPython is not running, this is a dummy no-op function")
140 print ("IPython is not running, this is a dummy no-op function")
141
141
142 def _dummy_silent(self,*args,**kw):
142 def _dummy_silent(self,*args,**kw):
143 """Dummy function, which doesn't do anything and emits no warnings."""
143 """Dummy function, which doesn't do anything and emits no warnings."""
144 pass
144 pass
145
145
146
146
147 def get(allow_dummy=False,dummy_warn=True):
147 def get(allow_dummy=False,dummy_warn=True):
148 """Get an IPApi object.
148 """Get an IPApi object.
149
149
150 If allow_dummy is true, returns an instance of IPythonNotRunning
150 If allow_dummy is true, returns an instance of IPythonNotRunning
151 instead of None if not running under IPython.
151 instead of None if not running under IPython.
152
152
153 If dummy_warn is false, the dummy instance will be completely silent.
153 If dummy_warn is false, the dummy instance will be completely silent.
154
154
155 Running this should be the first thing you do when writing extensions that
155 Running this should be the first thing you do when writing extensions that
156 can be imported as normal modules. You can then direct all the
156 can be imported as normal modules. You can then direct all the
157 configuration operations against the returned object.
157 configuration operations against the returned object.
158 """
158 """
159 global _RECENT_IP
159 global _RECENT_IP
160 if allow_dummy and not _RECENT_IP:
160 if allow_dummy and not _RECENT_IP:
161 _RECENT_IP = IPythonNotRunning(dummy_warn)
161 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 return _RECENT_IP
162 return _RECENT_IP
163
163
164
164
165 class IPApi(object):
165 class IPApi(object):
166 """ The actual API class for configuring IPython
166 """ The actual API class for configuring IPython
167
167
168 You should do all of the IPython configuration by getting an IPApi object
168 You should do all of the IPython configuration by getting an IPApi object
169 with IPython.ipapi.get() and using the attributes and methods of the
169 with IPython.ipapi.get() and using the attributes and methods of the
170 returned object."""
170 returned object."""
171
171
172 def __init__(self,ip):
172 def __init__(self,ip):
173
173
174 global _RECENT_IP
174 global _RECENT_IP
175
175
176 # All attributes exposed here are considered to be the public API of
176 # All attributes exposed here are considered to be the public API of
177 # IPython. As needs dictate, some of these may be wrapped as
177 # IPython. As needs dictate, some of these may be wrapped as
178 # properties.
178 # properties.
179
179
180 self.magic = ip.ipmagic
180 self.magic = ip.ipmagic
181
181
182 self.system = ip.system
182 self.system = ip.system
183
183
184 self.set_hook = ip.set_hook
184 self.set_hook = ip.set_hook
185
185
186 self.set_custom_exc = ip.set_custom_exc
186 self.set_custom_exc = ip.set_custom_exc
187
187
188 self.user_ns = ip.user_ns
188 self.user_ns = ip.user_ns
189
189
190 self.set_crash_handler = ip.set_crash_handler
190 self.set_crash_handler = ip.set_crash_handler
191
191
192 # Session-specific data store, which can be used to store
192 # Session-specific data store, which can be used to store
193 # data that should persist through the ipython session.
193 # data that should persist through the ipython session.
194 self.meta = ip.meta
194 self.meta = ip.meta
195
195
196 # The ipython instance provided
196 # The ipython instance provided
197 self.IP = ip
197 self.IP = ip
198
198
199 self.extensions = {}
199 self.extensions = {}
200
200
201 self.dbg = DebugTools(self)
201 self.dbg = DebugTools(self)
202
202
203 _RECENT_IP = self
203 _RECENT_IP = self
204
204
205 # Use a property for some things which are added to the instance very
205 # Use a property for some things which are added to the instance very
206 # late. I don't have time right now to disentangle the initialization
206 # late. I don't have time right now to disentangle the initialization
207 # order issues, so a property lets us delay item extraction while
207 # order issues, so a property lets us delay item extraction while
208 # providing a normal attribute API.
208 # providing a normal attribute API.
209 def get_db(self):
209 def get_db(self):
210 """A handle to persistent dict-like database (a PickleShareDB object)"""
210 """A handle to persistent dict-like database (a PickleShareDB object)"""
211 return self.IP.db
211 return self.IP.db
212
212
213 db = property(get_db,None,None,get_db.__doc__)
213 db = property(get_db,None,None,get_db.__doc__)
214
214
215 def get_options(self):
215 def get_options(self):
216 """All configurable variables."""
216 """All configurable variables."""
217
217
218 # catch typos by disabling new attribute creation. If new attr creation
218 # catch typos by disabling new attribute creation. If new attr creation
219 # is in fact wanted (e.g. when exposing new options), do
219 # is in fact wanted (e.g. when exposing new options), do
220 # allow_new_attr(True) for the received rc struct.
220 # allow_new_attr(True) for the received rc struct.
221
221
222 self.IP.rc.allow_new_attr(False)
222 return self.IP
223 return self.IP.rc
224
223
225 options = property(get_options,None,None,get_options.__doc__)
224 options = property(get_options,None,None,get_options.__doc__)
226
225
227 def expose_magic(self,magicname, func):
226 def expose_magic(self,magicname, func):
228 """Expose own function as magic function for ipython
227 """Expose own function as magic function for ipython
229
228
230 def foo_impl(self,parameter_s=''):
229 def foo_impl(self,parameter_s=''):
231 'My very own magic!. (Use docstrings, IPython reads them).'
230 'My very own magic!. (Use docstrings, IPython reads them).'
232 print 'Magic function. Passed parameter is between < >:'
231 print 'Magic function. Passed parameter is between < >:'
233 print '<%s>' % parameter_s
232 print '<%s>' % parameter_s
234 print 'The self object is:',self
233 print 'The self object is:',self
235
234
236 ipapi.expose_magic('foo',foo_impl)
235 ipapi.expose_magic('foo',foo_impl)
237 """
236 """
238
237
239 import new
238 import new
240 im = new.instancemethod(func,self.IP, self.IP.__class__)
239 im = new.instancemethod(func,self.IP, self.IP.__class__)
241 old = getattr(self.IP, "magic_" + magicname, None)
240 old = getattr(self.IP, "magic_" + magicname, None)
242 if old:
241 if old:
243 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
242 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
244 (magicname,old) )
243 (magicname,old) )
245
244
246 setattr(self.IP, "magic_" + magicname, im)
245 setattr(self.IP, "magic_" + magicname, im)
247
246
248 def ex(self,cmd):
247 def ex(self,cmd):
249 """ Execute a normal python statement in user namespace """
248 """ Execute a normal python statement in user namespace """
250 exec cmd in self.user_ns
249 exec cmd in self.user_ns
251
250
252 def ev(self,expr):
251 def ev(self,expr):
253 """ Evaluate python expression expr in user namespace
252 """ Evaluate python expression expr in user namespace
254
253
255 Returns the result of evaluation"""
254 Returns the result of evaluation"""
256 return eval(expr,self.user_ns)
255 return eval(expr,self.user_ns)
257
256
258 def runlines(self,lines):
257 def runlines(self,lines):
259 """ Run the specified lines in interpreter, honoring ipython directives.
258 """ Run the specified lines in interpreter, honoring ipython directives.
260
259
261 This allows %magic and !shell escape notations.
260 This allows %magic and !shell escape notations.
262
261
263 Takes either all lines in one string or list of lines.
262 Takes either all lines in one string or list of lines.
264 """
263 """
265
264
266 def cleanup_ipy_script(script):
265 def cleanup_ipy_script(script):
267 """ Make a script safe for _ip.runlines()
266 """ Make a script safe for _ip.runlines()
268
267
269 - Removes empty lines Suffixes all indented blocks that end with
268 - Removes empty lines Suffixes all indented blocks that end with
270 - unindented lines with empty lines
269 - unindented lines with empty lines
271 """
270 """
272
271
273 res = []
272 res = []
274 lines = script.splitlines()
273 lines = script.splitlines()
275
274
276 level = 0
275 level = 0
277 for l in lines:
276 for l in lines:
278 lstripped = l.lstrip()
277 lstripped = l.lstrip()
279 stripped = l.strip()
278 stripped = l.strip()
280 if not stripped:
279 if not stripped:
281 continue
280 continue
282 newlevel = len(l) - len(lstripped)
281 newlevel = len(l) - len(lstripped)
283 def is_secondary_block_start(s):
282 def is_secondary_block_start(s):
284 if not s.endswith(':'):
283 if not s.endswith(':'):
285 return False
284 return False
286 if (s.startswith('elif') or
285 if (s.startswith('elif') or
287 s.startswith('else') or
286 s.startswith('else') or
288 s.startswith('except') or
287 s.startswith('except') or
289 s.startswith('finally')):
288 s.startswith('finally')):
290 return True
289 return True
291
290
292 if level > 0 and newlevel == 0 and \
291 if level > 0 and newlevel == 0 and \
293 not is_secondary_block_start(stripped):
292 not is_secondary_block_start(stripped):
294 # add empty line
293 # add empty line
295 res.append('')
294 res.append('')
296
295
297 res.append(l)
296 res.append(l)
298 level = newlevel
297 level = newlevel
299 return '\n'.join(res) + '\n'
298 return '\n'.join(res) + '\n'
300
299
301 if isinstance(lines,basestring):
300 if isinstance(lines,basestring):
302 script = lines
301 script = lines
303 else:
302 else:
304 script = '\n'.join(lines)
303 script = '\n'.join(lines)
305 clean=cleanup_ipy_script(script)
304 clean=cleanup_ipy_script(script)
306 # print "_ip.runlines() script:\n",clean # dbg
305 # print "_ip.runlines() script:\n",clean # dbg
307 self.IP.runlines(clean)
306 self.IP.runlines(clean)
308
307
309 def to_user_ns(self,vars, interactive = True):
308 def to_user_ns(self,vars, interactive = True):
310 """Inject a group of variables into the IPython user namespace.
309 """Inject a group of variables into the IPython user namespace.
311
310
312 Inputs:
311 Inputs:
313
312
314 - vars: string with variable names separated by whitespace, or a
313 - vars: string with variable names separated by whitespace, or a
315 dict with name/value pairs.
314 dict with name/value pairs.
316
315
317 - interactive: if True (default), the var will be listed with
316 - interactive: if True (default), the var will be listed with
318 %whos et. al.
317 %whos et. al.
319
318
320 This utility routine is meant to ease interactive debugging work,
319 This utility routine is meant to ease interactive debugging work,
321 where you want to easily propagate some internal variable in your code
320 where you want to easily propagate some internal variable in your code
322 up to the interactive namespace for further exploration.
321 up to the interactive namespace for further exploration.
323
322
324 When you run code via %run, globals in your script become visible at
323 When you run code via %run, globals in your script become visible at
325 the interactive prompt, but this doesn't happen for locals inside your
324 the interactive prompt, but this doesn't happen for locals inside your
326 own functions and methods. Yet when debugging, it is common to want
325 own functions and methods. Yet when debugging, it is common to want
327 to explore some internal variables further at the interactive propmt.
326 to explore some internal variables further at the interactive propmt.
328
327
329 Examples:
328 Examples:
330
329
331 To use this, you first must obtain a handle on the ipython object as
330 To use this, you first must obtain a handle on the ipython object as
332 indicated above, via:
331 indicated above, via:
333
332
334 from IPython.core import ipapi
333 from IPython.core import ipapi
335 ip = ipapi.get()
334 ip = ipapi.get()
336
335
337 Once this is done, inside a routine foo() where you want to expose
336 Once this is done, inside a routine foo() where you want to expose
338 variables x and y, you do the following:
337 variables x and y, you do the following:
339
338
340 def foo():
339 def foo():
341 ...
340 ...
342 x = your_computation()
341 x = your_computation()
343 y = something_else()
342 y = something_else()
344
343
345 # This pushes x and y to the interactive prompt immediately, even
344 # This pushes x and y to the interactive prompt immediately, even
346 # if this routine crashes on the next line after:
345 # if this routine crashes on the next line after:
347 ip.to_user_ns('x y')
346 ip.to_user_ns('x y')
348 ...
347 ...
349
348
350 # To expose *ALL* the local variables from the function, use:
349 # To expose *ALL* the local variables from the function, use:
351 ip.to_user_ns(locals())
350 ip.to_user_ns(locals())
352
351
353 ...
352 ...
354 # return
353 # return
355
354
356
355
357 If you need to rename variables, the dict input makes it easy. For
356 If you need to rename variables, the dict input makes it easy. For
358 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
357 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
359 in IPython user namespace:
358 in IPython user namespace:
360
359
361 ip.to_user_ns(dict(x=foo,y=bar))
360 ip.to_user_ns(dict(x=foo,y=bar))
362 """
361 """
363
362
364 # print 'vars given:',vars # dbg
363 # print 'vars given:',vars # dbg
365
364
366 # We need a dict of name/value pairs to do namespace updates.
365 # We need a dict of name/value pairs to do namespace updates.
367 if isinstance(vars,dict):
366 if isinstance(vars,dict):
368 # If a dict was given, no need to change anything.
367 # If a dict was given, no need to change anything.
369 vdict = vars
368 vdict = vars
370 elif isinstance(vars,basestring):
369 elif isinstance(vars,basestring):
371 # If a string with names was given, get the caller's frame to
370 # If a string with names was given, get the caller's frame to
372 # evaluate the given names in
371 # evaluate the given names in
373 cf = sys._getframe(1)
372 cf = sys._getframe(1)
374 vdict = {}
373 vdict = {}
375 for name in vars.split():
374 for name in vars.split():
376 try:
375 try:
377 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
376 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
378 except:
377 except:
379 print ('could not get var. %s from %s' %
378 print ('could not get var. %s from %s' %
380 (name,cf.f_code.co_name))
379 (name,cf.f_code.co_name))
381 else:
380 else:
382 raise ValueError('vars must be a string or a dict')
381 raise ValueError('vars must be a string or a dict')
383
382
384 # Propagate variables to user namespace
383 # Propagate variables to user namespace
385 self.user_ns.update(vdict)
384 self.user_ns.update(vdict)
386
385
387 # And configure interactive visibility
386 # And configure interactive visibility
388 config_ns = self.IP.user_config_ns
387 config_ns = self.IP.user_config_ns
389 if interactive:
388 if interactive:
390 for name,val in vdict.iteritems():
389 for name,val in vdict.iteritems():
391 config_ns.pop(name,None)
390 config_ns.pop(name,None)
392 else:
391 else:
393 for name,val in vdict.iteritems():
392 for name,val in vdict.iteritems():
394 config_ns[name] = val
393 config_ns[name] = val
395
394
396 def expand_alias(self,line):
395 def expand_alias(self,line):
397 """ Expand an alias in the command line
396 """ Expand an alias in the command line
398
397
399 Returns the provided command line, possibly with the first word
398 Returns the provided command line, possibly with the first word
400 (command) translated according to alias expansion rules.
399 (command) translated according to alias expansion rules.
401
400
402 [ipython]|16> _ip.expand_aliases("np myfile.txt")
401 [ipython]|16> _ip.expand_aliases("np myfile.txt")
403 <16> 'q:/opt/np/notepad++.exe myfile.txt'
402 <16> 'q:/opt/np/notepad++.exe myfile.txt'
404 """
403 """
405
404
406 pre,fn,rest = self.IP.split_user_input(line)
405 pre,fn,rest = self.IP.split_user_input(line)
407 res = pre + self.IP.expand_aliases(fn,rest)
406 res = pre + self.IP.expand_aliases(fn,rest)
408 return res
407 return res
409
408
410 def itpl(self, s, depth = 1):
409 def itpl(self, s, depth = 1):
411 """ Expand Itpl format string s.
410 """ Expand Itpl format string s.
412
411
413 Only callable from command line (i.e. prefilter results);
412 Only callable from command line (i.e. prefilter results);
414 If you use in your scripts, you need to use a bigger depth!
413 If you use in your scripts, you need to use a bigger depth!
415 """
414 """
416 return self.IP.var_expand(s, depth)
415 return self.IP.var_expand(s, depth)
417
416
418 def defalias(self, name, cmd):
417 def defalias(self, name, cmd):
419 """ Define a new alias
418 """ Define a new alias
420
419
421 _ip.defalias('bb','bldmake bldfiles')
420 _ip.defalias('bb','bldmake bldfiles')
422
421
423 Creates a new alias named 'bb' in ipython user namespace
422 Creates a new alias named 'bb' in ipython user namespace
424 """
423 """
425
424
426 self.dbg.check_hotname(name)
425 self.dbg.check_hotname(name)
427
426
428 if name in self.IP.alias_table:
427 if name in self.IP.alias_table:
429 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
428 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
430 % (name, cmd, self.IP.alias_table[name]))
429 % (name, cmd, self.IP.alias_table[name]))
431
430
432 if callable(cmd):
431 if callable(cmd):
433 self.IP.alias_table[name] = cmd
432 self.IP.alias_table[name] = cmd
434 from IPython.core import shadowns
433 from IPython.core import shadowns
435 setattr(shadowns, name,cmd)
434 setattr(shadowns, name,cmd)
436 return
435 return
437
436
438 if isinstance(cmd,basestring):
437 if isinstance(cmd,basestring):
439 nargs = cmd.count('%s')
438 nargs = cmd.count('%s')
440 if nargs>0 and cmd.find('%l')>=0:
439 if nargs>0 and cmd.find('%l')>=0:
441 raise Exception('The %s and %l specifiers are mutually '
440 raise Exception('The %s and %l specifiers are mutually '
442 'exclusive in alias definitions.')
441 'exclusive in alias definitions.')
443
442
444 self.IP.alias_table[name] = (nargs,cmd)
443 self.IP.alias_table[name] = (nargs,cmd)
445 return
444 return
446
445
447 # just put it in - it's probably (0,'foo')
446 # just put it in - it's probably (0,'foo')
448 self.IP.alias_table[name] = cmd
447 self.IP.alias_table[name] = cmd
449
448
450 def defmacro(self, *args):
449 def defmacro(self, *args):
451 """ Define a new macro
450 """ Define a new macro
452
451
453 2 forms of calling:
452 2 forms of calling:
454
453
455 mac = _ip.defmacro('print "hello"\nprint "world"')
454 mac = _ip.defmacro('print "hello"\nprint "world"')
456
455
457 (doesn't put the created macro on user namespace)
456 (doesn't put the created macro on user namespace)
458
457
459 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
458 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
460
459
461 (creates a macro named 'build' in user namespace)
460 (creates a macro named 'build' in user namespace)
462 """
461 """
463
462
464 from IPython.core import macro
463 from IPython.core import macro
465
464
466 if len(args) == 1:
465 if len(args) == 1:
467 return macro.Macro(args[0])
466 return macro.Macro(args[0])
468 elif len(args) == 2:
467 elif len(args) == 2:
469 self.user_ns[args[0]] = macro.Macro(args[1])
468 self.user_ns[args[0]] = macro.Macro(args[1])
470 else:
469 else:
471 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
470 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
472
471
473 def set_next_input(self, s):
472 def set_next_input(self, s):
474 """ Sets the 'default' input string for the next command line.
473 """ Sets the 'default' input string for the next command line.
475
474
476 Requires readline.
475 Requires readline.
477
476
478 Example:
477 Example:
479
478
480 [D:\ipython]|1> _ip.set_next_input("Hello Word")
479 [D:\ipython]|1> _ip.set_next_input("Hello Word")
481 [D:\ipython]|2> Hello Word_ # cursor is here
480 [D:\ipython]|2> Hello Word_ # cursor is here
482 """
481 """
483
482
484 self.IP.rl_next_input = s
483 self.IP.rl_next_input = s
485
484
486 def load(self, mod):
485 def load(self, mod):
487 """ Load an extension.
486 """ Load an extension.
488
487
489 Some modules should (or must) be 'load()':ed, rather than just imported.
488 Some modules should (or must) be 'load()':ed, rather than just imported.
490
489
491 Loading will do:
490 Loading will do:
492
491
493 - run init_ipython(ip)
492 - run init_ipython(ip)
494 - run ipython_firstrun(ip)
493 - run ipython_firstrun(ip)
495 """
494 """
496
495
497 if mod in self.extensions:
496 if mod in self.extensions:
498 # just to make sure we don't init it twice
497 # just to make sure we don't init it twice
499 # note that if you 'load' a module that has already been
498 # note that if you 'load' a module that has already been
500 # imported, init_ipython gets run anyway
499 # imported, init_ipython gets run anyway
501
500
502 return self.extensions[mod]
501 return self.extensions[mod]
503 __import__(mod)
502 __import__(mod)
504 m = sys.modules[mod]
503 m = sys.modules[mod]
505 if hasattr(m,'init_ipython'):
504 if hasattr(m,'init_ipython'):
506 m.init_ipython(self)
505 m.init_ipython(self)
507
506
508 if hasattr(m,'ipython_firstrun'):
507 if hasattr(m,'ipython_firstrun'):
509 already_loaded = self.db.get('firstrun_done', set())
508 already_loaded = self.db.get('firstrun_done', set())
510 if mod not in already_loaded:
509 if mod not in already_loaded:
511 m.ipython_firstrun(self)
510 m.ipython_firstrun(self)
512 already_loaded.add(mod)
511 already_loaded.add(mod)
513 self.db['firstrun_done'] = already_loaded
512 self.db['firstrun_done'] = already_loaded
514
513
515 self.extensions[mod] = m
514 self.extensions[mod] = m
516 return m
515 return m
517
516
518
517
519 class DebugTools:
518 class DebugTools:
520 """ Used for debugging mishaps in api usage
519 """ Used for debugging mishaps in api usage
521
520
522 So far, tracing redefinitions is supported.
521 So far, tracing redefinitions is supported.
523 """
522 """
524
523
525 def __init__(self, ip):
524 def __init__(self, ip):
526 self.ip = ip
525 self.ip = ip
527 self.debugmode = False
526 self.debugmode = False
528 self.hotnames = set()
527 self.hotnames = set()
529
528
530 def hotname(self, name_to_catch):
529 def hotname(self, name_to_catch):
531 self.hotnames.add(name_to_catch)
530 self.hotnames.add(name_to_catch)
532
531
533 def debug_stack(self, msg = None):
532 def debug_stack(self, msg = None):
534 if not self.debugmode:
533 if not self.debugmode:
535 return
534 return
536
535
537 import traceback
536 import traceback
538 if msg is not None:
537 if msg is not None:
539 print '====== %s ========' % msg
538 print '====== %s ========' % msg
540 traceback.print_stack()
539 traceback.print_stack()
541
540
542 def check_hotname(self,name):
541 def check_hotname(self,name):
543 if name in self.hotnames:
542 if name in self.hotnames:
544 self.debug_stack( "HotName '%s' caught" % name)
543 self.debug_stack( "HotName '%s' caught" % name)
545
544
546
545
547 def launch_new_instance(user_ns = None,shellclass = None):
546 def launch_new_instance(user_ns = None,shellclass = None):
548 """ Make and start a new ipython instance.
547 """ Make and start a new ipython instance.
549
548
550 This can be called even without having an already initialized
549 This can be called even without having an already initialized
551 ipython session running.
550 ipython session running.
552
551
553 This is also used as the egg entry point for the 'ipython' script.
552 This is also used as the egg entry point for the 'ipython' script.
554
553
555 """
554 """
556 ses = make_session(user_ns,shellclass)
555 ses = make_session(user_ns,shellclass)
557 ses.mainloop()
556 ses.mainloop()
558
557
559
558
560 def make_user_ns(user_ns = None):
559 def make_user_ns(user_ns = None):
561 """Return a valid user interactive namespace.
560 """Return a valid user interactive namespace.
562
561
563 This builds a dict with the minimal information needed to operate as a
562 This builds a dict with the minimal information needed to operate as a
564 valid IPython user namespace, which you can pass to the various embedding
563 valid IPython user namespace, which you can pass to the various embedding
565 classes in ipython.
564 classes in ipython.
566
565
567 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
566 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
568 to make both the local and global namespace objects simultaneously.
567 to make both the local and global namespace objects simultaneously.
569
568
570 :Parameters:
569 :Parameters:
571 user_ns : dict-like, optional
570 user_ns : dict-like, optional
572 The current user namespace. The items in this namespace should be
571 The current user namespace. The items in this namespace should be
573 included in the output. If None, an appropriate blank namespace
572 included in the output. If None, an appropriate blank namespace
574 should be created.
573 should be created.
575
574
576 :Returns:
575 :Returns:
577 A dictionary-like object to be used as the local namespace of the
576 A dictionary-like object to be used as the local namespace of the
578 interpreter.
577 interpreter.
579 """
578 """
580
579
581 raise NotImplementedError
580 raise NotImplementedError
582
581
583
582
584 def make_user_global_ns(ns = None):
583 def make_user_global_ns(ns = None):
585 """Return a valid user global namespace.
584 """Return a valid user global namespace.
586
585
587 Similar to make_user_ns(), but global namespaces are really only needed in
586 Similar to make_user_ns(), but global namespaces are really only needed in
588 embedded applications, where there is a distinction between the user's
587 embedded applications, where there is a distinction between the user's
589 interactive namespace and the global one where ipython is running.
588 interactive namespace and the global one where ipython is running.
590
589
591 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
590 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
592 to make both the local and global namespace objects simultaneously.
591 to make both the local and global namespace objects simultaneously.
593
592
594 :Parameters:
593 :Parameters:
595 ns : dict, optional
594 ns : dict, optional
596 The current user global namespace. The items in this namespace
595 The current user global namespace. The items in this namespace
597 should be included in the output. If None, an appropriate blank
596 should be included in the output. If None, an appropriate blank
598 namespace should be created.
597 namespace should be created.
599
598
600 :Returns:
599 :Returns:
601 A true dict to be used as the global namespace of the interpreter.
600 A true dict to be used as the global namespace of the interpreter.
602 """
601 """
603
602
604 raise NotImplementedError
603 raise NotImplementedError
605
604
606 # Record the true objects in order to be able to test if the user has overridden
605 # Record the true objects in order to be able to test if the user has overridden
607 # these API functions.
606 # these API functions.
608 _make_user_ns = make_user_ns
607 _make_user_ns = make_user_ns
609 _make_user_global_ns = make_user_global_ns
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 """Return a valid local and global user interactive namespaces.
612 """Return a valid local and global user interactive namespaces.
614
613
615 This builds a dict with the minimal information needed to operate as a
614 This builds a dict with the minimal information needed to operate as a
616 valid IPython user namespace, which you can pass to the various embedding
615 valid IPython user namespace, which you can pass to the various embedding
617 classes in ipython. The default implementation returns the same dict for
616 classes in ipython. The default implementation returns the same dict for
618 both the locals and the globals to allow functions to refer to variables in
617 both the locals and the globals to allow functions to refer to variables in
619 the namespace. Customized implementations can return different dicts. The
618 the namespace. Customized implementations can return different dicts. The
620 locals dictionary can actually be anything following the basic mapping
619 locals dictionary can actually be anything following the basic mapping
621 protocol of a dict, but the globals dict must be a true dict, not even
620 protocol of a dict, but the globals dict must be a true dict, not even
622 a subclass. It is recommended that any custom object for the locals
621 a subclass. It is recommended that any custom object for the locals
623 namespace synchronize with the globals dict somehow.
622 namespace synchronize with the globals dict somehow.
624
623
625 Raises TypeError if the provided globals namespace is not a true dict.
624 Raises TypeError if the provided globals namespace is not a true dict.
626
625
627 :Parameters:
626 :Parameters:
628 user_ns : dict-like, optional
627 user_ns : dict-like, optional
629 The current user namespace. The items in this namespace should be
628 The current user namespace. The items in this namespace should be
630 included in the output. If None, an appropriate blank namespace
629 included in the output. If None, an appropriate blank namespace
631 should be created.
630 should be created.
632 user_global_ns : dict, optional
631 user_global_ns : dict, optional
633 The current user global namespace. The items in this namespace
632 The current user global namespace. The items in this namespace
634 should be included in the output. If None, an appropriate blank
633 should be included in the output. If None, an appropriate blank
635 namespace should be created.
634 namespace should be created.
636
635
637 :Returns:
636 :Returns:
638 A tuple pair of dictionary-like object to be used as the local namespace
637 A tuple pair of dictionary-like object to be used as the local namespace
639 of the interpreter and a dict to be used as the global namespace.
638 of the interpreter and a dict to be used as the global namespace.
640 """
639 """
641
640
642 if user_ns is None:
641 if user_ns is None:
643 if make_user_ns is not _make_user_ns:
642 if make_user_ns is not _make_user_ns:
644 # Old API overridden.
643 # Old API overridden.
645 # FIXME: Issue DeprecationWarning, or just let the old API live on?
644 # FIXME: Issue DeprecationWarning, or just let the old API live on?
646 user_ns = make_user_ns(user_ns)
645 user_ns = make_user_ns(user_ns)
647 else:
646 else:
648 # Set __name__ to __main__ to better match the behavior of the
647 # Set __name__ to __main__ to better match the behavior of the
649 # normal interpreter.
648 # normal interpreter.
650 user_ns = {'__name__' :'__main__',
649 user_ns = {'__name__' :'__main__',
651 '__builtins__' : __builtin__,
650 '__builtins__' : __builtin__,
652 }
651 }
653 else:
652 else:
654 user_ns.setdefault('__name__','__main__')
653 user_ns.setdefault('__name__','__main__')
655 user_ns.setdefault('__builtins__',__builtin__)
654 user_ns.setdefault('__builtins__',__builtin__)
656
655
657 if user_global_ns is None:
656 if user_global_ns is None:
658 if make_user_global_ns is not _make_user_global_ns:
657 if make_user_global_ns is not _make_user_global_ns:
659 # Old API overridden.
658 # Old API overridden.
660 user_global_ns = make_user_global_ns(user_global_ns)
659 user_global_ns = make_user_global_ns(user_global_ns)
661 else:
660 else:
662 user_global_ns = user_ns
661 user_global_ns = user_ns
663 if type(user_global_ns) is not dict:
662 if type(user_global_ns) is not dict:
664 raise TypeError("user_global_ns must be a true dict; got %r"
663 raise TypeError("user_global_ns must be a true dict; got %r"
665 % type(user_global_ns))
664 % type(user_global_ns))
666
665
667 return user_ns, user_global_ns
666 return user_ns, user_global_ns
668
667
669
668
670 def make_session(user_ns = None, shellclass = None):
669 def make_session(user_ns = None, shellclass = None):
671 """Makes, but does not launch an IPython session.
670 """Makes, but does not launch an IPython session.
672
671
673 Later on you can call obj.mainloop() on the returned object.
672 Later on you can call obj.mainloop() on the returned object.
674
673
675 Inputs:
674 Inputs:
676
675
677 - user_ns(None): a dict to be used as the user's namespace with initial
676 - user_ns(None): a dict to be used as the user's namespace with initial
678 data.
677 data.
679
678
680 WARNING: This should *not* be run when a session exists already."""
679 WARNING: This should *not* be run when a session exists already."""
681
680
682 import IPython.core.shell
681 import IPython.core.shell
683 if shellclass is None:
682 if shellclass is None:
684 return IPython.core.shell.start(user_ns)
683 return IPython.core.shell.start(user_ns)
685 return shellclass(user_ns = user_ns)
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 Main IPython Component
4
5 Requires Python 2.4 or newer.
6
7 This file contains all the classes and helper functions specific to IPython.
8 """
4 """
9
5
10 #*****************************************************************************
6 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
13 #
10 #
14 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
16 #
13 #-----------------------------------------------------------------------------
17 # Note: this code originally subclassed code.InteractiveConsole from the
14
18 # Python standard library. Over time, all of that class has been copied
15 #-----------------------------------------------------------------------------
19 # verbatim here for modifications which could not be accomplished by
16 # Imports
20 # subclassing. At this point, there are no dependencies at all on the code
17 #-----------------------------------------------------------------------------
21 # module anymore (it is not even imported). The Python License (sec. 2)
18
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
30 import __main__
19 import __main__
31 import __builtin__
20 import __builtin__
32 import StringIO
21 import StringIO
33 import bdb
22 import bdb
34 import codeop
23 import codeop
35 import exceptions
24 import exceptions
36 import glob
25 import glob
37 import keyword
26 import keyword
38 import new
27 import new
39 import os
28 import os
40 import re
29 import re
41 import shutil
30 import shutil
42 import string
31 import string
43 import sys
32 import sys
44 import tempfile
33 import tempfile
45
34
46 # IPython's own modules
47 #import IPython
48 from IPython.core import ultratb
35 from IPython.core import ultratb
49 from IPython.utils import PyColorize
50 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
51 from IPython.extensions import pickleshare
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 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
53 from IPython.external.Itpl import ItplNS
54 from IPython.core.logger import Logger
42 from IPython.core.logger import Logger
55 from IPython.core.magic import Magic
43 from IPython.core.magic import Magic
56 from IPython.core.prompts import CachedOutput
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 from IPython.lib.backgroundjobs import BackgroundJobManager
51 from IPython.lib.backgroundjobs import BackgroundJobManager
52 from IPython.utils.ipstruct import Struct
53 from IPython.utils import PyColorize
59 from IPython.utils.genutils import *
54 from IPython.utils.genutils import *
60 from IPython.utils.strdispatch import StrDispatch
55 from IPython.utils.strdispatch import StrDispatch
61 from IPython.core import ipapi
56
62 import IPython.core.history
57 from IPython.utils.traitlets import (
63 import IPython.core.prefilter as prefilter
58 Int, Float, Str, Bool
64 from IPython.core import shadowns
59 )
60
61 #-----------------------------------------------------------------------------
65 # Globals
62 # Globals
63 #-----------------------------------------------------------------------------
64
66
65
67 # store the builtin raw_input globally, and use this always, in case user code
66 # store the builtin raw_input globally, and use this always, in case user code
68 # overwrites it (like wx.py.PyShell does)
67 # overwrites it (like wx.py.PyShell does)
69 raw_input_original = raw_input
68 raw_input_original = raw_input
70
69
71 # compiled regexps for autoindent management
70 # compiled regexps for autoindent management
72 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
71 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
73
72
74
73
75 #****************************************************************************
74 #-----------------------------------------------------------------------------
76 # Some utility function definitions
75 # Utilities
76 #-----------------------------------------------------------------------------
77
77
78
78 ini_spaces_re = re.compile(r'^(\s+)')
79 ini_spaces_re = re.compile(r'^(\s+)')
79
80
81
80 def num_ini_spaces(strng):
82 def num_ini_spaces(strng):
81 """Return the number of initial spaces in a string"""
83 """Return the number of initial spaces in a string"""
82
84
83 ini_spaces = ini_spaces_re.match(strng)
85 ini_spaces = ini_spaces_re.match(strng)
84 if ini_spaces:
86 if ini_spaces:
85 return ini_spaces.end()
87 return ini_spaces.end()
86 else:
88 else:
87 return 0
89 return 0
88
90
91
89 def softspace(file, newvalue):
92 def softspace(file, newvalue):
90 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
91
94
92 oldvalue = 0
95 oldvalue = 0
93 try:
96 try:
94 oldvalue = file.softspace
97 oldvalue = file.softspace
95 except AttributeError:
98 except AttributeError:
96 pass
99 pass
97 try:
100 try:
98 file.softspace = newvalue
101 file.softspace = newvalue
99 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
100 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
101 pass
104 pass
102 return oldvalue
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 class SpaceInInput(exceptions.Exception): pass
108 class SpaceInInput(exceptions.Exception): pass
303
109
304
305 #****************************************************************************
306 # Local use classes
307 class Bunch: pass
110 class Bunch: pass
308
111
309 class Undefined: pass
112 class Undefined: pass
310
113
311 class Quitter(object):
114 class Quitter(object):
312 """Simple class to handle exit, similar to Python 2.5's.
115 """Simple class to handle exit, similar to Python 2.5's.
313
116
314 It handles exiting in an ipython-safe manner, which the one in Python 2.5
117 It handles exiting in an ipython-safe manner, which the one in Python 2.5
315 doesn't do (obviously, since it doesn't know about ipython)."""
118 doesn't do (obviously, since it doesn't know about ipython)."""
316
119
317 def __init__(self,shell,name):
120 def __init__(self,shell,name):
318 self.shell = shell
121 self.shell = shell
319 self.name = name
122 self.name = name
320
123
321 def __repr__(self):
124 def __repr__(self):
322 return 'Type %s() to exit.' % self.name
125 return 'Type %s() to exit.' % self.name
323 __str__ = __repr__
126 __str__ = __repr__
324
127
325 def __call__(self):
128 def __call__(self):
326 self.shell.exit()
129 self.shell.exit()
327
130
328 class InputList(list):
131 class InputList(list):
329 """Class to store user input.
132 """Class to store user input.
330
133
331 It's basically a list, but slices return a string instead of a list, thus
134 It's basically a list, but slices return a string instead of a list, thus
332 allowing things like (assuming 'In' is an instance):
135 allowing things like (assuming 'In' is an instance):
333
136
334 exec In[4:7]
137 exec In[4:7]
335
138
336 or
139 or
337
140
338 exec In[5:9] + In[14] + In[21:25]"""
141 exec In[5:9] + In[14] + In[21:25]"""
339
142
340 def __getslice__(self,i,j):
143 def __getslice__(self,i,j):
341 return ''.join(list.__getslice__(self,i,j))
144 return ''.join(list.__getslice__(self,i,j))
342
145
343 class SyntaxTB(ultratb.ListTB):
146 class SyntaxTB(ultratb.ListTB):
344 """Extension which holds some state: the last exception value"""
147 """Extension which holds some state: the last exception value"""
345
148
346 def __init__(self,color_scheme = 'NoColor'):
149 def __init__(self,color_scheme = 'NoColor'):
347 ultratb.ListTB.__init__(self,color_scheme)
150 ultratb.ListTB.__init__(self,color_scheme)
348 self.last_syntax_error = None
151 self.last_syntax_error = None
349
152
350 def __call__(self, etype, value, elist):
153 def __call__(self, etype, value, elist):
351 self.last_syntax_error = value
154 self.last_syntax_error = value
352 ultratb.ListTB.__call__(self,etype,value,elist)
155 ultratb.ListTB.__call__(self,etype,value,elist)
353
156
354 def clear_err_state(self):
157 def clear_err_state(self):
355 """Return the current error state and clear it"""
158 """Return the current error state and clear it"""
356 e = self.last_syntax_error
159 e = self.last_syntax_error
357 self.last_syntax_error = None
160 self.last_syntax_error = None
358 return e
161 return e
359
162
360 #****************************************************************************
163
164 #-----------------------------------------------------------------------------
361 # Main IPython class
165 # Main IPython class
166 #-----------------------------------------------------------------------------
362
167
363 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
168 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
364 # until a full rewrite is made. I've cleaned all cross-class uses of
169 # until a full rewrite is made. I've cleaned all cross-class uses of
365 # attributes and methods, but too much user code out there relies on the
170 # attributes and methods, but too much user code out there relies on the
366 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
171 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
367 #
172 #
368 # But at least now, all the pieces have been separated and we could, in
173 # But at least now, all the pieces have been separated and we could, in
369 # principle, stop using the mixin. This will ease the transition to the
174 # principle, stop using the mixin. This will ease the transition to the
370 # chainsaw branch.
175 # chainsaw branch.
371
176
372 # For reference, the following is the list of 'self.foo' uses in the Magic
177 # For reference, the following is the list of 'self.foo' uses in the Magic
373 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
178 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
374 # class, to prevent clashes.
179 # class, to prevent clashes.
375
180
376 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
181 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
377 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
182 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
378 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
183 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
379 # 'self.value']
184 # 'self.value']
380
185
381 class InteractiveShell(object,Magic):
186 class InteractiveShell(Component, Magic):
382 """An enhanced console for Python."""
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 # class attribute to indicate whether the class supports threads or not.
262 # class attribute to indicate whether the class supports threads or not.
385 # Subclasses with thread support should override this as needed.
263 # Subclasses with thread support should override this as needed.
386 isthreaded = False
264 isthreaded = False
387
265
388 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
266 def __init__(self, name, parent=None, config=None, usage=None,
389 user_ns=None,user_global_ns=None,banner2='',
267 user_ns=None, user_global_ns=None, banner2='',
390 custom_exceptions=((),None),embedded=False):
268 custom_exceptions=((),None), embedded=False):
391
269
392 # log system
270 super(InteractiveShell, self).__init__(parent, config=config, name=name)
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()
397
271
398 # Store the actual shell's name
272 self.init_instance_attrs()
399 self.name = name
273 self.init_usage(usage)
400 self.more = False
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
281 Magic.__init__(self, self)
403 # global/local namespaces need to be handled differently in that case
282
404 self.embedded = embedded
283 self.init_syntax_highlighting()
405 if embedded:
284 self.init_hooks()
406 # Control variable so users can, from within the embedded instance,
285 self.init_pushd_popd_magic()
407 # permanently deactivate it.
286 self.init_traceback_handlers(custom_exceptions)
408 self.embedded_active = True
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 # command compiler
303 # command compiler
411 self.compile = codeop.CommandCompiler()
304 self.compile = codeop.CommandCompiler()
412
305
413 # User input buffer
306 # User input buffer
414 self.buffer = []
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 # Make an empty namespace, which extension writers can rely on both
309 # Make an empty namespace, which extension writers can rely on both
425 # existing and NEVER being used by ipython itself. This gives them a
310 # existing and NEVER being used by ipython itself. This gives them a
426 # convenient location for storing additional information and state
311 # convenient location for storing additional information and state
427 # their extensions may require, without fear of collisions with other
312 # their extensions may require, without fear of collisions with other
428 # ipython names that may develop later.
313 # ipython names that may develop later.
429 self.meta = Struct()
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 # Create the namespace where the user will operate. user_ns is
364 # Create the namespace where the user will operate. user_ns is
432 # normally the only one used, and it is passed to the exec calls as
365 # normally the only one used, and it is passed to the exec calls as
433 # the locals argument. But we do carry a user_global_ns namespace
366 # the locals argument. But we do carry a user_global_ns namespace
434 # given as the exec 'globals' argument, This is useful in embedding
367 # given as the exec 'globals' argument, This is useful in embedding
435 # situations where the ipython shell opens in a context where the
368 # situations where the ipython shell opens in a context where the
436 # distinction between locals and globals is meaningful. For
369 # distinction between locals and globals is meaningful. For
437 # non-embedded contexts, it is just the same object as the user_ns dict.
370 # non-embedded contexts, it is just the same object as the user_ns dict.
438
371
439 # FIXME. For some strange reason, __builtins__ is showing up at user
372 # FIXME. For some strange reason, __builtins__ is showing up at user
440 # level as a dict instead of a module. This is a manual fix, but I
373 # level as a dict instead of a module. This is a manual fix, but I
441 # should really track down where the problem is coming from. Alex
374 # should really track down where the problem is coming from. Alex
442 # Schmolck reported this problem first.
375 # Schmolck reported this problem first.
443
376
444 # A useful post by Alex Martelli on this topic:
377 # A useful post by Alex Martelli on this topic:
445 # Re: inconsistent value from __builtins__
378 # Re: inconsistent value from __builtins__
446 # Von: Alex Martelli <aleaxit@yahoo.com>
379 # Von: Alex Martelli <aleaxit@yahoo.com>
447 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
380 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
448 # Gruppen: comp.lang.python
381 # Gruppen: comp.lang.python
449
382
450 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
383 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
451 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
384 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
452 # > <type 'dict'>
385 # > <type 'dict'>
453 # > >>> print type(__builtins__)
386 # > >>> print type(__builtins__)
454 # > <type 'module'>
387 # > <type 'module'>
455 # > Is this difference in return value intentional?
388 # > Is this difference in return value intentional?
456
389
457 # Well, it's documented that '__builtins__' can be either a dictionary
390 # Well, it's documented that '__builtins__' can be either a dictionary
458 # or a module, and it's been that way for a long time. Whether it's
391 # or a module, and it's been that way for a long time. Whether it's
459 # intentional (or sensible), I don't know. In any case, the idea is
392 # intentional (or sensible), I don't know. In any case, the idea is
460 # that if you need to access the built-in namespace directly, you
393 # that if you need to access the built-in namespace directly, you
461 # should start with "import __builtin__" (note, no 's') which will
394 # should start with "import __builtin__" (note, no 's') which will
462 # definitely give you a module. Yeah, it's somewhat confusing:-(.
395 # definitely give you a module. Yeah, it's somewhat confusing:-(.
463
396
464 # These routines return properly built dicts as needed by the rest of
397 # These routines return properly built dicts as needed by the rest of
465 # the code, and can also be used by extension writers to generate
398 # the code, and can also be used by extension writers to generate
466 # properly initialized namespaces.
399 # properly initialized namespaces.
467 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
400 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
468 user_global_ns)
401 user_global_ns)
469
402
470 # Assign namespaces
403 # Assign namespaces
471 # This is the namespace where all normal user variables live
404 # This is the namespace where all normal user variables live
472 self.user_ns = user_ns
405 self.user_ns = user_ns
473 self.user_global_ns = user_global_ns
406 self.user_global_ns = user_global_ns
474
407
475 # An auxiliary namespace that checks what parts of the user_ns were
408 # An auxiliary namespace that checks what parts of the user_ns were
476 # loaded at startup, so we can list later only variables defined in
409 # loaded at startup, so we can list later only variables defined in
477 # actual interactive use. Since it is always a subset of user_ns, it
410 # actual interactive use. Since it is always a subset of user_ns, it
478 # doesn't need to be seaparately tracked in the ns_table
411 # doesn't need to be seaparately tracked in the ns_table
479 self.user_config_ns = {}
412 self.user_config_ns = {}
480
413
481 # A namespace to keep track of internal data structures to prevent
414 # A namespace to keep track of internal data structures to prevent
482 # them from cluttering user-visible stuff. Will be updated later
415 # them from cluttering user-visible stuff. Will be updated later
483 self.internal_ns = {}
416 self.internal_ns = {}
484
417
485 # Namespace of system aliases. Each entry in the alias
418 # Namespace of system aliases. Each entry in the alias
486 # table must be a 2-tuple of the form (N,name), where N is the number
419 # table must be a 2-tuple of the form (N,name), where N is the number
487 # of positional arguments of the alias.
420 # of positional arguments of the alias.
488 self.alias_table = {}
421 self.alias_table = {}
489
422
490 # Now that FakeModule produces a real module, we've run into a nasty
423 # Now that FakeModule produces a real module, we've run into a nasty
491 # problem: after script execution (via %run), the module where the user
424 # problem: after script execution (via %run), the module where the user
492 # code ran is deleted. Now that this object is a true module (needed
425 # code ran is deleted. Now that this object is a true module (needed
493 # so docetst and other tools work correctly), the Python module
426 # so docetst and other tools work correctly), the Python module
494 # teardown mechanism runs over it, and sets to None every variable
427 # teardown mechanism runs over it, and sets to None every variable
495 # present in that module. Top-level references to objects from the
428 # present in that module. Top-level references to objects from the
496 # script survive, because the user_ns is updated with them. However,
429 # script survive, because the user_ns is updated with them. However,
497 # calling functions defined in the script that use other things from
430 # calling functions defined in the script that use other things from
498 # the script will fail, because the function's closure had references
431 # the script will fail, because the function's closure had references
499 # to the original objects, which are now all None. So we must protect
432 # to the original objects, which are now all None. So we must protect
500 # these modules from deletion by keeping a cache.
433 # these modules from deletion by keeping a cache.
501 #
434 #
502 # To avoid keeping stale modules around (we only need the one from the
435 # To avoid keeping stale modules around (we only need the one from the
503 # last run), we use a dict keyed with the full path to the script, so
436 # last run), we use a dict keyed with the full path to the script, so
504 # only the last version of the module is held in the cache. Note,
437 # only the last version of the module is held in the cache. Note,
505 # however, that we must cache the module *namespace contents* (their
438 # however, that we must cache the module *namespace contents* (their
506 # __dict__). Because if we try to cache the actual modules, old ones
439 # __dict__). Because if we try to cache the actual modules, old ones
507 # (uncached) could be destroyed while still holding references (such as
440 # (uncached) could be destroyed while still holding references (such as
508 # those held by GUI objects that tend to be long-lived)>
441 # those held by GUI objects that tend to be long-lived)>
509 #
442 #
510 # The %reset command will flush this cache. See the cache_main_mod()
443 # The %reset command will flush this cache. See the cache_main_mod()
511 # and clear_main_mod_cache() methods for details on use.
444 # and clear_main_mod_cache() methods for details on use.
512
445
513 # This is the cache used for 'main' namespaces
446 # This is the cache used for 'main' namespaces
514 self._main_ns_cache = {}
447 self._main_ns_cache = {}
515 # And this is the single instance of FakeModule whose __dict__ we keep
448 # And this is the single instance of FakeModule whose __dict__ we keep
516 # copying and clearing for reuse on each %run
449 # copying and clearing for reuse on each %run
517 self._user_main_module = FakeModule()
450 self._user_main_module = FakeModule()
518
451
519 # A table holding all the namespaces IPython deals with, so that
452 # A table holding all the namespaces IPython deals with, so that
520 # introspection facilities can search easily.
453 # introspection facilities can search easily.
521 self.ns_table = {'user':user_ns,
454 self.ns_table = {'user':user_ns,
522 'user_global':user_global_ns,
455 'user_global':user_global_ns,
523 'alias':self.alias_table,
456 'alias':self.alias_table,
524 'internal':self.internal_ns,
457 'internal':self.internal_ns,
525 'builtin':__builtin__.__dict__
458 'builtin':__builtin__.__dict__
526 }
459 }
527
460
528 # Similarly, track all namespaces where references can be held and that
461 # Similarly, track all namespaces where references can be held and that
529 # we can safely clear (so it can NOT include builtin). This one can be
462 # we can safely clear (so it can NOT include builtin). This one can be
530 # a simple list.
463 # a simple list.
531 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
464 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
532 self.alias_table, self.internal_ns,
465 self.alias_table, self.internal_ns,
533 self._main_ns_cache ]
466 self._main_ns_cache ]
534
467
535 # We need to insert into sys.modules something that looks like a
468 # We need to insert into sys.modules something that looks like a
536 # module but which accesses the IPython namespace, for shelve and
469 # module but which accesses the IPython namespace, for shelve and
537 # pickle to work interactively. Normally they rely on getting
470 # pickle to work interactively. Normally they rely on getting
538 # everything out of __main__, but for embedding purposes each IPython
471 # everything out of __main__, but for embedding purposes each IPython
539 # instance has its own private namespace, so we can't go shoving
472 # instance has its own private namespace, so we can't go shoving
540 # everything into __main__.
473 # everything into __main__.
541
474
542 # note, however, that we should only do this for non-embedded
475 # note, however, that we should only do this for non-embedded
543 # ipythons, which really mimic the __main__.__dict__ with their own
476 # ipythons, which really mimic the __main__.__dict__ with their own
544 # namespace. Embedded instances, on the other hand, should not do
477 # namespace. Embedded instances, on the other hand, should not do
545 # this because they need to manage the user local/global namespaces
478 # this because they need to manage the user local/global namespaces
546 # only, but they live within a 'normal' __main__ (meaning, they
479 # only, but they live within a 'normal' __main__ (meaning, they
547 # shouldn't overtake the execution environment of the script they're
480 # shouldn't overtake the execution environment of the script they're
548 # embedded in).
481 # embedded in).
549
482
550 if not embedded:
483 if not self.embedded:
551 try:
484 try:
552 main_name = self.user_ns['__name__']
485 main_name = self.user_ns['__name__']
553 except KeyError:
486 except KeyError:
554 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
487 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
555 else:
488 else:
556 #print "pickle hack in place" # dbg
557 #print 'main_name:',main_name # dbg
558 sys.modules[main_name] = FakeModule(self.user_ns)
489 sys.modules[main_name] = FakeModule(self.user_ns)
559
490
491 def init_history(self):
560 # List of input with multi-line handling.
492 # List of input with multi-line handling.
561 self.input_hist = InputList()
493 self.input_hist = InputList()
562 # This one will hold the 'raw' input history, without any
494 # This one will hold the 'raw' input history, without any
563 # pre-processing. This will allow users to retrieve the input just as
495 # pre-processing. This will allow users to retrieve the input just as
564 # it was exactly typed in by the user, with %hist -r.
496 # it was exactly typed in by the user, with %hist -r.
565 self.input_hist_raw = InputList()
497 self.input_hist_raw = InputList()
566
498
567 # list of visited directories
499 # list of visited directories
568 try:
500 try:
569 self.dir_hist = [os.getcwd()]
501 self.dir_hist = [os.getcwd()]
570 except OSError:
502 except OSError:
571 self.dir_hist = []
503 self.dir_hist = []
572
504
573 # dict of output history
505 # dict of output history
574 self.output_hist = {}
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 # Get system encoding at startup time. Certain terminals (like Emacs
516 # Get system encoding at startup time. Certain terminals (like Emacs
577 # under Win32 have it set to None, and we need to have a known valid
517 # under Win32 have it set to None, and we need to have a known valid
578 # encoding to use in the raw_input() method
518 # encoding to use in the raw_input() method
579 try:
519 try:
580 self.stdin_encoding = sys.stdin.encoding or 'ascii'
520 self.stdin_encoding = sys.stdin.encoding or 'ascii'
581 except AttributeError:
521 except AttributeError:
582 self.stdin_encoding = 'ascii'
522 self.stdin_encoding = 'ascii'
583
523
584 # dict of things NOT to alias (keywords, builtins and some magics)
524 def init_handlers(self):
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
598 # escapes for automatic behavior on the command line
525 # escapes for automatic behavior on the command line
599 self.ESC_SHELL = '!'
526 self.ESC_SHELL = '!'
600 self.ESC_SH_CAP = '!!'
527 self.ESC_SH_CAP = '!!'
601 self.ESC_HELP = '?'
528 self.ESC_HELP = '?'
602 self.ESC_MAGIC = '%'
529 self.ESC_MAGIC = '%'
603 self.ESC_QUOTE = ','
530 self.ESC_QUOTE = ','
604 self.ESC_QUOTE2 = ';'
531 self.ESC_QUOTE2 = ';'
605 self.ESC_PAREN = '/'
532 self.ESC_PAREN = '/'
606
533
607 # And their associated handlers
534 # And their associated handlers
608 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
535 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
609 self.ESC_QUOTE : self.handle_auto,
536 self.ESC_QUOTE : self.handle_auto,
610 self.ESC_QUOTE2 : self.handle_auto,
537 self.ESC_QUOTE2 : self.handle_auto,
611 self.ESC_MAGIC : self.handle_magic,
538 self.ESC_MAGIC : self.handle_magic,
612 self.ESC_HELP : self.handle_help,
539 self.ESC_HELP : self.handle_help,
613 self.ESC_SHELL : self.handle_shell_escape,
540 self.ESC_SHELL : self.handle_shell_escape,
614 self.ESC_SH_CAP : self.handle_shell_escape,
541 self.ESC_SH_CAP : self.handle_shell_escape,
615 }
542 }
616
543
617 # class initializations
544 def init_syntax_highlighting(self):
618 Magic.__init__(self,self)
619
620 # Python source parser/formatter for syntax highlighting
545 # Python source parser/formatter for syntax highlighting
621 pyformat = PyColorize.Parser().format
546 pyformat = PyColorize.Parser().format
622 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
547 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
623
548
549 def init_hooks(self):
624 # hooks holds pointers used for user-side customizations
550 # hooks holds pointers used for user-side customizations
625 self.hooks = Struct()
551 self.hooks = Struct()
626
552
627 self.strdispatchers = {}
553 self.strdispatchers = {}
628
554
629 # Set all default hooks, defined in the IPython.hooks module.
555 # Set all default hooks, defined in the IPython.hooks module.
630 import IPython.core.hooks
556 import IPython.core.hooks
631 hooks = IPython.core.hooks
557 hooks = IPython.core.hooks
632 for hook_name in hooks.__all__:
558 for hook_name in hooks.__all__:
633 # default hooks have priority 100, i.e. low; user hooks should have
559 # default hooks have priority 100, i.e. low; user hooks should have
634 # 0-100 priority
560 # 0-100 priority
635 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
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)
563 def init_pushd_popd_magic(self):
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 """
674 # for pushd/popd management
564 # for pushd/popd management
675 try:
565 try:
676 self.home_dir = get_home_dir()
566 self.home_dir = get_home_dir()
677 except HomeDirError,msg:
567 except HomeDirError, msg:
678 fatal(msg)
568 fatal(msg)
679
569
680 self.dir_stack = []
570 self.dir_stack = []
681
571
682 # Functions to call the underlying shell.
572 def init_traceback_handlers(self, custom_exceptions):
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
711 # Syntax error handler.
573 # Syntax error handler.
712 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
574 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
713
575
714 # The interactive one is initialized with an offset, meaning we always
576 # The interactive one is initialized with an offset, meaning we always
715 # want to remove the topmost item in the traceback, which is our own
577 # want to remove the topmost item in the traceback, which is our own
716 # internal code. Valid modes: ['Plain','Context','Verbose']
578 # internal code. Valid modes: ['Plain','Context','Verbose']
717 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
579 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
718 color_scheme='NoColor',
580 color_scheme='NoColor',
719 tb_offset = 1)
581 tb_offset = 1)
720
582
721 # IPython itself shouldn't crash. This will produce a detailed
583 # IPython itself shouldn't crash. This will produce a detailed
722 # post-mortem if it does. But we only install the crash handler for
584 # post-mortem if it does. But we only install the crash handler for
723 # non-threaded shells, the threaded ones use a normal verbose reporter
585 # non-threaded shells, the threaded ones use a normal verbose reporter
724 # and lose the crash handler. This is because exceptions in the main
586 # and lose the crash handler. This is because exceptions in the main
725 # thread (such as in GUI code) propagate directly to sys.excepthook,
587 # thread (such as in GUI code) propagate directly to sys.excepthook,
726 # and there's no point in printing crash dumps for every user exception.
588 # and there's no point in printing crash dumps for every user exception.
727 if self.isthreaded:
589 if self.isthreaded:
728 ipCrashHandler = ultratb.FormattedTB()
590 ipCrashHandler = ultratb.FormattedTB()
729 else:
591 else:
730 from IPython.core import crashhandler
592 from IPython.core import crashhandler
731 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
593 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
732 self.set_crash_handler(ipCrashHandler)
594 self.set_crash_handler(ipCrashHandler)
733
595
734 # and add any custom exception handlers the user may have specified
596 # and add any custom exception handlers the user may have specified
735 self.set_custom_exc(*custom_exceptions)
597 self.set_custom_exc(*custom_exceptions)
736
598
737 # indentation management
599 def init_logger(self):
738 self.autoindent = False
600 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
739 self.indent_current_nsp = 0
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 # Make some aliases automatically
631 # Make some aliases automatically
742 # Prepare list of shell aliases to auto-define
632 # Prepare list of shell aliases to auto-define
743 if os.name == 'posix':
633 if os.name == 'posix':
744 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
634 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
745 'mv mv -i','rm rm -i','cp cp -i',
635 'mv mv -i','rm rm -i','cp cp -i',
746 'cat cat','less less','clear clear',
636 'cat cat','less less','clear clear',
747 # a better ls
637 # a better ls
748 'ls ls -F',
638 'ls ls -F',
749 # long ls
639 # long ls
750 'll ls -lF')
640 'll ls -lF')
751 # Extra ls aliases with color, which need special treatment on BSD
641 # Extra ls aliases with color, which need special treatment on BSD
752 # variants
642 # variants
753 ls_extra = ( # color ls
643 ls_extra = ( # color ls
754 'lc ls -F -o --color',
644 'lc ls -F -o --color',
755 # ls normal files only
645 # ls normal files only
756 'lf ls -F -o --color %l | grep ^-',
646 'lf ls -F -o --color %l | grep ^-',
757 # ls symbolic links
647 # ls symbolic links
758 'lk ls -F -o --color %l | grep ^l',
648 'lk ls -F -o --color %l | grep ^l',
759 # directories or links to directories,
649 # directories or links to directories,
760 'ldir ls -F -o --color %l | grep /$',
650 'ldir ls -F -o --color %l | grep /$',
761 # things which are executable
651 # things which are executable
762 'lx ls -F -o --color %l | grep ^-..x',
652 'lx ls -F -o --color %l | grep ^-..x',
763 )
653 )
764 # The BSDs don't ship GNU ls, so they don't understand the
654 # The BSDs don't ship GNU ls, so they don't understand the
765 # --color switch out of the box
655 # --color switch out of the box
766 if 'bsd' in sys.platform:
656 if 'bsd' in sys.platform:
767 ls_extra = ( # ls normal files only
657 ls_extra = ( # ls normal files only
768 'lf ls -lF | grep ^-',
658 'lf ls -lF | grep ^-',
769 # ls symbolic links
659 # ls symbolic links
770 'lk ls -lF | grep ^l',
660 'lk ls -lF | grep ^l',
771 # directories or links to directories,
661 # directories or links to directories,
772 'ldir ls -lF | grep /$',
662 'ldir ls -lF | grep /$',
773 # things which are executable
663 # things which are executable
774 'lx ls -lF | grep ^-..x',
664 'lx ls -lF | grep ^-..x',
775 )
665 )
776 auto_alias = auto_alias + ls_extra
666 auto_alias = auto_alias + ls_extra
777 elif os.name in ['nt','dos']:
667 elif os.name in ['nt','dos']:
778 auto_alias = ('ls dir /on',
668 auto_alias = ('ls dir /on',
779 'ddir dir /ad /on', 'ldir dir /ad /on',
669 'ddir dir /ad /on', 'ldir dir /ad /on',
780 'mkdir mkdir','rmdir rmdir','echo echo',
670 'mkdir mkdir','rmdir rmdir','echo echo',
781 'ren ren','cls cls','copy copy')
671 'ren ren','cls cls','copy copy')
782 else:
672 else:
783 auto_alias = ()
673 auto_alias = ()
784 self.auto_alias = [s.split(None,1) for s in auto_alias]
674 self.auto_alias = [s.split(None,1) for s in auto_alias]
785
675
786 # Produce a public API instance
676 # Load default aliases
787 self.api = ipapi.IPApi(self)
677 for alias, cmd in self.auto_alias:
678 self.define_alias(alias,cmd)
788
679
789 # Initialize all user-visible namespaces
680 # Load user aliases
790 self.init_namespaces()
681 for alias in self.alias:
791
682 self.magic_alias(alias)
792 # Call the actual (public) initializer
793 self.init_auto_alias()
794
683
684 def init_builtins(self):
795 # track which builtins we add, so we can clean up later
685 # track which builtins we add, so we can clean up later
796 self.builtins_added = {}
686 self.builtins_added = {}
797 # This method will add the necessary builtins for operation, but
687 # This method will add the necessary builtins for operation, but
798 # tracking what it did via the builtins_added dict.
688 # tracking what it did via the builtins_added dict.
799
689
800 #TODO: remove this, redundant
690 #TODO: remove this, redundant
801 self.add_builtins()
691 self.add_builtins()
802 # end __init__
803
692
804 def var_expand(self,cmd,depth=0):
693 def init_shadow_hist(self):
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
829 try:
694 try:
830 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
695 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
831 except exceptions.UnicodeDecodeError:
696 except exceptions.UnicodeDecodeError:
832 print "Your ipythondir can't be decoded to unicode!"
697 print "Your ipythondir can't be decoded to unicode!"
833 print "Please set HOME environment variable to something that"
698 print "Please set HOME environment variable to something that"
834 print r"only has ASCII characters, e.g. c:\home"
699 print r"only has ASCII characters, e.g. c:\home"
835 print "Now it is",rc.ipythondir
700 print "Now it is", self.config.IPYTHONDIR
836 sys.exit()
701 sys.exit()
837 self.shadowhist = IPython.core.history.ShadowHist(self.db)
702 self.shadowhist = ipcorehist.ShadowHist(self.db)
838
703
839 def post_config_initialization(self):
704 def post_config_initialization(self):
840 """Post configuration init method
705 """Post configuration init method
841
706
842 This is called after the configuration files have been processed to
707 This is called after the configuration files have been processed to
843 'finalize' the initialization."""
708 'finalize' the initialization."""
844
709
845 rc = self.rc
846
847 # Object inspector
710 # Object inspector
848 self.inspector = oinspect.Inspector(oinspect.InspectColors,
711 self.inspector = oinspect.Inspector(oinspect.InspectColors,
849 PyColorize.ANSICodeColors,
712 PyColorize.ANSICodeColors,
850 'NoColor',
713 'NoColor',
851 rc.object_info_string_level)
714 self.object_info_string_level)
852
715
853 self.rl_next_input = None
716 self.rl_next_input = None
854 self.rl_do_indent = False
717 self.rl_do_indent = False
855 # Load readline proper
718 # Load readline proper
856 if rc.readline:
719 if self.readline_use:
857 self.init_readline()
720 self.init_readline()
858
859 # local shortcut, this is used a LOT
860 self.log = self.logger.log
861
721
862 # Initialize cache, set in/out prompts and printing system
722 # Initialize cache, set in/out prompts and printing system
863 self.outputcache = CachedOutput(self,
723 self.outputcache = CachedOutput(self,
864 rc.cache_size,
724 self.cache_size,
865 rc.pprint,
725 self.pprint,
866 input_sep = rc.separate_in,
726 input_sep = self.separate_in,
867 output_sep = rc.separate_out,
727 output_sep = self.separate_out,
868 output_sep2 = rc.separate_out2,
728 output_sep2 = self.separate_out2,
869 ps1 = rc.prompt_in1,
729 ps1 = self.prompt_in1,
870 ps2 = rc.prompt_in2,
730 ps2 = self.prompt_in2,
871 ps_out = rc.prompt_out,
731 ps_out = self.prompt_out,
872 pad_left = rc.prompts_pad_left)
732 pad_left = self.prompts_pad_left)
873
733
874 # user may have over-ridden the default print hook:
734 # user may have over-ridden the default print hook:
875 try:
735 try:
876 self.outputcache.__class__.display = self.hooks.display
736 self.outputcache.__class__.display = self.hooks.display
877 except AttributeError:
737 except AttributeError:
878 pass
738 pass
879
739
880 # I don't like assigning globally to sys, because it means when
740 # I don't like assigning globally to sys, because it means when
881 # embedding instances, each embedded instance overrides the previous
741 # embedding instances, each embedded instance overrides the previous
882 # choice. But sys.displayhook seems to be called internally by exec,
742 # choice. But sys.displayhook seems to be called internally by exec,
883 # so I don't see a way around it. We first save the original and then
743 # so I don't see a way around it. We first save the original and then
884 # overwrite it.
744 # overwrite it.
885 self.sys_displayhook = sys.displayhook
745 self.sys_displayhook = sys.displayhook
886 sys.displayhook = self.outputcache
746 sys.displayhook = self.outputcache
887
747
888 # Do a proper resetting of doctest, including the necessary displayhook
748 # Do a proper resetting of doctest, including the necessary displayhook
889 # monkeypatching
749 # monkeypatching
890 try:
750 try:
891 doctest_reload()
751 doctest_reload()
892 except ImportError:
752 except ImportError:
893 warn("doctest module does not exist.")
753 warn("doctest module does not exist.")
894
754
895 # Set user colors (don't do it in the constructor above so that it
755 # Set user colors (don't do it in the constructor above so that it
896 # doesn't crash if colors option is invalid)
756 # doesn't crash if colors option is invalid)
897 self.magic_colors(rc.colors)
757 self.magic_colors(self.colors)
898
758
899 # Set calling of pdb on exceptions
759 # Set calling of pdb on exceptions
900 self.call_pdb = rc.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 self.hooks.late_startup_hook()
764 self.hooks.late_startup_hook()
907
765
908 for cmd in self.rc.autoexec:
766 for cmd in self.autoexec:
909 #print "autoexec>",cmd #dbg
767 #print "autoexec>",cmd #dbg
910 self.api.runlines(cmd)
768 self.api.runlines(cmd)
911
769
912 batchrun = False
770 batchrun = False
913 for batchfile in [path(arg) for arg in self.rc.args
771 if self.config.has_key('EXECFILE'):
914 if arg.lower().endswith('.ipy')]:
772 for batchfile in [path(arg) for arg in self.config.EXECFILE
915 if not batchfile.isfile():
773 if arg.lower().endswith('.ipy')]:
916 print "No such batch file:", batchfile
774 if not batchfile.isfile():
917 continue
775 print "No such batch file:", batchfile
918 self.api.runlines(batchfile.text())
776 continue
919 batchrun = True
777 self.api.runlines(batchfile.text())
778 batchrun = True
920 # without -i option, exit after running the batch file
779 # without -i option, exit after running the batch file
921 if batchrun and not self.rc.interact:
780 if batchrun and not self.interactive:
922 self.ask_exit()
781 self.ask_exit()
923
782
924 def init_namespaces(self):
783 def init_namespaces(self):
925 """Initialize all user-visible namespaces to their minimum defaults.
784 """Initialize all user-visible namespaces to their minimum defaults.
926
785
927 Certain history lists are also initialized here, as they effectively
786 Certain history lists are also initialized here, as they effectively
928 act as user namespaces.
787 act as user namespaces.
929
788
930 Notes
789 Notes
931 -----
790 -----
932 All data structures here are only filled in, they are NOT reset by this
791 All data structures here are only filled in, they are NOT reset by this
933 method. If they were not empty before, data will simply be added to
792 method. If they were not empty before, data will simply be added to
934 therm.
793 therm.
935 """
794 """
936 # The user namespace MUST have a pointer to the shell itself.
795 # The user namespace MUST have a pointer to the shell itself.
937 self.user_ns[self.name] = self
796 self.user_ns[self.name] = self
938
797
939 # Store the public api instance
798 # Store the public api instance
940 self.user_ns['_ip'] = self.api
799 self.user_ns['_ip'] = self.api
941
800
942 # make global variables for user access to the histories
801 # make global variables for user access to the histories
943 self.user_ns['_ih'] = self.input_hist
802 self.user_ns['_ih'] = self.input_hist
944 self.user_ns['_oh'] = self.output_hist
803 self.user_ns['_oh'] = self.output_hist
945 self.user_ns['_dh'] = self.dir_hist
804 self.user_ns['_dh'] = self.dir_hist
946
805
947 # user aliases to input and output histories
806 # user aliases to input and output histories
948 self.user_ns['In'] = self.input_hist
807 self.user_ns['In'] = self.input_hist
949 self.user_ns['Out'] = self.output_hist
808 self.user_ns['Out'] = self.output_hist
950
809
951 self.user_ns['_sh'] = shadowns
810 self.user_ns['_sh'] = shadowns
952
811
953 # Fill the history zero entry, user counter starts at 1
812 # Fill the history zero entry, user counter starts at 1
954 self.input_hist.append('\n')
813 self.input_hist.append('\n')
955 self.input_hist_raw.append('\n')
814 self.input_hist_raw.append('\n')
956
815
957 def add_builtins(self):
816 def add_builtins(self):
958 """Store ipython references into the builtin namespace.
817 """Store ipython references into the builtin namespace.
959
818
960 Some parts of ipython operate via builtins injected here, which hold a
819 Some parts of ipython operate via builtins injected here, which hold a
961 reference to IPython itself."""
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 builtins_new = dict(__IPYTHON__ = self,
830 builtins_new = dict(__IPYTHON__ = self,
965 ip_set_hook = self.set_hook,
831 ip_set_hook = self.set_hook,
966 jobs = self.jobs,
832 jobs = self.jobs,
967 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
833 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
968 ipalias = wrap_deprecated(self.ipalias),
834 ipalias = wrap_deprecated(self.ipalias),
969 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
835 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
970 #_ip = self.api
836 #_ip = self.api
971 )
837 )
972 for biname,bival in builtins_new.items():
838 for biname,bival in builtins_new.items():
973 try:
839 try:
974 # store the orignal value so we can restore it
840 # store the orignal value so we can restore it
975 self.builtins_added[biname] = __builtin__.__dict__[biname]
841 self.builtins_added[biname] = __builtin__.__dict__[biname]
976 except KeyError:
842 except KeyError:
977 # or mark that it wasn't defined, and we'll just delete it at
843 # or mark that it wasn't defined, and we'll just delete it at
978 # cleanup
844 # cleanup
979 self.builtins_added[biname] = Undefined
845 self.builtins_added[biname] = Undefined
980 __builtin__.__dict__[biname] = bival
846 __builtin__.__dict__[biname] = bival
981
847
982 # Keep in the builtins a flag for when IPython is active. We set it
848 # Keep in the builtins a flag for when IPython is active. We set it
983 # with setdefault so that multiple nested IPythons don't clobber one
849 # with setdefault so that multiple nested IPythons don't clobber one
984 # another. Each will increase its value by one upon being activated,
850 # another. Each will increase its value by one upon being activated,
985 # which also gives us a way to determine the nesting level.
851 # which also gives us a way to determine the nesting level.
986 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
852 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
987
853
988 def clean_builtins(self):
854 def clean_builtins(self):
989 """Remove any builtins which might have been added by add_builtins, or
855 """Remove any builtins which might have been added by add_builtins, or
990 restore overwritten ones to their previous values."""
856 restore overwritten ones to their previous values."""
991 for biname,bival in self.builtins_added.items():
857 for biname,bival in self.builtins_added.items():
992 if bival is Undefined:
858 if bival is Undefined:
993 del __builtin__.__dict__[biname]
859 del __builtin__.__dict__[biname]
994 else:
860 else:
995 __builtin__.__dict__[biname] = bival
861 __builtin__.__dict__[biname] = bival
996 self.builtins_added.clear()
862 self.builtins_added.clear()
997
863
998 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
864 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
999 """set_hook(name,hook) -> sets an internal IPython hook.
865 """set_hook(name,hook) -> sets an internal IPython hook.
1000
866
1001 IPython exposes some of its internal API as user-modifiable hooks. By
867 IPython exposes some of its internal API as user-modifiable hooks. By
1002 adding your function to one of these hooks, you can modify IPython's
868 adding your function to one of these hooks, you can modify IPython's
1003 behavior to call at runtime your own routines."""
869 behavior to call at runtime your own routines."""
1004
870
1005 # At some point in the future, this should validate the hook before it
871 # At some point in the future, this should validate the hook before it
1006 # accepts it. Probably at least check that the hook takes the number
872 # accepts it. Probably at least check that the hook takes the number
1007 # of args it's supposed to.
873 # of args it's supposed to.
1008
874
1009 f = new.instancemethod(hook,self,self.__class__)
875 f = new.instancemethod(hook,self,self.__class__)
1010
876
1011 # check if the hook is for strdispatcher first
877 # check if the hook is for strdispatcher first
1012 if str_key is not None:
878 if str_key is not None:
1013 sdp = self.strdispatchers.get(name, StrDispatch())
879 sdp = self.strdispatchers.get(name, StrDispatch())
1014 sdp.add_s(str_key, f, priority )
880 sdp.add_s(str_key, f, priority )
1015 self.strdispatchers[name] = sdp
881 self.strdispatchers[name] = sdp
1016 return
882 return
1017 if re_key is not None:
883 if re_key is not None:
1018 sdp = self.strdispatchers.get(name, StrDispatch())
884 sdp = self.strdispatchers.get(name, StrDispatch())
1019 sdp.add_re(re.compile(re_key), f, priority )
885 sdp.add_re(re.compile(re_key), f, priority )
1020 self.strdispatchers[name] = sdp
886 self.strdispatchers[name] = sdp
1021 return
887 return
1022
888
1023 dp = getattr(self.hooks, name, None)
889 dp = getattr(self.hooks, name, None)
1024 if name not in IPython.core.hooks.__all__:
890 if name not in IPython.core.hooks.__all__:
1025 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
891 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1026 if not dp:
892 if not dp:
1027 dp = IPython.core.hooks.CommandChainDispatcher()
893 dp = IPython.core.hooks.CommandChainDispatcher()
1028
894
1029 try:
895 try:
1030 dp.add(f,priority)
896 dp.add(f,priority)
1031 except AttributeError:
897 except AttributeError:
1032 # it was not commandchain, plain old func - replace
898 # it was not commandchain, plain old func - replace
1033 dp = f
899 dp = f
1034
900
1035 setattr(self.hooks,name, dp)
901 setattr(self.hooks,name, dp)
1036
902
1037
903
1038 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
904 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1039
905
1040 def set_crash_handler(self,crashHandler):
906 def set_crash_handler(self,crashHandler):
1041 """Set the IPython crash handler.
907 """Set the IPython crash handler.
1042
908
1043 This must be a callable with a signature suitable for use as
909 This must be a callable with a signature suitable for use as
1044 sys.excepthook."""
910 sys.excepthook."""
1045
911
1046 # Install the given crash handler as the Python exception hook
912 # Install the given crash handler as the Python exception hook
1047 sys.excepthook = crashHandler
913 sys.excepthook = crashHandler
1048
914
1049 # The instance will store a pointer to this, so that runtime code
915 # The instance will store a pointer to this, so that runtime code
1050 # (such as magics) can access it. This is because during the
916 # (such as magics) can access it. This is because during the
1051 # read-eval loop, it gets temporarily overwritten (to deal with GUI
917 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1052 # frameworks).
918 # frameworks).
1053 self.sys_excepthook = sys.excepthook
919 self.sys_excepthook = sys.excepthook
1054
920
1055
921
1056 def set_custom_exc(self,exc_tuple,handler):
922 def set_custom_exc(self,exc_tuple,handler):
1057 """set_custom_exc(exc_tuple,handler)
923 """set_custom_exc(exc_tuple,handler)
1058
924
1059 Set a custom exception handler, which will be called if any of the
925 Set a custom exception handler, which will be called if any of the
1060 exceptions in exc_tuple occur in the mainloop (specifically, in the
926 exceptions in exc_tuple occur in the mainloop (specifically, in the
1061 runcode() method.
927 runcode() method.
1062
928
1063 Inputs:
929 Inputs:
1064
930
1065 - exc_tuple: a *tuple* of valid exceptions to call the defined
931 - exc_tuple: a *tuple* of valid exceptions to call the defined
1066 handler for. It is very important that you use a tuple, and NOT A
932 handler for. It is very important that you use a tuple, and NOT A
1067 LIST here, because of the way Python's except statement works. If
933 LIST here, because of the way Python's except statement works. If
1068 you only want to trap a single exception, use a singleton tuple:
934 you only want to trap a single exception, use a singleton tuple:
1069
935
1070 exc_tuple == (MyCustomException,)
936 exc_tuple == (MyCustomException,)
1071
937
1072 - handler: this must be defined as a function with the following
938 - handler: this must be defined as a function with the following
1073 basic interface: def my_handler(self,etype,value,tb).
939 basic interface: def my_handler(self,etype,value,tb).
1074
940
1075 This will be made into an instance method (via new.instancemethod)
941 This will be made into an instance method (via new.instancemethod)
1076 of IPython itself, and it will be called if any of the exceptions
942 of IPython itself, and it will be called if any of the exceptions
1077 listed in the exc_tuple are caught. If the handler is None, an
943 listed in the exc_tuple are caught. If the handler is None, an
1078 internal basic one is used, which just prints basic info.
944 internal basic one is used, which just prints basic info.
1079
945
1080 WARNING: by putting in your own exception handler into IPython's main
946 WARNING: by putting in your own exception handler into IPython's main
1081 execution loop, you run a very good chance of nasty crashes. This
947 execution loop, you run a very good chance of nasty crashes. This
1082 facility should only be used if you really know what you are doing."""
948 facility should only be used if you really know what you are doing."""
1083
949
1084 assert type(exc_tuple)==type(()) , \
950 assert type(exc_tuple)==type(()) , \
1085 "The custom exceptions must be given AS A TUPLE."
951 "The custom exceptions must be given AS A TUPLE."
1086
952
1087 def dummy_handler(self,etype,value,tb):
953 def dummy_handler(self,etype,value,tb):
1088 print '*** Simple custom exception handler ***'
954 print '*** Simple custom exception handler ***'
1089 print 'Exception type :',etype
955 print 'Exception type :',etype
1090 print 'Exception value:',value
956 print 'Exception value:',value
1091 print 'Traceback :',tb
957 print 'Traceback :',tb
1092 print 'Source code :','\n'.join(self.buffer)
958 print 'Source code :','\n'.join(self.buffer)
1093
959
1094 if handler is None: handler = dummy_handler
960 if handler is None: handler = dummy_handler
1095
961
1096 self.CustomTB = new.instancemethod(handler,self,self.__class__)
962 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1097 self.custom_exceptions = exc_tuple
963 self.custom_exceptions = exc_tuple
1098
964
1099 def set_custom_completer(self,completer,pos=0):
965 def set_custom_completer(self,completer,pos=0):
1100 """set_custom_completer(completer,pos=0)
966 """set_custom_completer(completer,pos=0)
1101
967
1102 Adds a new custom completer function.
968 Adds a new custom completer function.
1103
969
1104 The position argument (defaults to 0) is the index in the completers
970 The position argument (defaults to 0) is the index in the completers
1105 list where you want the completer to be inserted."""
971 list where you want the completer to be inserted."""
1106
972
1107 newcomp = new.instancemethod(completer,self.Completer,
973 newcomp = new.instancemethod(completer,self.Completer,
1108 self.Completer.__class__)
974 self.Completer.__class__)
1109 self.Completer.matchers.insert(pos,newcomp)
975 self.Completer.matchers.insert(pos,newcomp)
1110
976
1111 def set_completer(self):
977 def set_completer(self):
1112 """reset readline's completer to be our own."""
978 """reset readline's completer to be our own."""
1113 self.readline.set_completer(self.Completer.complete)
979 self.readline.set_completer(self.Completer.complete)
1114
980
1115 def _get_call_pdb(self):
981 def _get_call_pdb(self):
1116 return self._call_pdb
982 return self._call_pdb
1117
983
1118 def _set_call_pdb(self,val):
984 def _set_call_pdb(self,val):
1119
985
1120 if val not in (0,1,False,True):
986 if val not in (0,1,False,True):
1121 raise ValueError,'new call_pdb value must be boolean'
987 raise ValueError,'new call_pdb value must be boolean'
1122
988
1123 # store value in instance
989 # store value in instance
1124 self._call_pdb = val
990 self._call_pdb = val
1125
991
1126 # notify the actual exception handlers
992 # notify the actual exception handlers
1127 self.InteractiveTB.call_pdb = val
993 self.InteractiveTB.call_pdb = val
1128 if self.isthreaded:
994 if self.isthreaded:
1129 try:
995 try:
1130 self.sys_excepthook.call_pdb = val
996 self.sys_excepthook.call_pdb = val
1131 except:
997 except:
1132 warn('Failed to activate pdb for threaded exception handler')
998 warn('Failed to activate pdb for threaded exception handler')
1133
999
1134 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1000 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1135 'Control auto-activation of pdb at exceptions')
1001 'Control auto-activation of pdb at exceptions')
1136
1002
1137 # These special functions get installed in the builtin namespace, to
1003 # These special functions get installed in the builtin namespace, to
1138 # provide programmatic (pure python) access to magics, aliases and system
1004 # provide programmatic (pure python) access to magics, aliases and system
1139 # calls. This is important for logging, user scripting, and more.
1005 # calls. This is important for logging, user scripting, and more.
1140
1006
1141 # We are basically exposing, via normal python functions, the three
1007 # We are basically exposing, via normal python functions, the three
1142 # mechanisms in which ipython offers special call modes (magics for
1008 # mechanisms in which ipython offers special call modes (magics for
1143 # internal control, aliases for direct system access via pre-selected
1009 # internal control, aliases for direct system access via pre-selected
1144 # names, and !cmd for calling arbitrary system commands).
1010 # names, and !cmd for calling arbitrary system commands).
1145
1011
1146 def ipmagic(self,arg_s):
1012 def ipmagic(self,arg_s):
1147 """Call a magic function by name.
1013 """Call a magic function by name.
1148
1014
1149 Input: a string containing the name of the magic function to call and any
1015 Input: a string containing the name of the magic function to call and any
1150 additional arguments to be passed to the magic.
1016 additional arguments to be passed to the magic.
1151
1017
1152 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1018 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1153 prompt:
1019 prompt:
1154
1020
1155 In[1]: %name -opt foo bar
1021 In[1]: %name -opt foo bar
1156
1022
1157 To call a magic without arguments, simply use ipmagic('name').
1023 To call a magic without arguments, simply use ipmagic('name').
1158
1024
1159 This provides a proper Python function to call IPython's magics in any
1025 This provides a proper Python function to call IPython's magics in any
1160 valid Python code you can type at the interpreter, including loops and
1026 valid Python code you can type at the interpreter, including loops and
1161 compound statements. It is added by IPython to the Python builtin
1027 compound statements. It is added by IPython to the Python builtin
1162 namespace upon initialization."""
1028 namespace upon initialization."""
1163
1029
1164 args = arg_s.split(' ',1)
1030 args = arg_s.split(' ',1)
1165 magic_name = args[0]
1031 magic_name = args[0]
1166 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1032 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1167
1033
1168 try:
1034 try:
1169 magic_args = args[1]
1035 magic_args = args[1]
1170 except IndexError:
1036 except IndexError:
1171 magic_args = ''
1037 magic_args = ''
1172 fn = getattr(self,'magic_'+magic_name,None)
1038 fn = getattr(self,'magic_'+magic_name,None)
1173 if fn is None:
1039 if fn is None:
1174 error("Magic function `%s` not found." % magic_name)
1040 error("Magic function `%s` not found." % magic_name)
1175 else:
1041 else:
1176 magic_args = self.var_expand(magic_args,1)
1042 magic_args = self.var_expand(magic_args,1)
1177 return fn(magic_args)
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 def ipalias(self,arg_s):
1065 def ipalias(self,arg_s):
1180 """Call an alias by name.
1066 """Call an alias by name.
1181
1067
1182 Input: a string containing the name of the alias to call and any
1068 Input: a string containing the name of the alias to call and any
1183 additional arguments to be passed to the magic.
1069 additional arguments to be passed to the magic.
1184
1070
1185 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1071 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1186 prompt:
1072 prompt:
1187
1073
1188 In[1]: name -opt foo bar
1074 In[1]: name -opt foo bar
1189
1075
1190 To call an alias without arguments, simply use ipalias('name').
1076 To call an alias without arguments, simply use ipalias('name').
1191
1077
1192 This provides a proper Python function to call IPython's aliases in any
1078 This provides a proper Python function to call IPython's aliases in any
1193 valid Python code you can type at the interpreter, including loops and
1079 valid Python code you can type at the interpreter, including loops and
1194 compound statements. It is added by IPython to the Python builtin
1080 compound statements. It is added by IPython to the Python builtin
1195 namespace upon initialization."""
1081 namespace upon initialization."""
1196
1082
1197 args = arg_s.split(' ',1)
1083 args = arg_s.split(' ',1)
1198 alias_name = args[0]
1084 alias_name = args[0]
1199 try:
1085 try:
1200 alias_args = args[1]
1086 alias_args = args[1]
1201 except IndexError:
1087 except IndexError:
1202 alias_args = ''
1088 alias_args = ''
1203 if alias_name in self.alias_table:
1089 if alias_name in self.alias_table:
1204 self.call_alias(alias_name,alias_args)
1090 self.call_alias(alias_name,alias_args)
1205 else:
1091 else:
1206 error("Alias `%s` not found." % alias_name)
1092 error("Alias `%s` not found." % alias_name)
1207
1093
1208 def ipsystem(self,arg_s):
1094 def system(self, cmd):
1209 """Make a system call, using IPython."""
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 def complete(self,text):
1110 def complete(self,text):
1214 """Return a sorted list of all possible completions on text.
1111 """Return a sorted list of all possible completions on text.
1215
1112
1216 Inputs:
1113 Inputs:
1217
1114
1218 - text: a string of text to be completed on.
1115 - text: a string of text to be completed on.
1219
1116
1220 This is a wrapper around the completion mechanism, similar to what
1117 This is a wrapper around the completion mechanism, similar to what
1221 readline does at the command line when the TAB key is hit. By
1118 readline does at the command line when the TAB key is hit. By
1222 exposing it as a method, it can be used by other non-readline
1119 exposing it as a method, it can be used by other non-readline
1223 environments (such as GUIs) for text completion.
1120 environments (such as GUIs) for text completion.
1224
1121
1225 Simple usage example:
1122 Simple usage example:
1226
1123
1227 In [7]: x = 'hello'
1124 In [7]: x = 'hello'
1228
1125
1229 In [8]: x
1126 In [8]: x
1230 Out[8]: 'hello'
1127 Out[8]: 'hello'
1231
1128
1232 In [9]: print x
1129 In [9]: print x
1233 hello
1130 hello
1234
1131
1235 In [10]: _ip.IP.complete('x.l')
1132 In [10]: _ip.IP.complete('x.l')
1236 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1133 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1237 """
1134 """
1238
1135
1239 complete = self.Completer.complete
1136 complete = self.Completer.complete
1240 state = 0
1137 state = 0
1241 # use a dict so we get unique keys, since ipyhton's multiple
1138 # use a dict so we get unique keys, since ipyhton's multiple
1242 # completers can return duplicates. When we make 2.4 a requirement,
1139 # completers can return duplicates. When we make 2.4 a requirement,
1243 # start using sets instead, which are faster.
1140 # start using sets instead, which are faster.
1244 comps = {}
1141 comps = {}
1245 while True:
1142 while True:
1246 newcomp = complete(text,state,line_buffer=text)
1143 newcomp = complete(text,state,line_buffer=text)
1247 if newcomp is None:
1144 if newcomp is None:
1248 break
1145 break
1249 comps[newcomp] = 1
1146 comps[newcomp] = 1
1250 state += 1
1147 state += 1
1251 outcomps = comps.keys()
1148 outcomps = comps.keys()
1252 outcomps.sort()
1149 outcomps.sort()
1253 #print "T:",text,"OC:",outcomps # dbg
1150 #print "T:",text,"OC:",outcomps # dbg
1254 #print "vars:",self.user_ns.keys()
1151 #print "vars:",self.user_ns.keys()
1255 return outcomps
1152 return outcomps
1256
1153
1257 def set_completer_frame(self, frame=None):
1154 def set_completer_frame(self, frame=None):
1258 if frame:
1155 if frame:
1259 self.Completer.namespace = frame.f_locals
1156 self.Completer.namespace = frame.f_locals
1260 self.Completer.global_namespace = frame.f_globals
1157 self.Completer.global_namespace = frame.f_globals
1261 else:
1158 else:
1262 self.Completer.namespace = self.user_ns
1159 self.Completer.namespace = self.user_ns
1263 self.Completer.global_namespace = self.user_global_ns
1160 self.Completer.global_namespace = self.user_global_ns
1264
1161
1265 def init_auto_alias(self):
1162 def init_auto_alias(self):
1266 """Define some aliases automatically.
1163 """Define some aliases automatically.
1267
1164
1268 These are ALL parameter-less aliases"""
1165 These are ALL parameter-less aliases"""
1269
1166
1270 for alias,cmd in self.auto_alias:
1167 for alias,cmd in self.auto_alias:
1271 self.getapi().defalias(alias,cmd)
1168 self.getapi().defalias(alias,cmd)
1272
1169
1273
1170
1274 def alias_table_validate(self,verbose=0):
1171 def alias_table_validate(self,verbose=0):
1275 """Update information about the alias table.
1172 """Update information about the alias table.
1276
1173
1277 In particular, make sure no Python keywords/builtins are in it."""
1174 In particular, make sure no Python keywords/builtins are in it."""
1278
1175
1279 no_alias = self.no_alias
1176 no_alias = self.no_alias
1280 for k in self.alias_table.keys():
1177 for k in self.alias_table.keys():
1281 if k in no_alias:
1178 if k in no_alias:
1282 del self.alias_table[k]
1179 del self.alias_table[k]
1283 if verbose:
1180 if verbose:
1284 print ("Deleting alias <%s>, it's a Python "
1181 print ("Deleting alias <%s>, it's a Python "
1285 "keyword or builtin." % k)
1182 "keyword or builtin." % k)
1286
1183
1287 def set_autoindent(self,value=None):
1184 def set_autoindent(self,value=None):
1288 """Set the autoindent flag, checking for readline support.
1185 """Set the autoindent flag, checking for readline support.
1289
1186
1290 If called with no arguments, it acts as a toggle."""
1187 If called with no arguments, it acts as a toggle."""
1291
1188
1292 if not self.has_readline:
1189 if not self.has_readline:
1293 if os.name == 'posix':
1190 if os.name == 'posix':
1294 warn("The auto-indent feature requires the readline library")
1191 warn("The auto-indent feature requires the readline library")
1295 self.autoindent = 0
1192 self.autoindent = 0
1296 return
1193 return
1297 if value is None:
1194 if value is None:
1298 self.autoindent = not self.autoindent
1195 self.autoindent = not self.autoindent
1299 else:
1196 else:
1300 self.autoindent = value
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 def atexit_operations(self):
1199 def atexit_operations(self):
1325 """This will be executed at the time of exit.
1200 """This will be executed at the time of exit.
1326
1201
1327 Saving of persistent data should be performed here. """
1202 Saving of persistent data should be performed here. """
1328
1203
1329 #print '*** IPython exit cleanup ***' # dbg
1204 #print '*** IPython exit cleanup ***' # dbg
1330 # input history
1205 # input history
1331 self.savehist()
1206 self.savehist()
1332
1207
1333 # Cleanup all tempfiles left around
1208 # Cleanup all tempfiles left around
1334 for tfile in self.tempfiles:
1209 for tfile in self.tempfiles:
1335 try:
1210 try:
1336 os.unlink(tfile)
1211 os.unlink(tfile)
1337 except OSError:
1212 except OSError:
1338 pass
1213 pass
1339
1214
1340 # Clear all user namespaces to release all references cleanly.
1215 # Clear all user namespaces to release all references cleanly.
1341 self.reset()
1216 self.reset()
1342
1217
1343 # Run user hooks
1218 # Run user hooks
1344 self.hooks.shutdown_hook()
1219 self.hooks.shutdown_hook()
1345
1220
1346 def reset(self):
1221 def reset(self):
1347 """Clear all internal namespaces.
1222 """Clear all internal namespaces.
1348
1223
1349 Note that this is much more aggressive than %reset, since it clears
1224 Note that this is much more aggressive than %reset, since it clears
1350 fully all namespaces, as well as all input/output lists.
1225 fully all namespaces, as well as all input/output lists.
1351 """
1226 """
1352 for ns in self.ns_refs_table:
1227 for ns in self.ns_refs_table:
1353 ns.clear()
1228 ns.clear()
1354
1229
1355 # Clear input and output histories
1230 # Clear input and output histories
1356 self.input_hist[:] = []
1231 self.input_hist[:] = []
1357 self.input_hist_raw[:] = []
1232 self.input_hist_raw[:] = []
1358 self.output_hist.clear()
1233 self.output_hist.clear()
1359 # Restore the user namespaces to minimal usability
1234 # Restore the user namespaces to minimal usability
1360 self.init_namespaces()
1235 self.init_namespaces()
1361
1236
1362 def savehist(self):
1237 def savehist(self):
1363 """Save input history to a file (via readline library)."""
1238 """Save input history to a file (via readline library)."""
1364
1239
1365 if not self.has_readline:
1240 if not self.has_readline:
1366 return
1241 return
1367
1242
1368 try:
1243 try:
1369 self.readline.write_history_file(self.histfile)
1244 self.readline.write_history_file(self.histfile)
1370 except:
1245 except:
1371 print 'Unable to save IPython command history to file: ' + \
1246 print 'Unable to save IPython command history to file: ' + \
1372 `self.histfile`
1247 `self.histfile`
1373
1248
1374 def reloadhist(self):
1249 def reloadhist(self):
1375 """Reload the input history from disk file."""
1250 """Reload the input history from disk file."""
1376
1251
1377 if self.has_readline:
1252 if self.has_readline:
1378 try:
1253 try:
1379 self.readline.clear_history()
1254 self.readline.clear_history()
1380 self.readline.read_history_file(self.shell.histfile)
1255 self.readline.read_history_file(self.shell.histfile)
1381 except AttributeError:
1256 except AttributeError:
1382 pass
1257 pass
1383
1258
1384
1259
1385 def history_saving_wrapper(self, func):
1260 def history_saving_wrapper(self, func):
1386 """ Wrap func for readline history saving
1261 """ Wrap func for readline history saving
1387
1262
1388 Convert func into callable that saves & restores
1263 Convert func into callable that saves & restores
1389 history around the call """
1264 history around the call """
1390
1265
1391 if not self.has_readline:
1266 if not self.has_readline:
1392 return func
1267 return func
1393
1268
1394 def wrapper():
1269 def wrapper():
1395 self.savehist()
1270 self.savehist()
1396 try:
1271 try:
1397 func()
1272 func()
1398 finally:
1273 finally:
1399 readline.read_history_file(self.histfile)
1274 readline.read_history_file(self.histfile)
1400 return wrapper
1275 return wrapper
1401
1276
1402 def pre_readline(self):
1277 def pre_readline(self):
1403 """readline hook to be used at the start of each line.
1278 """readline hook to be used at the start of each line.
1404
1279
1405 Currently it handles auto-indent only."""
1280 Currently it handles auto-indent only."""
1406
1281
1407 #debugx('self.indent_current_nsp','pre_readline:')
1282 #debugx('self.indent_current_nsp','pre_readline:')
1408
1283
1409 if self.rl_do_indent:
1284 if self.rl_do_indent:
1410 self.readline.insert_text(self.indent_current_str())
1285 self.readline.insert_text(self.indent_current_str())
1411 if self.rl_next_input is not None:
1286 if self.rl_next_input is not None:
1412 self.readline.insert_text(self.rl_next_input)
1287 self.readline.insert_text(self.rl_next_input)
1413 self.rl_next_input = None
1288 self.rl_next_input = None
1414
1289
1415 def init_readline(self):
1290 def init_readline(self):
1416 """Command history completion/saving/reloading."""
1291 """Command history completion/saving/reloading."""
1417
1292
1418
1293
1419 import IPython.utils.rlineimpl as readline
1294 import IPython.utils.rlineimpl as readline
1420
1295
1421 if not readline.have_readline:
1296 if not readline.have_readline:
1422 self.has_readline = 0
1297 self.has_readline = 0
1423 self.readline = None
1298 self.readline = None
1424 # no point in bugging windows users with this every time:
1299 # no point in bugging windows users with this every time:
1425 warn('Readline services not available on this platform.')
1300 warn('Readline services not available on this platform.')
1426 else:
1301 else:
1427 sys.modules['readline'] = readline
1302 sys.modules['readline'] = readline
1428 import atexit
1303 import atexit
1429 from IPython.core.completer import IPCompleter
1304 from IPython.core.completer import IPCompleter
1430 self.Completer = IPCompleter(self,
1305 self.Completer = IPCompleter(self,
1431 self.user_ns,
1306 self.user_ns,
1432 self.user_global_ns,
1307 self.user_global_ns,
1433 self.rc.readline_omit__names,
1308 self.readline_omit__names,
1434 self.alias_table)
1309 self.alias_table)
1435 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1310 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1436 self.strdispatchers['complete_command'] = sdisp
1311 self.strdispatchers['complete_command'] = sdisp
1437 self.Completer.custom_completers = sdisp
1312 self.Completer.custom_completers = sdisp
1438 # Platform-specific configuration
1313 # Platform-specific configuration
1439 if os.name == 'nt':
1314 if os.name == 'nt':
1440 self.readline_startup_hook = readline.set_pre_input_hook
1315 self.readline_startup_hook = readline.set_pre_input_hook
1441 else:
1316 else:
1442 self.readline_startup_hook = readline.set_startup_hook
1317 self.readline_startup_hook = readline.set_startup_hook
1443
1318
1444 # Load user's initrc file (readline config)
1319 # Load user's initrc file (readline config)
1445 # Or if libedit is used, load editrc.
1320 # Or if libedit is used, load editrc.
1446 inputrc_name = os.environ.get('INPUTRC')
1321 inputrc_name = os.environ.get('INPUTRC')
1447 if inputrc_name is None:
1322 if inputrc_name is None:
1448 home_dir = get_home_dir()
1323 home_dir = get_home_dir()
1449 if home_dir is not None:
1324 if home_dir is not None:
1450 inputrc_name = '.inputrc'
1325 inputrc_name = '.inputrc'
1451 if readline.uses_libedit:
1326 if readline.uses_libedit:
1452 inputrc_name = '.editrc'
1327 inputrc_name = '.editrc'
1453 inputrc_name = os.path.join(home_dir, inputrc_name)
1328 inputrc_name = os.path.join(home_dir, inputrc_name)
1454 if os.path.isfile(inputrc_name):
1329 if os.path.isfile(inputrc_name):
1455 try:
1330 try:
1456 readline.read_init_file(inputrc_name)
1331 readline.read_init_file(inputrc_name)
1457 except:
1332 except:
1458 warn('Problems reading readline initialization file <%s>'
1333 warn('Problems reading readline initialization file <%s>'
1459 % inputrc_name)
1334 % inputrc_name)
1460
1335
1461 self.has_readline = 1
1336 self.has_readline = 1
1462 self.readline = readline
1337 self.readline = readline
1463 # save this in sys so embedded copies can restore it properly
1338 # save this in sys so embedded copies can restore it properly
1464 sys.ipcompleter = self.Completer.complete
1339 sys.ipcompleter = self.Completer.complete
1465 self.set_completer()
1340 self.set_completer()
1466
1341
1467 # Configure readline according to user's prefs
1342 # Configure readline according to user's prefs
1468 # This is only done if GNU readline is being used. If libedit
1343 # This is only done if GNU readline is being used. If libedit
1469 # is being used (as on Leopard) the readline config is
1344 # is being used (as on Leopard) the readline config is
1470 # not run as the syntax for libedit is different.
1345 # not run as the syntax for libedit is different.
1471 if not readline.uses_libedit:
1346 if not readline.uses_libedit:
1472 for rlcommand in self.rc.readline_parse_and_bind:
1347 for rlcommand in self.readline_parse_and_bind:
1473 #print "loading rl:",rlcommand # dbg
1348 #print "loading rl:",rlcommand # dbg
1474 readline.parse_and_bind(rlcommand)
1349 readline.parse_and_bind(rlcommand)
1475
1350
1476 # Remove some chars from the delimiters list. If we encounter
1351 # Remove some chars from the delimiters list. If we encounter
1477 # unicode chars, discard them.
1352 # unicode chars, discard them.
1478 delims = readline.get_completer_delims().encode("ascii", "ignore")
1353 delims = readline.get_completer_delims().encode("ascii", "ignore")
1479 delims = delims.translate(string._idmap,
1354 delims = delims.translate(string._idmap,
1480 self.rc.readline_remove_delims)
1355 self.readline_remove_delims)
1481 readline.set_completer_delims(delims)
1356 readline.set_completer_delims(delims)
1482 # otherwise we end up with a monster history after a while:
1357 # otherwise we end up with a monster history after a while:
1483 readline.set_history_length(1000)
1358 readline.set_history_length(1000)
1484 try:
1359 try:
1485 #print '*** Reading readline history' # dbg
1360 #print '*** Reading readline history' # dbg
1486 readline.read_history_file(self.histfile)
1361 readline.read_history_file(self.histfile)
1487 except IOError:
1362 except IOError:
1488 pass # It doesn't exist yet.
1363 pass # It doesn't exist yet.
1489
1364
1490 atexit.register(self.atexit_operations)
1365 atexit.register(self.atexit_operations)
1491 del atexit
1366 del atexit
1492
1367
1493 # Configure auto-indent for all platforms
1368 # Configure auto-indent for all platforms
1494 self.set_autoindent(self.rc.autoindent)
1369 self.set_autoindent(self.autoindent)
1495
1370
1496 def ask_yes_no(self,prompt,default=True):
1371 def ask_yes_no(self,prompt,default=True):
1497 if self.rc.quiet:
1372 if self.quiet:
1498 return True
1373 return True
1499 return ask_yes_no(prompt,default)
1374 return ask_yes_no(prompt,default)
1500
1375
1501 def new_main_mod(self,ns=None):
1376 def new_main_mod(self,ns=None):
1502 """Return a new 'main' module object for user code execution.
1377 """Return a new 'main' module object for user code execution.
1503 """
1378 """
1504 main_mod = self._user_main_module
1379 main_mod = self._user_main_module
1505 init_fakemod_dict(main_mod,ns)
1380 init_fakemod_dict(main_mod,ns)
1506 return main_mod
1381 return main_mod
1507
1382
1508 def cache_main_mod(self,ns,fname):
1383 def cache_main_mod(self,ns,fname):
1509 """Cache a main module's namespace.
1384 """Cache a main module's namespace.
1510
1385
1511 When scripts are executed via %run, we must keep a reference to the
1386 When scripts are executed via %run, we must keep a reference to the
1512 namespace of their __main__ module (a FakeModule instance) around so
1387 namespace of their __main__ module (a FakeModule instance) around so
1513 that Python doesn't clear it, rendering objects defined therein
1388 that Python doesn't clear it, rendering objects defined therein
1514 useless.
1389 useless.
1515
1390
1516 This method keeps said reference in a private dict, keyed by the
1391 This method keeps said reference in a private dict, keyed by the
1517 absolute path of the module object (which corresponds to the script
1392 absolute path of the module object (which corresponds to the script
1518 path). This way, for multiple executions of the same script we only
1393 path). This way, for multiple executions of the same script we only
1519 keep one copy of the namespace (the last one), thus preventing memory
1394 keep one copy of the namespace (the last one), thus preventing memory
1520 leaks from old references while allowing the objects from the last
1395 leaks from old references while allowing the objects from the last
1521 execution to be accessible.
1396 execution to be accessible.
1522
1397
1523 Note: we can not allow the actual FakeModule instances to be deleted,
1398 Note: we can not allow the actual FakeModule instances to be deleted,
1524 because of how Python tears down modules (it hard-sets all their
1399 because of how Python tears down modules (it hard-sets all their
1525 references to None without regard for reference counts). This method
1400 references to None without regard for reference counts). This method
1526 must therefore make a *copy* of the given namespace, to allow the
1401 must therefore make a *copy* of the given namespace, to allow the
1527 original module's __dict__ to be cleared and reused.
1402 original module's __dict__ to be cleared and reused.
1528
1403
1529
1404
1530 Parameters
1405 Parameters
1531 ----------
1406 ----------
1532 ns : a namespace (a dict, typically)
1407 ns : a namespace (a dict, typically)
1533
1408
1534 fname : str
1409 fname : str
1535 Filename associated with the namespace.
1410 Filename associated with the namespace.
1536
1411
1537 Examples
1412 Examples
1538 --------
1413 --------
1539
1414
1540 In [10]: import IPython
1415 In [10]: import IPython
1541
1416
1542 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1417 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1543
1418
1544 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1419 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1545 Out[12]: True
1420 Out[12]: True
1546 """
1421 """
1547 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1422 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1548
1423
1549 def clear_main_mod_cache(self):
1424 def clear_main_mod_cache(self):
1550 """Clear the cache of main modules.
1425 """Clear the cache of main modules.
1551
1426
1552 Mainly for use by utilities like %reset.
1427 Mainly for use by utilities like %reset.
1553
1428
1554 Examples
1429 Examples
1555 --------
1430 --------
1556
1431
1557 In [15]: import IPython
1432 In [15]: import IPython
1558
1433
1559 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1434 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1560
1435
1561 In [17]: len(_ip.IP._main_ns_cache) > 0
1436 In [17]: len(_ip.IP._main_ns_cache) > 0
1562 Out[17]: True
1437 Out[17]: True
1563
1438
1564 In [18]: _ip.IP.clear_main_mod_cache()
1439 In [18]: _ip.IP.clear_main_mod_cache()
1565
1440
1566 In [19]: len(_ip.IP._main_ns_cache) == 0
1441 In [19]: len(_ip.IP._main_ns_cache) == 0
1567 Out[19]: True
1442 Out[19]: True
1568 """
1443 """
1569 self._main_ns_cache.clear()
1444 self._main_ns_cache.clear()
1570
1445
1571 def _should_recompile(self,e):
1446 def _should_recompile(self,e):
1572 """Utility routine for edit_syntax_error"""
1447 """Utility routine for edit_syntax_error"""
1573
1448
1574 if e.filename in ('<ipython console>','<input>','<string>',
1449 if e.filename in ('<ipython console>','<input>','<string>',
1575 '<console>','<BackgroundJob compilation>',
1450 '<console>','<BackgroundJob compilation>',
1576 None):
1451 None):
1577
1452
1578 return False
1453 return False
1579 try:
1454 try:
1580 if (self.rc.autoedit_syntax and
1455 if (self.autoedit_syntax and
1581 not self.ask_yes_no('Return to editor to correct syntax error? '
1456 not self.ask_yes_no('Return to editor to correct syntax error? '
1582 '[Y/n] ','y')):
1457 '[Y/n] ','y')):
1583 return False
1458 return False
1584 except EOFError:
1459 except EOFError:
1585 return False
1460 return False
1586
1461
1587 def int0(x):
1462 def int0(x):
1588 try:
1463 try:
1589 return int(x)
1464 return int(x)
1590 except TypeError:
1465 except TypeError:
1591 return 0
1466 return 0
1592 # always pass integer line and offset values to editor hook
1467 # always pass integer line and offset values to editor hook
1593 try:
1468 try:
1594 self.hooks.fix_error_editor(e.filename,
1469 self.hooks.fix_error_editor(e.filename,
1595 int0(e.lineno),int0(e.offset),e.msg)
1470 int0(e.lineno),int0(e.offset),e.msg)
1596 except ipapi.TryNext:
1471 except ipapi.TryNext:
1597 warn('Could not open editor')
1472 warn('Could not open editor')
1598 return False
1473 return False
1599 return True
1474 return True
1600
1475
1601 def edit_syntax_error(self):
1476 def edit_syntax_error(self):
1602 """The bottom half of the syntax error handler called in the main loop.
1477 """The bottom half of the syntax error handler called in the main loop.
1603
1478
1604 Loop until syntax error is fixed or user cancels.
1479 Loop until syntax error is fixed or user cancels.
1605 """
1480 """
1606
1481
1607 while self.SyntaxTB.last_syntax_error:
1482 while self.SyntaxTB.last_syntax_error:
1608 # copy and clear last_syntax_error
1483 # copy and clear last_syntax_error
1609 err = self.SyntaxTB.clear_err_state()
1484 err = self.SyntaxTB.clear_err_state()
1610 if not self._should_recompile(err):
1485 if not self._should_recompile(err):
1611 return
1486 return
1612 try:
1487 try:
1613 # may set last_syntax_error again if a SyntaxError is raised
1488 # may set last_syntax_error again if a SyntaxError is raised
1614 self.safe_execfile(err.filename,self.user_ns)
1489 self.safe_execfile(err.filename,self.user_ns)
1615 except:
1490 except:
1616 self.showtraceback()
1491 self.showtraceback()
1617 else:
1492 else:
1618 try:
1493 try:
1619 f = file(err.filename)
1494 f = file(err.filename)
1620 try:
1495 try:
1621 sys.displayhook(f.read())
1496 sys.displayhook(f.read())
1622 finally:
1497 finally:
1623 f.close()
1498 f.close()
1624 except:
1499 except:
1625 self.showtraceback()
1500 self.showtraceback()
1626
1501
1627 def showsyntaxerror(self, filename=None):
1502 def showsyntaxerror(self, filename=None):
1628 """Display the syntax error that just occurred.
1503 """Display the syntax error that just occurred.
1629
1504
1630 This doesn't display a stack trace because there isn't one.
1505 This doesn't display a stack trace because there isn't one.
1631
1506
1632 If a filename is given, it is stuffed in the exception instead
1507 If a filename is given, it is stuffed in the exception instead
1633 of what was there before (because Python's parser always uses
1508 of what was there before (because Python's parser always uses
1634 "<string>" when reading from a string).
1509 "<string>" when reading from a string).
1635 """
1510 """
1636 etype, value, last_traceback = sys.exc_info()
1511 etype, value, last_traceback = sys.exc_info()
1637
1512
1638 # See note about these variables in showtraceback() below
1513 # See note about these variables in showtraceback() below
1639 sys.last_type = etype
1514 sys.last_type = etype
1640 sys.last_value = value
1515 sys.last_value = value
1641 sys.last_traceback = last_traceback
1516 sys.last_traceback = last_traceback
1642
1517
1643 if filename and etype is SyntaxError:
1518 if filename and etype is SyntaxError:
1644 # Work hard to stuff the correct filename in the exception
1519 # Work hard to stuff the correct filename in the exception
1645 try:
1520 try:
1646 msg, (dummy_filename, lineno, offset, line) = value
1521 msg, (dummy_filename, lineno, offset, line) = value
1647 except:
1522 except:
1648 # Not the format we expect; leave it alone
1523 # Not the format we expect; leave it alone
1649 pass
1524 pass
1650 else:
1525 else:
1651 # Stuff in the right filename
1526 # Stuff in the right filename
1652 try:
1527 try:
1653 # Assume SyntaxError is a class exception
1528 # Assume SyntaxError is a class exception
1654 value = SyntaxError(msg, (filename, lineno, offset, line))
1529 value = SyntaxError(msg, (filename, lineno, offset, line))
1655 except:
1530 except:
1656 # If that failed, assume SyntaxError is a string
1531 # If that failed, assume SyntaxError is a string
1657 value = msg, (filename, lineno, offset, line)
1532 value = msg, (filename, lineno, offset, line)
1658 self.SyntaxTB(etype,value,[])
1533 self.SyntaxTB(etype,value,[])
1659
1534
1660 def debugger(self,force=False):
1535 def debugger(self,force=False):
1661 """Call the pydb/pdb debugger.
1536 """Call the pydb/pdb debugger.
1662
1537
1663 Keywords:
1538 Keywords:
1664
1539
1665 - force(False): by default, this routine checks the instance call_pdb
1540 - force(False): by default, this routine checks the instance call_pdb
1666 flag and does not actually invoke the debugger if the flag is false.
1541 flag and does not actually invoke the debugger if the flag is false.
1667 The 'force' option forces the debugger to activate even if the flag
1542 The 'force' option forces the debugger to activate even if the flag
1668 is false.
1543 is false.
1669 """
1544 """
1670
1545
1671 if not (force or self.call_pdb):
1546 if not (force or self.call_pdb):
1672 return
1547 return
1673
1548
1674 if not hasattr(sys,'last_traceback'):
1549 if not hasattr(sys,'last_traceback'):
1675 error('No traceback has been produced, nothing to debug.')
1550 error('No traceback has been produced, nothing to debug.')
1676 return
1551 return
1677
1552
1678 # use pydb if available
1553 # use pydb if available
1679 if debugger.has_pydb:
1554 if debugger.has_pydb:
1680 from pydb import pm
1555 from pydb import pm
1681 else:
1556 else:
1682 # fallback to our internal debugger
1557 # fallback to our internal debugger
1683 pm = lambda : self.InteractiveTB.debugger(force=True)
1558 pm = lambda : self.InteractiveTB.debugger(force=True)
1684 self.history_saving_wrapper(pm)()
1559 self.history_saving_wrapper(pm)()
1685
1560
1686 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1561 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1687 """Display the exception that just occurred.
1562 """Display the exception that just occurred.
1688
1563
1689 If nothing is known about the exception, this is the method which
1564 If nothing is known about the exception, this is the method which
1690 should be used throughout the code for presenting user tracebacks,
1565 should be used throughout the code for presenting user tracebacks,
1691 rather than directly invoking the InteractiveTB object.
1566 rather than directly invoking the InteractiveTB object.
1692
1567
1693 A specific showsyntaxerror() also exists, but this method can take
1568 A specific showsyntaxerror() also exists, but this method can take
1694 care of calling it if needed, so unless you are explicitly catching a
1569 care of calling it if needed, so unless you are explicitly catching a
1695 SyntaxError exception, don't try to analyze the stack manually and
1570 SyntaxError exception, don't try to analyze the stack manually and
1696 simply call this method."""
1571 simply call this method."""
1697
1572
1698
1573
1699 # Though this won't be called by syntax errors in the input line,
1574 # Though this won't be called by syntax errors in the input line,
1700 # there may be SyntaxError cases whith imported code.
1575 # there may be SyntaxError cases whith imported code.
1701
1576
1702 try:
1577 try:
1703 if exc_tuple is None:
1578 if exc_tuple is None:
1704 etype, value, tb = sys.exc_info()
1579 etype, value, tb = sys.exc_info()
1705 else:
1580 else:
1706 etype, value, tb = exc_tuple
1581 etype, value, tb = exc_tuple
1707
1582
1708 if etype is SyntaxError:
1583 if etype is SyntaxError:
1709 self.showsyntaxerror(filename)
1584 self.showsyntaxerror(filename)
1710 elif etype is ipapi.UsageError:
1585 elif etype is ipapi.UsageError:
1711 print "UsageError:", value
1586 print "UsageError:", value
1712 else:
1587 else:
1713 # WARNING: these variables are somewhat deprecated and not
1588 # WARNING: these variables are somewhat deprecated and not
1714 # necessarily safe to use in a threaded environment, but tools
1589 # necessarily safe to use in a threaded environment, but tools
1715 # like pdb depend on their existence, so let's set them. If we
1590 # like pdb depend on their existence, so let's set them. If we
1716 # find problems in the field, we'll need to revisit their use.
1591 # find problems in the field, we'll need to revisit their use.
1717 sys.last_type = etype
1592 sys.last_type = etype
1718 sys.last_value = value
1593 sys.last_value = value
1719 sys.last_traceback = tb
1594 sys.last_traceback = tb
1720
1595
1721 if etype in self.custom_exceptions:
1596 if etype in self.custom_exceptions:
1722 self.CustomTB(etype,value,tb)
1597 self.CustomTB(etype,value,tb)
1723 else:
1598 else:
1724 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1599 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1725 if self.InteractiveTB.call_pdb and self.has_readline:
1600 if self.InteractiveTB.call_pdb and self.has_readline:
1726 # pdb mucks up readline, fix it back
1601 # pdb mucks up readline, fix it back
1727 self.set_completer()
1602 self.set_completer()
1728 except KeyboardInterrupt:
1603 except KeyboardInterrupt:
1729 self.write("\nKeyboardInterrupt\n")
1604 self.write("\nKeyboardInterrupt\n")
1730
1605
1731 def mainloop(self,banner=None):
1606 def mainloop(self, banner=None):
1732 """Creates the local namespace and starts the mainloop.
1607 """Start the mainloop.
1733
1608
1734 If an optional banner argument is given, it will override the
1609 If an optional banner argument is given, it will override the
1735 internally created default banner."""
1610 internally created default banner.
1736
1611 """
1737 if self.rc.c: # Emulate Python's -c option
1612 if self.c: # Emulate Python's -c option
1738 self.exec_init_cmd()
1613 self.exec_init_cmd()
1739 if banner is None:
1614
1740 if not self.rc.banner:
1615 if self.display_banner:
1741 banner = ''
1616 if banner is None:
1742 # banner is string? Use it directly!
1617 banner = self.banner
1743 elif isinstance(self.rc.banner,basestring):
1744 banner = self.rc.banner
1745 else:
1746 banner = self.BANNER+self.banner2
1747
1618
1748 # if you run stuff with -c <cmd>, raw hist is not updated
1619 # if you run stuff with -c <cmd>, raw hist is not updated
1749 # ensure that it's in sync
1620 # ensure that it's in sync
1750 if len(self.input_hist) != len (self.input_hist_raw):
1621 if len(self.input_hist) != len (self.input_hist_raw):
1751 self.input_hist_raw = InputList(self.input_hist)
1622 self.input_hist_raw = InputList(self.input_hist)
1752
1623
1753 while 1:
1624 while 1:
1754 try:
1625 try:
1755 self.interact(banner)
1626 self.interact()
1756 #self.interact_with_readline()
1627 #self.interact_with_readline()
1757
1758 # XXX for testing of a readline-decoupled repl loop, call
1628 # XXX for testing of a readline-decoupled repl loop, call
1759 # interact_with_readline above
1629 # interact_with_readline above
1760
1761 break
1630 break
1762 except KeyboardInterrupt:
1631 except KeyboardInterrupt:
1763 # this should not be necessary, but KeyboardInterrupt
1632 # this should not be necessary, but KeyboardInterrupt
1764 # handling seems rather unpredictable...
1633 # handling seems rather unpredictable...
1765 self.write("\nKeyboardInterrupt in interact()\n")
1634 self.write("\nKeyboardInterrupt in interact()\n")
1766
1635
1767 def exec_init_cmd(self):
1636 def exec_init_cmd(self):
1768 """Execute a command given at the command line.
1637 """Execute a command given at the command line.
1769
1638
1770 This emulates Python's -c option."""
1639 This emulates Python's -c option."""
1771
1640
1772 #sys.argv = ['-c']
1641 #sys.argv = ['-c']
1773 self.push(self.prefilter(self.rc.c, False))
1642 self.push(self.prefilter(self.c, False))
1774 if not self.rc.interact:
1643 if not self.interactive:
1775 self.ask_exit()
1644 self.ask_exit()
1776
1645
1777 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1646 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1778 """Embeds IPython into a running python program.
1647 """Embeds IPython into a running python program.
1779
1648
1780 Input:
1649 Input:
1781
1650
1782 - header: An optional header message can be specified.
1651 - header: An optional header message can be specified.
1783
1652
1784 - local_ns, global_ns: working namespaces. If given as None, the
1653 - local_ns, global_ns: working namespaces. If given as None, the
1785 IPython-initialized one is updated with __main__.__dict__, so that
1654 IPython-initialized one is updated with __main__.__dict__, so that
1786 program variables become visible but user-specific configuration
1655 program variables become visible but user-specific configuration
1787 remains possible.
1656 remains possible.
1788
1657
1789 - stack_depth: specifies how many levels in the stack to go to
1658 - stack_depth: specifies how many levels in the stack to go to
1790 looking for namespaces (when local_ns and global_ns are None). This
1659 looking for namespaces (when local_ns and global_ns are None). This
1791 allows an intermediate caller to make sure that this function gets
1660 allows an intermediate caller to make sure that this function gets
1792 the namespace from the intended level in the stack. By default (0)
1661 the namespace from the intended level in the stack. By default (0)
1793 it will get its locals and globals from the immediate caller.
1662 it will get its locals and globals from the immediate caller.
1794
1663
1795 Warning: it's possible to use this in a program which is being run by
1664 Warning: it's possible to use this in a program which is being run by
1796 IPython itself (via %run), but some funny things will happen (a few
1665 IPython itself (via %run), but some funny things will happen (a few
1797 globals get overwritten). In the future this will be cleaned up, as
1666 globals get overwritten). In the future this will be cleaned up, as
1798 there is no fundamental reason why it can't work perfectly."""
1667 there is no fundamental reason why it can't work perfectly."""
1799
1668
1800 # Get locals and globals from caller
1669 # Get locals and globals from caller
1801 if local_ns is None or global_ns is None:
1670 if local_ns is None or global_ns is None:
1802 call_frame = sys._getframe(stack_depth).f_back
1671 call_frame = sys._getframe(stack_depth).f_back
1803
1672
1804 if local_ns is None:
1673 if local_ns is None:
1805 local_ns = call_frame.f_locals
1674 local_ns = call_frame.f_locals
1806 if global_ns is None:
1675 if global_ns is None:
1807 global_ns = call_frame.f_globals
1676 global_ns = call_frame.f_globals
1808
1677
1809 # Update namespaces and fire up interpreter
1678 # Update namespaces and fire up interpreter
1810
1679
1811 # The global one is easy, we can just throw it in
1680 # The global one is easy, we can just throw it in
1812 self.user_global_ns = global_ns
1681 self.user_global_ns = global_ns
1813
1682
1814 # but the user/local one is tricky: ipython needs it to store internal
1683 # but the user/local one is tricky: ipython needs it to store internal
1815 # data, but we also need the locals. We'll copy locals in the user
1684 # data, but we also need the locals. We'll copy locals in the user
1816 # one, but will track what got copied so we can delete them at exit.
1685 # one, but will track what got copied so we can delete them at exit.
1817 # This is so that a later embedded call doesn't see locals from a
1686 # This is so that a later embedded call doesn't see locals from a
1818 # previous call (which most likely existed in a separate scope).
1687 # previous call (which most likely existed in a separate scope).
1819 local_varnames = local_ns.keys()
1688 local_varnames = local_ns.keys()
1820 self.user_ns.update(local_ns)
1689 self.user_ns.update(local_ns)
1821 #self.user_ns['local_ns'] = local_ns # dbg
1690 #self.user_ns['local_ns'] = local_ns # dbg
1822
1691
1823 # Patch for global embedding to make sure that things don't overwrite
1692 # Patch for global embedding to make sure that things don't overwrite
1824 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1693 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1825 # FIXME. Test this a bit more carefully (the if.. is new)
1694 # FIXME. Test this a bit more carefully (the if.. is new)
1826 if local_ns is None and global_ns is None:
1695 if local_ns is None and global_ns is None:
1827 self.user_global_ns.update(__main__.__dict__)
1696 self.user_global_ns.update(__main__.__dict__)
1828
1697
1829 # make sure the tab-completer has the correct frame information, so it
1698 # make sure the tab-completer has the correct frame information, so it
1830 # actually completes using the frame's locals/globals
1699 # actually completes using the frame's locals/globals
1831 self.set_completer_frame()
1700 self.set_completer_frame()
1832
1701
1833 # before activating the interactive mode, we need to make sure that
1702 # before activating the interactive mode, we need to make sure that
1834 # all names in the builtin namespace needed by ipython point to
1703 # all names in the builtin namespace needed by ipython point to
1835 # ourselves, and not to other instances.
1704 # ourselves, and not to other instances.
1836 self.add_builtins()
1705 self.add_builtins()
1837
1706
1838 self.interact(header)
1707 self.interact(header)
1839
1708
1840 # now, purge out the user namespace from anything we might have added
1709 # now, purge out the user namespace from anything we might have added
1841 # from the caller's local namespace
1710 # from the caller's local namespace
1842 delvar = self.user_ns.pop
1711 delvar = self.user_ns.pop
1843 for var in local_varnames:
1712 for var in local_varnames:
1844 delvar(var,None)
1713 delvar(var,None)
1845 # and clean builtins we may have overridden
1714 # and clean builtins we may have overridden
1846 self.clean_builtins()
1715 self.clean_builtins()
1847
1716
1848 def interact_prompt(self):
1717 def interact_prompt(self):
1849 """ Print the prompt (in read-eval-print loop)
1718 """ Print the prompt (in read-eval-print loop)
1850
1719
1851 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1720 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1852 used in standard IPython flow.
1721 used in standard IPython flow.
1853 """
1722 """
1854 if self.more:
1723 if self.more:
1855 try:
1724 try:
1856 prompt = self.hooks.generate_prompt(True)
1725 prompt = self.hooks.generate_prompt(True)
1857 except:
1726 except:
1858 self.showtraceback()
1727 self.showtraceback()
1859 if self.autoindent:
1728 if self.autoindent:
1860 self.rl_do_indent = True
1729 self.rl_do_indent = True
1861
1730
1862 else:
1731 else:
1863 try:
1732 try:
1864 prompt = self.hooks.generate_prompt(False)
1733 prompt = self.hooks.generate_prompt(False)
1865 except:
1734 except:
1866 self.showtraceback()
1735 self.showtraceback()
1867 self.write(prompt)
1736 self.write(prompt)
1868
1737
1869 def interact_handle_input(self,line):
1738 def interact_handle_input(self,line):
1870 """ Handle the input line (in read-eval-print loop)
1739 """ Handle the input line (in read-eval-print loop)
1871
1740
1872 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1741 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1873 used in standard IPython flow.
1742 used in standard IPython flow.
1874 """
1743 """
1875 if line.lstrip() == line:
1744 if line.lstrip() == line:
1876 self.shadowhist.add(line.strip())
1745 self.shadowhist.add(line.strip())
1877 lineout = self.prefilter(line,self.more)
1746 lineout = self.prefilter(line,self.more)
1878
1747
1879 if line.strip():
1748 if line.strip():
1880 if self.more:
1749 if self.more:
1881 self.input_hist_raw[-1] += '%s\n' % line
1750 self.input_hist_raw[-1] += '%s\n' % line
1882 else:
1751 else:
1883 self.input_hist_raw.append('%s\n' % line)
1752 self.input_hist_raw.append('%s\n' % line)
1884
1753
1885
1754
1886 self.more = self.push(lineout)
1755 self.more = self.push(lineout)
1887 if (self.SyntaxTB.last_syntax_error and
1756 if (self.SyntaxTB.last_syntax_error and
1888 self.rc.autoedit_syntax):
1757 self.autoedit_syntax):
1889 self.edit_syntax_error()
1758 self.edit_syntax_error()
1890
1759
1891 def interact_with_readline(self):
1760 def interact_with_readline(self):
1892 """ Demo of using interact_handle_input, interact_prompt
1761 """ Demo of using interact_handle_input, interact_prompt
1893
1762
1894 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1763 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1895 it should work like this.
1764 it should work like this.
1896 """
1765 """
1897 self.readline_startup_hook(self.pre_readline)
1766 self.readline_startup_hook(self.pre_readline)
1898 while not self.exit_now:
1767 while not self.exit_now:
1899 self.interact_prompt()
1768 self.interact_prompt()
1900 if self.more:
1769 if self.more:
1901 self.rl_do_indent = True
1770 self.rl_do_indent = True
1902 else:
1771 else:
1903 self.rl_do_indent = False
1772 self.rl_do_indent = False
1904 line = raw_input_original().decode(self.stdin_encoding)
1773 line = raw_input_original().decode(self.stdin_encoding)
1905 self.interact_handle_input(line)
1774 self.interact_handle_input(line)
1906
1775
1907
1908 def interact(self, banner=None):
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
1779 # batch run -> do not interact
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
1920 if self.exit_now:
1780 if self.exit_now:
1921 # batch run -> do not interact
1922 return
1781 return
1923 cprt = 'Type "copyright", "credits" or "license" for more information.'
1782
1924 if banner is None:
1783 if self.display_banner:
1925 self.write("Python %s on %s\n%s\n(%s)\n" %
1784 if banner is None:
1926 (sys.version, sys.platform, cprt,
1785 banner = self.banner
1927 self.__class__.__name__))
1928 else:
1929 self.write(banner)
1786 self.write(banner)
1930
1787
1931 more = 0
1788 more = 0
1932
1789
1933 # Mark activity in the builtins
1790 # Mark activity in the builtins
1934 __builtin__.__dict__['__IPYTHON__active'] += 1
1791 __builtin__.__dict__['__IPYTHON__active'] += 1
1935
1792
1936 if self.has_readline:
1793 if self.has_readline:
1937 self.readline_startup_hook(self.pre_readline)
1794 self.readline_startup_hook(self.pre_readline)
1938 # exit_now is set by a call to %Exit or %Quit, through the
1795 # exit_now is set by a call to %Exit or %Quit, through the
1939 # ask_exit callback.
1796 # ask_exit callback.
1940
1797
1941 while not self.exit_now:
1798 while not self.exit_now:
1942 self.hooks.pre_prompt_hook()
1799 self.hooks.pre_prompt_hook()
1943 if more:
1800 if more:
1944 try:
1801 try:
1945 prompt = self.hooks.generate_prompt(True)
1802 prompt = self.hooks.generate_prompt(True)
1946 except:
1803 except:
1947 self.showtraceback()
1804 self.showtraceback()
1948 if self.autoindent:
1805 if self.autoindent:
1949 self.rl_do_indent = True
1806 self.rl_do_indent = True
1950
1807
1951 else:
1808 else:
1952 try:
1809 try:
1953 prompt = self.hooks.generate_prompt(False)
1810 prompt = self.hooks.generate_prompt(False)
1954 except:
1811 except:
1955 self.showtraceback()
1812 self.showtraceback()
1956 try:
1813 try:
1957 line = self.raw_input(prompt,more)
1814 line = self.raw_input(prompt, more)
1958 if self.exit_now:
1815 if self.exit_now:
1959 # quick exit on sys.std[in|out] close
1816 # quick exit on sys.std[in|out] close
1960 break
1817 break
1961 if self.autoindent:
1818 if self.autoindent:
1962 self.rl_do_indent = False
1819 self.rl_do_indent = False
1963
1820
1964 except KeyboardInterrupt:
1821 except KeyboardInterrupt:
1965 #double-guard against keyboardinterrupts during kbdint handling
1822 #double-guard against keyboardinterrupts during kbdint handling
1966 try:
1823 try:
1967 self.write('\nKeyboardInterrupt\n')
1824 self.write('\nKeyboardInterrupt\n')
1968 self.resetbuffer()
1825 self.resetbuffer()
1969 # keep cache in sync with the prompt counter:
1826 # keep cache in sync with the prompt counter:
1970 self.outputcache.prompt_count -= 1
1827 self.outputcache.prompt_count -= 1
1971
1828
1972 if self.autoindent:
1829 if self.autoindent:
1973 self.indent_current_nsp = 0
1830 self.indent_current_nsp = 0
1974 more = 0
1831 more = 0
1975 except KeyboardInterrupt:
1832 except KeyboardInterrupt:
1976 pass
1833 pass
1977 except EOFError:
1834 except EOFError:
1978 if self.autoindent:
1835 if self.autoindent:
1979 self.rl_do_indent = False
1836 self.rl_do_indent = False
1980 self.readline_startup_hook(None)
1837 self.readline_startup_hook(None)
1981 self.write('\n')
1838 self.write('\n')
1982 self.exit()
1839 self.exit()
1983 except bdb.BdbQuit:
1840 except bdb.BdbQuit:
1984 warn('The Python debugger has exited with a BdbQuit exception.\n'
1841 warn('The Python debugger has exited with a BdbQuit exception.\n'
1985 'Because of how pdb handles the stack, it is impossible\n'
1842 'Because of how pdb handles the stack, it is impossible\n'
1986 'for IPython to properly format this particular exception.\n'
1843 'for IPython to properly format this particular exception.\n'
1987 'IPython will resume normal operation.')
1844 'IPython will resume normal operation.')
1988 except:
1845 except:
1989 # exceptions here are VERY RARE, but they can be triggered
1846 # exceptions here are VERY RARE, but they can be triggered
1990 # asynchronously by signal handlers, for example.
1847 # asynchronously by signal handlers, for example.
1991 self.showtraceback()
1848 self.showtraceback()
1992 else:
1849 else:
1993 more = self.push(line)
1850 more = self.push(line)
1994 if (self.SyntaxTB.last_syntax_error and
1851 if (self.SyntaxTB.last_syntax_error and
1995 self.rc.autoedit_syntax):
1852 self.autoedit_syntax):
1996 self.edit_syntax_error()
1853 self.edit_syntax_error()
1997
1854
1998 # We are off again...
1855 # We are off again...
1999 __builtin__.__dict__['__IPYTHON__active'] -= 1
1856 __builtin__.__dict__['__IPYTHON__active'] -= 1
2000
1857
2001 def excepthook(self, etype, value, tb):
1858 def excepthook(self, etype, value, tb):
2002 """One more defense for GUI apps that call sys.excepthook.
1859 """One more defense for GUI apps that call sys.excepthook.
2003
1860
2004 GUI frameworks like wxPython trap exceptions and call
1861 GUI frameworks like wxPython trap exceptions and call
2005 sys.excepthook themselves. I guess this is a feature that
1862 sys.excepthook themselves. I guess this is a feature that
2006 enables them to keep running after exceptions that would
1863 enables them to keep running after exceptions that would
2007 otherwise kill their mainloop. This is a bother for IPython
1864 otherwise kill their mainloop. This is a bother for IPython
2008 which excepts to catch all of the program exceptions with a try:
1865 which excepts to catch all of the program exceptions with a try:
2009 except: statement.
1866 except: statement.
2010
1867
2011 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1868 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2012 any app directly invokes sys.excepthook, it will look to the user like
1869 any app directly invokes sys.excepthook, it will look to the user like
2013 IPython crashed. In order to work around this, we can disable the
1870 IPython crashed. In order to work around this, we can disable the
2014 CrashHandler and replace it with this excepthook instead, which prints a
1871 CrashHandler and replace it with this excepthook instead, which prints a
2015 regular traceback using our InteractiveTB. In this fashion, apps which
1872 regular traceback using our InteractiveTB. In this fashion, apps which
2016 call sys.excepthook will generate a regular-looking exception from
1873 call sys.excepthook will generate a regular-looking exception from
2017 IPython, and the CrashHandler will only be triggered by real IPython
1874 IPython, and the CrashHandler will only be triggered by real IPython
2018 crashes.
1875 crashes.
2019
1876
2020 This hook should be used sparingly, only in places which are not likely
1877 This hook should be used sparingly, only in places which are not likely
2021 to be true IPython errors.
1878 to be true IPython errors.
2022 """
1879 """
2023 self.showtraceback((etype,value,tb),tb_offset=0)
1880 self.showtraceback((etype,value,tb),tb_offset=0)
2024
1881
2025 def expand_aliases(self,fn,rest):
1882 def expand_aliases(self,fn,rest):
2026 """ Expand multiple levels of aliases:
1883 """ Expand multiple levels of aliases:
2027
1884
2028 if:
1885 if:
2029
1886
2030 alias foo bar /tmp
1887 alias foo bar /tmp
2031 alias baz foo
1888 alias baz foo
2032
1889
2033 then:
1890 then:
2034
1891
2035 baz huhhahhei -> bar /tmp huhhahhei
1892 baz huhhahhei -> bar /tmp huhhahhei
2036
1893
2037 """
1894 """
2038 line = fn + " " + rest
1895 line = fn + " " + rest
2039
1896
2040 done = set()
1897 done = set()
2041 while 1:
1898 while 1:
2042 pre,fn,rest = prefilter.splitUserInput(line,
1899 pre,fn,rest = prefilter.splitUserInput(line,
2043 prefilter.shell_line_split)
1900 prefilter.shell_line_split)
2044 if fn in self.alias_table:
1901 if fn in self.alias_table:
2045 if fn in done:
1902 if fn in done:
2046 warn("Cyclic alias definition, repeated '%s'" % fn)
1903 warn("Cyclic alias definition, repeated '%s'" % fn)
2047 return ""
1904 return ""
2048 done.add(fn)
1905 done.add(fn)
2049
1906
2050 l2 = self.transform_alias(fn,rest)
1907 l2 = self.transform_alias(fn,rest)
2051 # dir -> dir
1908 # dir -> dir
2052 # print "alias",line, "->",l2 #dbg
1909 # print "alias",line, "->",l2 #dbg
2053 if l2 == line:
1910 if l2 == line:
2054 break
1911 break
2055 # ls -> ls -F should not recurse forever
1912 # ls -> ls -F should not recurse forever
2056 if l2.split(None,1)[0] == line.split(None,1)[0]:
1913 if l2.split(None,1)[0] == line.split(None,1)[0]:
2057 line = l2
1914 line = l2
2058 break
1915 break
2059
1916
2060 line=l2
1917 line=l2
2061
1918
2062
1919
2063 # print "al expand to",line #dbg
1920 # print "al expand to",line #dbg
2064 else:
1921 else:
2065 break
1922 break
2066
1923
2067 return line
1924 return line
2068
1925
2069 def transform_alias(self, alias,rest=''):
1926 def transform_alias(self, alias,rest=''):
2070 """ Transform alias to system command string.
1927 """ Transform alias to system command string.
2071 """
1928 """
2072 trg = self.alias_table[alias]
1929 trg = self.alias_table[alias]
2073
1930
2074 nargs,cmd = trg
1931 nargs,cmd = trg
2075 # print trg #dbg
1932 # print trg #dbg
2076 if ' ' in cmd and os.path.isfile(cmd):
1933 if ' ' in cmd and os.path.isfile(cmd):
2077 cmd = '"%s"' % cmd
1934 cmd = '"%s"' % cmd
2078
1935
2079 # Expand the %l special to be the user's input line
1936 # Expand the %l special to be the user's input line
2080 if cmd.find('%l') >= 0:
1937 if cmd.find('%l') >= 0:
2081 cmd = cmd.replace('%l',rest)
1938 cmd = cmd.replace('%l',rest)
2082 rest = ''
1939 rest = ''
2083 if nargs==0:
1940 if nargs==0:
2084 # Simple, argument-less aliases
1941 # Simple, argument-less aliases
2085 cmd = '%s %s' % (cmd,rest)
1942 cmd = '%s %s' % (cmd,rest)
2086 else:
1943 else:
2087 # Handle aliases with positional arguments
1944 # Handle aliases with positional arguments
2088 args = rest.split(None,nargs)
1945 args = rest.split(None,nargs)
2089 if len(args)< nargs:
1946 if len(args)< nargs:
2090 error('Alias <%s> requires %s arguments, %s given.' %
1947 error('Alias <%s> requires %s arguments, %s given.' %
2091 (alias,nargs,len(args)))
1948 (alias,nargs,len(args)))
2092 return None
1949 return None
2093 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1950 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2094 # Now call the macro, evaluating in the user's namespace
1951 # Now call the macro, evaluating in the user's namespace
2095 #print 'new command: <%r>' % cmd # dbg
1952 #print 'new command: <%r>' % cmd # dbg
2096 return cmd
1953 return cmd
2097
1954
2098 def call_alias(self,alias,rest=''):
1955 def call_alias(self,alias,rest=''):
2099 """Call an alias given its name and the rest of the line.
1956 """Call an alias given its name and the rest of the line.
2100
1957
2101 This is only used to provide backwards compatibility for users of
1958 This is only used to provide backwards compatibility for users of
2102 ipalias(), use of which is not recommended for anymore."""
1959 ipalias(), use of which is not recommended for anymore."""
2103
1960
2104 # Now call the macro, evaluating in the user's namespace
1961 # Now call the macro, evaluating in the user's namespace
2105 cmd = self.transform_alias(alias, rest)
1962 cmd = self.transform_alias(alias, rest)
2106 try:
1963 try:
2107 self.system(cmd)
1964 self.system(cmd)
2108 except:
1965 except:
2109 self.showtraceback()
1966 self.showtraceback()
2110
1967
2111 def indent_current_str(self):
1968 def indent_current_str(self):
2112 """return the current level of indentation as a string"""
1969 """return the current level of indentation as a string"""
2113 return self.indent_current_nsp * ' '
1970 return self.indent_current_nsp * ' '
2114
1971
2115 def autoindent_update(self,line):
1972 def autoindent_update(self,line):
2116 """Keep track of the indent level."""
1973 """Keep track of the indent level."""
2117
1974
2118 #debugx('line')
1975 #debugx('line')
2119 #debugx('self.indent_current_nsp')
1976 #debugx('self.indent_current_nsp')
2120 if self.autoindent:
1977 if self.autoindent:
2121 if line:
1978 if line:
2122 inisp = num_ini_spaces(line)
1979 inisp = num_ini_spaces(line)
2123 if inisp < self.indent_current_nsp:
1980 if inisp < self.indent_current_nsp:
2124 self.indent_current_nsp = inisp
1981 self.indent_current_nsp = inisp
2125
1982
2126 if line[-1] == ':':
1983 if line[-1] == ':':
2127 self.indent_current_nsp += 4
1984 self.indent_current_nsp += 4
2128 elif dedent_re.match(line):
1985 elif dedent_re.match(line):
2129 self.indent_current_nsp -= 4
1986 self.indent_current_nsp -= 4
2130 else:
1987 else:
2131 self.indent_current_nsp = 0
1988 self.indent_current_nsp = 0
2132
1989
2133 def runlines(self,lines):
1990 def runlines(self,lines):
2134 """Run a string of one or more lines of source.
1991 """Run a string of one or more lines of source.
2135
1992
2136 This method is capable of running a string containing multiple source
1993 This method is capable of running a string containing multiple source
2137 lines, as if they had been entered at the IPython prompt. Since it
1994 lines, as if they had been entered at the IPython prompt. Since it
2138 exposes IPython's processing machinery, the given strings can contain
1995 exposes IPython's processing machinery, the given strings can contain
2139 magic calls (%magic), special shell access (!cmd), etc."""
1996 magic calls (%magic), special shell access (!cmd), etc."""
2140
1997
2141 # We must start with a clean buffer, in case this is run from an
1998 # We must start with a clean buffer, in case this is run from an
2142 # interactive IPython session (via a magic, for example).
1999 # interactive IPython session (via a magic, for example).
2143 self.resetbuffer()
2000 self.resetbuffer()
2144 lines = lines.split('\n')
2001 lines = lines.split('\n')
2145 more = 0
2002 more = 0
2146
2003
2147 for line in lines:
2004 for line in lines:
2148 # skip blank lines so we don't mess up the prompt counter, but do
2005 # skip blank lines so we don't mess up the prompt counter, but do
2149 # NOT skip even a blank line if we are in a code block (more is
2006 # NOT skip even a blank line if we are in a code block (more is
2150 # true)
2007 # true)
2151
2008
2152 if line or more:
2009 if line or more:
2153 # push to raw history, so hist line numbers stay in sync
2010 # push to raw history, so hist line numbers stay in sync
2154 self.input_hist_raw.append("# " + line + "\n")
2011 self.input_hist_raw.append("# " + line + "\n")
2155 more = self.push(self.prefilter(line,more))
2012 more = self.push(self.prefilter(line,more))
2156 # IPython's runsource returns None if there was an error
2013 # IPython's runsource returns None if there was an error
2157 # compiling the code. This allows us to stop processing right
2014 # compiling the code. This allows us to stop processing right
2158 # away, so the user gets the error message at the right place.
2015 # away, so the user gets the error message at the right place.
2159 if more is None:
2016 if more is None:
2160 break
2017 break
2161 else:
2018 else:
2162 self.input_hist_raw.append("\n")
2019 self.input_hist_raw.append("\n")
2163 # final newline in case the input didn't have it, so that the code
2020 # final newline in case the input didn't have it, so that the code
2164 # actually does get executed
2021 # actually does get executed
2165 if more:
2022 if more:
2166 self.push('\n')
2023 self.push('\n')
2167
2024
2168 def runsource(self, source, filename='<input>', symbol='single'):
2025 def runsource(self, source, filename='<input>', symbol='single'):
2169 """Compile and run some source in the interpreter.
2026 """Compile and run some source in the interpreter.
2170
2027
2171 Arguments are as for compile_command().
2028 Arguments are as for compile_command().
2172
2029
2173 One several things can happen:
2030 One several things can happen:
2174
2031
2175 1) The input is incorrect; compile_command() raised an
2032 1) The input is incorrect; compile_command() raised an
2176 exception (SyntaxError or OverflowError). A syntax traceback
2033 exception (SyntaxError or OverflowError). A syntax traceback
2177 will be printed by calling the showsyntaxerror() method.
2034 will be printed by calling the showsyntaxerror() method.
2178
2035
2179 2) The input is incomplete, and more input is required;
2036 2) The input is incomplete, and more input is required;
2180 compile_command() returned None. Nothing happens.
2037 compile_command() returned None. Nothing happens.
2181
2038
2182 3) The input is complete; compile_command() returned a code
2039 3) The input is complete; compile_command() returned a code
2183 object. The code is executed by calling self.runcode() (which
2040 object. The code is executed by calling self.runcode() (which
2184 also handles run-time exceptions, except for SystemExit).
2041 also handles run-time exceptions, except for SystemExit).
2185
2042
2186 The return value is:
2043 The return value is:
2187
2044
2188 - True in case 2
2045 - True in case 2
2189
2046
2190 - False in the other cases, unless an exception is raised, where
2047 - False in the other cases, unless an exception is raised, where
2191 None is returned instead. This can be used by external callers to
2048 None is returned instead. This can be used by external callers to
2192 know whether to continue feeding input or not.
2049 know whether to continue feeding input or not.
2193
2050
2194 The return value can be used to decide whether to use sys.ps1 or
2051 The return value can be used to decide whether to use sys.ps1 or
2195 sys.ps2 to prompt the next line."""
2052 sys.ps2 to prompt the next line."""
2196
2053
2197 # if the source code has leading blanks, add 'if 1:\n' to it
2054 # if the source code has leading blanks, add 'if 1:\n' to it
2198 # this allows execution of indented pasted code. It is tempting
2055 # this allows execution of indented pasted code. It is tempting
2199 # to add '\n' at the end of source to run commands like ' a=1'
2056 # to add '\n' at the end of source to run commands like ' a=1'
2200 # directly, but this fails for more complicated scenarios
2057 # directly, but this fails for more complicated scenarios
2201 source=source.encode(self.stdin_encoding)
2058 source=source.encode(self.stdin_encoding)
2202 if source[:1] in [' ', '\t']:
2059 if source[:1] in [' ', '\t']:
2203 source = 'if 1:\n%s' % source
2060 source = 'if 1:\n%s' % source
2204
2061
2205 try:
2062 try:
2206 code = self.compile(source,filename,symbol)
2063 code = self.compile(source,filename,symbol)
2207 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2064 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2208 # Case 1
2065 # Case 1
2209 self.showsyntaxerror(filename)
2066 self.showsyntaxerror(filename)
2210 return None
2067 return None
2211
2068
2212 if code is None:
2069 if code is None:
2213 # Case 2
2070 # Case 2
2214 return True
2071 return True
2215
2072
2216 # Case 3
2073 # Case 3
2217 # We store the code object so that threaded shells and
2074 # We store the code object so that threaded shells and
2218 # custom exception handlers can access all this info if needed.
2075 # custom exception handlers can access all this info if needed.
2219 # The source corresponding to this can be obtained from the
2076 # The source corresponding to this can be obtained from the
2220 # buffer attribute as '\n'.join(self.buffer).
2077 # buffer attribute as '\n'.join(self.buffer).
2221 self.code_to_run = code
2078 self.code_to_run = code
2222 # now actually execute the code object
2079 # now actually execute the code object
2223 if self.runcode(code) == 0:
2080 if self.runcode(code) == 0:
2224 return False
2081 return False
2225 else:
2082 else:
2226 return None
2083 return None
2227
2084
2228 def runcode(self,code_obj):
2085 def runcode(self,code_obj):
2229 """Execute a code object.
2086 """Execute a code object.
2230
2087
2231 When an exception occurs, self.showtraceback() is called to display a
2088 When an exception occurs, self.showtraceback() is called to display a
2232 traceback.
2089 traceback.
2233
2090
2234 Return value: a flag indicating whether the code to be run completed
2091 Return value: a flag indicating whether the code to be run completed
2235 successfully:
2092 successfully:
2236
2093
2237 - 0: successful execution.
2094 - 0: successful execution.
2238 - 1: an error occurred.
2095 - 1: an error occurred.
2239 """
2096 """
2240
2097
2241 # Set our own excepthook in case the user code tries to call it
2098 # Set our own excepthook in case the user code tries to call it
2242 # directly, so that the IPython crash handler doesn't get triggered
2099 # directly, so that the IPython crash handler doesn't get triggered
2243 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2100 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2244
2101
2245 # we save the original sys.excepthook in the instance, in case config
2102 # we save the original sys.excepthook in the instance, in case config
2246 # code (such as magics) needs access to it.
2103 # code (such as magics) needs access to it.
2247 self.sys_excepthook = old_excepthook
2104 self.sys_excepthook = old_excepthook
2248 outflag = 1 # happens in more places, so it's easier as default
2105 outflag = 1 # happens in more places, so it's easier as default
2249 try:
2106 try:
2250 try:
2107 try:
2251 self.hooks.pre_runcode_hook()
2108 self.hooks.pre_runcode_hook()
2252 exec code_obj in self.user_global_ns, self.user_ns
2109 exec code_obj in self.user_global_ns, self.user_ns
2253 finally:
2110 finally:
2254 # Reset our crash handler in place
2111 # Reset our crash handler in place
2255 sys.excepthook = old_excepthook
2112 sys.excepthook = old_excepthook
2256 except SystemExit:
2113 except SystemExit:
2257 self.resetbuffer()
2114 self.resetbuffer()
2258 self.showtraceback()
2115 self.showtraceback()
2259 warn("Type %exit or %quit to exit IPython "
2116 warn("Type %exit or %quit to exit IPython "
2260 "(%Exit or %Quit do so unconditionally).",level=1)
2117 "(%Exit or %Quit do so unconditionally).",level=1)
2261 except self.custom_exceptions:
2118 except self.custom_exceptions:
2262 etype,value,tb = sys.exc_info()
2119 etype,value,tb = sys.exc_info()
2263 self.CustomTB(etype,value,tb)
2120 self.CustomTB(etype,value,tb)
2264 except:
2121 except:
2265 self.showtraceback()
2122 self.showtraceback()
2266 else:
2123 else:
2267 outflag = 0
2124 outflag = 0
2268 if softspace(sys.stdout, 0):
2125 if softspace(sys.stdout, 0):
2269 print
2126 print
2270 # Flush out code object which has been run (and source)
2127 # Flush out code object which has been run (and source)
2271 self.code_to_run = None
2128 self.code_to_run = None
2272 return outflag
2129 return outflag
2273
2130
2274 def push(self, line):
2131 def push(self, line):
2275 """Push a line to the interpreter.
2132 """Push a line to the interpreter.
2276
2133
2277 The line should not have a trailing newline; it may have
2134 The line should not have a trailing newline; it may have
2278 internal newlines. The line is appended to a buffer and the
2135 internal newlines. The line is appended to a buffer and the
2279 interpreter's runsource() method is called with the
2136 interpreter's runsource() method is called with the
2280 concatenated contents of the buffer as source. If this
2137 concatenated contents of the buffer as source. If this
2281 indicates that the command was executed or invalid, the buffer
2138 indicates that the command was executed or invalid, the buffer
2282 is reset; otherwise, the command is incomplete, and the buffer
2139 is reset; otherwise, the command is incomplete, and the buffer
2283 is left as it was after the line was appended. The return
2140 is left as it was after the line was appended. The return
2284 value is 1 if more input is required, 0 if the line was dealt
2141 value is 1 if more input is required, 0 if the line was dealt
2285 with in some way (this is the same as runsource()).
2142 with in some way (this is the same as runsource()).
2286 """
2143 """
2287
2144
2288 # autoindent management should be done here, and not in the
2145 # autoindent management should be done here, and not in the
2289 # interactive loop, since that one is only seen by keyboard input. We
2146 # interactive loop, since that one is only seen by keyboard input. We
2290 # need this done correctly even for code run via runlines (which uses
2147 # need this done correctly even for code run via runlines (which uses
2291 # push).
2148 # push).
2292
2149
2293 #print 'push line: <%s>' % line # dbg
2150 #print 'push line: <%s>' % line # dbg
2294 for subline in line.splitlines():
2151 for subline in line.splitlines():
2295 self.autoindent_update(subline)
2152 self.autoindent_update(subline)
2296 self.buffer.append(line)
2153 self.buffer.append(line)
2297 more = self.runsource('\n'.join(self.buffer), self.filename)
2154 more = self.runsource('\n'.join(self.buffer), self.filename)
2298 if not more:
2155 if not more:
2299 self.resetbuffer()
2156 self.resetbuffer()
2300 return more
2157 return more
2301
2158
2302 def split_user_input(self, line):
2159 def split_user_input(self, line):
2303 # This is really a hold-over to support ipapi and some extensions
2160 # This is really a hold-over to support ipapi and some extensions
2304 return prefilter.splitUserInput(line)
2161 return prefilter.splitUserInput(line)
2305
2162
2306 def resetbuffer(self):
2163 def resetbuffer(self):
2307 """Reset the input buffer."""
2164 """Reset the input buffer."""
2308 self.buffer[:] = []
2165 self.buffer[:] = []
2309
2166
2310 def raw_input(self,prompt='',continue_prompt=False):
2167 def raw_input(self,prompt='',continue_prompt=False):
2311 """Write a prompt and read a line.
2168 """Write a prompt and read a line.
2312
2169
2313 The returned line does not include the trailing newline.
2170 The returned line does not include the trailing newline.
2314 When the user enters the EOF key sequence, EOFError is raised.
2171 When the user enters the EOF key sequence, EOFError is raised.
2315
2172
2316 Optional inputs:
2173 Optional inputs:
2317
2174
2318 - prompt(''): a string to be printed to prompt the user.
2175 - prompt(''): a string to be printed to prompt the user.
2319
2176
2320 - continue_prompt(False): whether this line is the first one or a
2177 - continue_prompt(False): whether this line is the first one or a
2321 continuation in a sequence of inputs.
2178 continuation in a sequence of inputs.
2322 """
2179 """
2323
2180
2324 # Code run by the user may have modified the readline completer state.
2181 # Code run by the user may have modified the readline completer state.
2325 # We must ensure that our completer is back in place.
2182 # We must ensure that our completer is back in place.
2326 if self.has_readline:
2183 if self.has_readline:
2327 self.set_completer()
2184 self.set_completer()
2328
2185
2329 try:
2186 try:
2330 line = raw_input_original(prompt).decode(self.stdin_encoding)
2187 line = raw_input_original(prompt).decode(self.stdin_encoding)
2331 except ValueError:
2188 except ValueError:
2332 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2189 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2333 " or sys.stdout.close()!\nExiting IPython!")
2190 " or sys.stdout.close()!\nExiting IPython!")
2334 self.ask_exit()
2191 self.ask_exit()
2335 return ""
2192 return ""
2336
2193
2337 # Try to be reasonably smart about not re-indenting pasted input more
2194 # Try to be reasonably smart about not re-indenting pasted input more
2338 # than necessary. We do this by trimming out the auto-indent initial
2195 # than necessary. We do this by trimming out the auto-indent initial
2339 # spaces, if the user's actual input started itself with whitespace.
2196 # spaces, if the user's actual input started itself with whitespace.
2340 #debugx('self.buffer[-1]')
2197 #debugx('self.buffer[-1]')
2341
2198
2342 if self.autoindent:
2199 if self.autoindent:
2343 if num_ini_spaces(line) > self.indent_current_nsp:
2200 if num_ini_spaces(line) > self.indent_current_nsp:
2344 line = line[self.indent_current_nsp:]
2201 line = line[self.indent_current_nsp:]
2345 self.indent_current_nsp = 0
2202 self.indent_current_nsp = 0
2346
2203
2347 # store the unfiltered input before the user has any chance to modify
2204 # store the unfiltered input before the user has any chance to modify
2348 # it.
2205 # it.
2349 if line.strip():
2206 if line.strip():
2350 if continue_prompt:
2207 if continue_prompt:
2351 self.input_hist_raw[-1] += '%s\n' % line
2208 self.input_hist_raw[-1] += '%s\n' % line
2352 if self.has_readline: # and some config option is set?
2209 if self.has_readline: # and some config option is set?
2353 try:
2210 try:
2354 histlen = self.readline.get_current_history_length()
2211 histlen = self.readline.get_current_history_length()
2355 if histlen > 1:
2212 if histlen > 1:
2356 newhist = self.input_hist_raw[-1].rstrip()
2213 newhist = self.input_hist_raw[-1].rstrip()
2357 self.readline.remove_history_item(histlen-1)
2214 self.readline.remove_history_item(histlen-1)
2358 self.readline.replace_history_item(histlen-2,
2215 self.readline.replace_history_item(histlen-2,
2359 newhist.encode(self.stdin_encoding))
2216 newhist.encode(self.stdin_encoding))
2360 except AttributeError:
2217 except AttributeError:
2361 pass # re{move,place}_history_item are new in 2.4.
2218 pass # re{move,place}_history_item are new in 2.4.
2362 else:
2219 else:
2363 self.input_hist_raw.append('%s\n' % line)
2220 self.input_hist_raw.append('%s\n' % line)
2364 # only entries starting at first column go to shadow history
2221 # only entries starting at first column go to shadow history
2365 if line.lstrip() == line:
2222 if line.lstrip() == line:
2366 self.shadowhist.add(line.strip())
2223 self.shadowhist.add(line.strip())
2367 elif not continue_prompt:
2224 elif not continue_prompt:
2368 self.input_hist_raw.append('\n')
2225 self.input_hist_raw.append('\n')
2369 try:
2226 try:
2370 lineout = self.prefilter(line,continue_prompt)
2227 lineout = self.prefilter(line,continue_prompt)
2371 except:
2228 except:
2372 # blanket except, in case a user-defined prefilter crashes, so it
2229 # blanket except, in case a user-defined prefilter crashes, so it
2373 # can't take all of ipython with it.
2230 # can't take all of ipython with it.
2374 self.showtraceback()
2231 self.showtraceback()
2375 return ''
2232 return ''
2376 else:
2233 else:
2377 return lineout
2234 return lineout
2378
2235
2379 def _prefilter(self, line, continue_prompt):
2236 def _prefilter(self, line, continue_prompt):
2380 """Calls different preprocessors, depending on the form of line."""
2237 """Calls different preprocessors, depending on the form of line."""
2381
2238
2382 # All handlers *must* return a value, even if it's blank ('').
2239 # All handlers *must* return a value, even if it's blank ('').
2383
2240
2384 # Lines are NOT logged here. Handlers should process the line as
2241 # Lines are NOT logged here. Handlers should process the line as
2385 # needed, update the cache AND log it (so that the input cache array
2242 # needed, update the cache AND log it (so that the input cache array
2386 # stays synced).
2243 # stays synced).
2387
2244
2388 #.....................................................................
2245 #.....................................................................
2389 # Code begins
2246 # Code begins
2390
2247
2391 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2248 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2392
2249
2393 # save the line away in case we crash, so the post-mortem handler can
2250 # save the line away in case we crash, so the post-mortem handler can
2394 # record it
2251 # record it
2395 self._last_input_line = line
2252 self._last_input_line = line
2396
2253
2397 #print '***line: <%s>' % line # dbg
2254 #print '***line: <%s>' % line # dbg
2398
2255
2399 if not line:
2256 if not line:
2400 # Return immediately on purely empty lines, so that if the user
2257 # Return immediately on purely empty lines, so that if the user
2401 # previously typed some whitespace that started a continuation
2258 # previously typed some whitespace that started a continuation
2402 # prompt, he can break out of that loop with just an empty line.
2259 # prompt, he can break out of that loop with just an empty line.
2403 # This is how the default python prompt works.
2260 # This is how the default python prompt works.
2404
2261
2405 # Only return if the accumulated input buffer was just whitespace!
2262 # Only return if the accumulated input buffer was just whitespace!
2406 if ''.join(self.buffer).isspace():
2263 if ''.join(self.buffer).isspace():
2407 self.buffer[:] = []
2264 self.buffer[:] = []
2408 return ''
2265 return ''
2409
2266
2410 line_info = prefilter.LineInfo(line, continue_prompt)
2267 line_info = prefilter.LineInfo(line, continue_prompt)
2411
2268
2412 # the input history needs to track even empty lines
2269 # the input history needs to track even empty lines
2413 stripped = line.strip()
2270 stripped = line.strip()
2414
2271
2415 if not stripped:
2272 if not stripped:
2416 if not continue_prompt:
2273 if not continue_prompt:
2417 self.outputcache.prompt_count -= 1
2274 self.outputcache.prompt_count -= 1
2418 return self.handle_normal(line_info)
2275 return self.handle_normal(line_info)
2419
2276
2420 # print '***cont',continue_prompt # dbg
2277 # print '***cont',continue_prompt # dbg
2421 # special handlers are only allowed for single line statements
2278 # special handlers are only allowed for single line statements
2422 if continue_prompt and not self.rc.multi_line_specials:
2279 if continue_prompt and not self.multi_line_specials:
2423 return self.handle_normal(line_info)
2280 return self.handle_normal(line_info)
2424
2281
2425
2282
2426 # See whether any pre-existing handler can take care of it
2283 # See whether any pre-existing handler can take care of it
2427 rewritten = self.hooks.input_prefilter(stripped)
2284 rewritten = self.hooks.input_prefilter(stripped)
2428 if rewritten != stripped: # ok, some prefilter did something
2285 if rewritten != stripped: # ok, some prefilter did something
2429 rewritten = line_info.pre + rewritten # add indentation
2286 rewritten = line_info.pre + rewritten # add indentation
2430 return self.handle_normal(prefilter.LineInfo(rewritten,
2287 return self.handle_normal(prefilter.LineInfo(rewritten,
2431 continue_prompt))
2288 continue_prompt))
2432
2289
2433 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2290 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2434
2291
2435 return prefilter.prefilter(line_info, self)
2292 return prefilter.prefilter(line_info, self)
2436
2293
2437
2294
2438 def _prefilter_dumb(self, line, continue_prompt):
2295 def _prefilter_dumb(self, line, continue_prompt):
2439 """simple prefilter function, for debugging"""
2296 """simple prefilter function, for debugging"""
2440 return self.handle_normal(line,continue_prompt)
2297 return self.handle_normal(line,continue_prompt)
2441
2298
2442
2299
2443 def multiline_prefilter(self, line, continue_prompt):
2300 def multiline_prefilter(self, line, continue_prompt):
2444 """ Run _prefilter for each line of input
2301 """ Run _prefilter for each line of input
2445
2302
2446 Covers cases where there are multiple lines in the user entry,
2303 Covers cases where there are multiple lines in the user entry,
2447 which is the case when the user goes back to a multiline history
2304 which is the case when the user goes back to a multiline history
2448 entry and presses enter.
2305 entry and presses enter.
2449
2306
2450 """
2307 """
2451 out = []
2308 out = []
2452 for l in line.rstrip('\n').split('\n'):
2309 for l in line.rstrip('\n').split('\n'):
2453 out.append(self._prefilter(l, continue_prompt))
2310 out.append(self._prefilter(l, continue_prompt))
2454 return '\n'.join(out)
2311 return '\n'.join(out)
2455
2312
2456 # Set the default prefilter() function (this can be user-overridden)
2313 # Set the default prefilter() function (this can be user-overridden)
2457 prefilter = multiline_prefilter
2314 prefilter = multiline_prefilter
2458
2315
2459 def handle_normal(self,line_info):
2316 def handle_normal(self,line_info):
2460 """Handle normal input lines. Use as a template for handlers."""
2317 """Handle normal input lines. Use as a template for handlers."""
2461
2318
2462 # With autoindent on, we need some way to exit the input loop, and I
2319 # With autoindent on, we need some way to exit the input loop, and I
2463 # don't want to force the user to have to backspace all the way to
2320 # don't want to force the user to have to backspace all the way to
2464 # clear the line. The rule will be in this case, that either two
2321 # clear the line. The rule will be in this case, that either two
2465 # lines of pure whitespace in a row, or a line of pure whitespace but
2322 # lines of pure whitespace in a row, or a line of pure whitespace but
2466 # of a size different to the indent level, will exit the input loop.
2323 # of a size different to the indent level, will exit the input loop.
2467 line = line_info.line
2324 line = line_info.line
2468 continue_prompt = line_info.continue_prompt
2325 continue_prompt = line_info.continue_prompt
2469
2326
2470 if (continue_prompt and self.autoindent and line.isspace() and
2327 if (continue_prompt and self.autoindent and line.isspace() and
2471 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2328 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2472 (self.buffer[-1]).isspace() )):
2329 (self.buffer[-1]).isspace() )):
2473 line = ''
2330 line = ''
2474
2331
2475 self.log(line,line,continue_prompt)
2332 self.log(line,line,continue_prompt)
2476 return line
2333 return line
2477
2334
2478 def handle_alias(self,line_info):
2335 def handle_alias(self,line_info):
2479 """Handle alias input lines. """
2336 """Handle alias input lines. """
2480 tgt = self.alias_table[line_info.iFun]
2337 tgt = self.alias_table[line_info.iFun]
2481 # print "=>",tgt #dbg
2338 # print "=>",tgt #dbg
2482 if callable(tgt):
2339 if callable(tgt):
2483 if '$' in line_info.line:
2340 if '$' in line_info.line:
2484 call_meth = '(_ip, _ip.itpl(%s))'
2341 call_meth = '(_ip, _ip.itpl(%s))'
2485 else:
2342 else:
2486 call_meth = '(_ip,%s)'
2343 call_meth = '(_ip,%s)'
2487 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2344 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2488 line_info.iFun,
2345 line_info.iFun,
2489 make_quoted_expr(line_info.line))
2346 make_quoted_expr(line_info.line))
2490 else:
2347 else:
2491 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2348 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2492
2349
2493 # pre is needed, because it carries the leading whitespace. Otherwise
2350 # pre is needed, because it carries the leading whitespace. Otherwise
2494 # aliases won't work in indented sections.
2351 # aliases won't work in indented sections.
2495 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2352 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2496 make_quoted_expr( transformed ))
2353 make_quoted_expr( transformed ))
2497
2354
2498 self.log(line_info.line,line_out,line_info.continue_prompt)
2355 self.log(line_info.line,line_out,line_info.continue_prompt)
2499 #print 'line out:',line_out # dbg
2356 #print 'line out:',line_out # dbg
2500 return line_out
2357 return line_out
2501
2358
2502 def handle_shell_escape(self, line_info):
2359 def handle_shell_escape(self, line_info):
2503 """Execute the line in a shell, empty return value"""
2360 """Execute the line in a shell, empty return value"""
2504 #print 'line in :', `line` # dbg
2361 #print 'line in :', `line` # dbg
2505 line = line_info.line
2362 line = line_info.line
2506 if line.lstrip().startswith('!!'):
2363 if line.lstrip().startswith('!!'):
2507 # rewrite LineInfo's line, iFun and theRest to properly hold the
2364 # rewrite LineInfo's line, iFun and theRest to properly hold the
2508 # call to %sx and the actual command to be executed, so
2365 # call to %sx and the actual command to be executed, so
2509 # handle_magic can work correctly. Note that this works even if
2366 # handle_magic can work correctly. Note that this works even if
2510 # the line is indented, so it handles multi_line_specials
2367 # the line is indented, so it handles multi_line_specials
2511 # properly.
2368 # properly.
2512 new_rest = line.lstrip()[2:]
2369 new_rest = line.lstrip()[2:]
2513 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2370 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2514 line_info.iFun = 'sx'
2371 line_info.iFun = 'sx'
2515 line_info.theRest = new_rest
2372 line_info.theRest = new_rest
2516 return self.handle_magic(line_info)
2373 return self.handle_magic(line_info)
2517 else:
2374 else:
2518 cmd = line.lstrip().lstrip('!')
2375 cmd = line.lstrip().lstrip('!')
2519 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2376 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2520 make_quoted_expr(cmd))
2377 make_quoted_expr(cmd))
2521 # update cache/log and return
2378 # update cache/log and return
2522 self.log(line,line_out,line_info.continue_prompt)
2379 self.log(line,line_out,line_info.continue_prompt)
2523 return line_out
2380 return line_out
2524
2381
2525 def handle_magic(self, line_info):
2382 def handle_magic(self, line_info):
2526 """Execute magic functions."""
2383 """Execute magic functions."""
2527 iFun = line_info.iFun
2384 iFun = line_info.iFun
2528 theRest = line_info.theRest
2385 theRest = line_info.theRest
2529 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2386 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2530 make_quoted_expr(iFun + " " + theRest))
2387 make_quoted_expr(iFun + " " + theRest))
2531 self.log(line_info.line,cmd,line_info.continue_prompt)
2388 self.log(line_info.line,cmd,line_info.continue_prompt)
2532 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2389 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2533 return cmd
2390 return cmd
2534
2391
2535 def handle_auto(self, line_info):
2392 def handle_auto(self, line_info):
2536 """Hande lines which can be auto-executed, quoting if requested."""
2393 """Hande lines which can be auto-executed, quoting if requested."""
2537
2394
2538 line = line_info.line
2395 line = line_info.line
2539 iFun = line_info.iFun
2396 iFun = line_info.iFun
2540 theRest = line_info.theRest
2397 theRest = line_info.theRest
2541 pre = line_info.pre
2398 pre = line_info.pre
2542 continue_prompt = line_info.continue_prompt
2399 continue_prompt = line_info.continue_prompt
2543 obj = line_info.ofind(self)['obj']
2400 obj = line_info.ofind(self)['obj']
2544
2401
2545 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2402 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2546
2403
2547 # This should only be active for single-line input!
2404 # This should only be active for single-line input!
2548 if continue_prompt:
2405 if continue_prompt:
2549 self.log(line,line,continue_prompt)
2406 self.log(line,line,continue_prompt)
2550 return line
2407 return line
2551
2408
2552 force_auto = isinstance(obj, ipapi.IPyAutocall)
2409 force_auto = isinstance(obj, ipapi.IPyAutocall)
2553 auto_rewrite = True
2410 auto_rewrite = True
2554
2411
2555 if pre == self.ESC_QUOTE:
2412 if pre == self.ESC_QUOTE:
2556 # Auto-quote splitting on whitespace
2413 # Auto-quote splitting on whitespace
2557 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2414 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2558 elif pre == self.ESC_QUOTE2:
2415 elif pre == self.ESC_QUOTE2:
2559 # Auto-quote whole string
2416 # Auto-quote whole string
2560 newcmd = '%s("%s")' % (iFun,theRest)
2417 newcmd = '%s("%s")' % (iFun,theRest)
2561 elif pre == self.ESC_PAREN:
2418 elif pre == self.ESC_PAREN:
2562 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2419 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2563 else:
2420 else:
2564 # Auto-paren.
2421 # Auto-paren.
2565 # We only apply it to argument-less calls if the autocall
2422 # We only apply it to argument-less calls if the autocall
2566 # parameter is set to 2. We only need to check that autocall is <
2423 # parameter is set to 2. We only need to check that autocall is <
2567 # 2, since this function isn't called unless it's at least 1.
2424 # 2, since this function isn't called unless it's at least 1.
2568 if not theRest and (self.rc.autocall < 2) and not force_auto:
2425 if not theRest and (self.autocall < 2) and not force_auto:
2569 newcmd = '%s %s' % (iFun,theRest)
2426 newcmd = '%s %s' % (iFun,theRest)
2570 auto_rewrite = False
2427 auto_rewrite = False
2571 else:
2428 else:
2572 if not force_auto and theRest.startswith('['):
2429 if not force_auto and theRest.startswith('['):
2573 if hasattr(obj,'__getitem__'):
2430 if hasattr(obj,'__getitem__'):
2574 # Don't autocall in this case: item access for an object
2431 # Don't autocall in this case: item access for an object
2575 # which is BOTH callable and implements __getitem__.
2432 # which is BOTH callable and implements __getitem__.
2576 newcmd = '%s %s' % (iFun,theRest)
2433 newcmd = '%s %s' % (iFun,theRest)
2577 auto_rewrite = False
2434 auto_rewrite = False
2578 else:
2435 else:
2579 # if the object doesn't support [] access, go ahead and
2436 # if the object doesn't support [] access, go ahead and
2580 # autocall
2437 # autocall
2581 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2438 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2582 elif theRest.endswith(';'):
2439 elif theRest.endswith(';'):
2583 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2440 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2584 else:
2441 else:
2585 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2442 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2586
2443
2587 if auto_rewrite:
2444 if auto_rewrite:
2588 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2445 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2589
2446
2590 try:
2447 try:
2591 # plain ascii works better w/ pyreadline, on some machines, so
2448 # plain ascii works better w/ pyreadline, on some machines, so
2592 # we use it and only print uncolored rewrite if we have unicode
2449 # we use it and only print uncolored rewrite if we have unicode
2593 rw = str(rw)
2450 rw = str(rw)
2594 print >>Term.cout, rw
2451 print >>Term.cout, rw
2595 except UnicodeEncodeError:
2452 except UnicodeEncodeError:
2596 print "-------------->" + newcmd
2453 print "-------------->" + newcmd
2597
2454
2598 # log what is now valid Python, not the actual user input (without the
2455 # log what is now valid Python, not the actual user input (without the
2599 # final newline)
2456 # final newline)
2600 self.log(line,newcmd,continue_prompt)
2457 self.log(line,newcmd,continue_prompt)
2601 return newcmd
2458 return newcmd
2602
2459
2603 def handle_help(self, line_info):
2460 def handle_help(self, line_info):
2604 """Try to get some help for the object.
2461 """Try to get some help for the object.
2605
2462
2606 obj? or ?obj -> basic information.
2463 obj? or ?obj -> basic information.
2607 obj?? or ??obj -> more details.
2464 obj?? or ??obj -> more details.
2608 """
2465 """
2609
2466
2610 line = line_info.line
2467 line = line_info.line
2611 # We need to make sure that we don't process lines which would be
2468 # We need to make sure that we don't process lines which would be
2612 # otherwise valid python, such as "x=1 # what?"
2469 # otherwise valid python, such as "x=1 # what?"
2613 try:
2470 try:
2614 codeop.compile_command(line)
2471 codeop.compile_command(line)
2615 except SyntaxError:
2472 except SyntaxError:
2616 # We should only handle as help stuff which is NOT valid syntax
2473 # We should only handle as help stuff which is NOT valid syntax
2617 if line[0]==self.ESC_HELP:
2474 if line[0]==self.ESC_HELP:
2618 line = line[1:]
2475 line = line[1:]
2619 elif line[-1]==self.ESC_HELP:
2476 elif line[-1]==self.ESC_HELP:
2620 line = line[:-1]
2477 line = line[:-1]
2621 self.log(line,'#?'+line,line_info.continue_prompt)
2478 self.log(line,'#?'+line,line_info.continue_prompt)
2622 if line:
2479 if line:
2623 #print 'line:<%r>' % line # dbg
2480 #print 'line:<%r>' % line # dbg
2624 self.magic_pinfo(line)
2481 self.magic_pinfo(line)
2625 else:
2482 else:
2626 page(self.usage,screen_lines=self.rc.screen_length)
2483 page(self.usage,screen_lines=self.screen_length)
2627 return '' # Empty string is needed here!
2484 return '' # Empty string is needed here!
2628 except:
2485 except:
2629 # Pass any other exceptions through to the normal handler
2486 # Pass any other exceptions through to the normal handler
2630 return self.handle_normal(line_info)
2487 return self.handle_normal(line_info)
2631 else:
2488 else:
2632 # If the code compiles ok, we should handle it normally
2489 # If the code compiles ok, we should handle it normally
2633 return self.handle_normal(line_info)
2490 return self.handle_normal(line_info)
2634
2491
2635 def getapi(self):
2492 def getapi(self):
2636 """ Get an IPApi object for this shell instance
2493 """ Get an IPApi object for this shell instance
2637
2494
2638 Getting an IPApi object is always preferable to accessing the shell
2495 Getting an IPApi object is always preferable to accessing the shell
2639 directly, but this holds true especially for extensions.
2496 directly, but this holds true especially for extensions.
2640
2497
2641 It should always be possible to implement an extension with IPApi
2498 It should always be possible to implement an extension with IPApi
2642 alone. If not, contact maintainer to request an addition.
2499 alone. If not, contact maintainer to request an addition.
2643
2500
2644 """
2501 """
2645 return self.api
2502 return self.api
2646
2503
2647 def handle_emacs(self, line_info):
2504 def handle_emacs(self, line_info):
2648 """Handle input lines marked by python-mode."""
2505 """Handle input lines marked by python-mode."""
2649
2506
2650 # Currently, nothing is done. Later more functionality can be added
2507 # Currently, nothing is done. Later more functionality can be added
2651 # here if needed.
2508 # here if needed.
2652
2509
2653 # The input cache shouldn't be updated
2510 # The input cache shouldn't be updated
2654 return line_info.line
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 def mktempfile(self,data=None):
2529 def mktempfile(self,data=None):
2658 """Make a new tempfile and return its filename.
2530 """Make a new tempfile and return its filename.
2659
2531
2660 This makes a call to tempfile.mktemp, but it registers the created
2532 This makes a call to tempfile.mktemp, but it registers the created
2661 filename internally so ipython cleans it up at exit time.
2533 filename internally so ipython cleans it up at exit time.
2662
2534
2663 Optional inputs:
2535 Optional inputs:
2664
2536
2665 - data(None): if data is given, it gets written out to the temp file
2537 - data(None): if data is given, it gets written out to the temp file
2666 immediately, and the file is closed again."""
2538 immediately, and the file is closed again."""
2667
2539
2668 filename = tempfile.mktemp('.py','ipython_edit_')
2540 filename = tempfile.mktemp('.py','ipython_edit_')
2669 self.tempfiles.append(filename)
2541 self.tempfiles.append(filename)
2670
2542
2671 if data:
2543 if data:
2672 tmp_file = open(filename,'w')
2544 tmp_file = open(filename,'w')
2673 tmp_file.write(data)
2545 tmp_file.write(data)
2674 tmp_file.close()
2546 tmp_file.close()
2675 return filename
2547 return filename
2676
2548
2677 def write(self,data):
2549 def write(self,data):
2678 """Write a string to the default output"""
2550 """Write a string to the default output"""
2679 Term.cout.write(data)
2551 Term.cout.write(data)
2680
2552
2681 def write_err(self,data):
2553 def write_err(self,data):
2682 """Write a string to the default error output"""
2554 """Write a string to the default error output"""
2683 Term.cerr.write(data)
2555 Term.cerr.write(data)
2684
2556
2685 def ask_exit(self):
2557 def ask_exit(self):
2686 """ Call for exiting. Can be overiden and used as a callback. """
2558 """ Call for exiting. Can be overiden and used as a callback. """
2687 self.exit_now = True
2559 self.exit_now = True
2688
2560
2689 def exit(self):
2561 def exit(self):
2690 """Handle interactive exit.
2562 """Handle interactive exit.
2691
2563
2692 This method calls the ask_exit callback."""
2564 This method calls the ask_exit callback."""
2693
2565 print "IN self.exit", self.confirm_exit
2694 if self.rc.confirm_exit:
2566 if self.confirm_exit:
2695 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2567 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2696 self.ask_exit()
2568 self.ask_exit()
2697 else:
2569 else:
2698 self.ask_exit()
2570 self.ask_exit()
2699
2571
2700 def safe_execfile(self,fname,*where,**kw):
2572 def safe_execfile(self,fname,*where,**kw):
2701 """A safe version of the builtin execfile().
2573 """A safe version of the builtin execfile().
2702
2574
2703 This version will never throw an exception, and knows how to handle
2575 This version will never throw an exception, and knows how to handle
2704 ipython logs as well.
2576 ipython logs as well.
2705
2577
2706 :Parameters:
2578 :Parameters:
2707 fname : string
2579 fname : string
2708 Name of the file to be executed.
2580 Name of the file to be executed.
2709
2581
2710 where : tuple
2582 where : tuple
2711 One or two namespaces, passed to execfile() as (globals,locals).
2583 One or two namespaces, passed to execfile() as (globals,locals).
2712 If only one is given, it is passed as both.
2584 If only one is given, it is passed as both.
2713
2585
2714 :Keywords:
2586 :Keywords:
2715 islog : boolean (False)
2587 islog : boolean (False)
2716
2588
2717 quiet : boolean (True)
2589 quiet : boolean (True)
2718
2590
2719 exit_ignore : boolean (False)
2591 exit_ignore : boolean (False)
2720 """
2592 """
2721
2593
2722 def syspath_cleanup():
2594 def syspath_cleanup():
2723 """Internal cleanup routine for sys.path."""
2595 """Internal cleanup routine for sys.path."""
2724 if add_dname:
2596 if add_dname:
2725 try:
2597 try:
2726 sys.path.remove(dname)
2598 sys.path.remove(dname)
2727 except ValueError:
2599 except ValueError:
2728 # For some reason the user has already removed it, ignore.
2600 # For some reason the user has already removed it, ignore.
2729 pass
2601 pass
2730
2602
2731 fname = os.path.expanduser(fname)
2603 fname = os.path.expanduser(fname)
2732
2604
2733 # Find things also in current directory. This is needed to mimic the
2605 # Find things also in current directory. This is needed to mimic the
2734 # behavior of running a script from the system command line, where
2606 # behavior of running a script from the system command line, where
2735 # Python inserts the script's directory into sys.path
2607 # Python inserts the script's directory into sys.path
2736 dname = os.path.dirname(os.path.abspath(fname))
2608 dname = os.path.dirname(os.path.abspath(fname))
2737 add_dname = False
2609 add_dname = False
2738 if dname not in sys.path:
2610 if dname not in sys.path:
2739 sys.path.insert(0,dname)
2611 sys.path.insert(0,dname)
2740 add_dname = True
2612 add_dname = True
2741
2613
2742 try:
2614 try:
2743 xfile = open(fname)
2615 xfile = open(fname)
2744 except:
2616 except:
2745 print >> Term.cerr, \
2617 print >> Term.cerr, \
2746 'Could not open file <%s> for safe execution.' % fname
2618 'Could not open file <%s> for safe execution.' % fname
2747 syspath_cleanup()
2619 syspath_cleanup()
2748 return None
2620 return None
2749
2621
2750 kw.setdefault('islog',0)
2622 kw.setdefault('islog',0)
2751 kw.setdefault('quiet',1)
2623 kw.setdefault('quiet',1)
2752 kw.setdefault('exit_ignore',0)
2624 kw.setdefault('exit_ignore',0)
2753
2625
2754 first = xfile.readline()
2626 first = xfile.readline()
2755 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2627 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2756 xfile.close()
2628 xfile.close()
2757 # line by line execution
2629 # line by line execution
2758 if first.startswith(loghead) or kw['islog']:
2630 if first.startswith(loghead) or kw['islog']:
2759 print 'Loading log file <%s> one line at a time...' % fname
2631 print 'Loading log file <%s> one line at a time...' % fname
2760 if kw['quiet']:
2632 if kw['quiet']:
2761 stdout_save = sys.stdout
2633 stdout_save = sys.stdout
2762 sys.stdout = StringIO.StringIO()
2634 sys.stdout = StringIO.StringIO()
2763 try:
2635 try:
2764 globs,locs = where[0:2]
2636 globs,locs = where[0:2]
2765 except:
2637 except:
2766 try:
2638 try:
2767 globs = locs = where[0]
2639 globs = locs = where[0]
2768 except:
2640 except:
2769 globs = locs = globals()
2641 globs = locs = globals()
2770 badblocks = []
2642 badblocks = []
2771
2643
2772 # we also need to identify indented blocks of code when replaying
2644 # we also need to identify indented blocks of code when replaying
2773 # logs and put them together before passing them to an exec
2645 # logs and put them together before passing them to an exec
2774 # statement. This takes a bit of regexp and look-ahead work in the
2646 # statement. This takes a bit of regexp and look-ahead work in the
2775 # file. It's easiest if we swallow the whole thing in memory
2647 # file. It's easiest if we swallow the whole thing in memory
2776 # first, and manually walk through the lines list moving the
2648 # first, and manually walk through the lines list moving the
2777 # counter ourselves.
2649 # counter ourselves.
2778 indent_re = re.compile('\s+\S')
2650 indent_re = re.compile('\s+\S')
2779 xfile = open(fname)
2651 xfile = open(fname)
2780 filelines = xfile.readlines()
2652 filelines = xfile.readlines()
2781 xfile.close()
2653 xfile.close()
2782 nlines = len(filelines)
2654 nlines = len(filelines)
2783 lnum = 0
2655 lnum = 0
2784 while lnum < nlines:
2656 while lnum < nlines:
2785 line = filelines[lnum]
2657 line = filelines[lnum]
2786 lnum += 1
2658 lnum += 1
2787 # don't re-insert logger status info into cache
2659 # don't re-insert logger status info into cache
2788 if line.startswith('#log#'):
2660 if line.startswith('#log#'):
2789 continue
2661 continue
2790 else:
2662 else:
2791 # build a block of code (maybe a single line) for execution
2663 # build a block of code (maybe a single line) for execution
2792 block = line
2664 block = line
2793 try:
2665 try:
2794 next = filelines[lnum] # lnum has already incremented
2666 next = filelines[lnum] # lnum has already incremented
2795 except:
2667 except:
2796 next = None
2668 next = None
2797 while next and indent_re.match(next):
2669 while next and indent_re.match(next):
2798 block += next
2670 block += next
2799 lnum += 1
2671 lnum += 1
2800 try:
2672 try:
2801 next = filelines[lnum]
2673 next = filelines[lnum]
2802 except:
2674 except:
2803 next = None
2675 next = None
2804 # now execute the block of one or more lines
2676 # now execute the block of one or more lines
2805 try:
2677 try:
2806 exec block in globs,locs
2678 exec block in globs,locs
2807 except SystemExit:
2679 except SystemExit:
2808 pass
2680 pass
2809 except:
2681 except:
2810 badblocks.append(block.rstrip())
2682 badblocks.append(block.rstrip())
2811 if kw['quiet']: # restore stdout
2683 if kw['quiet']: # restore stdout
2812 sys.stdout.close()
2684 sys.stdout.close()
2813 sys.stdout = stdout_save
2685 sys.stdout = stdout_save
2814 print 'Finished replaying log file <%s>' % fname
2686 print 'Finished replaying log file <%s>' % fname
2815 if badblocks:
2687 if badblocks:
2816 print >> sys.stderr, ('\nThe following lines/blocks in file '
2688 print >> sys.stderr, ('\nThe following lines/blocks in file '
2817 '<%s> reported errors:' % fname)
2689 '<%s> reported errors:' % fname)
2818
2690
2819 for badline in badblocks:
2691 for badline in badblocks:
2820 print >> sys.stderr, badline
2692 print >> sys.stderr, badline
2821 else: # regular file execution
2693 else: # regular file execution
2822 try:
2694 try:
2823 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2695 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2824 # Work around a bug in Python for Windows. The bug was
2696 # Work around a bug in Python for Windows. The bug was
2825 # fixed in in Python 2.5 r54159 and 54158, but that's still
2697 # fixed in in Python 2.5 r54159 and 54158, but that's still
2826 # SVN Python as of March/07. For details, see:
2698 # SVN Python as of March/07. For details, see:
2827 # http://projects.scipy.org/ipython/ipython/ticket/123
2699 # http://projects.scipy.org/ipython/ipython/ticket/123
2828 try:
2700 try:
2829 globs,locs = where[0:2]
2701 globs,locs = where[0:2]
2830 except:
2702 except:
2831 try:
2703 try:
2832 globs = locs = where[0]
2704 globs = locs = where[0]
2833 except:
2705 except:
2834 globs = locs = globals()
2706 globs = locs = globals()
2835 exec file(fname) in globs,locs
2707 exec file(fname) in globs,locs
2836 else:
2708 else:
2837 execfile(fname,*where)
2709 execfile(fname,*where)
2838 except SyntaxError:
2710 except SyntaxError:
2839 self.showsyntaxerror()
2711 self.showsyntaxerror()
2840 warn('Failure executing file: <%s>' % fname)
2712 warn('Failure executing file: <%s>' % fname)
2841 except SystemExit,status:
2713 except SystemExit,status:
2842 # Code that correctly sets the exit status flag to success (0)
2714 # Code that correctly sets the exit status flag to success (0)
2843 # shouldn't be bothered with a traceback. Note that a plain
2715 # shouldn't be bothered with a traceback. Note that a plain
2844 # sys.exit() does NOT set the message to 0 (it's empty) so that
2716 # sys.exit() does NOT set the message to 0 (it's empty) so that
2845 # will still get a traceback. Note that the structure of the
2717 # will still get a traceback. Note that the structure of the
2846 # SystemExit exception changed between Python 2.4 and 2.5, so
2718 # SystemExit exception changed between Python 2.4 and 2.5, so
2847 # the checks must be done in a version-dependent way.
2719 # the checks must be done in a version-dependent way.
2848 show = False
2720 show = False
2849
2721
2850 if sys.version_info[:2] > (2,5):
2722 if sys.version_info[:2] > (2,5):
2851 if status.message!=0 and not kw['exit_ignore']:
2723 if status.message!=0 and not kw['exit_ignore']:
2852 show = True
2724 show = True
2853 else:
2725 else:
2854 if status.code and not kw['exit_ignore']:
2726 if status.code and not kw['exit_ignore']:
2855 show = True
2727 show = True
2856 if show:
2728 if show:
2857 self.showtraceback()
2729 self.showtraceback()
2858 warn('Failure executing file: <%s>' % fname)
2730 warn('Failure executing file: <%s>' % fname)
2859 except:
2731 except:
2860 self.showtraceback()
2732 self.showtraceback()
2861 warn('Failure executing file: <%s>' % fname)
2733 warn('Failure executing file: <%s>' % fname)
2862
2734
2863 syspath_cleanup()
2735 syspath_cleanup()
2864
2736
2865 #************************* end of file <iplib.py> *****************************
2737 #************************* end of file <iplib.py> *****************************
@@ -1,792 +1,793 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 try:
18 try:
19 credits._Printer__data = """
19 credits._Printer__data = """
20 Python: %s
20 Python: %s
21
21
22 IPython: The IPython Development Team.
22 IPython: The IPython Development Team.
23 See http://ipython.scipy.org for more information.""" \
23 See http://ipython.scipy.org for more information.""" \
24 % credits._Printer__data
24 % credits._Printer__data
25
25
26 copyright._Printer__data += """
26 copyright._Printer__data += """
27
27
28 Copyright (c) 2008-2009 The IPython Development Team.
28 Copyright (c) 2008-2009 The IPython Development Team.
29 Copyright (c) 2001-2007 Fernando Perez, Janko Hauser, Nathan Gray.
29 Copyright (c) 2001-2007 Fernando Perez, Janko Hauser, Nathan Gray.
30 All Rights Reserved."""
30 All Rights Reserved."""
31 except NameError:
31 except NameError:
32 # Can happen if ipython was started with 'python -S', so that site.py is
32 # Can happen if ipython was started with 'python -S', so that site.py is
33 # not loaded
33 # not loaded
34 pass
34 pass
35
35
36 #****************************************************************************
36 #****************************************************************************
37 # Required modules
37 # Required modules
38
38
39 # From the standard library
39 # From the standard library
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import os
42 import os
43 import sys
43 import sys
44 from pprint import pprint
44 from pprint import pprint
45 import warnings
45 import warnings
46
46
47 # Our own
47 # Our own
48 from IPython.utils import DPyGetOpt
48 from IPython.utils import DPyGetOpt
49 from IPython.core import release
49 from IPython.core import release
50 from IPython.core.oldusersetup import user_setup
50 from IPython.utils.ipstruct import Struct
51 from IPython.utils.ipstruct import Struct
51 from IPython.core.outputtrap import OutputTrap
52 from IPython.core.outputtrap import OutputTrap
52 from IPython.config.configloader import ConfigLoader
53 from IPython.config.configloader import ConfigLoader
53 from IPython.core.iplib import InteractiveShell
54 from IPython.core.iplib import InteractiveShell
54 from IPython.core.usage import cmd_line_usage, interactive_usage
55 from IPython.core.usage import cmd_line_usage, interactive_usage
55 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
56
57
57
58
58 def force_import(modname,force_reload=False):
59 def force_import(modname,force_reload=False):
59 if modname in sys.modules and force_reload:
60 if modname in sys.modules and force_reload:
60 info("reloading: %s" % modname)
61 info("reloading: %s" % modname)
61 reload(sys.modules[modname])
62 reload(sys.modules[modname])
62 else:
63 else:
63 __import__(modname)
64 __import__(modname)
64
65
65
66
66 def threaded_shell_warning():
67 def threaded_shell_warning():
67 msg = """
68 msg = """
68
69
69 The IPython threaded shells and their associated command line
70 The IPython threaded shells and their associated command line
70 arguments (pylab/wthread/gthread/qthread/q4thread) have been
71 arguments (pylab/wthread/gthread/qthread/q4thread) have been
71 deprecated. See the %gui magic for information on the new interface.
72 deprecated. See the %gui magic for information on the new interface.
72 """
73 """
73 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
74 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
74
75
75
76
76 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
77 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
78 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
78 rc_override=None,shell_class=InteractiveShell,
79 rc_override=None,shell_class=InteractiveShell,
79 embedded=False,**kw):
80 embedded=False,**kw):
80 """This is a dump of IPython into a single function.
81 """This is a dump of IPython into a single function.
81
82
82 Later it will have to be broken up in a sensible manner.
83 Later it will have to be broken up in a sensible manner.
83
84
84 Arguments:
85 Arguments:
85
86
86 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
87 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
87 script name, b/c DPyGetOpt strips the first argument only for the real
88 script name, b/c DPyGetOpt strips the first argument only for the real
88 sys.argv.
89 sys.argv.
89
90
90 - user_ns: a dict to be used as the user's namespace."""
91 - user_ns: a dict to be used as the user's namespace."""
91
92
92 #----------------------------------------------------------------------
93 #----------------------------------------------------------------------
93 # Defaults and initialization
94 # Defaults and initialization
94
95
95 # For developer debugging, deactivates crash handler and uses pdb.
96 # For developer debugging, deactivates crash handler and uses pdb.
96 DEVDEBUG = True
97 DEVDEBUG = True
97
98
98 if argv is None:
99 if argv is None:
99 argv = sys.argv
100 argv = sys.argv
100
101
101 # __IP is the main global that lives throughout and represents the whole
102 # __IP is the main global that lives throughout and represents the whole
102 # application. If the user redefines it, all bets are off as to what
103 # application. If the user redefines it, all bets are off as to what
103 # happens.
104 # happens.
104
105
105 # __IP is the name of he global which the caller will have accessible as
106 # __IP is the name of he global which the caller will have accessible as
106 # __IP.name. We set its name via the first parameter passed to
107 # __IP.name. We set its name via the first parameter passed to
107 # InteractiveShell:
108 # InteractiveShell:
108
109
109 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
110 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
110 embedded=embedded,**kw)
111 embedded=embedded,**kw)
111
112
112 # Put 'help' in the user namespace
113 # Put 'help' in the user namespace
113 try:
114 try:
114 from site import _Helper
115 from site import _Helper
115 IP.user_ns['help'] = _Helper()
116 IP.user_ns['help'] = _Helper()
116 except ImportError:
117 except ImportError:
117 warn('help() not available - check site.py')
118 warn('help() not available - check site.py')
118
119
119 if DEVDEBUG:
120 if DEVDEBUG:
120 # For developer debugging only (global flag)
121 # For developer debugging only (global flag)
121 from IPython.core import ultratb
122 from IPython.core import ultratb
122 sys.excepthook = ultratb.VerboseTB(call_pdb=1)
123 sys.excepthook = ultratb.VerboseTB(call_pdb=1)
123
124
124 IP.BANNER_PARTS = ['Python %s\n'
125 IP.BANNER_PARTS = ['Python %s\n'
125 'Type "copyright", "credits" or "license" '
126 'Type "copyright", "credits" or "license" '
126 'for more information.\n'
127 'for more information.\n'
127 % (sys.version.split('\n')[0],),
128 % (sys.version.split('\n')[0],),
128 "IPython %s -- An enhanced Interactive Python."
129 "IPython %s -- An enhanced Interactive Python."
129 % (release.version,),
130 % (release.version,),
130 """\
131 """\
131 ? -> Introduction and overview of IPython's features.
132 ? -> Introduction and overview of IPython's features.
132 %quickref -> Quick reference.
133 %quickref -> Quick reference.
133 help -> Python's own help system.
134 help -> Python's own help system.
134 object? -> Details about 'object'. ?object also works, ?? prints more.
135 object? -> Details about 'object'. ?object also works, ?? prints more.
135 """ ]
136 """ ]
136
137
137 IP.usage = interactive_usage
138 IP.usage = interactive_usage
138
139
139 # Platform-dependent suffix.
140 # Platform-dependent suffix.
140 if os.name == 'posix':
141 if os.name == 'posix':
141 rc_suffix = ''
142 rc_suffix = ''
142 else:
143 else:
143 rc_suffix = '.ini'
144 rc_suffix = '.ini'
144
145
145 # default directory for configuration
146 # default directory for configuration
146 ipythondir_def = get_ipython_dir()
147 ipythondir_def = get_ipython_dir()
147
148
148 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
149 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
149
150
150 # we need the directory where IPython itself is installed
151 # we need the directory where IPython itself is installed
151 import IPython
152 import IPython
152 IPython_dir = os.path.dirname(IPython.__file__)
153 IPython_dir = os.path.dirname(IPython.__file__)
153 del IPython
154 del IPython
154
155
155 #-------------------------------------------------------------------------
156 #-------------------------------------------------------------------------
156 # Command line handling
157 # Command line handling
157
158
158 # Valid command line options (uses DPyGetOpt syntax, like Perl's
159 # Valid command line options (uses DPyGetOpt syntax, like Perl's
159 # GetOpt::Long)
160 # GetOpt::Long)
160
161
161 # Any key not listed here gets deleted even if in the file (like session
162 # Any key not listed here gets deleted even if in the file (like session
162 # or profile). That's deliberate, to maintain the rc namespace clean.
163 # or profile). That's deliberate, to maintain the rc namespace clean.
163
164
164 # Each set of options appears twice: under _conv only the names are
165 # Each set of options appears twice: under _conv only the names are
165 # listed, indicating which type they must be converted to when reading the
166 # listed, indicating which type they must be converted to when reading the
166 # ipythonrc file. And under DPyGetOpt they are listed with the regular
167 # ipythonrc file. And under DPyGetOpt they are listed with the regular
167 # DPyGetOpt syntax (=s,=i,:f,etc).
168 # DPyGetOpt syntax (=s,=i,:f,etc).
168
169
169 # Make sure there's a space before each end of line (they get auto-joined!)
170 # Make sure there's a space before each end of line (they get auto-joined!)
170 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
171 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
171 'c=s classic|cl color_info! colors=s confirm_exit! '
172 'c=s classic|cl color_info! colors=s confirm_exit! '
172 'debug! deep_reload! editor=s log|l messages! nosep '
173 'debug! deep_reload! editor=s log|l messages! nosep '
173 'object_info_string_level=i pdb! '
174 'object_info_string_level=i pdb! '
174 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
175 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
175 'pydb! '
176 'pydb! '
176 'pylab_import_all! '
177 'pylab_import_all! '
177 'quick screen_length|sl=i prompts_pad_left=i '
178 'quick screen_length|sl=i prompts_pad_left=i '
178 'logfile|lf=s logplay|lp=s profile|p=s '
179 'logfile|lf=s logplay|lp=s profile|p=s '
179 'readline! readline_merge_completions! '
180 'readline! readline_merge_completions! '
180 'readline_omit__names! '
181 'readline_omit__names! '
181 'rcfile=s separate_in|si=s separate_out|so=s '
182 'rcfile=s separate_in|si=s separate_out|so=s '
182 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
183 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
183 'magic_docstrings system_verbose! '
184 'magic_docstrings system_verbose! '
184 'multi_line_specials! '
185 'multi_line_specials! '
185 'term_title! wxversion=s '
186 'term_title! wxversion=s '
186 'autoedit_syntax!')
187 'autoedit_syntax!')
187
188
188 # Options that can *only* appear at the cmd line (not in rcfiles).
189 # Options that can *only* appear at the cmd line (not in rcfiles).
189
190
190 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
191 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
191 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
192 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
192 # 'twisted!' # disabled for now.
193 # 'twisted!' # disabled for now.
193 )
194 )
194
195
195 # Build the actual name list to be used by DPyGetOpt
196 # Build the actual name list to be used by DPyGetOpt
196 opts_names = qw(cmdline_opts) + qw(cmdline_only)
197 opts_names = qw(cmdline_opts) + qw(cmdline_only)
197
198
198 # Set sensible command line defaults.
199 # Set sensible command line defaults.
199 # This should have everything from cmdline_opts and cmdline_only
200 # This should have everything from cmdline_opts and cmdline_only
200 opts_def = Struct(autocall = 1,
201 opts_def = Struct(autocall = 1,
201 autoedit_syntax = 0,
202 autoedit_syntax = 0,
202 autoindent = 0,
203 autoindent = 0,
203 automagic = 1,
204 automagic = 1,
204 autoexec = [],
205 autoexec = [],
205 banner = 1,
206 banner = 1,
206 c = '',
207 c = '',
207 cache_size = 1000,
208 cache_size = 1000,
208 classic = 0,
209 classic = 0,
209 color_info = 0,
210 color_info = 0,
210 colors = 'NoColor',
211 colors = 'NoColor',
211 confirm_exit = 1,
212 confirm_exit = 1,
212 debug = 0,
213 debug = 0,
213 deep_reload = 0,
214 deep_reload = 0,
214 editor = '0',
215 editor = '0',
215 gthread = 0,
216 gthread = 0,
216 help = 0,
217 help = 0,
217 interact = 0,
218 interact = 0,
218 ipythondir = ipythondir_def,
219 ipythondir = ipythondir_def,
219 log = 0,
220 log = 0,
220 logfile = '',
221 logfile = '',
221 logplay = '',
222 logplay = '',
222 messages = 1,
223 messages = 1,
223 multi_line_specials = 1,
224 multi_line_specials = 1,
224 nosep = 0,
225 nosep = 0,
225 object_info_string_level = 0,
226 object_info_string_level = 0,
226 pdb = 0,
227 pdb = 0,
227 pprint = 0,
228 pprint = 0,
228 profile = '',
229 profile = '',
229 prompt_in1 = 'In [\\#]: ',
230 prompt_in1 = 'In [\\#]: ',
230 prompt_in2 = ' .\\D.: ',
231 prompt_in2 = ' .\\D.: ',
231 prompt_out = 'Out[\\#]: ',
232 prompt_out = 'Out[\\#]: ',
232 prompts_pad_left = 1,
233 prompts_pad_left = 1,
233 pydb = 0,
234 pydb = 0,
234 pylab = 0,
235 pylab = 0,
235 pylab_import_all = 1,
236 pylab_import_all = 1,
236 q4thread = 0,
237 q4thread = 0,
237 qthread = 0,
238 qthread = 0,
238 quick = 0,
239 quick = 0,
239 quiet = 0,
240 quiet = 0,
240 rcfile = 'ipythonrc' + rc_suffix,
241 rcfile = 'ipythonrc' + rc_suffix,
241 readline = 1,
242 readline = 1,
242 readline_merge_completions = 1,
243 readline_merge_completions = 1,
243 readline_omit__names = 0,
244 readline_omit__names = 0,
244 screen_length = 0,
245 screen_length = 0,
245 separate_in = '\n',
246 separate_in = '\n',
246 separate_out = '\n',
247 separate_out = '\n',
247 separate_out2 = '',
248 separate_out2 = '',
248 system_header = 'IPython system call: ',
249 system_header = 'IPython system call: ',
249 system_verbose = 0,
250 system_verbose = 0,
250 term_title = 1,
251 term_title = 1,
251 tk = 0,
252 tk = 0,
252 #twisted= 0, # disabled for now
253 #twisted= 0, # disabled for now
253 upgrade = 0,
254 upgrade = 0,
254 Version = 0,
255 Version = 0,
255 wildcards_case_sensitive = 1,
256 wildcards_case_sensitive = 1,
256 wthread = 0,
257 wthread = 0,
257 wxversion = '0',
258 wxversion = '0',
258 xmode = 'Context',
259 xmode = 'Context',
259 magic_docstrings = 0, # undocumented, for doc generation
260 magic_docstrings = 0, # undocumented, for doc generation
260 )
261 )
261
262
262 # Things that will *only* appear in rcfiles (not at the command line).
263 # Things that will *only* appear in rcfiles (not at the command line).
263 # Make sure there's a space before each end of line (they get auto-joined!)
264 # Make sure there's a space before each end of line (they get auto-joined!)
264 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
265 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
265 qw_lol: 'import_some ',
266 qw_lol: 'import_some ',
266 # for things with embedded whitespace:
267 # for things with embedded whitespace:
267 list_strings:'execute alias readline_parse_and_bind ',
268 list_strings:'execute alias readline_parse_and_bind ',
268 # Regular strings need no conversion:
269 # Regular strings need no conversion:
269 None:'readline_remove_delims ',
270 None:'readline_remove_delims ',
270 }
271 }
271 # Default values for these
272 # Default values for these
272 rc_def = Struct(include = [],
273 rc_def = Struct(include = [],
273 import_mod = [],
274 import_mod = [],
274 import_all = [],
275 import_all = [],
275 import_some = [[]],
276 import_some = [[]],
276 execute = [],
277 execute = [],
277 execfile = [],
278 execfile = [],
278 alias = [],
279 alias = [],
279 readline_parse_and_bind = [],
280 readline_parse_and_bind = [],
280 readline_remove_delims = '',
281 readline_remove_delims = '',
281 )
282 )
282
283
283 # Build the type conversion dictionary from the above tables:
284 # Build the type conversion dictionary from the above tables:
284 typeconv = rcfile_opts.copy()
285 typeconv = rcfile_opts.copy()
285 typeconv.update(optstr2types(cmdline_opts))
286 typeconv.update(optstr2types(cmdline_opts))
286
287
287 # FIXME: the None key appears in both, put that back together by hand. Ugly!
288 # FIXME: the None key appears in both, put that back together by hand. Ugly!
288 typeconv[None] += ' ' + rcfile_opts[None]
289 typeconv[None] += ' ' + rcfile_opts[None]
289
290
290 # Remove quotes at ends of all strings (used to protect spaces)
291 # Remove quotes at ends of all strings (used to protect spaces)
291 typeconv[unquote_ends] = typeconv[None]
292 typeconv[unquote_ends] = typeconv[None]
292 del typeconv[None]
293 del typeconv[None]
293
294
294 # Build the list we'll use to make all config decisions with defaults:
295 # Build the list we'll use to make all config decisions with defaults:
295 opts_all = opts_def.copy()
296 opts_all = opts_def.copy()
296 opts_all.update(rc_def)
297 opts_all.update(rc_def)
297
298
298 # Build conflict resolver for recursive loading of config files:
299 # Build conflict resolver for recursive loading of config files:
299 # - preserve means the outermost file maintains the value, it is not
300 # - preserve means the outermost file maintains the value, it is not
300 # overwritten if an included file has the same key.
301 # overwritten if an included file has the same key.
301 # - add_flip applies + to the two values, so it better make sense to add
302 # - add_flip applies + to the two values, so it better make sense to add
302 # those types of keys. But it flips them first so that things loaded
303 # those types of keys. But it flips them first so that things loaded
303 # deeper in the inclusion chain have lower precedence.
304 # deeper in the inclusion chain have lower precedence.
304 conflict = {'preserve': ' '.join([ typeconv[int],
305 conflict = {'preserve': ' '.join([ typeconv[int],
305 typeconv[unquote_ends] ]),
306 typeconv[unquote_ends] ]),
306 'add_flip': ' '.join([ typeconv[qwflat],
307 'add_flip': ' '.join([ typeconv[qwflat],
307 typeconv[qw_lol],
308 typeconv[qw_lol],
308 typeconv[list_strings] ])
309 typeconv[list_strings] ])
309 }
310 }
310
311
311 # Now actually process the command line
312 # Now actually process the command line
312 getopt = DPyGetOpt.DPyGetOpt()
313 getopt = DPyGetOpt.DPyGetOpt()
313 getopt.setIgnoreCase(0)
314 getopt.setIgnoreCase(0)
314
315
315 getopt.parseConfiguration(opts_names)
316 getopt.parseConfiguration(opts_names)
316
317
317 try:
318 try:
318 getopt.processArguments(argv)
319 getopt.processArguments(argv)
319 except DPyGetOpt.ArgumentError, exc:
320 except DPyGetOpt.ArgumentError, exc:
320 print cmd_line_usage
321 print cmd_line_usage
321 warn('\nError in Arguments: "%s"' % exc)
322 warn('\nError in Arguments: "%s"' % exc)
322 sys.exit(1)
323 sys.exit(1)
323
324
324 # convert the options dict to a struct for much lighter syntax later
325 # convert the options dict to a struct for much lighter syntax later
325 opts = Struct(getopt.optionValues)
326 opts = Struct(getopt.optionValues)
326 args = getopt.freeValues
327 args = getopt.freeValues
327
328
328 # this is the struct (which has default values at this point) with which
329 # this is the struct (which has default values at this point) with which
329 # we make all decisions:
330 # we make all decisions:
330 opts_all.update(opts)
331 opts_all.update(opts)
331
332
332 # Options that force an immediate exit
333 # Options that force an immediate exit
333 if opts_all.help:
334 if opts_all.help:
334 page(cmd_line_usage)
335 page(cmd_line_usage)
335 sys.exit()
336 sys.exit()
336
337
337 if opts_all.Version:
338 if opts_all.Version:
338 print release.version
339 print release.version
339 sys.exit()
340 sys.exit()
340
341
341 if opts_all.magic_docstrings:
342 if opts_all.magic_docstrings:
342 IP.magic_magic('-latex')
343 IP.magic_magic('-latex')
343 sys.exit()
344 sys.exit()
344
345
345 # Display the deprecation warnings about threaded shells
346 # Display the deprecation warnings about threaded shells
346 if opts_all.pylab == 1: threaded_shell_warning()
347 if opts_all.pylab == 1: threaded_shell_warning()
347 if opts_all.wthread == 1: threaded_shell_warning()
348 if opts_all.wthread == 1: threaded_shell_warning()
348 if opts_all.qthread == 1: threaded_shell_warning()
349 if opts_all.qthread == 1: threaded_shell_warning()
349 if opts_all.q4thread == 1: threaded_shell_warning()
350 if opts_all.q4thread == 1: threaded_shell_warning()
350 if opts_all.gthread == 1: threaded_shell_warning()
351 if opts_all.gthread == 1: threaded_shell_warning()
351
352
352 # add personal ipythondir to sys.path so that users can put things in
353 # add personal ipythondir to sys.path so that users can put things in
353 # there for customization
354 # there for customization
354 sys.path.append(os.path.abspath(opts_all.ipythondir))
355 sys.path.append(os.path.abspath(opts_all.ipythondir))
355
356
356 # Create user config directory if it doesn't exist. This must be done
357 # Create user config directory if it doesn't exist. This must be done
357 # *after* getting the cmd line options.
358 # *after* getting the cmd line options.
358 if not os.path.isdir(opts_all.ipythondir):
359 if not os.path.isdir(opts_all.ipythondir):
359 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
360 user_setup(opts_all.ipythondir,rc_suffix,'install')
360
361
361 # upgrade user config files while preserving a copy of the originals
362 # upgrade user config files while preserving a copy of the originals
362 if opts_all.upgrade:
363 if opts_all.upgrade:
363 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
364 user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
364
365
365 # check mutually exclusive options in the *original* command line
366 # check mutually exclusive options in the *original* command line
366 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
367 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
367 qw('classic profile'),qw('classic rcfile')])
368 qw('classic profile'),qw('classic rcfile')])
368
369
369 #---------------------------------------------------------------------------
370 #---------------------------------------------------------------------------
370 # Log replay
371 # Log replay
371
372
372 # if -logplay, we need to 'become' the other session. That basically means
373 # if -logplay, we need to 'become' the other session. That basically means
373 # replacing the current command line environment with that of the old
374 # replacing the current command line environment with that of the old
374 # session and moving on.
375 # session and moving on.
375
376
376 # this is needed so that later we know we're in session reload mode, as
377 # this is needed so that later we know we're in session reload mode, as
377 # opts_all will get overwritten:
378 # opts_all will get overwritten:
378 load_logplay = 0
379 load_logplay = 0
379
380
380 if opts_all.logplay:
381 if opts_all.logplay:
381 load_logplay = opts_all.logplay
382 load_logplay = opts_all.logplay
382 opts_debug_save = opts_all.debug
383 opts_debug_save = opts_all.debug
383 try:
384 try:
384 logplay = open(opts_all.logplay)
385 logplay = open(opts_all.logplay)
385 except IOError:
386 except IOError:
386 if opts_all.debug: IP.InteractiveTB()
387 if opts_all.debug: IP.InteractiveTB()
387 warn('Could not open logplay file '+`opts_all.logplay`)
388 warn('Could not open logplay file '+`opts_all.logplay`)
388 # restore state as if nothing had happened and move on, but make
389 # restore state as if nothing had happened and move on, but make
389 # sure that later we don't try to actually load the session file
390 # sure that later we don't try to actually load the session file
390 logplay = None
391 logplay = None
391 load_logplay = 0
392 load_logplay = 0
392 del opts_all.logplay
393 del opts_all.logplay
393 else:
394 else:
394 try:
395 try:
395 logplay.readline()
396 logplay.readline()
396 logplay.readline();
397 logplay.readline();
397 # this reloads that session's command line
398 # this reloads that session's command line
398 cmd = logplay.readline()[6:]
399 cmd = logplay.readline()[6:]
399 exec cmd
400 exec cmd
400 # restore the true debug flag given so that the process of
401 # restore the true debug flag given so that the process of
401 # session loading itself can be monitored.
402 # session loading itself can be monitored.
402 opts.debug = opts_debug_save
403 opts.debug = opts_debug_save
403 # save the logplay flag so later we don't overwrite the log
404 # save the logplay flag so later we don't overwrite the log
404 opts.logplay = load_logplay
405 opts.logplay = load_logplay
405 # now we must update our own structure with defaults
406 # now we must update our own structure with defaults
406 opts_all.update(opts)
407 opts_all.update(opts)
407 # now load args
408 # now load args
408 cmd = logplay.readline()[6:]
409 cmd = logplay.readline()[6:]
409 exec cmd
410 exec cmd
410 logplay.close()
411 logplay.close()
411 except:
412 except:
412 logplay.close()
413 logplay.close()
413 if opts_all.debug: IP.InteractiveTB()
414 if opts_all.debug: IP.InteractiveTB()
414 warn("Logplay file lacking full configuration information.\n"
415 warn("Logplay file lacking full configuration information.\n"
415 "I'll try to read it, but some things may not work.")
416 "I'll try to read it, but some things may not work.")
416
417
417 #-------------------------------------------------------------------------
418 #-------------------------------------------------------------------------
418 # set up output traps: catch all output from files, being run, modules
419 # set up output traps: catch all output from files, being run, modules
419 # loaded, etc. Then give it to the user in a clean form at the end.
420 # loaded, etc. Then give it to the user in a clean form at the end.
420
421
421 msg_out = 'Output messages. '
422 msg_out = 'Output messages. '
422 msg_err = 'Error messages. '
423 msg_err = 'Error messages. '
423 msg_sep = '\n'
424 msg_sep = '\n'
424 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
425 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
425 msg_err,msg_sep,debug,
426 msg_err,msg_sep,debug,
426 quiet_out=1),
427 quiet_out=1),
427 user_exec = OutputTrap('User File Execution',msg_out,
428 user_exec = OutputTrap('User File Execution',msg_out,
428 msg_err,msg_sep,debug),
429 msg_err,msg_sep,debug),
429 logplay = OutputTrap('Log Loader',msg_out,
430 logplay = OutputTrap('Log Loader',msg_out,
430 msg_err,msg_sep,debug),
431 msg_err,msg_sep,debug),
431 summary = ''
432 summary = ''
432 )
433 )
433
434
434 #-------------------------------------------------------------------------
435 #-------------------------------------------------------------------------
435 # Process user ipythonrc-type configuration files
436 # Process user ipythonrc-type configuration files
436
437
437 # turn on output trapping and log to msg.config
438 # turn on output trapping and log to msg.config
438 # remember that with debug on, trapping is actually disabled
439 # remember that with debug on, trapping is actually disabled
439 msg.config.trap_all()
440 msg.config.trap_all()
440
441
441 # look for rcfile in current or default directory
442 # look for rcfile in current or default directory
442 try:
443 try:
443 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
444 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
444 except IOError:
445 except IOError:
445 if opts_all.debug: IP.InteractiveTB()
446 if opts_all.debug: IP.InteractiveTB()
446 warn('Configuration file %s not found. Ignoring request.'
447 warn('Configuration file %s not found. Ignoring request.'
447 % (opts_all.rcfile) )
448 % (opts_all.rcfile) )
448
449
449 print opts_all.rcfile, opts_all.ipythondir
450 print opts_all.rcfile, opts_all.ipythondir
450
451
451 # 'profiles' are a shorthand notation for config filenames
452 # 'profiles' are a shorthand notation for config filenames
452 profile_handled_by_legacy = False
453 profile_handled_by_legacy = False
453 if opts_all.profile:
454 if opts_all.profile:
454
455
455 try:
456 try:
456 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
457 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
457 + rc_suffix,
458 + rc_suffix,
458 opts_all.ipythondir)
459 opts_all.ipythondir)
459 profile_handled_by_legacy = True
460 profile_handled_by_legacy = True
460 except IOError:
461 except IOError:
461 if opts_all.debug: IP.InteractiveTB()
462 if opts_all.debug: IP.InteractiveTB()
462 opts.profile = '' # remove profile from options if invalid
463 opts.profile = '' # remove profile from options if invalid
463 # We won't warn anymore, primary method is ipy_profile_PROFNAME
464 # We won't warn anymore, primary method is ipy_profile_PROFNAME
464 # which does trigger a warning.
465 # which does trigger a warning.
465
466
466 # load the config file
467 # load the config file
467 rcfiledata = None
468 rcfiledata = None
468 if opts_all.quick:
469 if opts_all.quick:
469 print 'Launching IPython in quick mode. No config file read.'
470 print 'Launching IPython in quick mode. No config file read.'
470 elif opts_all.rcfile:
471 elif opts_all.rcfile:
471 try:
472 try:
472 cfg_loader = ConfigLoader(conflict)
473 cfg_loader = ConfigLoader(conflict)
473 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
474 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
474 'include',opts_all.ipythondir,
475 'include',opts_all.ipythondir,
475 purge = 1,
476 purge = 1,
476 unique = conflict['preserve'])
477 unique = conflict['preserve'])
477 except:
478 except:
478 IP.InteractiveTB()
479 IP.InteractiveTB()
479 warn('Problems loading configuration file '+
480 warn('Problems loading configuration file '+
480 `opts_all.rcfile`+
481 `opts_all.rcfile`+
481 '\nStarting with default -bare bones- configuration.')
482 '\nStarting with default -bare bones- configuration.')
482 else:
483 else:
483 warn('No valid configuration file found in either currrent directory\n'+
484 warn('No valid configuration file found in either currrent directory\n'+
484 'or in the IPython config. directory: '+`opts_all.ipythondir`+
485 'or in the IPython config. directory: '+`opts_all.ipythondir`+
485 '\nProceeding with internal defaults.')
486 '\nProceeding with internal defaults.')
486
487
487 #------------------------------------------------------------------------
488 #------------------------------------------------------------------------
488 # Set exception handlers in mode requested by user.
489 # Set exception handlers in mode requested by user.
489 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
490 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
490 IP.magic_xmode(opts_all.xmode)
491 IP.magic_xmode(opts_all.xmode)
491 otrap.release_out()
492 otrap.release_out()
492
493
493 #------------------------------------------------------------------------
494 #------------------------------------------------------------------------
494 # Execute user config
495 # Execute user config
495
496
496 # Create a valid config structure with the right precedence order:
497 # Create a valid config structure with the right precedence order:
497 # defaults < rcfile < command line. This needs to be in the instance, so
498 # defaults < rcfile < command line. This needs to be in the instance, so
498 # that method calls below that rely on it find it.
499 # that method calls below that rely on it find it.
499 IP.rc = rc_def.copy()
500 IP.rc = rc_def.copy()
500
501
501 # Work with a local alias inside this routine to avoid unnecessary
502 # Work with a local alias inside this routine to avoid unnecessary
502 # attribute lookups.
503 # attribute lookups.
503 IP_rc = IP.rc
504 IP_rc = IP.rc
504
505
505 IP_rc.update(opts_def)
506 IP_rc.update(opts_def)
506 if rcfiledata:
507 if rcfiledata:
507 IP_rc.update(rcfiledata)
508 IP_rc.update(rcfiledata)
508 IP_rc.update(opts)
509 IP_rc.update(opts)
509 if rc_override is not None:
510 if rc_override is not None:
510 IP_rc.update(rc_override)
511 IP_rc.update(rc_override)
511
512
512 # Store the original cmd line for reference:
513 # Store the original cmd line for reference:
513 IP_rc.opts = opts
514 IP_rc.opts = opts
514 IP_rc.args = args
515 IP_rc.args = args
515
516
516 # create a *runtime* Struct like rc for holding parameters which may be
517 # create a *runtime* Struct like rc for holding parameters which may be
517 # created and/or modified by runtime user extensions.
518 # created and/or modified by runtime user extensions.
518 IP.runtime_rc = Struct()
519 IP.runtime_rc = Struct()
519
520
520 # from this point on, all config should be handled through IP_rc,
521 # from this point on, all config should be handled through IP_rc,
521 # opts* shouldn't be used anymore.
522 # opts* shouldn't be used anymore.
522
523
523
524
524 # update IP_rc with some special things that need manual
525 # update IP_rc with some special things that need manual
525 # tweaks. Basically options which affect other options. I guess this
526 # tweaks. Basically options which affect other options. I guess this
526 # should just be written so that options are fully orthogonal and we
527 # should just be written so that options are fully orthogonal and we
527 # wouldn't worry about this stuff!
528 # wouldn't worry about this stuff!
528
529
529 if IP_rc.classic:
530 if IP_rc.classic:
530 IP_rc.quick = 1
531 IP_rc.quick = 1
531 IP_rc.cache_size = 0
532 IP_rc.cache_size = 0
532 IP_rc.pprint = 0
533 IP_rc.pprint = 0
533 IP_rc.prompt_in1 = '>>> '
534 IP_rc.prompt_in1 = '>>> '
534 IP_rc.prompt_in2 = '... '
535 IP_rc.prompt_in2 = '... '
535 IP_rc.prompt_out = ''
536 IP_rc.prompt_out = ''
536 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
537 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
537 IP_rc.colors = 'NoColor'
538 IP_rc.colors = 'NoColor'
538 IP_rc.xmode = 'Plain'
539 IP_rc.xmode = 'Plain'
539
540
540 IP.pre_config_initialization()
541 IP.pre_config_initialization()
541 # configure readline
542 # configure readline
542
543
543 # update exception handlers with rc file status
544 # update exception handlers with rc file status
544 otrap.trap_out() # I don't want these messages ever.
545 otrap.trap_out() # I don't want these messages ever.
545 IP.magic_xmode(IP_rc.xmode)
546 IP.magic_xmode(IP_rc.xmode)
546 otrap.release_out()
547 otrap.release_out()
547
548
548 # activate logging if requested and not reloading a log
549 # activate logging if requested and not reloading a log
549 if IP_rc.logplay:
550 if IP_rc.logplay:
550 IP.magic_logstart(IP_rc.logplay + ' append')
551 IP.magic_logstart(IP_rc.logplay + ' append')
551 elif IP_rc.logfile:
552 elif IP_rc.logfile:
552 IP.magic_logstart(IP_rc.logfile)
553 IP.magic_logstart(IP_rc.logfile)
553 elif IP_rc.log:
554 elif IP_rc.log:
554 IP.magic_logstart()
555 IP.magic_logstart()
555
556
556 # find user editor so that it we don't have to look it up constantly
557 # find user editor so that it we don't have to look it up constantly
557 if IP_rc.editor.strip()=='0':
558 if IP_rc.editor.strip()=='0':
558 try:
559 try:
559 ed = os.environ['EDITOR']
560 ed = os.environ['EDITOR']
560 except KeyError:
561 except KeyError:
561 if os.name == 'posix':
562 if os.name == 'posix':
562 ed = 'vi' # the only one guaranteed to be there!
563 ed = 'vi' # the only one guaranteed to be there!
563 else:
564 else:
564 ed = 'notepad' # same in Windows!
565 ed = 'notepad' # same in Windows!
565 IP_rc.editor = ed
566 IP_rc.editor = ed
566
567
567 # Keep track of whether this is an embedded instance or not (useful for
568 # Keep track of whether this is an embedded instance or not (useful for
568 # post-mortems).
569 # post-mortems).
569 IP_rc.embedded = IP.embedded
570 IP_rc.embedded = IP.embedded
570
571
571 # Recursive reload
572 # Recursive reload
572 try:
573 try:
573 from IPython.lib import deepreload
574 from IPython.lib import deepreload
574 if IP_rc.deep_reload:
575 if IP_rc.deep_reload:
575 __builtin__.reload = deepreload.reload
576 __builtin__.reload = deepreload.reload
576 else:
577 else:
577 __builtin__.dreload = deepreload.reload
578 __builtin__.dreload = deepreload.reload
578 del deepreload
579 del deepreload
579 except ImportError:
580 except ImportError:
580 pass
581 pass
581
582
582 # Save the current state of our namespace so that the interactive shell
583 # Save the current state of our namespace so that the interactive shell
583 # can later know which variables have been created by us from config files
584 # can later know which variables have been created by us from config files
584 # and loading. This way, loading a file (in any way) is treated just like
585 # and loading. This way, loading a file (in any way) is treated just like
585 # defining things on the command line, and %who works as expected.
586 # defining things on the command line, and %who works as expected.
586
587
587 # DON'T do anything that affects the namespace beyond this point!
588 # DON'T do anything that affects the namespace beyond this point!
588 IP.internal_ns.update(__main__.__dict__)
589 IP.internal_ns.update(__main__.__dict__)
589
590
590 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
591 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
591
592
592 # Now run through the different sections of the users's config
593 # Now run through the different sections of the users's config
593 if IP_rc.debug:
594 if IP_rc.debug:
594 print 'Trying to execute the following configuration structure:'
595 print 'Trying to execute the following configuration structure:'
595 print '(Things listed first are deeper in the inclusion tree and get'
596 print '(Things listed first are deeper in the inclusion tree and get'
596 print 'loaded first).\n'
597 print 'loaded first).\n'
597 pprint(IP_rc.__dict__)
598 pprint(IP_rc.__dict__)
598
599
599 for mod in IP_rc.import_mod:
600 for mod in IP_rc.import_mod:
600 try:
601 try:
601 exec 'import '+mod in IP.user_ns
602 exec 'import '+mod in IP.user_ns
602 except :
603 except :
603 IP.InteractiveTB()
604 IP.InteractiveTB()
604 import_fail_info(mod)
605 import_fail_info(mod)
605
606
606 for mod_fn in IP_rc.import_some:
607 for mod_fn in IP_rc.import_some:
607 if not mod_fn == []:
608 if not mod_fn == []:
608 mod,fn = mod_fn[0],','.join(mod_fn[1:])
609 mod,fn = mod_fn[0],','.join(mod_fn[1:])
609 try:
610 try:
610 exec 'from '+mod+' import '+fn in IP.user_ns
611 exec 'from '+mod+' import '+fn in IP.user_ns
611 except :
612 except :
612 IP.InteractiveTB()
613 IP.InteractiveTB()
613 import_fail_info(mod,fn)
614 import_fail_info(mod,fn)
614
615
615 for mod in IP_rc.import_all:
616 for mod in IP_rc.import_all:
616 try:
617 try:
617 exec 'from '+mod+' import *' in IP.user_ns
618 exec 'from '+mod+' import *' in IP.user_ns
618 except :
619 except :
619 IP.InteractiveTB()
620 IP.InteractiveTB()
620 import_fail_info(mod)
621 import_fail_info(mod)
621
622
622 for code in IP_rc.execute:
623 for code in IP_rc.execute:
623 try:
624 try:
624 exec code in IP.user_ns
625 exec code in IP.user_ns
625 except:
626 except:
626 IP.InteractiveTB()
627 IP.InteractiveTB()
627 warn('Failure executing code: ' + `code`)
628 warn('Failure executing code: ' + `code`)
628
629
629 # Execute the files the user wants in ipythonrc
630 # Execute the files the user wants in ipythonrc
630 for file in IP_rc.execfile:
631 for file in IP_rc.execfile:
631 try:
632 try:
632 file = filefind(file,sys.path+[IPython_dir])
633 file = filefind(file,sys.path+[IPython_dir])
633 except IOError:
634 except IOError:
634 warn(itpl('File $file not found. Skipping it.'))
635 warn(itpl('File $file not found. Skipping it.'))
635 else:
636 else:
636 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
637 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
637
638
638 # finally, try importing ipy_*_conf for final configuration
639 # finally, try importing ipy_*_conf for final configuration
639 try:
640 try:
640 import ipy_system_conf
641 import ipy_system_conf
641 except ImportError:
642 except ImportError:
642 if opts_all.debug: IP.InteractiveTB()
643 if opts_all.debug: IP.InteractiveTB()
643 warn("Could not import 'ipy_system_conf'")
644 warn("Could not import 'ipy_system_conf'")
644 except:
645 except:
645 IP.InteractiveTB()
646 IP.InteractiveTB()
646 import_fail_info('ipy_system_conf')
647 import_fail_info('ipy_system_conf')
647
648
648 # only import prof module if ipythonrc-PROF was not found
649 # only import prof module if ipythonrc-PROF was not found
649 if opts_all.profile and not profile_handled_by_legacy:
650 if opts_all.profile and not profile_handled_by_legacy:
650 profmodname = 'ipy_profile_' + opts_all.profile
651 profmodname = 'ipy_profile_' + opts_all.profile
651 try:
652 try:
652 force_import(profmodname)
653 force_import(profmodname)
653 except:
654 except:
654 IP.InteractiveTB()
655 IP.InteractiveTB()
655 print "Error importing",profmodname,\
656 print "Error importing",profmodname,\
656 "- perhaps you should run %upgrade?"
657 "- perhaps you should run %upgrade?"
657 import_fail_info(profmodname)
658 import_fail_info(profmodname)
658 else:
659 else:
659 opts.profile = opts_all.profile
660 opts.profile = opts_all.profile
660 else:
661 else:
661 force_import('ipy_profile_none')
662 force_import('ipy_profile_none')
662 # XXX - this is wrong: ipy_user_conf should not be loaded unconditionally,
663 # XXX - this is wrong: ipy_user_conf should not be loaded unconditionally,
663 # since the user could have specified a config file path by hand.
664 # since the user could have specified a config file path by hand.
664 try:
665 try:
665 force_import('ipy_user_conf')
666 force_import('ipy_user_conf')
666 except:
667 except:
667 conf = opts_all.ipythondir + "/ipy_user_conf.py"
668 conf = opts_all.ipythondir + "/ipy_user_conf.py"
668 IP.InteractiveTB()
669 IP.InteractiveTB()
669 if not os.path.isfile(conf):
670 if not os.path.isfile(conf):
670 warn(conf + ' does not exist, please run %upgrade!')
671 warn(conf + ' does not exist, please run %upgrade!')
671
672
672 import_fail_info("ipy_user_conf")
673 import_fail_info("ipy_user_conf")
673
674
674 # Define the history file for saving commands in between sessions
675 # Define the history file for saving commands in between sessions
675 try:
676 try:
676 histfname = 'history-%s' % opts.profile
677 histfname = 'history-%s' % opts.profile
677 except AttributeError:
678 except AttributeError:
678 histfname = 'history'
679 histfname = 'history'
679 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
680 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
680
681
681 # finally, push the argv to options again to ensure highest priority
682 # finally, push the argv to options again to ensure highest priority
682 IP_rc.update(opts)
683 IP_rc.update(opts)
683
684
684 # release stdout and stderr and save config log into a global summary
685 # release stdout and stderr and save config log into a global summary
685 msg.config.release_all()
686 msg.config.release_all()
686 if IP_rc.messages:
687 if IP_rc.messages:
687 msg.summary += msg.config.summary_all()
688 msg.summary += msg.config.summary_all()
688
689
689 #------------------------------------------------------------------------
690 #------------------------------------------------------------------------
690 # Setup interactive session
691 # Setup interactive session
691
692
692 # Now we should be fully configured. We can then execute files or load
693 # Now we should be fully configured. We can then execute files or load
693 # things only needed for interactive use. Then we'll open the shell.
694 # things only needed for interactive use. Then we'll open the shell.
694
695
695 # Take a snapshot of the user namespace before opening the shell. That way
696 # Take a snapshot of the user namespace before opening the shell. That way
696 # we'll be able to identify which things were interactively defined and
697 # we'll be able to identify which things were interactively defined and
697 # which were defined through config files.
698 # which were defined through config files.
698 IP.user_config_ns.update(IP.user_ns)
699 IP.user_config_ns.update(IP.user_ns)
699
700
700 # Force reading a file as if it were a session log. Slower but safer.
701 # Force reading a file as if it were a session log. Slower but safer.
701 if load_logplay:
702 if load_logplay:
702 print 'Replaying log...'
703 print 'Replaying log...'
703 try:
704 try:
704 if IP_rc.debug:
705 if IP_rc.debug:
705 logplay_quiet = 0
706 logplay_quiet = 0
706 else:
707 else:
707 logplay_quiet = 1
708 logplay_quiet = 1
708
709
709 msg.logplay.trap_all()
710 msg.logplay.trap_all()
710 IP.safe_execfile(load_logplay,IP.user_ns,
711 IP.safe_execfile(load_logplay,IP.user_ns,
711 islog = 1, quiet = logplay_quiet)
712 islog = 1, quiet = logplay_quiet)
712 msg.logplay.release_all()
713 msg.logplay.release_all()
713 if IP_rc.messages:
714 if IP_rc.messages:
714 msg.summary += msg.logplay.summary_all()
715 msg.summary += msg.logplay.summary_all()
715 except:
716 except:
716 warn('Problems replaying logfile %s.' % load_logplay)
717 warn('Problems replaying logfile %s.' % load_logplay)
717 IP.InteractiveTB()
718 IP.InteractiveTB()
718
719
719 # Load remaining files in command line
720 # Load remaining files in command line
720 msg.user_exec.trap_all()
721 msg.user_exec.trap_all()
721
722
722 # Do NOT execute files named in the command line as scripts to be loaded
723 # Do NOT execute files named in the command line as scripts to be loaded
723 # by embedded instances. Doing so has the potential for an infinite
724 # by embedded instances. Doing so has the potential for an infinite
724 # recursion if there are exceptions thrown in the process.
725 # recursion if there are exceptions thrown in the process.
725
726
726 # XXX FIXME: the execution of user files should be moved out to after
727 # XXX FIXME: the execution of user files should be moved out to after
727 # ipython is fully initialized, just as if they were run via %run at the
728 # ipython is fully initialized, just as if they were run via %run at the
728 # ipython prompt. This would also give them the benefit of ipython's
729 # ipython prompt. This would also give them the benefit of ipython's
729 # nice tracebacks.
730 # nice tracebacks.
730
731
731 if (not embedded and IP_rc.args and
732 if (not embedded and IP_rc.args and
732 not IP_rc.args[0].lower().endswith('.ipy')):
733 not IP_rc.args[0].lower().endswith('.ipy')):
733 name_save = IP.user_ns['__name__']
734 name_save = IP.user_ns['__name__']
734 IP.user_ns['__name__'] = '__main__'
735 IP.user_ns['__name__'] = '__main__'
735 # Set our own excepthook in case the user code tries to call it
736 # Set our own excepthook in case the user code tries to call it
736 # directly. This prevents triggering the IPython crash handler.
737 # directly. This prevents triggering the IPython crash handler.
737 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
738 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
738
739
739 save_argv = sys.argv[1:] # save it for later restoring
740 save_argv = sys.argv[1:] # save it for later restoring
740
741
741 sys.argv = args
742 sys.argv = args
742
743
743 try:
744 try:
744 IP.safe_execfile(args[0], IP.user_ns)
745 IP.safe_execfile(args[0], IP.user_ns)
745 finally:
746 finally:
746 # Reset our crash handler in place
747 # Reset our crash handler in place
747 sys.excepthook = old_excepthook
748 sys.excepthook = old_excepthook
748 sys.argv[:] = save_argv
749 sys.argv[:] = save_argv
749 IP.user_ns['__name__'] = name_save
750 IP.user_ns['__name__'] = name_save
750
751
751 msg.user_exec.release_all()
752 msg.user_exec.release_all()
752
753
753 if IP_rc.messages:
754 if IP_rc.messages:
754 msg.summary += msg.user_exec.summary_all()
755 msg.summary += msg.user_exec.summary_all()
755
756
756 # since we can't specify a null string on the cmd line, 0 is the equivalent:
757 # since we can't specify a null string on the cmd line, 0 is the equivalent:
757 if IP_rc.nosep:
758 if IP_rc.nosep:
758 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
759 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
759 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
760 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
760 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
761 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
761 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
762 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
762 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
763 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
763 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
764 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
764 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
765 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
765
766
766 # Determine how many lines at the bottom of the screen are needed for
767 # Determine how many lines at the bottom of the screen are needed for
767 # showing prompts, so we can know wheter long strings are to be printed or
768 # showing prompts, so we can know wheter long strings are to be printed or
768 # paged:
769 # paged:
769 num_lines_bot = IP_rc.separate_in.count('\n')+1
770 num_lines_bot = IP_rc.separate_in.count('\n')+1
770 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
771 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
771
772
772 # configure startup banner
773 # configure startup banner
773 if IP_rc.c: # regular python doesn't print the banner with -c
774 if IP_rc.c: # regular python doesn't print the banner with -c
774 IP_rc.banner = 0
775 IP_rc.banner = 0
775 if IP_rc.banner:
776 if IP_rc.banner:
776 BANN_P = IP.BANNER_PARTS
777 BANN_P = IP.BANNER_PARTS
777 else:
778 else:
778 BANN_P = []
779 BANN_P = []
779
780
780 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
781 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
781
782
782 # add message log (possibly empty)
783 # add message log (possibly empty)
783 if msg.summary: BANN_P.append(msg.summary)
784 if msg.summary: BANN_P.append(msg.summary)
784 # Final banner is a string
785 # Final banner is a string
785 IP.BANNER = '\n'.join(BANN_P)
786 IP.BANNER = '\n'.join(BANN_P)
786
787
787 # Finalize the IPython instance. This assumes the rc structure is fully
788 # Finalize the IPython instance. This assumes the rc structure is fully
788 # in place.
789 # in place.
789 IP.post_config_initialization()
790 IP.post_config_initialization()
790
791
791 return IP
792 return IP
792 #************************ end of file <ipmaker.py> **************************
793 #************************ end of file <ipmaker.py> **************************
@@ -1,3587 +1,3588 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import re
24 import re
25 import tempfile
25 import tempfile
26 import time
26 import time
27 import cPickle as pickle
27 import cPickle as pickle
28 import textwrap
28 import textwrap
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pprint, pformat
31 from pprint import pprint, pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 import IPython
45 import IPython
46 from IPython.utils import wildcard
46 from IPython.utils import wildcard
47 from IPython.core import debugger, oinspect
47 from IPython.core import debugger, oinspect
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.utils.PyColorize import Parser
50 from IPython.utils.PyColorize import Parser
51 from IPython.utils.ipstruct import Struct
51 from IPython.utils.ipstruct import Struct
52 from IPython.core.macro import Macro
52 from IPython.core.macro import Macro
53 from IPython.utils.genutils import *
53 from IPython.utils.genutils import *
54 from IPython.utils import platutils
54 from IPython.utils import platutils
55 import IPython.utils.generics
55 import IPython.utils.generics
56 from IPython.core import ipapi
56 from IPython.core import ipapi
57 from IPython.core.ipapi import UsageError
57 from IPython.core.ipapi import UsageError
58 from IPython.testing import decorators as testdec
58 from IPython.testing import decorators as testdec
59
59
60 #***************************************************************************
60 #***************************************************************************
61 # Utility functions
61 # Utility functions
62 def on_off(tag):
62 def on_off(tag):
63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
64 return ['OFF','ON'][tag]
64 return ['OFF','ON'][tag]
65
65
66 class Bunch: pass
66 class Bunch: pass
67
67
68 def compress_dhist(dh):
68 def compress_dhist(dh):
69 head, tail = dh[:-10], dh[-10:]
69 head, tail = dh[:-10], dh[-10:]
70
70
71 newhead = []
71 newhead = []
72 done = set()
72 done = set()
73 for h in head:
73 for h in head:
74 if h in done:
74 if h in done:
75 continue
75 continue
76 newhead.append(h)
76 newhead.append(h)
77 done.add(h)
77 done.add(h)
78
78
79 return newhead + tail
79 return newhead + tail
80
80
81
81
82 #***************************************************************************
82 #***************************************************************************
83 # Main class implementing Magic functionality
83 # Main class implementing Magic functionality
84 class Magic:
84 class Magic:
85 """Magic functions for InteractiveShell.
85 """Magic functions for InteractiveShell.
86
86
87 Shell functions which can be reached as %function_name. All magic
87 Shell functions which can be reached as %function_name. All magic
88 functions should accept a string, which they can parse for their own
88 functions should accept a string, which they can parse for their own
89 needs. This can make some functions easier to type, eg `%cd ../`
89 needs. This can make some functions easier to type, eg `%cd ../`
90 vs. `%cd("../")`
90 vs. `%cd("../")`
91
91
92 ALL definitions MUST begin with the prefix magic_. The user won't need it
92 ALL definitions MUST begin with the prefix magic_. The user won't need it
93 at the command line, but it is is needed in the definition. """
93 at the command line, but it is is needed in the definition. """
94
94
95 # class globals
95 # class globals
96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
97 'Automagic is ON, % prefix NOT needed for magic functions.']
97 'Automagic is ON, % prefix NOT needed for magic functions.']
98
98
99 #......................................................................
99 #......................................................................
100 # some utility functions
100 # some utility functions
101
101
102 def __init__(self,shell):
102 def __init__(self,shell):
103
103
104 self.options_table = {}
104 self.options_table = {}
105 if profile is None:
105 if profile is None:
106 self.magic_prun = self.profile_missing_notice
106 self.magic_prun = self.profile_missing_notice
107 self.shell = shell
107 self.shell = shell
108
108
109 # namespace for holding state we may need
109 # namespace for holding state we may need
110 self._magic_state = Bunch()
110 self._magic_state = Bunch()
111
111
112 def profile_missing_notice(self, *args, **kwargs):
112 def profile_missing_notice(self, *args, **kwargs):
113 error("""\
113 error("""\
114 The profile module could not be found. It has been removed from the standard
114 The profile module could not be found. It has been removed from the standard
115 python packages because of its non-free license. To use profiling, install the
115 python packages because of its non-free license. To use profiling, install the
116 python-profiler package from non-free.""")
116 python-profiler package from non-free.""")
117
117
118 def default_option(self,fn,optstr):
118 def default_option(self,fn,optstr):
119 """Make an entry in the options_table for fn, with value optstr"""
119 """Make an entry in the options_table for fn, with value optstr"""
120
120
121 if fn not in self.lsmagic():
121 if fn not in self.lsmagic():
122 error("%s is not a magic function" % fn)
122 error("%s is not a magic function" % fn)
123 self.options_table[fn] = optstr
123 self.options_table[fn] = optstr
124
124
125 def lsmagic(self):
125 def lsmagic(self):
126 """Return a list of currently available magic functions.
126 """Return a list of currently available magic functions.
127
127
128 Gives a list of the bare names after mangling (['ls','cd', ...], not
128 Gives a list of the bare names after mangling (['ls','cd', ...], not
129 ['magic_ls','magic_cd',...]"""
129 ['magic_ls','magic_cd',...]"""
130
130
131 # FIXME. This needs a cleanup, in the way the magics list is built.
131 # FIXME. This needs a cleanup, in the way the magics list is built.
132
132
133 # magics in class definition
133 # magics in class definition
134 class_magic = lambda fn: fn.startswith('magic_') and \
134 class_magic = lambda fn: fn.startswith('magic_') and \
135 callable(Magic.__dict__[fn])
135 callable(Magic.__dict__[fn])
136 # in instance namespace (run-time user additions)
136 # in instance namespace (run-time user additions)
137 inst_magic = lambda fn: fn.startswith('magic_') and \
137 inst_magic = lambda fn: fn.startswith('magic_') and \
138 callable(self.__dict__[fn])
138 callable(self.__dict__[fn])
139 # and bound magics by user (so they can access self):
139 # and bound magics by user (so they can access self):
140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
141 callable(self.__class__.__dict__[fn])
141 callable(self.__class__.__dict__[fn])
142 magics = filter(class_magic,Magic.__dict__.keys()) + \
142 magics = filter(class_magic,Magic.__dict__.keys()) + \
143 filter(inst_magic,self.__dict__.keys()) + \
143 filter(inst_magic,self.__dict__.keys()) + \
144 filter(inst_bound_magic,self.__class__.__dict__.keys())
144 filter(inst_bound_magic,self.__class__.__dict__.keys())
145 out = []
145 out = []
146 for fn in set(magics):
146 for fn in set(magics):
147 out.append(fn.replace('magic_','',1))
147 out.append(fn.replace('magic_','',1))
148 out.sort()
148 out.sort()
149 return out
149 return out
150
150
151 def extract_input_slices(self,slices,raw=False):
151 def extract_input_slices(self,slices,raw=False):
152 """Return as a string a set of input history slices.
152 """Return as a string a set of input history slices.
153
153
154 Inputs:
154 Inputs:
155
155
156 - slices: the set of slices is given as a list of strings (like
156 - slices: the set of slices is given as a list of strings (like
157 ['1','4:8','9'], since this function is for use by magic functions
157 ['1','4:8','9'], since this function is for use by magic functions
158 which get their arguments as strings.
158 which get their arguments as strings.
159
159
160 Optional inputs:
160 Optional inputs:
161
161
162 - raw(False): by default, the processed input is used. If this is
162 - raw(False): by default, the processed input is used. If this is
163 true, the raw input history is used instead.
163 true, the raw input history is used instead.
164
164
165 Note that slices can be called with two notations:
165 Note that slices can be called with two notations:
166
166
167 N:M -> standard python form, means including items N...(M-1).
167 N:M -> standard python form, means including items N...(M-1).
168
168
169 N-M -> include items N..M (closed endpoint)."""
169 N-M -> include items N..M (closed endpoint)."""
170
170
171 if raw:
171 if raw:
172 hist = self.shell.input_hist_raw
172 hist = self.shell.input_hist_raw
173 else:
173 else:
174 hist = self.shell.input_hist
174 hist = self.shell.input_hist
175
175
176 cmds = []
176 cmds = []
177 for chunk in slices:
177 for chunk in slices:
178 if ':' in chunk:
178 if ':' in chunk:
179 ini,fin = map(int,chunk.split(':'))
179 ini,fin = map(int,chunk.split(':'))
180 elif '-' in chunk:
180 elif '-' in chunk:
181 ini,fin = map(int,chunk.split('-'))
181 ini,fin = map(int,chunk.split('-'))
182 fin += 1
182 fin += 1
183 else:
183 else:
184 ini = int(chunk)
184 ini = int(chunk)
185 fin = ini+1
185 fin = ini+1
186 cmds.append(hist[ini:fin])
186 cmds.append(hist[ini:fin])
187 return cmds
187 return cmds
188
188
189 def _ofind(self, oname, namespaces=None):
189 def _ofind(self, oname, namespaces=None):
190 """Find an object in the available namespaces.
190 """Find an object in the available namespaces.
191
191
192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
193
193
194 Has special code to detect magic functions.
194 Has special code to detect magic functions.
195 """
195 """
196
196
197 oname = oname.strip()
197 oname = oname.strip()
198
198
199 alias_ns = None
199 alias_ns = None
200 if namespaces is None:
200 if namespaces is None:
201 # Namespaces to search in:
201 # Namespaces to search in:
202 # Put them in a list. The order is important so that we
202 # Put them in a list. The order is important so that we
203 # find things in the same order that Python finds them.
203 # find things in the same order that Python finds them.
204 namespaces = [ ('Interactive', self.shell.user_ns),
204 namespaces = [ ('Interactive', self.shell.user_ns),
205 ('IPython internal', self.shell.internal_ns),
205 ('IPython internal', self.shell.internal_ns),
206 ('Python builtin', __builtin__.__dict__),
206 ('Python builtin', __builtin__.__dict__),
207 ('Alias', self.shell.alias_table),
207 ('Alias', self.shell.alias_table),
208 ]
208 ]
209 alias_ns = self.shell.alias_table
209 alias_ns = self.shell.alias_table
210
210
211 # initialize results to 'null'
211 # initialize results to 'null'
212 found = 0; obj = None; ospace = None; ds = None;
212 found = 0; obj = None; ospace = None; ds = None;
213 ismagic = 0; isalias = 0; parent = None
213 ismagic = 0; isalias = 0; parent = None
214
214
215 # Look for the given name by splitting it in parts. If the head is
215 # Look for the given name by splitting it in parts. If the head is
216 # found, then we look for all the remaining parts as members, and only
216 # found, then we look for all the remaining parts as members, and only
217 # declare success if we can find them all.
217 # declare success if we can find them all.
218 oname_parts = oname.split('.')
218 oname_parts = oname.split('.')
219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
220 for nsname,ns in namespaces:
220 for nsname,ns in namespaces:
221 try:
221 try:
222 obj = ns[oname_head]
222 obj = ns[oname_head]
223 except KeyError:
223 except KeyError:
224 continue
224 continue
225 else:
225 else:
226 #print 'oname_rest:', oname_rest # dbg
226 #print 'oname_rest:', oname_rest # dbg
227 for part in oname_rest:
227 for part in oname_rest:
228 try:
228 try:
229 parent = obj
229 parent = obj
230 obj = getattr(obj,part)
230 obj = getattr(obj,part)
231 except:
231 except:
232 # Blanket except b/c some badly implemented objects
232 # Blanket except b/c some badly implemented objects
233 # allow __getattr__ to raise exceptions other than
233 # allow __getattr__ to raise exceptions other than
234 # AttributeError, which then crashes IPython.
234 # AttributeError, which then crashes IPython.
235 break
235 break
236 else:
236 else:
237 # If we finish the for loop (no break), we got all members
237 # If we finish the for loop (no break), we got all members
238 found = 1
238 found = 1
239 ospace = nsname
239 ospace = nsname
240 if ns == alias_ns:
240 if ns == alias_ns:
241 isalias = 1
241 isalias = 1
242 break # namespace loop
242 break # namespace loop
243
243
244 # Try to see if it's magic
244 # Try to see if it's magic
245 if not found:
245 if not found:
246 if oname.startswith(self.shell.ESC_MAGIC):
246 if oname.startswith(self.shell.ESC_MAGIC):
247 oname = oname[1:]
247 oname = oname[1:]
248 obj = getattr(self,'magic_'+oname,None)
248 obj = getattr(self,'magic_'+oname,None)
249 if obj is not None:
249 if obj is not None:
250 found = 1
250 found = 1
251 ospace = 'IPython internal'
251 ospace = 'IPython internal'
252 ismagic = 1
252 ismagic = 1
253
253
254 # Last try: special-case some literals like '', [], {}, etc:
254 # Last try: special-case some literals like '', [], {}, etc:
255 if not found and oname_head in ["''",'""','[]','{}','()']:
255 if not found and oname_head in ["''",'""','[]','{}','()']:
256 obj = eval(oname_head)
256 obj = eval(oname_head)
257 found = 1
257 found = 1
258 ospace = 'Interactive'
258 ospace = 'Interactive'
259
259
260 return {'found':found, 'obj':obj, 'namespace':ospace,
260 return {'found':found, 'obj':obj, 'namespace':ospace,
261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
262
262
263 def arg_err(self,func):
263 def arg_err(self,func):
264 """Print docstring if incorrect arguments were passed"""
264 """Print docstring if incorrect arguments were passed"""
265 print 'Error in arguments:'
265 print 'Error in arguments:'
266 print OInspect.getdoc(func)
266 print OInspect.getdoc(func)
267
267
268 def format_latex(self,strng):
268 def format_latex(self,strng):
269 """Format a string for latex inclusion."""
269 """Format a string for latex inclusion."""
270
270
271 # Characters that need to be escaped for latex:
271 # Characters that need to be escaped for latex:
272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
273 # Magic command names as headers:
273 # Magic command names as headers:
274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
275 re.MULTILINE)
275 re.MULTILINE)
276 # Magic commands
276 # Magic commands
277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
278 re.MULTILINE)
278 re.MULTILINE)
279 # Paragraph continue
279 # Paragraph continue
280 par_re = re.compile(r'\\$',re.MULTILINE)
280 par_re = re.compile(r'\\$',re.MULTILINE)
281
281
282 # The "\n" symbol
282 # The "\n" symbol
283 newline_re = re.compile(r'\\n')
283 newline_re = re.compile(r'\\n')
284
284
285 # Now build the string for output:
285 # Now build the string for output:
286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
288 strng)
288 strng)
289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
290 strng = par_re.sub(r'\\\\',strng)
290 strng = par_re.sub(r'\\\\',strng)
291 strng = escape_re.sub(r'\\\1',strng)
291 strng = escape_re.sub(r'\\\1',strng)
292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
293 return strng
293 return strng
294
294
295 def format_screen(self,strng):
295 def format_screen(self,strng):
296 """Format a string for screen printing.
296 """Format a string for screen printing.
297
297
298 This removes some latex-type format codes."""
298 This removes some latex-type format codes."""
299 # Paragraph continue
299 # Paragraph continue
300 par_re = re.compile(r'\\$',re.MULTILINE)
300 par_re = re.compile(r'\\$',re.MULTILINE)
301 strng = par_re.sub('',strng)
301 strng = par_re.sub('',strng)
302 return strng
302 return strng
303
303
304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
305 """Parse options passed to an argument string.
305 """Parse options passed to an argument string.
306
306
307 The interface is similar to that of getopt(), but it returns back a
307 The interface is similar to that of getopt(), but it returns back a
308 Struct with the options as keys and the stripped argument string still
308 Struct with the options as keys and the stripped argument string still
309 as a string.
309 as a string.
310
310
311 arg_str is quoted as a true sys.argv vector by using shlex.split.
311 arg_str is quoted as a true sys.argv vector by using shlex.split.
312 This allows us to easily expand variables, glob files, quote
312 This allows us to easily expand variables, glob files, quote
313 arguments, etc.
313 arguments, etc.
314
314
315 Options:
315 Options:
316 -mode: default 'string'. If given as 'list', the argument string is
316 -mode: default 'string'. If given as 'list', the argument string is
317 returned as a list (split on whitespace) instead of a string.
317 returned as a list (split on whitespace) instead of a string.
318
318
319 -list_all: put all option values in lists. Normally only options
319 -list_all: put all option values in lists. Normally only options
320 appearing more than once are put in a list.
320 appearing more than once are put in a list.
321
321
322 -posix (True): whether to split the input line in POSIX mode or not,
322 -posix (True): whether to split the input line in POSIX mode or not,
323 as per the conventions outlined in the shlex module from the
323 as per the conventions outlined in the shlex module from the
324 standard library."""
324 standard library."""
325
325
326 # inject default options at the beginning of the input line
326 # inject default options at the beginning of the input line
327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
329
329
330 mode = kw.get('mode','string')
330 mode = kw.get('mode','string')
331 if mode not in ['string','list']:
331 if mode not in ['string','list']:
332 raise ValueError,'incorrect mode given: %s' % mode
332 raise ValueError,'incorrect mode given: %s' % mode
333 # Get options
333 # Get options
334 list_all = kw.get('list_all',0)
334 list_all = kw.get('list_all',0)
335 posix = kw.get('posix',True)
335 posix = kw.get('posix',True)
336
336
337 # Check if we have more than one argument to warrant extra processing:
337 # Check if we have more than one argument to warrant extra processing:
338 odict = {} # Dictionary with options
338 odict = {} # Dictionary with options
339 args = arg_str.split()
339 args = arg_str.split()
340 if len(args) >= 1:
340 if len(args) >= 1:
341 # If the list of inputs only has 0 or 1 thing in it, there's no
341 # If the list of inputs only has 0 or 1 thing in it, there's no
342 # need to look for options
342 # need to look for options
343 argv = arg_split(arg_str,posix)
343 argv = arg_split(arg_str,posix)
344 # Do regular option processing
344 # Do regular option processing
345 try:
345 try:
346 opts,args = getopt(argv,opt_str,*long_opts)
346 opts,args = getopt(argv,opt_str,*long_opts)
347 except GetoptError,e:
347 except GetoptError,e:
348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
349 " ".join(long_opts)))
349 " ".join(long_opts)))
350 for o,a in opts:
350 for o,a in opts:
351 if o.startswith('--'):
351 if o.startswith('--'):
352 o = o[2:]
352 o = o[2:]
353 else:
353 else:
354 o = o[1:]
354 o = o[1:]
355 try:
355 try:
356 odict[o].append(a)
356 odict[o].append(a)
357 except AttributeError:
357 except AttributeError:
358 odict[o] = [odict[o],a]
358 odict[o] = [odict[o],a]
359 except KeyError:
359 except KeyError:
360 if list_all:
360 if list_all:
361 odict[o] = [a]
361 odict[o] = [a]
362 else:
362 else:
363 odict[o] = a
363 odict[o] = a
364
364
365 # Prepare opts,args for return
365 # Prepare opts,args for return
366 opts = Struct(odict)
366 opts = Struct(odict)
367 if mode == 'string':
367 if mode == 'string':
368 args = ' '.join(args)
368 args = ' '.join(args)
369
369
370 return opts,args
370 return opts,args
371
371
372 #......................................................................
372 #......................................................................
373 # And now the actual magic functions
373 # And now the actual magic functions
374
374
375 # Functions for IPython shell work (vars,funcs, config, etc)
375 # Functions for IPython shell work (vars,funcs, config, etc)
376 def magic_lsmagic(self, parameter_s = ''):
376 def magic_lsmagic(self, parameter_s = ''):
377 """List currently available magic functions."""
377 """List currently available magic functions."""
378 mesc = self.shell.ESC_MAGIC
378 mesc = self.shell.ESC_MAGIC
379 print 'Available magic functions:\n'+mesc+\
379 print 'Available magic functions:\n'+mesc+\
380 (' '+mesc).join(self.lsmagic())
380 (' '+mesc).join(self.lsmagic())
381 print '\n' + Magic.auto_status[self.shell.rc.automagic]
381 print '\n' + Magic.auto_status[self.shell.automagic]
382 return None
382 return None
383
383
384 def magic_magic(self, parameter_s = ''):
384 def magic_magic(self, parameter_s = ''):
385 """Print information about the magic function system.
385 """Print information about the magic function system.
386
386
387 Supported formats: -latex, -brief, -rest
387 Supported formats: -latex, -brief, -rest
388 """
388 """
389
389
390 mode = ''
390 mode = ''
391 try:
391 try:
392 if parameter_s.split()[0] == '-latex':
392 if parameter_s.split()[0] == '-latex':
393 mode = 'latex'
393 mode = 'latex'
394 if parameter_s.split()[0] == '-brief':
394 if parameter_s.split()[0] == '-brief':
395 mode = 'brief'
395 mode = 'brief'
396 if parameter_s.split()[0] == '-rest':
396 if parameter_s.split()[0] == '-rest':
397 mode = 'rest'
397 mode = 'rest'
398 rest_docs = []
398 rest_docs = []
399 except:
399 except:
400 pass
400 pass
401
401
402 magic_docs = []
402 magic_docs = []
403 for fname in self.lsmagic():
403 for fname in self.lsmagic():
404 mname = 'magic_' + fname
404 mname = 'magic_' + fname
405 for space in (Magic,self,self.__class__):
405 for space in (Magic,self,self.__class__):
406 try:
406 try:
407 fn = space.__dict__[mname]
407 fn = space.__dict__[mname]
408 except KeyError:
408 except KeyError:
409 pass
409 pass
410 else:
410 else:
411 break
411 break
412 if mode == 'brief':
412 if mode == 'brief':
413 # only first line
413 # only first line
414 if fn.__doc__:
414 if fn.__doc__:
415 fndoc = fn.__doc__.split('\n',1)[0]
415 fndoc = fn.__doc__.split('\n',1)[0]
416 else:
416 else:
417 fndoc = 'No documentation'
417 fndoc = 'No documentation'
418 else:
418 else:
419 if fn.__doc__:
419 if fn.__doc__:
420 fndoc = fn.__doc__.rstrip()
420 fndoc = fn.__doc__.rstrip()
421 else:
421 else:
422 fndoc = 'No documentation'
422 fndoc = 'No documentation'
423
423
424
424
425 if mode == 'rest':
425 if mode == 'rest':
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
427 fname,fndoc))
427 fname,fndoc))
428
428
429 else:
429 else:
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
431 fname,fndoc))
431 fname,fndoc))
432
432
433 magic_docs = ''.join(magic_docs)
433 magic_docs = ''.join(magic_docs)
434
434
435 if mode == 'rest':
435 if mode == 'rest':
436 return "".join(rest_docs)
436 return "".join(rest_docs)
437
437
438 if mode == 'latex':
438 if mode == 'latex':
439 print self.format_latex(magic_docs)
439 print self.format_latex(magic_docs)
440 return
440 return
441 else:
441 else:
442 magic_docs = self.format_screen(magic_docs)
442 magic_docs = self.format_screen(magic_docs)
443 if mode == 'brief':
443 if mode == 'brief':
444 return magic_docs
444 return magic_docs
445
445
446 outmsg = """
446 outmsg = """
447 IPython's 'magic' functions
447 IPython's 'magic' functions
448 ===========================
448 ===========================
449
449
450 The magic function system provides a series of functions which allow you to
450 The magic function system provides a series of functions which allow you to
451 control the behavior of IPython itself, plus a lot of system-type
451 control the behavior of IPython itself, plus a lot of system-type
452 features. All these functions are prefixed with a % character, but parameters
452 features. All these functions are prefixed with a % character, but parameters
453 are given without parentheses or quotes.
453 are given without parentheses or quotes.
454
454
455 NOTE: If you have 'automagic' enabled (via the command line option or with the
455 NOTE: If you have 'automagic' enabled (via the command line option or with the
456 %automagic function), you don't need to type in the % explicitly. By default,
456 %automagic function), you don't need to type in the % explicitly. By default,
457 IPython ships with automagic on, so you should only rarely need the % escape.
457 IPython ships with automagic on, so you should only rarely need the % escape.
458
458
459 Example: typing '%cd mydir' (without the quotes) changes you working directory
459 Example: typing '%cd mydir' (without the quotes) changes you working directory
460 to 'mydir', if it exists.
460 to 'mydir', if it exists.
461
461
462 You can define your own magic functions to extend the system. See the supplied
462 You can define your own magic functions to extend the system. See the supplied
463 ipythonrc and example-magic.py files for details (in your ipython
463 ipythonrc and example-magic.py files for details (in your ipython
464 configuration directory, typically $HOME/.ipython/).
464 configuration directory, typically $HOME/.ipython/).
465
465
466 You can also define your own aliased names for magic functions. In your
466 You can also define your own aliased names for magic functions. In your
467 ipythonrc file, placing a line like:
467 ipythonrc file, placing a line like:
468
468
469 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
469 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
470
470
471 will define %pf as a new name for %profile.
471 will define %pf as a new name for %profile.
472
472
473 You can also call magics in code using the ipmagic() function, which IPython
473 You can also call magics in code using the ipmagic() function, which IPython
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
475
475
476 For a list of the available magic functions, use %lsmagic. For a description
476 For a list of the available magic functions, use %lsmagic. For a description
477 of any of them, type %magic_name?, e.g. '%cd?'.
477 of any of them, type %magic_name?, e.g. '%cd?'.
478
478
479 Currently the magic system has the following functions:\n"""
479 Currently the magic system has the following functions:\n"""
480
480
481 mesc = self.shell.ESC_MAGIC
481 mesc = self.shell.ESC_MAGIC
482 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
483 "\n\n%s%s\n\n%s" % (outmsg,
483 "\n\n%s%s\n\n%s" % (outmsg,
484 magic_docs,mesc,mesc,
484 magic_docs,mesc,mesc,
485 (' '+mesc).join(self.lsmagic()),
485 (' '+mesc).join(self.lsmagic()),
486 Magic.auto_status[self.shell.rc.automagic] ) )
486 Magic.auto_status[self.shell.automagic] ) )
487
487
488 page(outmsg,screen_lines=self.shell.rc.screen_length)
488 page(outmsg,screen_lines=self.shell.screen_length)
489
489
490
490
491 def magic_autoindent(self, parameter_s = ''):
491 def magic_autoindent(self, parameter_s = ''):
492 """Toggle autoindent on/off (if available)."""
492 """Toggle autoindent on/off (if available)."""
493
493
494 self.shell.set_autoindent()
494 self.shell.set_autoindent()
495 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
495 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
496
496
497
497
498 def magic_automagic(self, parameter_s = ''):
498 def magic_automagic(self, parameter_s = ''):
499 """Make magic functions callable without having to type the initial %.
499 """Make magic functions callable without having to type the initial %.
500
500
501 Without argumentsl toggles on/off (when off, you must call it as
501 Without argumentsl toggles on/off (when off, you must call it as
502 %automagic, of course). With arguments it sets the value, and you can
502 %automagic, of course). With arguments it sets the value, and you can
503 use any of (case insensitive):
503 use any of (case insensitive):
504
504
505 - on,1,True: to activate
505 - on,1,True: to activate
506
506
507 - off,0,False: to deactivate.
507 - off,0,False: to deactivate.
508
508
509 Note that magic functions have lowest priority, so if there's a
509 Note that magic functions have lowest priority, so if there's a
510 variable whose name collides with that of a magic fn, automagic won't
510 variable whose name collides with that of a magic fn, automagic won't
511 work for that function (you get the variable instead). However, if you
511 work for that function (you get the variable instead). However, if you
512 delete the variable (del var), the previously shadowed magic function
512 delete the variable (del var), the previously shadowed magic function
513 becomes visible to automagic again."""
513 becomes visible to automagic again."""
514
514
515 rc = self.shell.rc
516 arg = parameter_s.lower()
515 arg = parameter_s.lower()
517 if parameter_s in ('on','1','true'):
516 if parameter_s in ('on','1','true'):
518 rc.automagic = True
517 self.shell.automagic = True
519 elif parameter_s in ('off','0','false'):
518 elif parameter_s in ('off','0','false'):
520 rc.automagic = False
519 self.shell.automagic = False
521 else:
520 else:
522 rc.automagic = not rc.automagic
521 self.shell.automagic = not self.shell.automagic
523 print '\n' + Magic.auto_status[rc.automagic]
522 print '\n' + Magic.auto_status[self.shell.automagic]
524
523
525 @testdec.skip_doctest
524 @testdec.skip_doctest
526 def magic_autocall(self, parameter_s = ''):
525 def magic_autocall(self, parameter_s = ''):
527 """Make functions callable without having to type parentheses.
526 """Make functions callable without having to type parentheses.
528
527
529 Usage:
528 Usage:
530
529
531 %autocall [mode]
530 %autocall [mode]
532
531
533 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
534 value is toggled on and off (remembering the previous state).
533 value is toggled on and off (remembering the previous state).
535
534
536 In more detail, these values mean:
535 In more detail, these values mean:
537
536
538 0 -> fully disabled
537 0 -> fully disabled
539
538
540 1 -> active, but do not apply if there are no arguments on the line.
539 1 -> active, but do not apply if there are no arguments on the line.
541
540
542 In this mode, you get:
541 In this mode, you get:
543
542
544 In [1]: callable
543 In [1]: callable
545 Out[1]: <built-in function callable>
544 Out[1]: <built-in function callable>
546
545
547 In [2]: callable 'hello'
546 In [2]: callable 'hello'
548 ------> callable('hello')
547 ------> callable('hello')
549 Out[2]: False
548 Out[2]: False
550
549
551 2 -> Active always. Even if no arguments are present, the callable
550 2 -> Active always. Even if no arguments are present, the callable
552 object is called:
551 object is called:
553
552
554 In [2]: float
553 In [2]: float
555 ------> float()
554 ------> float()
556 Out[2]: 0.0
555 Out[2]: 0.0
557
556
558 Note that even with autocall off, you can still use '/' at the start of
557 Note that even with autocall off, you can still use '/' at the start of
559 a line to treat the first argument on the command line as a function
558 a line to treat the first argument on the command line as a function
560 and add parentheses to it:
559 and add parentheses to it:
561
560
562 In [8]: /str 43
561 In [8]: /str 43
563 ------> str(43)
562 ------> str(43)
564 Out[8]: '43'
563 Out[8]: '43'
565
564
566 # all-random (note for auto-testing)
565 # all-random (note for auto-testing)
567 """
566 """
568
567
569 rc = self.shell.rc
570
571 if parameter_s:
568 if parameter_s:
572 arg = int(parameter_s)
569 arg = int(parameter_s)
573 else:
570 else:
574 arg = 'toggle'
571 arg = 'toggle'
575
572
576 if not arg in (0,1,2,'toggle'):
573 if not arg in (0,1,2,'toggle'):
577 error('Valid modes: (0->Off, 1->Smart, 2->Full')
574 error('Valid modes: (0->Off, 1->Smart, 2->Full')
578 return
575 return
579
576
580 if arg in (0,1,2):
577 if arg in (0,1,2):
581 rc.autocall = arg
578 self.shell.autocall = arg
582 else: # toggle
579 else: # toggle
583 if rc.autocall:
580 if self.shell.autocall:
584 self._magic_state.autocall_save = rc.autocall
581 self._magic_state.autocall_save = self.shell.autocall
585 rc.autocall = 0
582 self.shell.autocall = 0
586 else:
583 else:
587 try:
584 try:
588 rc.autocall = self._magic_state.autocall_save
585 self.shell.autocall = self._magic_state.autocall_save
589 except AttributeError:
586 except AttributeError:
590 rc.autocall = self._magic_state.autocall_save = 1
587 self.shell.autocall = self._magic_state.autocall_save = 1
591
588
592 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
589 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
593
590
594 def magic_system_verbose(self, parameter_s = ''):
591 def magic_system_verbose(self, parameter_s = ''):
595 """Set verbose printing of system calls.
592 """Set verbose printing of system calls.
596
593
597 If called without an argument, act as a toggle"""
594 If called without an argument, act as a toggle"""
598
595
599 if parameter_s:
596 if parameter_s:
600 val = bool(eval(parameter_s))
597 val = bool(eval(parameter_s))
601 else:
598 else:
602 val = None
599 val = None
603
600
604 self.shell.rc_set_toggle('system_verbose',val)
601 if self.shell.system_verbose:
602 self.shell.system_verbose = False
603 else:
604 self.shell.system_verbose = True
605 print "System verbose printing is:",\
605 print "System verbose printing is:",\
606 ['OFF','ON'][self.shell.rc.system_verbose]
606 ['OFF','ON'][self.shell.system_verbose]
607
607
608
608
609 def magic_page(self, parameter_s=''):
609 def magic_page(self, parameter_s=''):
610 """Pretty print the object and display it through a pager.
610 """Pretty print the object and display it through a pager.
611
611
612 %page [options] OBJECT
612 %page [options] OBJECT
613
613
614 If no object is given, use _ (last output).
614 If no object is given, use _ (last output).
615
615
616 Options:
616 Options:
617
617
618 -r: page str(object), don't pretty-print it."""
618 -r: page str(object), don't pretty-print it."""
619
619
620 # After a function contributed by Olivier Aubert, slightly modified.
620 # After a function contributed by Olivier Aubert, slightly modified.
621
621
622 # Process options/args
622 # Process options/args
623 opts,args = self.parse_options(parameter_s,'r')
623 opts,args = self.parse_options(parameter_s,'r')
624 raw = 'r' in opts
624 raw = 'r' in opts
625
625
626 oname = args and args or '_'
626 oname = args and args or '_'
627 info = self._ofind(oname)
627 info = self._ofind(oname)
628 if info['found']:
628 if info['found']:
629 txt = (raw and str or pformat)( info['obj'] )
629 txt = (raw and str or pformat)( info['obj'] )
630 page(txt)
630 page(txt)
631 else:
631 else:
632 print 'Object `%s` not found' % oname
632 print 'Object `%s` not found' % oname
633
633
634 def magic_profile(self, parameter_s=''):
634 def magic_profile(self, parameter_s=''):
635 """Print your currently active IPyhton profile."""
635 """Print your currently active IPyhton profile."""
636 if self.shell.rc.profile:
636 if self.shell.profile:
637 printpl('Current IPython profile: $self.shell.rc.profile.')
637 printpl('Current IPython profile: $self.shell.profile.')
638 else:
638 else:
639 print 'No profile active.'
639 print 'No profile active.'
640
640
641 def magic_pinfo(self, parameter_s='', namespaces=None):
641 def magic_pinfo(self, parameter_s='', namespaces=None):
642 """Provide detailed information about an object.
642 """Provide detailed information about an object.
643
643
644 '%pinfo object' is just a synonym for object? or ?object."""
644 '%pinfo object' is just a synonym for object? or ?object."""
645
645
646 #print 'pinfo par: <%s>' % parameter_s # dbg
646 #print 'pinfo par: <%s>' % parameter_s # dbg
647
647
648
648
649 # detail_level: 0 -> obj? , 1 -> obj??
649 # detail_level: 0 -> obj? , 1 -> obj??
650 detail_level = 0
650 detail_level = 0
651 # We need to detect if we got called as 'pinfo pinfo foo', which can
651 # We need to detect if we got called as 'pinfo pinfo foo', which can
652 # happen if the user types 'pinfo foo?' at the cmd line.
652 # happen if the user types 'pinfo foo?' at the cmd line.
653 pinfo,qmark1,oname,qmark2 = \
653 pinfo,qmark1,oname,qmark2 = \
654 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
654 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
655 if pinfo or qmark1 or qmark2:
655 if pinfo or qmark1 or qmark2:
656 detail_level = 1
656 detail_level = 1
657 if "*" in oname:
657 if "*" in oname:
658 self.magic_psearch(oname)
658 self.magic_psearch(oname)
659 else:
659 else:
660 self._inspect('pinfo', oname, detail_level=detail_level,
660 self._inspect('pinfo', oname, detail_level=detail_level,
661 namespaces=namespaces)
661 namespaces=namespaces)
662
662
663 def magic_pdef(self, parameter_s='', namespaces=None):
663 def magic_pdef(self, parameter_s='', namespaces=None):
664 """Print the definition header for any callable object.
664 """Print the definition header for any callable object.
665
665
666 If the object is a class, print the constructor information."""
666 If the object is a class, print the constructor information."""
667 self._inspect('pdef',parameter_s, namespaces)
667 self._inspect('pdef',parameter_s, namespaces)
668
668
669 def magic_pdoc(self, parameter_s='', namespaces=None):
669 def magic_pdoc(self, parameter_s='', namespaces=None):
670 """Print the docstring for an object.
670 """Print the docstring for an object.
671
671
672 If the given object is a class, it will print both the class and the
672 If the given object is a class, it will print both the class and the
673 constructor docstrings."""
673 constructor docstrings."""
674 self._inspect('pdoc',parameter_s, namespaces)
674 self._inspect('pdoc',parameter_s, namespaces)
675
675
676 def magic_psource(self, parameter_s='', namespaces=None):
676 def magic_psource(self, parameter_s='', namespaces=None):
677 """Print (or run through pager) the source code for an object."""
677 """Print (or run through pager) the source code for an object."""
678 self._inspect('psource',parameter_s, namespaces)
678 self._inspect('psource',parameter_s, namespaces)
679
679
680 def magic_pfile(self, parameter_s=''):
680 def magic_pfile(self, parameter_s=''):
681 """Print (or run through pager) the file where an object is defined.
681 """Print (or run through pager) the file where an object is defined.
682
682
683 The file opens at the line where the object definition begins. IPython
683 The file opens at the line where the object definition begins. IPython
684 will honor the environment variable PAGER if set, and otherwise will
684 will honor the environment variable PAGER if set, and otherwise will
685 do its best to print the file in a convenient form.
685 do its best to print the file in a convenient form.
686
686
687 If the given argument is not an object currently defined, IPython will
687 If the given argument is not an object currently defined, IPython will
688 try to interpret it as a filename (automatically adding a .py extension
688 try to interpret it as a filename (automatically adding a .py extension
689 if needed). You can thus use %pfile as a syntax highlighting code
689 if needed). You can thus use %pfile as a syntax highlighting code
690 viewer."""
690 viewer."""
691
691
692 # first interpret argument as an object name
692 # first interpret argument as an object name
693 out = self._inspect('pfile',parameter_s)
693 out = self._inspect('pfile',parameter_s)
694 # if not, try the input as a filename
694 # if not, try the input as a filename
695 if out == 'not found':
695 if out == 'not found':
696 try:
696 try:
697 filename = get_py_filename(parameter_s)
697 filename = get_py_filename(parameter_s)
698 except IOError,msg:
698 except IOError,msg:
699 print msg
699 print msg
700 return
700 return
701 page(self.shell.inspector.format(file(filename).read()))
701 page(self.shell.inspector.format(file(filename).read()))
702
702
703 def _inspect(self,meth,oname,namespaces=None,**kw):
703 def _inspect(self,meth,oname,namespaces=None,**kw):
704 """Generic interface to the inspector system.
704 """Generic interface to the inspector system.
705
705
706 This function is meant to be called by pdef, pdoc & friends."""
706 This function is meant to be called by pdef, pdoc & friends."""
707
707
708 #oname = oname.strip()
708 #oname = oname.strip()
709 #print '1- oname: <%r>' % oname # dbg
709 #print '1- oname: <%r>' % oname # dbg
710 try:
710 try:
711 oname = oname.strip().encode('ascii')
711 oname = oname.strip().encode('ascii')
712 #print '2- oname: <%r>' % oname # dbg
712 #print '2- oname: <%r>' % oname # dbg
713 except UnicodeEncodeError:
713 except UnicodeEncodeError:
714 print 'Python identifiers can only contain ascii characters.'
714 print 'Python identifiers can only contain ascii characters.'
715 return 'not found'
715 return 'not found'
716
716
717 info = Struct(self._ofind(oname, namespaces))
717 info = Struct(self._ofind(oname, namespaces))
718
718
719 if info.found:
719 if info.found:
720 try:
720 try:
721 IPython.utils.generics.inspect_object(info.obj)
721 IPython.utils.generics.inspect_object(info.obj)
722 return
722 return
723 except ipapi.TryNext:
723 except ipapi.TryNext:
724 pass
724 pass
725 # Get the docstring of the class property if it exists.
725 # Get the docstring of the class property if it exists.
726 path = oname.split('.')
726 path = oname.split('.')
727 root = '.'.join(path[:-1])
727 root = '.'.join(path[:-1])
728 if info.parent is not None:
728 if info.parent is not None:
729 try:
729 try:
730 target = getattr(info.parent, '__class__')
730 target = getattr(info.parent, '__class__')
731 # The object belongs to a class instance.
731 # The object belongs to a class instance.
732 try:
732 try:
733 target = getattr(target, path[-1])
733 target = getattr(target, path[-1])
734 # The class defines the object.
734 # The class defines the object.
735 if isinstance(target, property):
735 if isinstance(target, property):
736 oname = root + '.__class__.' + path[-1]
736 oname = root + '.__class__.' + path[-1]
737 info = Struct(self._ofind(oname))
737 info = Struct(self._ofind(oname))
738 except AttributeError: pass
738 except AttributeError: pass
739 except AttributeError: pass
739 except AttributeError: pass
740
740
741 pmethod = getattr(self.shell.inspector,meth)
741 pmethod = getattr(self.shell.inspector,meth)
742 formatter = info.ismagic and self.format_screen or None
742 formatter = info.ismagic and self.format_screen or None
743 if meth == 'pdoc':
743 if meth == 'pdoc':
744 pmethod(info.obj,oname,formatter)
744 pmethod(info.obj,oname,formatter)
745 elif meth == 'pinfo':
745 elif meth == 'pinfo':
746 pmethod(info.obj,oname,formatter,info,**kw)
746 pmethod(info.obj,oname,formatter,info,**kw)
747 else:
747 else:
748 pmethod(info.obj,oname)
748 pmethod(info.obj,oname)
749 else:
749 else:
750 print 'Object `%s` not found.' % oname
750 print 'Object `%s` not found.' % oname
751 return 'not found' # so callers can take other action
751 return 'not found' # so callers can take other action
752
752
753 def magic_psearch(self, parameter_s=''):
753 def magic_psearch(self, parameter_s=''):
754 """Search for object in namespaces by wildcard.
754 """Search for object in namespaces by wildcard.
755
755
756 %psearch [options] PATTERN [OBJECT TYPE]
756 %psearch [options] PATTERN [OBJECT TYPE]
757
757
758 Note: ? can be used as a synonym for %psearch, at the beginning or at
758 Note: ? can be used as a synonym for %psearch, at the beginning or at
759 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
759 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
760 rest of the command line must be unchanged (options come first), so
760 rest of the command line must be unchanged (options come first), so
761 for example the following forms are equivalent
761 for example the following forms are equivalent
762
762
763 %psearch -i a* function
763 %psearch -i a* function
764 -i a* function?
764 -i a* function?
765 ?-i a* function
765 ?-i a* function
766
766
767 Arguments:
767 Arguments:
768
768
769 PATTERN
769 PATTERN
770
770
771 where PATTERN is a string containing * as a wildcard similar to its
771 where PATTERN is a string containing * as a wildcard similar to its
772 use in a shell. The pattern is matched in all namespaces on the
772 use in a shell. The pattern is matched in all namespaces on the
773 search path. By default objects starting with a single _ are not
773 search path. By default objects starting with a single _ are not
774 matched, many IPython generated objects have a single
774 matched, many IPython generated objects have a single
775 underscore. The default is case insensitive matching. Matching is
775 underscore. The default is case insensitive matching. Matching is
776 also done on the attributes of objects and not only on the objects
776 also done on the attributes of objects and not only on the objects
777 in a module.
777 in a module.
778
778
779 [OBJECT TYPE]
779 [OBJECT TYPE]
780
780
781 Is the name of a python type from the types module. The name is
781 Is the name of a python type from the types module. The name is
782 given in lowercase without the ending type, ex. StringType is
782 given in lowercase without the ending type, ex. StringType is
783 written string. By adding a type here only objects matching the
783 written string. By adding a type here only objects matching the
784 given type are matched. Using all here makes the pattern match all
784 given type are matched. Using all here makes the pattern match all
785 types (this is the default).
785 types (this is the default).
786
786
787 Options:
787 Options:
788
788
789 -a: makes the pattern match even objects whose names start with a
789 -a: makes the pattern match even objects whose names start with a
790 single underscore. These names are normally ommitted from the
790 single underscore. These names are normally ommitted from the
791 search.
791 search.
792
792
793 -i/-c: make the pattern case insensitive/sensitive. If neither of
793 -i/-c: make the pattern case insensitive/sensitive. If neither of
794 these options is given, the default is read from your ipythonrc
794 these options is given, the default is read from your ipythonrc
795 file. The option name which sets this value is
795 file. The option name which sets this value is
796 'wildcards_case_sensitive'. If this option is not specified in your
796 'wildcards_case_sensitive'. If this option is not specified in your
797 ipythonrc file, IPython's internal default is to do a case sensitive
797 ipythonrc file, IPython's internal default is to do a case sensitive
798 search.
798 search.
799
799
800 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
800 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
801 specifiy can be searched in any of the following namespaces:
801 specifiy can be searched in any of the following namespaces:
802 'builtin', 'user', 'user_global','internal', 'alias', where
802 'builtin', 'user', 'user_global','internal', 'alias', where
803 'builtin' and 'user' are the search defaults. Note that you should
803 'builtin' and 'user' are the search defaults. Note that you should
804 not use quotes when specifying namespaces.
804 not use quotes when specifying namespaces.
805
805
806 'Builtin' contains the python module builtin, 'user' contains all
806 'Builtin' contains the python module builtin, 'user' contains all
807 user data, 'alias' only contain the shell aliases and no python
807 user data, 'alias' only contain the shell aliases and no python
808 objects, 'internal' contains objects used by IPython. The
808 objects, 'internal' contains objects used by IPython. The
809 'user_global' namespace is only used by embedded IPython instances,
809 'user_global' namespace is only used by embedded IPython instances,
810 and it contains module-level globals. You can add namespaces to the
810 and it contains module-level globals. You can add namespaces to the
811 search with -s or exclude them with -e (these options can be given
811 search with -s or exclude them with -e (these options can be given
812 more than once).
812 more than once).
813
813
814 Examples:
814 Examples:
815
815
816 %psearch a* -> objects beginning with an a
816 %psearch a* -> objects beginning with an a
817 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
817 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
818 %psearch a* function -> all functions beginning with an a
818 %psearch a* function -> all functions beginning with an a
819 %psearch re.e* -> objects beginning with an e in module re
819 %psearch re.e* -> objects beginning with an e in module re
820 %psearch r*.e* -> objects that start with e in modules starting in r
820 %psearch r*.e* -> objects that start with e in modules starting in r
821 %psearch r*.* string -> all strings in modules beginning with r
821 %psearch r*.* string -> all strings in modules beginning with r
822
822
823 Case sensitve search:
823 Case sensitve search:
824
824
825 %psearch -c a* list all object beginning with lower case a
825 %psearch -c a* list all object beginning with lower case a
826
826
827 Show objects beginning with a single _:
827 Show objects beginning with a single _:
828
828
829 %psearch -a _* list objects beginning with a single underscore"""
829 %psearch -a _* list objects beginning with a single underscore"""
830 try:
830 try:
831 parameter_s = parameter_s.encode('ascii')
831 parameter_s = parameter_s.encode('ascii')
832 except UnicodeEncodeError:
832 except UnicodeEncodeError:
833 print 'Python identifiers can only contain ascii characters.'
833 print 'Python identifiers can only contain ascii characters.'
834 return
834 return
835
835
836 # default namespaces to be searched
836 # default namespaces to be searched
837 def_search = ['user','builtin']
837 def_search = ['user','builtin']
838
838
839 # Process options/args
839 # Process options/args
840 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
840 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
841 opt = opts.get
841 opt = opts.get
842 shell = self.shell
842 shell = self.shell
843 psearch = shell.inspector.psearch
843 psearch = shell.inspector.psearch
844
844
845 # select case options
845 # select case options
846 if opts.has_key('i'):
846 if opts.has_key('i'):
847 ignore_case = True
847 ignore_case = True
848 elif opts.has_key('c'):
848 elif opts.has_key('c'):
849 ignore_case = False
849 ignore_case = False
850 else:
850 else:
851 ignore_case = not shell.rc.wildcards_case_sensitive
851 ignore_case = not shell.wildcards_case_sensitive
852
852
853 # Build list of namespaces to search from user options
853 # Build list of namespaces to search from user options
854 def_search.extend(opt('s',[]))
854 def_search.extend(opt('s',[]))
855 ns_exclude = ns_exclude=opt('e',[])
855 ns_exclude = ns_exclude=opt('e',[])
856 ns_search = [nm for nm in def_search if nm not in ns_exclude]
856 ns_search = [nm for nm in def_search if nm not in ns_exclude]
857
857
858 # Call the actual search
858 # Call the actual search
859 try:
859 try:
860 psearch(args,shell.ns_table,ns_search,
860 psearch(args,shell.ns_table,ns_search,
861 show_all=opt('a'),ignore_case=ignore_case)
861 show_all=opt('a'),ignore_case=ignore_case)
862 except:
862 except:
863 shell.showtraceback()
863 shell.showtraceback()
864
864
865 def magic_who_ls(self, parameter_s=''):
865 def magic_who_ls(self, parameter_s=''):
866 """Return a sorted list of all interactive variables.
866 """Return a sorted list of all interactive variables.
867
867
868 If arguments are given, only variables of types matching these
868 If arguments are given, only variables of types matching these
869 arguments are returned."""
869 arguments are returned."""
870
870
871 user_ns = self.shell.user_ns
871 user_ns = self.shell.user_ns
872 internal_ns = self.shell.internal_ns
872 internal_ns = self.shell.internal_ns
873 user_config_ns = self.shell.user_config_ns
873 user_config_ns = self.shell.user_config_ns
874 out = []
874 out = []
875 typelist = parameter_s.split()
875 typelist = parameter_s.split()
876
876
877 for i in user_ns:
877 for i in user_ns:
878 if not (i.startswith('_') or i.startswith('_i')) \
878 if not (i.startswith('_') or i.startswith('_i')) \
879 and not (i in internal_ns or i in user_config_ns):
879 and not (i in internal_ns or i in user_config_ns):
880 if typelist:
880 if typelist:
881 if type(user_ns[i]).__name__ in typelist:
881 if type(user_ns[i]).__name__ in typelist:
882 out.append(i)
882 out.append(i)
883 else:
883 else:
884 out.append(i)
884 out.append(i)
885 out.sort()
885 out.sort()
886 return out
886 return out
887
887
888 def magic_who(self, parameter_s=''):
888 def magic_who(self, parameter_s=''):
889 """Print all interactive variables, with some minimal formatting.
889 """Print all interactive variables, with some minimal formatting.
890
890
891 If any arguments are given, only variables whose type matches one of
891 If any arguments are given, only variables whose type matches one of
892 these are printed. For example:
892 these are printed. For example:
893
893
894 %who function str
894 %who function str
895
895
896 will only list functions and strings, excluding all other types of
896 will only list functions and strings, excluding all other types of
897 variables. To find the proper type names, simply use type(var) at a
897 variables. To find the proper type names, simply use type(var) at a
898 command line to see how python prints type names. For example:
898 command line to see how python prints type names. For example:
899
899
900 In [1]: type('hello')\\
900 In [1]: type('hello')\\
901 Out[1]: <type 'str'>
901 Out[1]: <type 'str'>
902
902
903 indicates that the type name for strings is 'str'.
903 indicates that the type name for strings is 'str'.
904
904
905 %who always excludes executed names loaded through your configuration
905 %who always excludes executed names loaded through your configuration
906 file and things which are internal to IPython.
906 file and things which are internal to IPython.
907
907
908 This is deliberate, as typically you may load many modules and the
908 This is deliberate, as typically you may load many modules and the
909 purpose of %who is to show you only what you've manually defined."""
909 purpose of %who is to show you only what you've manually defined."""
910
910
911 varlist = self.magic_who_ls(parameter_s)
911 varlist = self.magic_who_ls(parameter_s)
912 if not varlist:
912 if not varlist:
913 if parameter_s:
913 if parameter_s:
914 print 'No variables match your requested type.'
914 print 'No variables match your requested type.'
915 else:
915 else:
916 print 'Interactive namespace is empty.'
916 print 'Interactive namespace is empty.'
917 return
917 return
918
918
919 # if we have variables, move on...
919 # if we have variables, move on...
920 count = 0
920 count = 0
921 for i in varlist:
921 for i in varlist:
922 print i+'\t',
922 print i+'\t',
923 count += 1
923 count += 1
924 if count > 8:
924 if count > 8:
925 count = 0
925 count = 0
926 print
926 print
927 print
927 print
928
928
929 def magic_whos(self, parameter_s=''):
929 def magic_whos(self, parameter_s=''):
930 """Like %who, but gives some extra information about each variable.
930 """Like %who, but gives some extra information about each variable.
931
931
932 The same type filtering of %who can be applied here.
932 The same type filtering of %who can be applied here.
933
933
934 For all variables, the type is printed. Additionally it prints:
934 For all variables, the type is printed. Additionally it prints:
935
935
936 - For {},[],(): their length.
936 - For {},[],(): their length.
937
937
938 - For numpy and Numeric arrays, a summary with shape, number of
938 - For numpy and Numeric arrays, a summary with shape, number of
939 elements, typecode and size in memory.
939 elements, typecode and size in memory.
940
940
941 - Everything else: a string representation, snipping their middle if
941 - Everything else: a string representation, snipping their middle if
942 too long."""
942 too long."""
943
943
944 varnames = self.magic_who_ls(parameter_s)
944 varnames = self.magic_who_ls(parameter_s)
945 if not varnames:
945 if not varnames:
946 if parameter_s:
946 if parameter_s:
947 print 'No variables match your requested type.'
947 print 'No variables match your requested type.'
948 else:
948 else:
949 print 'Interactive namespace is empty.'
949 print 'Interactive namespace is empty.'
950 return
950 return
951
951
952 # if we have variables, move on...
952 # if we have variables, move on...
953
953
954 # for these types, show len() instead of data:
954 # for these types, show len() instead of data:
955 seq_types = [types.DictType,types.ListType,types.TupleType]
955 seq_types = [types.DictType,types.ListType,types.TupleType]
956
956
957 # for numpy/Numeric arrays, display summary info
957 # for numpy/Numeric arrays, display summary info
958 try:
958 try:
959 import numpy
959 import numpy
960 except ImportError:
960 except ImportError:
961 ndarray_type = None
961 ndarray_type = None
962 else:
962 else:
963 ndarray_type = numpy.ndarray.__name__
963 ndarray_type = numpy.ndarray.__name__
964 try:
964 try:
965 import Numeric
965 import Numeric
966 except ImportError:
966 except ImportError:
967 array_type = None
967 array_type = None
968 else:
968 else:
969 array_type = Numeric.ArrayType.__name__
969 array_type = Numeric.ArrayType.__name__
970
970
971 # Find all variable names and types so we can figure out column sizes
971 # Find all variable names and types so we can figure out column sizes
972 def get_vars(i):
972 def get_vars(i):
973 return self.shell.user_ns[i]
973 return self.shell.user_ns[i]
974
974
975 # some types are well known and can be shorter
975 # some types are well known and can be shorter
976 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
976 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
977 def type_name(v):
977 def type_name(v):
978 tn = type(v).__name__
978 tn = type(v).__name__
979 return abbrevs.get(tn,tn)
979 return abbrevs.get(tn,tn)
980
980
981 varlist = map(get_vars,varnames)
981 varlist = map(get_vars,varnames)
982
982
983 typelist = []
983 typelist = []
984 for vv in varlist:
984 for vv in varlist:
985 tt = type_name(vv)
985 tt = type_name(vv)
986
986
987 if tt=='instance':
987 if tt=='instance':
988 typelist.append( abbrevs.get(str(vv.__class__),
988 typelist.append( abbrevs.get(str(vv.__class__),
989 str(vv.__class__)))
989 str(vv.__class__)))
990 else:
990 else:
991 typelist.append(tt)
991 typelist.append(tt)
992
992
993 # column labels and # of spaces as separator
993 # column labels and # of spaces as separator
994 varlabel = 'Variable'
994 varlabel = 'Variable'
995 typelabel = 'Type'
995 typelabel = 'Type'
996 datalabel = 'Data/Info'
996 datalabel = 'Data/Info'
997 colsep = 3
997 colsep = 3
998 # variable format strings
998 # variable format strings
999 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
999 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1000 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1000 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1001 aformat = "%s: %s elems, type `%s`, %s bytes"
1001 aformat = "%s: %s elems, type `%s`, %s bytes"
1002 # find the size of the columns to format the output nicely
1002 # find the size of the columns to format the output nicely
1003 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1003 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1004 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1004 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1005 # table header
1005 # table header
1006 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1006 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1007 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1007 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1008 # and the table itself
1008 # and the table itself
1009 kb = 1024
1009 kb = 1024
1010 Mb = 1048576 # kb**2
1010 Mb = 1048576 # kb**2
1011 for vname,var,vtype in zip(varnames,varlist,typelist):
1011 for vname,var,vtype in zip(varnames,varlist,typelist):
1012 print itpl(vformat),
1012 print itpl(vformat),
1013 if vtype in seq_types:
1013 if vtype in seq_types:
1014 print len(var)
1014 print len(var)
1015 elif vtype in [array_type,ndarray_type]:
1015 elif vtype in [array_type,ndarray_type]:
1016 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1016 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1017 if vtype==ndarray_type:
1017 if vtype==ndarray_type:
1018 # numpy
1018 # numpy
1019 vsize = var.size
1019 vsize = var.size
1020 vbytes = vsize*var.itemsize
1020 vbytes = vsize*var.itemsize
1021 vdtype = var.dtype
1021 vdtype = var.dtype
1022 else:
1022 else:
1023 # Numeric
1023 # Numeric
1024 vsize = Numeric.size(var)
1024 vsize = Numeric.size(var)
1025 vbytes = vsize*var.itemsize()
1025 vbytes = vsize*var.itemsize()
1026 vdtype = var.typecode()
1026 vdtype = var.typecode()
1027
1027
1028 if vbytes < 100000:
1028 if vbytes < 100000:
1029 print aformat % (vshape,vsize,vdtype,vbytes)
1029 print aformat % (vshape,vsize,vdtype,vbytes)
1030 else:
1030 else:
1031 print aformat % (vshape,vsize,vdtype,vbytes),
1031 print aformat % (vshape,vsize,vdtype,vbytes),
1032 if vbytes < Mb:
1032 if vbytes < Mb:
1033 print '(%s kb)' % (vbytes/kb,)
1033 print '(%s kb)' % (vbytes/kb,)
1034 else:
1034 else:
1035 print '(%s Mb)' % (vbytes/Mb,)
1035 print '(%s Mb)' % (vbytes/Mb,)
1036 else:
1036 else:
1037 try:
1037 try:
1038 vstr = str(var)
1038 vstr = str(var)
1039 except UnicodeEncodeError:
1039 except UnicodeEncodeError:
1040 vstr = unicode(var).encode(sys.getdefaultencoding(),
1040 vstr = unicode(var).encode(sys.getdefaultencoding(),
1041 'backslashreplace')
1041 'backslashreplace')
1042 vstr = vstr.replace('\n','\\n')
1042 vstr = vstr.replace('\n','\\n')
1043 if len(vstr) < 50:
1043 if len(vstr) < 50:
1044 print vstr
1044 print vstr
1045 else:
1045 else:
1046 printpl(vfmt_short)
1046 printpl(vfmt_short)
1047
1047
1048 def magic_reset(self, parameter_s=''):
1048 def magic_reset(self, parameter_s=''):
1049 """Resets the namespace by removing all names defined by the user.
1049 """Resets the namespace by removing all names defined by the user.
1050
1050
1051 Input/Output history are left around in case you need them.
1051 Input/Output history are left around in case you need them.
1052
1052
1053 Parameters
1053 Parameters
1054 ----------
1054 ----------
1055 -y : force reset without asking for confirmation.
1055 -y : force reset without asking for confirmation.
1056
1056
1057 Examples
1057 Examples
1058 --------
1058 --------
1059 In [6]: a = 1
1059 In [6]: a = 1
1060
1060
1061 In [7]: a
1061 In [7]: a
1062 Out[7]: 1
1062 Out[7]: 1
1063
1063
1064 In [8]: 'a' in _ip.user_ns
1064 In [8]: 'a' in _ip.user_ns
1065 Out[8]: True
1065 Out[8]: True
1066
1066
1067 In [9]: %reset -f
1067 In [9]: %reset -f
1068
1068
1069 In [10]: 'a' in _ip.user_ns
1069 In [10]: 'a' in _ip.user_ns
1070 Out[10]: False
1070 Out[10]: False
1071 """
1071 """
1072
1072
1073 if parameter_s == '-f':
1073 if parameter_s == '-f':
1074 ans = True
1074 ans = True
1075 else:
1075 else:
1076 ans = self.shell.ask_yes_no(
1076 ans = self.shell.ask_yes_no(
1077 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1077 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1078 if not ans:
1078 if not ans:
1079 print 'Nothing done.'
1079 print 'Nothing done.'
1080 return
1080 return
1081 user_ns = self.shell.user_ns
1081 user_ns = self.shell.user_ns
1082 for i in self.magic_who_ls():
1082 for i in self.magic_who_ls():
1083 del(user_ns[i])
1083 del(user_ns[i])
1084
1084
1085 # Also flush the private list of module references kept for script
1085 # Also flush the private list of module references kept for script
1086 # execution protection
1086 # execution protection
1087 self.shell.clear_main_mod_cache()
1087 self.shell.clear_main_mod_cache()
1088
1088
1089 def magic_logstart(self,parameter_s=''):
1089 def magic_logstart(self,parameter_s=''):
1090 """Start logging anywhere in a session.
1090 """Start logging anywhere in a session.
1091
1091
1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1093
1093
1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1095 current directory, in 'rotate' mode (see below).
1095 current directory, in 'rotate' mode (see below).
1096
1096
1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1098 history up to that point and then continues logging.
1098 history up to that point and then continues logging.
1099
1099
1100 %logstart takes a second optional parameter: logging mode. This can be one
1100 %logstart takes a second optional parameter: logging mode. This can be one
1101 of (note that the modes are given unquoted):\\
1101 of (note that the modes are given unquoted):\\
1102 append: well, that says it.\\
1102 append: well, that says it.\\
1103 backup: rename (if exists) to name~ and start name.\\
1103 backup: rename (if exists) to name~ and start name.\\
1104 global: single logfile in your home dir, appended to.\\
1104 global: single logfile in your home dir, appended to.\\
1105 over : overwrite existing log.\\
1105 over : overwrite existing log.\\
1106 rotate: create rotating logs name.1~, name.2~, etc.
1106 rotate: create rotating logs name.1~, name.2~, etc.
1107
1107
1108 Options:
1108 Options:
1109
1109
1110 -o: log also IPython's output. In this mode, all commands which
1110 -o: log also IPython's output. In this mode, all commands which
1111 generate an Out[NN] prompt are recorded to the logfile, right after
1111 generate an Out[NN] prompt are recorded to the logfile, right after
1112 their corresponding input line. The output lines are always
1112 their corresponding input line. The output lines are always
1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1114 Python code.
1114 Python code.
1115
1115
1116 Since this marker is always the same, filtering only the output from
1116 Since this marker is always the same, filtering only the output from
1117 a log is very easy, using for example a simple awk call:
1117 a log is very easy, using for example a simple awk call:
1118
1118
1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1120
1120
1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1122 input, so that user lines are logged in their final form, converted
1122 input, so that user lines are logged in their final form, converted
1123 into valid Python. For example, %Exit is logged as
1123 into valid Python. For example, %Exit is logged as
1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1125 exactly as typed, with no transformations applied.
1125 exactly as typed, with no transformations applied.
1126
1126
1127 -t: put timestamps before each input line logged (these are put in
1127 -t: put timestamps before each input line logged (these are put in
1128 comments)."""
1128 comments)."""
1129
1129
1130 opts,par = self.parse_options(parameter_s,'ort')
1130 opts,par = self.parse_options(parameter_s,'ort')
1131 log_output = 'o' in opts
1131 log_output = 'o' in opts
1132 log_raw_input = 'r' in opts
1132 log_raw_input = 'r' in opts
1133 timestamp = 't' in opts
1133 timestamp = 't' in opts
1134
1134
1135 rc = self.shell.rc
1136 logger = self.shell.logger
1135 logger = self.shell.logger
1137
1136
1138 # if no args are given, the defaults set in the logger constructor by
1137 # if no args are given, the defaults set in the logger constructor by
1139 # ipytohn remain valid
1138 # ipytohn remain valid
1140 if par:
1139 if par:
1141 try:
1140 try:
1142 logfname,logmode = par.split()
1141 logfname,logmode = par.split()
1143 except:
1142 except:
1144 logfname = par
1143 logfname = par
1145 logmode = 'backup'
1144 logmode = 'backup'
1146 else:
1145 else:
1147 logfname = logger.logfname
1146 logfname = logger.logfname
1148 logmode = logger.logmode
1147 logmode = logger.logmode
1149 # put logfname into rc struct as if it had been called on the command
1148 # put logfname into rc struct as if it had been called on the command
1150 # line, so it ends up saved in the log header Save it in case we need
1149 # line, so it ends up saved in the log header Save it in case we need
1151 # to restore it...
1150 # to restore it...
1152 old_logfile = rc.opts.get('logfile','')
1151 old_logfile = self.shell.logfile
1153 if logfname:
1152 if logfname:
1154 logfname = os.path.expanduser(logfname)
1153 logfname = os.path.expanduser(logfname)
1155 rc.opts.logfile = logfname
1154 self.shell.logfile = logfname
1156 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
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 try:
1159 try:
1158 started = logger.logstart(logfname,loghead,logmode,
1160 started = logger.logstart(logfname,loghead,logmode,
1159 log_output,timestamp,log_raw_input)
1161 log_output,timestamp,log_raw_input)
1160 except:
1162 except:
1161 rc.opts.logfile = old_logfile
1163 rc.opts.logfile = old_logfile
1162 warn("Couldn't start log: %s" % sys.exc_info()[1])
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1163 else:
1165 else:
1164 # log input history up to this point, optionally interleaving
1166 # log input history up to this point, optionally interleaving
1165 # output if requested
1167 # output if requested
1166
1168
1167 if timestamp:
1169 if timestamp:
1168 # disable timestamping for the previous history, since we've
1170 # disable timestamping for the previous history, since we've
1169 # lost those already (no time machine here).
1171 # lost those already (no time machine here).
1170 logger.timestamp = False
1172 logger.timestamp = False
1171
1173
1172 if log_raw_input:
1174 if log_raw_input:
1173 input_hist = self.shell.input_hist_raw
1175 input_hist = self.shell.input_hist_raw
1174 else:
1176 else:
1175 input_hist = self.shell.input_hist
1177 input_hist = self.shell.input_hist
1176
1178
1177 if log_output:
1179 if log_output:
1178 log_write = logger.log_write
1180 log_write = logger.log_write
1179 output_hist = self.shell.output_hist
1181 output_hist = self.shell.output_hist
1180 for n in range(1,len(input_hist)-1):
1182 for n in range(1,len(input_hist)-1):
1181 log_write(input_hist[n].rstrip())
1183 log_write(input_hist[n].rstrip())
1182 if n in output_hist:
1184 if n in output_hist:
1183 log_write(repr(output_hist[n]),'output')
1185 log_write(repr(output_hist[n]),'output')
1184 else:
1186 else:
1185 logger.log_write(input_hist[1:])
1187 logger.log_write(input_hist[1:])
1186 if timestamp:
1188 if timestamp:
1187 # re-enable timestamping
1189 # re-enable timestamping
1188 logger.timestamp = True
1190 logger.timestamp = True
1189
1191
1190 print ('Activating auto-logging. '
1192 print ('Activating auto-logging. '
1191 'Current session state plus future input saved.')
1193 'Current session state plus future input saved.')
1192 logger.logstate()
1194 logger.logstate()
1193
1195
1194 def magic_logstop(self,parameter_s=''):
1196 def magic_logstop(self,parameter_s=''):
1195 """Fully stop logging and close log file.
1197 """Fully stop logging and close log file.
1196
1198
1197 In order to start logging again, a new %logstart call needs to be made,
1199 In order to start logging again, a new %logstart call needs to be made,
1198 possibly (though not necessarily) with a new filename, mode and other
1200 possibly (though not necessarily) with a new filename, mode and other
1199 options."""
1201 options."""
1200 self.logger.logstop()
1202 self.logger.logstop()
1201
1203
1202 def magic_logoff(self,parameter_s=''):
1204 def magic_logoff(self,parameter_s=''):
1203 """Temporarily stop logging.
1205 """Temporarily stop logging.
1204
1206
1205 You must have previously started logging."""
1207 You must have previously started logging."""
1206 self.shell.logger.switch_log(0)
1208 self.shell.logger.switch_log(0)
1207
1209
1208 def magic_logon(self,parameter_s=''):
1210 def magic_logon(self,parameter_s=''):
1209 """Restart logging.
1211 """Restart logging.
1210
1212
1211 This function is for restarting logging which you've temporarily
1213 This function is for restarting logging which you've temporarily
1212 stopped with %logoff. For starting logging for the first time, you
1214 stopped with %logoff. For starting logging for the first time, you
1213 must use the %logstart function, which allows you to specify an
1215 must use the %logstart function, which allows you to specify an
1214 optional log filename."""
1216 optional log filename."""
1215
1217
1216 self.shell.logger.switch_log(1)
1218 self.shell.logger.switch_log(1)
1217
1219
1218 def magic_logstate(self,parameter_s=''):
1220 def magic_logstate(self,parameter_s=''):
1219 """Print the status of the logging system."""
1221 """Print the status of the logging system."""
1220
1222
1221 self.shell.logger.logstate()
1223 self.shell.logger.logstate()
1222
1224
1223 def magic_pdb(self, parameter_s=''):
1225 def magic_pdb(self, parameter_s=''):
1224 """Control the automatic calling of the pdb interactive debugger.
1226 """Control the automatic calling of the pdb interactive debugger.
1225
1227
1226 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1227 argument it works as a toggle.
1229 argument it works as a toggle.
1228
1230
1229 When an exception is triggered, IPython can optionally call the
1231 When an exception is triggered, IPython can optionally call the
1230 interactive pdb debugger after the traceback printout. %pdb toggles
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1231 this feature on and off.
1233 this feature on and off.
1232
1234
1233 The initial state of this feature is set in your ipythonrc
1235 The initial state of this feature is set in your ipythonrc
1234 configuration file (the variable is called 'pdb').
1236 configuration file (the variable is called 'pdb').
1235
1237
1236 If you want to just activate the debugger AFTER an exception has fired,
1238 If you want to just activate the debugger AFTER an exception has fired,
1237 without having to type '%pdb on' and rerunning your code, you can use
1239 without having to type '%pdb on' and rerunning your code, you can use
1238 the %debug magic."""
1240 the %debug magic."""
1239
1241
1240 par = parameter_s.strip().lower()
1242 par = parameter_s.strip().lower()
1241
1243
1242 if par:
1244 if par:
1243 try:
1245 try:
1244 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1245 except KeyError:
1247 except KeyError:
1246 print ('Incorrect argument. Use on/1, off/0, '
1248 print ('Incorrect argument. Use on/1, off/0, '
1247 'or nothing for a toggle.')
1249 'or nothing for a toggle.')
1248 return
1250 return
1249 else:
1251 else:
1250 # toggle
1252 # toggle
1251 new_pdb = not self.shell.call_pdb
1253 new_pdb = not self.shell.call_pdb
1252
1254
1253 # set on the shell
1255 # set on the shell
1254 self.shell.call_pdb = new_pdb
1256 self.shell.call_pdb = new_pdb
1255 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1256
1258
1257 def magic_debug(self, parameter_s=''):
1259 def magic_debug(self, parameter_s=''):
1258 """Activate the interactive debugger in post-mortem mode.
1260 """Activate the interactive debugger in post-mortem mode.
1259
1261
1260 If an exception has just occurred, this lets you inspect its stack
1262 If an exception has just occurred, this lets you inspect its stack
1261 frames interactively. Note that this will always work only on the last
1263 frames interactively. Note that this will always work only on the last
1262 traceback that occurred, so you must call this quickly after an
1264 traceback that occurred, so you must call this quickly after an
1263 exception that you wish to inspect has fired, because if another one
1265 exception that you wish to inspect has fired, because if another one
1264 occurs, it clobbers the previous one.
1266 occurs, it clobbers the previous one.
1265
1267
1266 If you want IPython to automatically do this on every exception, see
1268 If you want IPython to automatically do this on every exception, see
1267 the %pdb magic for more details.
1269 the %pdb magic for more details.
1268 """
1270 """
1269
1271
1270 self.shell.debugger(force=True)
1272 self.shell.debugger(force=True)
1271
1273
1272 @testdec.skip_doctest
1274 @testdec.skip_doctest
1273 def magic_prun(self, parameter_s ='',user_mode=1,
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1274 opts=None,arg_lst=None,prog_ns=None):
1276 opts=None,arg_lst=None,prog_ns=None):
1275
1277
1276 """Run a statement through the python code profiler.
1278 """Run a statement through the python code profiler.
1277
1279
1278 Usage:
1280 Usage:
1279 %prun [options] statement
1281 %prun [options] statement
1280
1282
1281 The given statement (which doesn't require quote marks) is run via the
1283 The given statement (which doesn't require quote marks) is run via the
1282 python profiler in a manner similar to the profile.run() function.
1284 python profiler in a manner similar to the profile.run() function.
1283 Namespaces are internally managed to work correctly; profile.run
1285 Namespaces are internally managed to work correctly; profile.run
1284 cannot be used in IPython because it makes certain assumptions about
1286 cannot be used in IPython because it makes certain assumptions about
1285 namespaces which do not hold under IPython.
1287 namespaces which do not hold under IPython.
1286
1288
1287 Options:
1289 Options:
1288
1290
1289 -l <limit>: you can place restrictions on what or how much of the
1291 -l <limit>: you can place restrictions on what or how much of the
1290 profile gets printed. The limit value can be:
1292 profile gets printed. The limit value can be:
1291
1293
1292 * A string: only information for function names containing this string
1294 * A string: only information for function names containing this string
1293 is printed.
1295 is printed.
1294
1296
1295 * An integer: only these many lines are printed.
1297 * An integer: only these many lines are printed.
1296
1298
1297 * A float (between 0 and 1): this fraction of the report is printed
1299 * A float (between 0 and 1): this fraction of the report is printed
1298 (for example, use a limit of 0.4 to see the topmost 40% only).
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1299
1301
1300 You can combine several limits with repeated use of the option. For
1302 You can combine several limits with repeated use of the option. For
1301 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1302 information about class constructors.
1304 information about class constructors.
1303
1305
1304 -r: return the pstats.Stats object generated by the profiling. This
1306 -r: return the pstats.Stats object generated by the profiling. This
1305 object has all the information about the profile in it, and you can
1307 object has all the information about the profile in it, and you can
1306 later use it for further analysis or in other functions.
1308 later use it for further analysis or in other functions.
1307
1309
1308 -s <key>: sort profile by given key. You can provide more than one key
1310 -s <key>: sort profile by given key. You can provide more than one key
1309 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1310 default sorting key is 'time'.
1312 default sorting key is 'time'.
1311
1313
1312 The following is copied verbatim from the profile documentation
1314 The following is copied verbatim from the profile documentation
1313 referenced below:
1315 referenced below:
1314
1316
1315 When more than one key is provided, additional keys are used as
1317 When more than one key is provided, additional keys are used as
1316 secondary criteria when the there is equality in all keys selected
1318 secondary criteria when the there is equality in all keys selected
1317 before them.
1319 before them.
1318
1320
1319 Abbreviations can be used for any key names, as long as the
1321 Abbreviations can be used for any key names, as long as the
1320 abbreviation is unambiguous. The following are the keys currently
1322 abbreviation is unambiguous. The following are the keys currently
1321 defined:
1323 defined:
1322
1324
1323 Valid Arg Meaning
1325 Valid Arg Meaning
1324 "calls" call count
1326 "calls" call count
1325 "cumulative" cumulative time
1327 "cumulative" cumulative time
1326 "file" file name
1328 "file" file name
1327 "module" file name
1329 "module" file name
1328 "pcalls" primitive call count
1330 "pcalls" primitive call count
1329 "line" line number
1331 "line" line number
1330 "name" function name
1332 "name" function name
1331 "nfl" name/file/line
1333 "nfl" name/file/line
1332 "stdname" standard name
1334 "stdname" standard name
1333 "time" internal time
1335 "time" internal time
1334
1336
1335 Note that all sorts on statistics are in descending order (placing
1337 Note that all sorts on statistics are in descending order (placing
1336 most time consuming items first), where as name, file, and line number
1338 most time consuming items first), where as name, file, and line number
1337 searches are in ascending order (i.e., alphabetical). The subtle
1339 searches are in ascending order (i.e., alphabetical). The subtle
1338 distinction between "nfl" and "stdname" is that the standard name is a
1340 distinction between "nfl" and "stdname" is that the standard name is a
1339 sort of the name as printed, which means that the embedded line
1341 sort of the name as printed, which means that the embedded line
1340 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1341 would (if the file names were the same) appear in the string order
1343 would (if the file names were the same) appear in the string order
1342 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1343 line numbers. In fact, sort_stats("nfl") is the same as
1345 line numbers. In fact, sort_stats("nfl") is the same as
1344 sort_stats("name", "file", "line").
1346 sort_stats("name", "file", "line").
1345
1347
1346 -T <filename>: save profile results as shown on screen to a text
1348 -T <filename>: save profile results as shown on screen to a text
1347 file. The profile is still shown on screen.
1349 file. The profile is still shown on screen.
1348
1350
1349 -D <filename>: save (via dump_stats) profile statistics to given
1351 -D <filename>: save (via dump_stats) profile statistics to given
1350 filename. This data is in a format understod by the pstats module, and
1352 filename. This data is in a format understod by the pstats module, and
1351 is generated by a call to the dump_stats() method of profile
1353 is generated by a call to the dump_stats() method of profile
1352 objects. The profile is still shown on screen.
1354 objects. The profile is still shown on screen.
1353
1355
1354 If you want to run complete programs under the profiler's control, use
1356 If you want to run complete programs under the profiler's control, use
1355 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1356 contains profiler specific options as described here.
1358 contains profiler specific options as described here.
1357
1359
1358 You can read the complete documentation for the profile module with::
1360 You can read the complete documentation for the profile module with::
1359
1361
1360 In [1]: import profile; profile.help()
1362 In [1]: import profile; profile.help()
1361 """
1363 """
1362
1364
1363 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1364 # protect user quote marks
1366 # protect user quote marks
1365 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1366
1368
1367 if user_mode: # regular user call
1369 if user_mode: # regular user call
1368 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1369 list_all=1)
1371 list_all=1)
1370 namespace = self.shell.user_ns
1372 namespace = self.shell.user_ns
1371 else: # called to run a program by %run -p
1373 else: # called to run a program by %run -p
1372 try:
1374 try:
1373 filename = get_py_filename(arg_lst[0])
1375 filename = get_py_filename(arg_lst[0])
1374 except IOError,msg:
1376 except IOError,msg:
1375 error(msg)
1377 error(msg)
1376 return
1378 return
1377
1379
1378 arg_str = 'execfile(filename,prog_ns)'
1380 arg_str = 'execfile(filename,prog_ns)'
1379 namespace = locals()
1381 namespace = locals()
1380
1382
1381 opts.merge(opts_def)
1383 opts.merge(opts_def)
1382
1384
1383 prof = profile.Profile()
1385 prof = profile.Profile()
1384 try:
1386 try:
1385 prof = prof.runctx(arg_str,namespace,namespace)
1387 prof = prof.runctx(arg_str,namespace,namespace)
1386 sys_exit = ''
1388 sys_exit = ''
1387 except SystemExit:
1389 except SystemExit:
1388 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390 sys_exit = """*** SystemExit exception caught in code being profiled."""
1389
1391
1390 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1391
1393
1392 lims = opts.l
1394 lims = opts.l
1393 if lims:
1395 if lims:
1394 lims = [] # rebuild lims with ints/floats/strings
1396 lims = [] # rebuild lims with ints/floats/strings
1395 for lim in opts.l:
1397 for lim in opts.l:
1396 try:
1398 try:
1397 lims.append(int(lim))
1399 lims.append(int(lim))
1398 except ValueError:
1400 except ValueError:
1399 try:
1401 try:
1400 lims.append(float(lim))
1402 lims.append(float(lim))
1401 except ValueError:
1403 except ValueError:
1402 lims.append(lim)
1404 lims.append(lim)
1403
1405
1404 # Trap output.
1406 # Trap output.
1405 stdout_trap = StringIO()
1407 stdout_trap = StringIO()
1406
1408
1407 if hasattr(stats,'stream'):
1409 if hasattr(stats,'stream'):
1408 # In newer versions of python, the stats object has a 'stream'
1410 # In newer versions of python, the stats object has a 'stream'
1409 # attribute to write into.
1411 # attribute to write into.
1410 stats.stream = stdout_trap
1412 stats.stream = stdout_trap
1411 stats.print_stats(*lims)
1413 stats.print_stats(*lims)
1412 else:
1414 else:
1413 # For older versions, we manually redirect stdout during printing
1415 # For older versions, we manually redirect stdout during printing
1414 sys_stdout = sys.stdout
1416 sys_stdout = sys.stdout
1415 try:
1417 try:
1416 sys.stdout = stdout_trap
1418 sys.stdout = stdout_trap
1417 stats.print_stats(*lims)
1419 stats.print_stats(*lims)
1418 finally:
1420 finally:
1419 sys.stdout = sys_stdout
1421 sys.stdout = sys_stdout
1420
1422
1421 output = stdout_trap.getvalue()
1423 output = stdout_trap.getvalue()
1422 output = output.rstrip()
1424 output = output.rstrip()
1423
1425
1424 page(output,screen_lines=self.shell.rc.screen_length)
1426 page(output,screen_lines=self.shell.screen_length)
1425 print sys_exit,
1427 print sys_exit,
1426
1428
1427 dump_file = opts.D[0]
1429 dump_file = opts.D[0]
1428 text_file = opts.T[0]
1430 text_file = opts.T[0]
1429 if dump_file:
1431 if dump_file:
1430 prof.dump_stats(dump_file)
1432 prof.dump_stats(dump_file)
1431 print '\n*** Profile stats marshalled to file',\
1433 print '\n*** Profile stats marshalled to file',\
1432 `dump_file`+'.',sys_exit
1434 `dump_file`+'.',sys_exit
1433 if text_file:
1435 if text_file:
1434 pfile = file(text_file,'w')
1436 pfile = file(text_file,'w')
1435 pfile.write(output)
1437 pfile.write(output)
1436 pfile.close()
1438 pfile.close()
1437 print '\n*** Profile printout saved to text file',\
1439 print '\n*** Profile printout saved to text file',\
1438 `text_file`+'.',sys_exit
1440 `text_file`+'.',sys_exit
1439
1441
1440 if opts.has_key('r'):
1442 if opts.has_key('r'):
1441 return stats
1443 return stats
1442 else:
1444 else:
1443 return None
1445 return None
1444
1446
1445 @testdec.skip_doctest
1447 @testdec.skip_doctest
1446 def magic_run(self, parameter_s ='',runner=None,
1448 def magic_run(self, parameter_s ='',runner=None,
1447 file_finder=get_py_filename):
1449 file_finder=get_py_filename):
1448 """Run the named file inside IPython as a program.
1450 """Run the named file inside IPython as a program.
1449
1451
1450 Usage:\\
1452 Usage:\\
1451 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1452
1454
1453 Parameters after the filename are passed as command-line arguments to
1455 Parameters after the filename are passed as command-line arguments to
1454 the program (put in sys.argv). Then, control returns to IPython's
1456 the program (put in sys.argv). Then, control returns to IPython's
1455 prompt.
1457 prompt.
1456
1458
1457 This is similar to running at a system prompt:\\
1459 This is similar to running at a system prompt:\\
1458 $ python file args\\
1460 $ python file args\\
1459 but with the advantage of giving you IPython's tracebacks, and of
1461 but with the advantage of giving you IPython's tracebacks, and of
1460 loading all variables into your interactive namespace for further use
1462 loading all variables into your interactive namespace for further use
1461 (unless -p is used, see below).
1463 (unless -p is used, see below).
1462
1464
1463 The file is executed in a namespace initially consisting only of
1465 The file is executed in a namespace initially consisting only of
1464 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 __name__=='__main__' and sys.argv constructed as indicated. It thus
1465 sees its environment as if it were being run as a stand-alone program
1467 sees its environment as if it were being run as a stand-alone program
1466 (except for sharing global objects such as previously imported
1468 (except for sharing global objects such as previously imported
1467 modules). But after execution, the IPython interactive namespace gets
1469 modules). But after execution, the IPython interactive namespace gets
1468 updated with all variables defined in the program (except for __name__
1470 updated with all variables defined in the program (except for __name__
1469 and sys.argv). This allows for very convenient loading of code for
1471 and sys.argv). This allows for very convenient loading of code for
1470 interactive work, while giving each program a 'clean sheet' to run in.
1472 interactive work, while giving each program a 'clean sheet' to run in.
1471
1473
1472 Options:
1474 Options:
1473
1475
1474 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 -n: __name__ is NOT set to '__main__', but to the running file's name
1475 without extension (as python does under import). This allows running
1477 without extension (as python does under import). This allows running
1476 scripts and reloading the definitions in them without calling code
1478 scripts and reloading the definitions in them without calling code
1477 protected by an ' if __name__ == "__main__" ' clause.
1479 protected by an ' if __name__ == "__main__" ' clause.
1478
1480
1479 -i: run the file in IPython's namespace instead of an empty one. This
1481 -i: run the file in IPython's namespace instead of an empty one. This
1480 is useful if you are experimenting with code written in a text editor
1482 is useful if you are experimenting with code written in a text editor
1481 which depends on variables defined interactively.
1483 which depends on variables defined interactively.
1482
1484
1483 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1484 being run. This is particularly useful if IPython is being used to
1486 being run. This is particularly useful if IPython is being used to
1485 run unittests, which always exit with a sys.exit() call. In such
1487 run unittests, which always exit with a sys.exit() call. In such
1486 cases you are interested in the output of the test results, not in
1488 cases you are interested in the output of the test results, not in
1487 seeing a traceback of the unittest module.
1489 seeing a traceback of the unittest module.
1488
1490
1489 -t: print timing information at the end of the run. IPython will give
1491 -t: print timing information at the end of the run. IPython will give
1490 you an estimated CPU time consumption for your script, which under
1492 you an estimated CPU time consumption for your script, which under
1491 Unix uses the resource module to avoid the wraparound problems of
1493 Unix uses the resource module to avoid the wraparound problems of
1492 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 time.clock(). Under Unix, an estimate of time spent on system tasks
1493 is also given (for Windows platforms this is reported as 0.0).
1495 is also given (for Windows platforms this is reported as 0.0).
1494
1496
1495 If -t is given, an additional -N<N> option can be given, where <N>
1497 If -t is given, an additional -N<N> option can be given, where <N>
1496 must be an integer indicating how many times you want the script to
1498 must be an integer indicating how many times you want the script to
1497 run. The final timing report will include total and per run results.
1499 run. The final timing report will include total and per run results.
1498
1500
1499 For example (testing the script uniq_stable.py):
1501 For example (testing the script uniq_stable.py):
1500
1502
1501 In [1]: run -t uniq_stable
1503 In [1]: run -t uniq_stable
1502
1504
1503 IPython CPU timings (estimated):\\
1505 IPython CPU timings (estimated):\\
1504 User : 0.19597 s.\\
1506 User : 0.19597 s.\\
1505 System: 0.0 s.\\
1507 System: 0.0 s.\\
1506
1508
1507 In [2]: run -t -N5 uniq_stable
1509 In [2]: run -t -N5 uniq_stable
1508
1510
1509 IPython CPU timings (estimated):\\
1511 IPython CPU timings (estimated):\\
1510 Total runs performed: 5\\
1512 Total runs performed: 5\\
1511 Times : Total Per run\\
1513 Times : Total Per run\\
1512 User : 0.910862 s, 0.1821724 s.\\
1514 User : 0.910862 s, 0.1821724 s.\\
1513 System: 0.0 s, 0.0 s.
1515 System: 0.0 s, 0.0 s.
1514
1516
1515 -d: run your program under the control of pdb, the Python debugger.
1517 -d: run your program under the control of pdb, the Python debugger.
1516 This allows you to execute your program step by step, watch variables,
1518 This allows you to execute your program step by step, watch variables,
1517 etc. Internally, what IPython does is similar to calling:
1519 etc. Internally, what IPython does is similar to calling:
1518
1520
1519 pdb.run('execfile("YOURFILENAME")')
1521 pdb.run('execfile("YOURFILENAME")')
1520
1522
1521 with a breakpoint set on line 1 of your file. You can change the line
1523 with a breakpoint set on line 1 of your file. You can change the line
1522 number for this automatic breakpoint to be <N> by using the -bN option
1524 number for this automatic breakpoint to be <N> by using the -bN option
1523 (where N must be an integer). For example:
1525 (where N must be an integer). For example:
1524
1526
1525 %run -d -b40 myscript
1527 %run -d -b40 myscript
1526
1528
1527 will set the first breakpoint at line 40 in myscript.py. Note that
1529 will set the first breakpoint at line 40 in myscript.py. Note that
1528 the first breakpoint must be set on a line which actually does
1530 the first breakpoint must be set on a line which actually does
1529 something (not a comment or docstring) for it to stop execution.
1531 something (not a comment or docstring) for it to stop execution.
1530
1532
1531 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1532 first enter 'c' (without qoutes) to start execution up to the first
1534 first enter 'c' (without qoutes) to start execution up to the first
1533 breakpoint.
1535 breakpoint.
1534
1536
1535 Entering 'help' gives information about the use of the debugger. You
1537 Entering 'help' gives information about the use of the debugger. You
1536 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 can easily see pdb's full documentation with "import pdb;pdb.help()"
1537 at a prompt.
1539 at a prompt.
1538
1540
1539 -p: run program under the control of the Python profiler module (which
1541 -p: run program under the control of the Python profiler module (which
1540 prints a detailed report of execution times, function calls, etc).
1542 prints a detailed report of execution times, function calls, etc).
1541
1543
1542 You can pass other options after -p which affect the behavior of the
1544 You can pass other options after -p which affect the behavior of the
1543 profiler itself. See the docs for %prun for details.
1545 profiler itself. See the docs for %prun for details.
1544
1546
1545 In this mode, the program's variables do NOT propagate back to the
1547 In this mode, the program's variables do NOT propagate back to the
1546 IPython interactive namespace (because they remain in the namespace
1548 IPython interactive namespace (because they remain in the namespace
1547 where the profiler executes them).
1549 where the profiler executes them).
1548
1550
1549 Internally this triggers a call to %prun, see its documentation for
1551 Internally this triggers a call to %prun, see its documentation for
1550 details on the options available specifically for profiling.
1552 details on the options available specifically for profiling.
1551
1553
1552 There is one special usage for which the text above doesn't apply:
1554 There is one special usage for which the text above doesn't apply:
1553 if the filename ends with .ipy, the file is run as ipython script,
1555 if the filename ends with .ipy, the file is run as ipython script,
1554 just as if the commands were written on IPython prompt.
1556 just as if the commands were written on IPython prompt.
1555 """
1557 """
1556
1558
1557 # get arguments and set sys.argv for program to be run.
1559 # get arguments and set sys.argv for program to be run.
1558 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1559 mode='list',list_all=1)
1561 mode='list',list_all=1)
1560
1562
1561 try:
1563 try:
1562 filename = file_finder(arg_lst[0])
1564 filename = file_finder(arg_lst[0])
1563 except IndexError:
1565 except IndexError:
1564 warn('you must provide at least a filename.')
1566 warn('you must provide at least a filename.')
1565 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1566 return
1568 return
1567 except IOError,msg:
1569 except IOError,msg:
1568 error(msg)
1570 error(msg)
1569 return
1571 return
1570
1572
1571 if filename.lower().endswith('.ipy'):
1573 if filename.lower().endswith('.ipy'):
1572 self.api.runlines(open(filename).read())
1574 self.api.runlines(open(filename).read())
1573 return
1575 return
1574
1576
1575 # Control the response to exit() calls made by the script being run
1577 # Control the response to exit() calls made by the script being run
1576 exit_ignore = opts.has_key('e')
1578 exit_ignore = opts.has_key('e')
1577
1579
1578 # Make sure that the running script gets a proper sys.argv as if it
1580 # Make sure that the running script gets a proper sys.argv as if it
1579 # were run from a system shell.
1581 # were run from a system shell.
1580 save_argv = sys.argv # save it for later restoring
1582 save_argv = sys.argv # save it for later restoring
1581 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1582
1584
1583 if opts.has_key('i'):
1585 if opts.has_key('i'):
1584 # Run in user's interactive namespace
1586 # Run in user's interactive namespace
1585 prog_ns = self.shell.user_ns
1587 prog_ns = self.shell.user_ns
1586 __name__save = self.shell.user_ns['__name__']
1588 __name__save = self.shell.user_ns['__name__']
1587 prog_ns['__name__'] = '__main__'
1589 prog_ns['__name__'] = '__main__'
1588 main_mod = self.shell.new_main_mod(prog_ns)
1590 main_mod = self.shell.new_main_mod(prog_ns)
1589 else:
1591 else:
1590 # Run in a fresh, empty namespace
1592 # Run in a fresh, empty namespace
1591 if opts.has_key('n'):
1593 if opts.has_key('n'):
1592 name = os.path.splitext(os.path.basename(filename))[0]
1594 name = os.path.splitext(os.path.basename(filename))[0]
1593 else:
1595 else:
1594 name = '__main__'
1596 name = '__main__'
1595
1597
1596 main_mod = self.shell.new_main_mod()
1598 main_mod = self.shell.new_main_mod()
1597 prog_ns = main_mod.__dict__
1599 prog_ns = main_mod.__dict__
1598 prog_ns['__name__'] = name
1600 prog_ns['__name__'] = name
1599
1601
1600 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1601 # set the __file__ global in the script's namespace
1603 # set the __file__ global in the script's namespace
1602 prog_ns['__file__'] = filename
1604 prog_ns['__file__'] = filename
1603
1605
1604 # pickle fix. See iplib for an explanation. But we need to make sure
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1605 # that, if we overwrite __main__, we replace it at the end
1607 # that, if we overwrite __main__, we replace it at the end
1606 main_mod_name = prog_ns['__name__']
1608 main_mod_name = prog_ns['__name__']
1607
1609
1608 if main_mod_name == '__main__':
1610 if main_mod_name == '__main__':
1609 restore_main = sys.modules['__main__']
1611 restore_main = sys.modules['__main__']
1610 else:
1612 else:
1611 restore_main = False
1613 restore_main = False
1612
1614
1613 # This needs to be undone at the end to prevent holding references to
1615 # This needs to be undone at the end to prevent holding references to
1614 # every single object ever created.
1616 # every single object ever created.
1615 sys.modules[main_mod_name] = main_mod
1617 sys.modules[main_mod_name] = main_mod
1616
1618
1617 stats = None
1619 stats = None
1618 try:
1620 try:
1619 self.shell.savehist()
1621 self.shell.savehist()
1620
1622
1621 if opts.has_key('p'):
1623 if opts.has_key('p'):
1622 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1623 else:
1625 else:
1624 if opts.has_key('d'):
1626 if opts.has_key('d'):
1625 deb = debugger.Pdb(self.shell.rc.colors)
1627 deb = debugger.Pdb(self.shell.colors)
1626 # reset Breakpoint state, which is moronically kept
1628 # reset Breakpoint state, which is moronically kept
1627 # in a class
1629 # in a class
1628 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.next = 1
1629 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bplist = {}
1630 bdb.Breakpoint.bpbynumber = [None]
1632 bdb.Breakpoint.bpbynumber = [None]
1631 # Set an initial breakpoint to stop execution
1633 # Set an initial breakpoint to stop execution
1632 maxtries = 10
1634 maxtries = 10
1633 bp = int(opts.get('b',[1])[0])
1635 bp = int(opts.get('b',[1])[0])
1634 checkline = deb.checkline(filename,bp)
1636 checkline = deb.checkline(filename,bp)
1635 if not checkline:
1637 if not checkline:
1636 for bp in range(bp+1,bp+maxtries+1):
1638 for bp in range(bp+1,bp+maxtries+1):
1637 if deb.checkline(filename,bp):
1639 if deb.checkline(filename,bp):
1638 break
1640 break
1639 else:
1641 else:
1640 msg = ("\nI failed to find a valid line to set "
1642 msg = ("\nI failed to find a valid line to set "
1641 "a breakpoint\n"
1643 "a breakpoint\n"
1642 "after trying up to line: %s.\n"
1644 "after trying up to line: %s.\n"
1643 "Please set a valid breakpoint manually "
1645 "Please set a valid breakpoint manually "
1644 "with the -b option." % bp)
1646 "with the -b option." % bp)
1645 error(msg)
1647 error(msg)
1646 return
1648 return
1647 # if we find a good linenumber, set the breakpoint
1649 # if we find a good linenumber, set the breakpoint
1648 deb.do_break('%s:%s' % (filename,bp))
1650 deb.do_break('%s:%s' % (filename,bp))
1649 # Start file run
1651 # Start file run
1650 print "NOTE: Enter 'c' at the",
1652 print "NOTE: Enter 'c' at the",
1651 print "%s prompt to start your script." % deb.prompt
1653 print "%s prompt to start your script." % deb.prompt
1652 try:
1654 try:
1653 deb.run('execfile("%s")' % filename,prog_ns)
1655 deb.run('execfile("%s")' % filename,prog_ns)
1654
1656
1655 except:
1657 except:
1656 etype, value, tb = sys.exc_info()
1658 etype, value, tb = sys.exc_info()
1657 # Skip three frames in the traceback: the %run one,
1659 # Skip three frames in the traceback: the %run one,
1658 # one inside bdb.py, and the command-line typed by the
1660 # one inside bdb.py, and the command-line typed by the
1659 # user (run by exec in pdb itself).
1661 # user (run by exec in pdb itself).
1660 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1661 else:
1663 else:
1662 if runner is None:
1664 if runner is None:
1663 runner = self.shell.safe_execfile
1665 runner = self.shell.safe_execfile
1664 if opts.has_key('t'):
1666 if opts.has_key('t'):
1665 # timed execution
1667 # timed execution
1666 try:
1668 try:
1667 nruns = int(opts['N'][0])
1669 nruns = int(opts['N'][0])
1668 if nruns < 1:
1670 if nruns < 1:
1669 error('Number of runs must be >=1')
1671 error('Number of runs must be >=1')
1670 return
1672 return
1671 except (KeyError):
1673 except (KeyError):
1672 nruns = 1
1674 nruns = 1
1673 if nruns == 1:
1675 if nruns == 1:
1674 t0 = clock2()
1676 t0 = clock2()
1675 runner(filename,prog_ns,prog_ns,
1677 runner(filename,prog_ns,prog_ns,
1676 exit_ignore=exit_ignore)
1678 exit_ignore=exit_ignore)
1677 t1 = clock2()
1679 t1 = clock2()
1678 t_usr = t1[0]-t0[0]
1680 t_usr = t1[0]-t0[0]
1679 t_sys = t1[1]-t0[1]
1681 t_sys = t1[1]-t0[1]
1680 print "\nIPython CPU timings (estimated):"
1682 print "\nIPython CPU timings (estimated):"
1681 print " User : %10s s." % t_usr
1683 print " User : %10s s." % t_usr
1682 print " System: %10s s." % t_sys
1684 print " System: %10s s." % t_sys
1683 else:
1685 else:
1684 runs = range(nruns)
1686 runs = range(nruns)
1685 t0 = clock2()
1687 t0 = clock2()
1686 for nr in runs:
1688 for nr in runs:
1687 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1688 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1689 t1 = clock2()
1691 t1 = clock2()
1690 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1691 t_sys = t1[1]-t0[1]
1693 t_sys = t1[1]-t0[1]
1692 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1693 print "Total runs performed:",nruns
1695 print "Total runs performed:",nruns
1694 print " Times : %10s %10s" % ('Total','Per run')
1696 print " Times : %10s %10s" % ('Total','Per run')
1695 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1696 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1697
1699
1698 else:
1700 else:
1699 # regular execution
1701 # regular execution
1700 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1701
1703
1702 if opts.has_key('i'):
1704 if opts.has_key('i'):
1703 self.shell.user_ns['__name__'] = __name__save
1705 self.shell.user_ns['__name__'] = __name__save
1704 else:
1706 else:
1705 # The shell MUST hold a reference to prog_ns so after %run
1707 # The shell MUST hold a reference to prog_ns so after %run
1706 # exits, the python deletion mechanism doesn't zero it out
1708 # exits, the python deletion mechanism doesn't zero it out
1707 # (leaving dangling references).
1709 # (leaving dangling references).
1708 self.shell.cache_main_mod(prog_ns,filename)
1710 self.shell.cache_main_mod(prog_ns,filename)
1709 # update IPython interactive namespace
1711 # update IPython interactive namespace
1710
1712
1711 # Some forms of read errors on the file may mean the
1713 # Some forms of read errors on the file may mean the
1712 # __name__ key was never set; using pop we don't have to
1714 # __name__ key was never set; using pop we don't have to
1713 # worry about a possible KeyError.
1715 # worry about a possible KeyError.
1714 prog_ns.pop('__name__', None)
1716 prog_ns.pop('__name__', None)
1715
1717
1716 self.shell.user_ns.update(prog_ns)
1718 self.shell.user_ns.update(prog_ns)
1717 finally:
1719 finally:
1718 # It's a bit of a mystery why, but __builtins__ can change from
1720 # It's a bit of a mystery why, but __builtins__ can change from
1719 # being a module to becoming a dict missing some key data after
1721 # being a module to becoming a dict missing some key data after
1720 # %run. As best I can see, this is NOT something IPython is doing
1722 # %run. As best I can see, this is NOT something IPython is doing
1721 # at all, and similar problems have been reported before:
1723 # at all, and similar problems have been reported before:
1722 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1723 # Since this seems to be done by the interpreter itself, the best
1725 # Since this seems to be done by the interpreter itself, the best
1724 # we can do is to at least restore __builtins__ for the user on
1726 # we can do is to at least restore __builtins__ for the user on
1725 # exit.
1727 # exit.
1726 self.shell.user_ns['__builtins__'] = __builtin__
1728 self.shell.user_ns['__builtins__'] = __builtin__
1727
1729
1728 # Ensure key global structures are restored
1730 # Ensure key global structures are restored
1729 sys.argv = save_argv
1731 sys.argv = save_argv
1730 if restore_main:
1732 if restore_main:
1731 sys.modules['__main__'] = restore_main
1733 sys.modules['__main__'] = restore_main
1732 else:
1734 else:
1733 # Remove from sys.modules the reference to main_mod we'd
1735 # Remove from sys.modules the reference to main_mod we'd
1734 # added. Otherwise it will trap references to objects
1736 # added. Otherwise it will trap references to objects
1735 # contained therein.
1737 # contained therein.
1736 del sys.modules[main_mod_name]
1738 del sys.modules[main_mod_name]
1737
1739
1738 self.shell.reloadhist()
1740 self.shell.reloadhist()
1739
1741
1740 return stats
1742 return stats
1741
1743
1742 def magic_runlog(self, parameter_s =''):
1744 def magic_runlog(self, parameter_s =''):
1743 """Run files as logs.
1745 """Run files as logs.
1744
1746
1745 Usage:\\
1747 Usage:\\
1746 %runlog file1 file2 ...
1748 %runlog file1 file2 ...
1747
1749
1748 Run the named files (treating them as log files) in sequence inside
1750 Run the named files (treating them as log files) in sequence inside
1749 the interpreter, and return to the prompt. This is much slower than
1751 the interpreter, and return to the prompt. This is much slower than
1750 %run because each line is executed in a try/except block, but it
1752 %run because each line is executed in a try/except block, but it
1751 allows running files with syntax errors in them.
1753 allows running files with syntax errors in them.
1752
1754
1753 Normally IPython will guess when a file is one of its own logfiles, so
1755 Normally IPython will guess when a file is one of its own logfiles, so
1754 you can typically use %run even for logs. This shorthand allows you to
1756 you can typically use %run even for logs. This shorthand allows you to
1755 force any file to be treated as a log file."""
1757 force any file to be treated as a log file."""
1756
1758
1757 for f in parameter_s.split():
1759 for f in parameter_s.split():
1758 self.shell.safe_execfile(f,self.shell.user_ns,
1760 self.shell.safe_execfile(f,self.shell.user_ns,
1759 self.shell.user_ns,islog=1)
1761 self.shell.user_ns,islog=1)
1760
1762
1761 @testdec.skip_doctest
1763 @testdec.skip_doctest
1762 def magic_timeit(self, parameter_s =''):
1764 def magic_timeit(self, parameter_s =''):
1763 """Time execution of a Python statement or expression
1765 """Time execution of a Python statement or expression
1764
1766
1765 Usage:\\
1767 Usage:\\
1766 %timeit [-n<N> -r<R> [-t|-c]] statement
1768 %timeit [-n<N> -r<R> [-t|-c]] statement
1767
1769
1768 Time execution of a Python statement or expression using the timeit
1770 Time execution of a Python statement or expression using the timeit
1769 module.
1771 module.
1770
1772
1771 Options:
1773 Options:
1772 -n<N>: execute the given statement <N> times in a loop. If this value
1774 -n<N>: execute the given statement <N> times in a loop. If this value
1773 is not given, a fitting value is chosen.
1775 is not given, a fitting value is chosen.
1774
1776
1775 -r<R>: repeat the loop iteration <R> times and take the best result.
1777 -r<R>: repeat the loop iteration <R> times and take the best result.
1776 Default: 3
1778 Default: 3
1777
1779
1778 -t: use time.time to measure the time, which is the default on Unix.
1780 -t: use time.time to measure the time, which is the default on Unix.
1779 This function measures wall time.
1781 This function measures wall time.
1780
1782
1781 -c: use time.clock to measure the time, which is the default on
1783 -c: use time.clock to measure the time, which is the default on
1782 Windows and measures wall time. On Unix, resource.getrusage is used
1784 Windows and measures wall time. On Unix, resource.getrusage is used
1783 instead and returns the CPU user time.
1785 instead and returns the CPU user time.
1784
1786
1785 -p<P>: use a precision of <P> digits to display the timing result.
1787 -p<P>: use a precision of <P> digits to display the timing result.
1786 Default: 3
1788 Default: 3
1787
1789
1788
1790
1789 Examples:
1791 Examples:
1790
1792
1791 In [1]: %timeit pass
1793 In [1]: %timeit pass
1792 10000000 loops, best of 3: 53.3 ns per loop
1794 10000000 loops, best of 3: 53.3 ns per loop
1793
1795
1794 In [2]: u = None
1796 In [2]: u = None
1795
1797
1796 In [3]: %timeit u is None
1798 In [3]: %timeit u is None
1797 10000000 loops, best of 3: 184 ns per loop
1799 10000000 loops, best of 3: 184 ns per loop
1798
1800
1799 In [4]: %timeit -r 4 u == None
1801 In [4]: %timeit -r 4 u == None
1800 1000000 loops, best of 4: 242 ns per loop
1802 1000000 loops, best of 4: 242 ns per loop
1801
1803
1802 In [5]: import time
1804 In [5]: import time
1803
1805
1804 In [6]: %timeit -n1 time.sleep(2)
1806 In [6]: %timeit -n1 time.sleep(2)
1805 1 loops, best of 3: 2 s per loop
1807 1 loops, best of 3: 2 s per loop
1806
1808
1807
1809
1808 The times reported by %timeit will be slightly higher than those
1810 The times reported by %timeit will be slightly higher than those
1809 reported by the timeit.py script when variables are accessed. This is
1811 reported by the timeit.py script when variables are accessed. This is
1810 due to the fact that %timeit executes the statement in the namespace
1812 due to the fact that %timeit executes the statement in the namespace
1811 of the shell, compared with timeit.py, which uses a single setup
1813 of the shell, compared with timeit.py, which uses a single setup
1812 statement to import function or create variables. Generally, the bias
1814 statement to import function or create variables. Generally, the bias
1813 does not matter as long as results from timeit.py are not mixed with
1815 does not matter as long as results from timeit.py are not mixed with
1814 those from %timeit."""
1816 those from %timeit."""
1815
1817
1816 import timeit
1818 import timeit
1817 import math
1819 import math
1818
1820
1819 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1821 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1820 # certain terminals. Until we figure out a robust way of
1822 # certain terminals. Until we figure out a robust way of
1821 # auto-detecting if the terminal can deal with it, use plain 'us' for
1823 # auto-detecting if the terminal can deal with it, use plain 'us' for
1822 # microseconds. I am really NOT happy about disabling the proper
1824 # microseconds. I am really NOT happy about disabling the proper
1823 # 'micro' prefix, but crashing is worse... If anyone knows what the
1825 # 'micro' prefix, but crashing is worse... If anyone knows what the
1824 # right solution for this is, I'm all ears...
1826 # right solution for this is, I'm all ears...
1825 #
1827 #
1826 # Note: using
1828 # Note: using
1827 #
1829 #
1828 # s = u'\xb5'
1830 # s = u'\xb5'
1829 # s.encode(sys.getdefaultencoding())
1831 # s.encode(sys.getdefaultencoding())
1830 #
1832 #
1831 # is not sufficient, as I've seen terminals where that fails but
1833 # is not sufficient, as I've seen terminals where that fails but
1832 # print s
1834 # print s
1833 #
1835 #
1834 # succeeds
1836 # succeeds
1835 #
1837 #
1836 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1838 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1837
1839
1838 #units = [u"s", u"ms",u'\xb5',"ns"]
1840 #units = [u"s", u"ms",u'\xb5',"ns"]
1839 units = [u"s", u"ms",u'us',"ns"]
1841 units = [u"s", u"ms",u'us',"ns"]
1840
1842
1841 scaling = [1, 1e3, 1e6, 1e9]
1843 scaling = [1, 1e3, 1e6, 1e9]
1842
1844
1843 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1845 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1844 posix=False)
1846 posix=False)
1845 if stmt == "":
1847 if stmt == "":
1846 return
1848 return
1847 timefunc = timeit.default_timer
1849 timefunc = timeit.default_timer
1848 number = int(getattr(opts, "n", 0))
1850 number = int(getattr(opts, "n", 0))
1849 repeat = int(getattr(opts, "r", timeit.default_repeat))
1851 repeat = int(getattr(opts, "r", timeit.default_repeat))
1850 precision = int(getattr(opts, "p", 3))
1852 precision = int(getattr(opts, "p", 3))
1851 if hasattr(opts, "t"):
1853 if hasattr(opts, "t"):
1852 timefunc = time.time
1854 timefunc = time.time
1853 if hasattr(opts, "c"):
1855 if hasattr(opts, "c"):
1854 timefunc = clock
1856 timefunc = clock
1855
1857
1856 timer = timeit.Timer(timer=timefunc)
1858 timer = timeit.Timer(timer=timefunc)
1857 # this code has tight coupling to the inner workings of timeit.Timer,
1859 # this code has tight coupling to the inner workings of timeit.Timer,
1858 # but is there a better way to achieve that the code stmt has access
1860 # but is there a better way to achieve that the code stmt has access
1859 # to the shell namespace?
1861 # to the shell namespace?
1860
1862
1861 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1863 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1862 'setup': "pass"}
1864 'setup': "pass"}
1863 # Track compilation time so it can be reported if too long
1865 # Track compilation time so it can be reported if too long
1864 # Minimum time above which compilation time will be reported
1866 # Minimum time above which compilation time will be reported
1865 tc_min = 0.1
1867 tc_min = 0.1
1866
1868
1867 t0 = clock()
1869 t0 = clock()
1868 code = compile(src, "<magic-timeit>", "exec")
1870 code = compile(src, "<magic-timeit>", "exec")
1869 tc = clock()-t0
1871 tc = clock()-t0
1870
1872
1871 ns = {}
1873 ns = {}
1872 exec code in self.shell.user_ns, ns
1874 exec code in self.shell.user_ns, ns
1873 timer.inner = ns["inner"]
1875 timer.inner = ns["inner"]
1874
1876
1875 if number == 0:
1877 if number == 0:
1876 # determine number so that 0.2 <= total time < 2.0
1878 # determine number so that 0.2 <= total time < 2.0
1877 number = 1
1879 number = 1
1878 for i in range(1, 10):
1880 for i in range(1, 10):
1879 if timer.timeit(number) >= 0.2:
1881 if timer.timeit(number) >= 0.2:
1880 break
1882 break
1881 number *= 10
1883 number *= 10
1882
1884
1883 best = min(timer.repeat(repeat, number)) / number
1885 best = min(timer.repeat(repeat, number)) / number
1884
1886
1885 if best > 0.0:
1887 if best > 0.0:
1886 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1888 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1887 else:
1889 else:
1888 order = 3
1890 order = 3
1889 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1891 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1890 precision,
1892 precision,
1891 best * scaling[order],
1893 best * scaling[order],
1892 units[order])
1894 units[order])
1893 if tc > tc_min:
1895 if tc > tc_min:
1894 print "Compiler time: %.2f s" % tc
1896 print "Compiler time: %.2f s" % tc
1895
1897
1896 @testdec.skip_doctest
1898 @testdec.skip_doctest
1897 def magic_time(self,parameter_s = ''):
1899 def magic_time(self,parameter_s = ''):
1898 """Time execution of a Python statement or expression.
1900 """Time execution of a Python statement or expression.
1899
1901
1900 The CPU and wall clock times are printed, and the value of the
1902 The CPU and wall clock times are printed, and the value of the
1901 expression (if any) is returned. Note that under Win32, system time
1903 expression (if any) is returned. Note that under Win32, system time
1902 is always reported as 0, since it can not be measured.
1904 is always reported as 0, since it can not be measured.
1903
1905
1904 This function provides very basic timing functionality. In Python
1906 This function provides very basic timing functionality. In Python
1905 2.3, the timeit module offers more control and sophistication, so this
1907 2.3, the timeit module offers more control and sophistication, so this
1906 could be rewritten to use it (patches welcome).
1908 could be rewritten to use it (patches welcome).
1907
1909
1908 Some examples:
1910 Some examples:
1909
1911
1910 In [1]: time 2**128
1912 In [1]: time 2**128
1911 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1913 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1912 Wall time: 0.00
1914 Wall time: 0.00
1913 Out[1]: 340282366920938463463374607431768211456L
1915 Out[1]: 340282366920938463463374607431768211456L
1914
1916
1915 In [2]: n = 1000000
1917 In [2]: n = 1000000
1916
1918
1917 In [3]: time sum(range(n))
1919 In [3]: time sum(range(n))
1918 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1920 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1919 Wall time: 1.37
1921 Wall time: 1.37
1920 Out[3]: 499999500000L
1922 Out[3]: 499999500000L
1921
1923
1922 In [4]: time print 'hello world'
1924 In [4]: time print 'hello world'
1923 hello world
1925 hello world
1924 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1926 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1925 Wall time: 0.00
1927 Wall time: 0.00
1926
1928
1927 Note that the time needed by Python to compile the given expression
1929 Note that the time needed by Python to compile the given expression
1928 will be reported if it is more than 0.1s. In this example, the
1930 will be reported if it is more than 0.1s. In this example, the
1929 actual exponentiation is done by Python at compilation time, so while
1931 actual exponentiation is done by Python at compilation time, so while
1930 the expression can take a noticeable amount of time to compute, that
1932 the expression can take a noticeable amount of time to compute, that
1931 time is purely due to the compilation:
1933 time is purely due to the compilation:
1932
1934
1933 In [5]: time 3**9999;
1935 In [5]: time 3**9999;
1934 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1935 Wall time: 0.00 s
1937 Wall time: 0.00 s
1936
1938
1937 In [6]: time 3**999999;
1939 In [6]: time 3**999999;
1938 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1940 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1939 Wall time: 0.00 s
1941 Wall time: 0.00 s
1940 Compiler : 0.78 s
1942 Compiler : 0.78 s
1941 """
1943 """
1942
1944
1943 # fail immediately if the given expression can't be compiled
1945 # fail immediately if the given expression can't be compiled
1944
1946
1945 expr = self.shell.prefilter(parameter_s,False)
1947 expr = self.shell.prefilter(parameter_s,False)
1946
1948
1947 # Minimum time above which compilation time will be reported
1949 # Minimum time above which compilation time will be reported
1948 tc_min = 0.1
1950 tc_min = 0.1
1949
1951
1950 try:
1952 try:
1951 mode = 'eval'
1953 mode = 'eval'
1952 t0 = clock()
1954 t0 = clock()
1953 code = compile(expr,'<timed eval>',mode)
1955 code = compile(expr,'<timed eval>',mode)
1954 tc = clock()-t0
1956 tc = clock()-t0
1955 except SyntaxError:
1957 except SyntaxError:
1956 mode = 'exec'
1958 mode = 'exec'
1957 t0 = clock()
1959 t0 = clock()
1958 code = compile(expr,'<timed exec>',mode)
1960 code = compile(expr,'<timed exec>',mode)
1959 tc = clock()-t0
1961 tc = clock()-t0
1960 # skew measurement as little as possible
1962 # skew measurement as little as possible
1961 glob = self.shell.user_ns
1963 glob = self.shell.user_ns
1962 clk = clock2
1964 clk = clock2
1963 wtime = time.time
1965 wtime = time.time
1964 # time execution
1966 # time execution
1965 wall_st = wtime()
1967 wall_st = wtime()
1966 if mode=='eval':
1968 if mode=='eval':
1967 st = clk()
1969 st = clk()
1968 out = eval(code,glob)
1970 out = eval(code,glob)
1969 end = clk()
1971 end = clk()
1970 else:
1972 else:
1971 st = clk()
1973 st = clk()
1972 exec code in glob
1974 exec code in glob
1973 end = clk()
1975 end = clk()
1974 out = None
1976 out = None
1975 wall_end = wtime()
1977 wall_end = wtime()
1976 # Compute actual times and report
1978 # Compute actual times and report
1977 wall_time = wall_end-wall_st
1979 wall_time = wall_end-wall_st
1978 cpu_user = end[0]-st[0]
1980 cpu_user = end[0]-st[0]
1979 cpu_sys = end[1]-st[1]
1981 cpu_sys = end[1]-st[1]
1980 cpu_tot = cpu_user+cpu_sys
1982 cpu_tot = cpu_user+cpu_sys
1981 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1983 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1982 (cpu_user,cpu_sys,cpu_tot)
1984 (cpu_user,cpu_sys,cpu_tot)
1983 print "Wall time: %.2f s" % wall_time
1985 print "Wall time: %.2f s" % wall_time
1984 if tc > tc_min:
1986 if tc > tc_min:
1985 print "Compiler : %.2f s" % tc
1987 print "Compiler : %.2f s" % tc
1986 return out
1988 return out
1987
1989
1988 @testdec.skip_doctest
1990 @testdec.skip_doctest
1989 def magic_macro(self,parameter_s = ''):
1991 def magic_macro(self,parameter_s = ''):
1990 """Define a set of input lines as a macro for future re-execution.
1992 """Define a set of input lines as a macro for future re-execution.
1991
1993
1992 Usage:\\
1994 Usage:\\
1993 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1995 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1994
1996
1995 Options:
1997 Options:
1996
1998
1997 -r: use 'raw' input. By default, the 'processed' history is used,
1999 -r: use 'raw' input. By default, the 'processed' history is used,
1998 so that magics are loaded in their transformed version to valid
2000 so that magics are loaded in their transformed version to valid
1999 Python. If this option is given, the raw input as typed as the
2001 Python. If this option is given, the raw input as typed as the
2000 command line is used instead.
2002 command line is used instead.
2001
2003
2002 This will define a global variable called `name` which is a string
2004 This will define a global variable called `name` which is a string
2003 made of joining the slices and lines you specify (n1,n2,... numbers
2005 made of joining the slices and lines you specify (n1,n2,... numbers
2004 above) from your input history into a single string. This variable
2006 above) from your input history into a single string. This variable
2005 acts like an automatic function which re-executes those lines as if
2007 acts like an automatic function which re-executes those lines as if
2006 you had typed them. You just type 'name' at the prompt and the code
2008 you had typed them. You just type 'name' at the prompt and the code
2007 executes.
2009 executes.
2008
2010
2009 The notation for indicating number ranges is: n1-n2 means 'use line
2011 The notation for indicating number ranges is: n1-n2 means 'use line
2010 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2012 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2011 using the lines numbered 5,6 and 7.
2013 using the lines numbered 5,6 and 7.
2012
2014
2013 Note: as a 'hidden' feature, you can also use traditional python slice
2015 Note: as a 'hidden' feature, you can also use traditional python slice
2014 notation, where N:M means numbers N through M-1.
2016 notation, where N:M means numbers N through M-1.
2015
2017
2016 For example, if your history contains (%hist prints it):
2018 For example, if your history contains (%hist prints it):
2017
2019
2018 44: x=1
2020 44: x=1
2019 45: y=3
2021 45: y=3
2020 46: z=x+y
2022 46: z=x+y
2021 47: print x
2023 47: print x
2022 48: a=5
2024 48: a=5
2023 49: print 'x',x,'y',y
2025 49: print 'x',x,'y',y
2024
2026
2025 you can create a macro with lines 44 through 47 (included) and line 49
2027 you can create a macro with lines 44 through 47 (included) and line 49
2026 called my_macro with:
2028 called my_macro with:
2027
2029
2028 In [55]: %macro my_macro 44-47 49
2030 In [55]: %macro my_macro 44-47 49
2029
2031
2030 Now, typing `my_macro` (without quotes) will re-execute all this code
2032 Now, typing `my_macro` (without quotes) will re-execute all this code
2031 in one pass.
2033 in one pass.
2032
2034
2033 You don't need to give the line-numbers in order, and any given line
2035 You don't need to give the line-numbers in order, and any given line
2034 number can appear multiple times. You can assemble macros with any
2036 number can appear multiple times. You can assemble macros with any
2035 lines from your input history in any order.
2037 lines from your input history in any order.
2036
2038
2037 The macro is a simple object which holds its value in an attribute,
2039 The macro is a simple object which holds its value in an attribute,
2038 but IPython's display system checks for macros and executes them as
2040 but IPython's display system checks for macros and executes them as
2039 code instead of printing them when you type their name.
2041 code instead of printing them when you type their name.
2040
2042
2041 You can view a macro's contents by explicitly printing it with:
2043 You can view a macro's contents by explicitly printing it with:
2042
2044
2043 'print macro_name'.
2045 'print macro_name'.
2044
2046
2045 For one-off cases which DON'T contain magic function calls in them you
2047 For one-off cases which DON'T contain magic function calls in them you
2046 can obtain similar results by explicitly executing slices from your
2048 can obtain similar results by explicitly executing slices from your
2047 input history with:
2049 input history with:
2048
2050
2049 In [60]: exec In[44:48]+In[49]"""
2051 In [60]: exec In[44:48]+In[49]"""
2050
2052
2051 opts,args = self.parse_options(parameter_s,'r',mode='list')
2053 opts,args = self.parse_options(parameter_s,'r',mode='list')
2052 if not args:
2054 if not args:
2053 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2055 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2054 macs.sort()
2056 macs.sort()
2055 return macs
2057 return macs
2056 if len(args) == 1:
2058 if len(args) == 1:
2057 raise UsageError(
2059 raise UsageError(
2058 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2060 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2059 name,ranges = args[0], args[1:]
2061 name,ranges = args[0], args[1:]
2060
2062
2061 #print 'rng',ranges # dbg
2063 #print 'rng',ranges # dbg
2062 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2064 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2063 macro = Macro(lines)
2065 macro = Macro(lines)
2064 self.shell.user_ns.update({name:macro})
2066 self.shell.user_ns.update({name:macro})
2065 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2067 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2066 print 'Macro contents:'
2068 print 'Macro contents:'
2067 print macro,
2069 print macro,
2068
2070
2069 def magic_save(self,parameter_s = ''):
2071 def magic_save(self,parameter_s = ''):
2070 """Save a set of lines to a given filename.
2072 """Save a set of lines to a given filename.
2071
2073
2072 Usage:\\
2074 Usage:\\
2073 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2075 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2074
2076
2075 Options:
2077 Options:
2076
2078
2077 -r: use 'raw' input. By default, the 'processed' history is used,
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2078 so that magics are loaded in their transformed version to valid
2080 so that magics are loaded in their transformed version to valid
2079 Python. If this option is given, the raw input as typed as the
2081 Python. If this option is given, the raw input as typed as the
2080 command line is used instead.
2082 command line is used instead.
2081
2083
2082 This function uses the same syntax as %macro for line extraction, but
2084 This function uses the same syntax as %macro for line extraction, but
2083 instead of creating a macro it saves the resulting string to the
2085 instead of creating a macro it saves the resulting string to the
2084 filename you specify.
2086 filename you specify.
2085
2087
2086 It adds a '.py' extension to the file if you don't do so yourself, and
2088 It adds a '.py' extension to the file if you don't do so yourself, and
2087 it asks for confirmation before overwriting existing files."""
2089 it asks for confirmation before overwriting existing files."""
2088
2090
2089 opts,args = self.parse_options(parameter_s,'r',mode='list')
2091 opts,args = self.parse_options(parameter_s,'r',mode='list')
2090 fname,ranges = args[0], args[1:]
2092 fname,ranges = args[0], args[1:]
2091 if not fname.endswith('.py'):
2093 if not fname.endswith('.py'):
2092 fname += '.py'
2094 fname += '.py'
2093 if os.path.isfile(fname):
2095 if os.path.isfile(fname):
2094 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2096 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2095 if ans.lower() not in ['y','yes']:
2097 if ans.lower() not in ['y','yes']:
2096 print 'Operation cancelled.'
2098 print 'Operation cancelled.'
2097 return
2099 return
2098 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2100 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2099 f = file(fname,'w')
2101 f = file(fname,'w')
2100 f.write(cmds)
2102 f.write(cmds)
2101 f.close()
2103 f.close()
2102 print 'The following commands were written to file `%s`:' % fname
2104 print 'The following commands were written to file `%s`:' % fname
2103 print cmds
2105 print cmds
2104
2106
2105 def _edit_macro(self,mname,macro):
2107 def _edit_macro(self,mname,macro):
2106 """open an editor with the macro data in a file"""
2108 """open an editor with the macro data in a file"""
2107 filename = self.shell.mktempfile(macro.value)
2109 filename = self.shell.mktempfile(macro.value)
2108 self.shell.hooks.editor(filename)
2110 self.shell.hooks.editor(filename)
2109
2111
2110 # and make a new macro object, to replace the old one
2112 # and make a new macro object, to replace the old one
2111 mfile = open(filename)
2113 mfile = open(filename)
2112 mvalue = mfile.read()
2114 mvalue = mfile.read()
2113 mfile.close()
2115 mfile.close()
2114 self.shell.user_ns[mname] = Macro(mvalue)
2116 self.shell.user_ns[mname] = Macro(mvalue)
2115
2117
2116 def magic_ed(self,parameter_s=''):
2118 def magic_ed(self,parameter_s=''):
2117 """Alias to %edit."""
2119 """Alias to %edit."""
2118 return self.magic_edit(parameter_s)
2120 return self.magic_edit(parameter_s)
2119
2121
2120 @testdec.skip_doctest
2122 @testdec.skip_doctest
2121 def magic_edit(self,parameter_s='',last_call=['','']):
2123 def magic_edit(self,parameter_s='',last_call=['','']):
2122 """Bring up an editor and execute the resulting code.
2124 """Bring up an editor and execute the resulting code.
2123
2125
2124 Usage:
2126 Usage:
2125 %edit [options] [args]
2127 %edit [options] [args]
2126
2128
2127 %edit runs IPython's editor hook. The default version of this hook is
2129 %edit runs IPython's editor hook. The default version of this hook is
2128 set to call the __IPYTHON__.rc.editor command. This is read from your
2130 set to call the __IPYTHON__.rc.editor command. This is read from your
2129 environment variable $EDITOR. If this isn't found, it will default to
2131 environment variable $EDITOR. If this isn't found, it will default to
2130 vi under Linux/Unix and to notepad under Windows. See the end of this
2132 vi under Linux/Unix and to notepad under Windows. See the end of this
2131 docstring for how to change the editor hook.
2133 docstring for how to change the editor hook.
2132
2134
2133 You can also set the value of this editor via the command line option
2135 You can also set the value of this editor via the command line option
2134 '-editor' or in your ipythonrc file. This is useful if you wish to use
2136 '-editor' or in your ipythonrc file. This is useful if you wish to use
2135 specifically for IPython an editor different from your typical default
2137 specifically for IPython an editor different from your typical default
2136 (and for Windows users who typically don't set environment variables).
2138 (and for Windows users who typically don't set environment variables).
2137
2139
2138 This command allows you to conveniently edit multi-line code right in
2140 This command allows you to conveniently edit multi-line code right in
2139 your IPython session.
2141 your IPython session.
2140
2142
2141 If called without arguments, %edit opens up an empty editor with a
2143 If called without arguments, %edit opens up an empty editor with a
2142 temporary file and will execute the contents of this file when you
2144 temporary file and will execute the contents of this file when you
2143 close it (don't forget to save it!).
2145 close it (don't forget to save it!).
2144
2146
2145
2147
2146 Options:
2148 Options:
2147
2149
2148 -n <number>: open the editor at a specified line number. By default,
2150 -n <number>: open the editor at a specified line number. By default,
2149 the IPython editor hook uses the unix syntax 'editor +N filename', but
2151 the IPython editor hook uses the unix syntax 'editor +N filename', but
2150 you can configure this by providing your own modified hook if your
2152 you can configure this by providing your own modified hook if your
2151 favorite editor supports line-number specifications with a different
2153 favorite editor supports line-number specifications with a different
2152 syntax.
2154 syntax.
2153
2155
2154 -p: this will call the editor with the same data as the previous time
2156 -p: this will call the editor with the same data as the previous time
2155 it was used, regardless of how long ago (in your current session) it
2157 it was used, regardless of how long ago (in your current session) it
2156 was.
2158 was.
2157
2159
2158 -r: use 'raw' input. This option only applies to input taken from the
2160 -r: use 'raw' input. This option only applies to input taken from the
2159 user's history. By default, the 'processed' history is used, so that
2161 user's history. By default, the 'processed' history is used, so that
2160 magics are loaded in their transformed version to valid Python. If
2162 magics are loaded in their transformed version to valid Python. If
2161 this option is given, the raw input as typed as the command line is
2163 this option is given, the raw input as typed as the command line is
2162 used instead. When you exit the editor, it will be executed by
2164 used instead. When you exit the editor, it will be executed by
2163 IPython's own processor.
2165 IPython's own processor.
2164
2166
2165 -x: do not execute the edited code immediately upon exit. This is
2167 -x: do not execute the edited code immediately upon exit. This is
2166 mainly useful if you are editing programs which need to be called with
2168 mainly useful if you are editing programs which need to be called with
2167 command line arguments, which you can then do using %run.
2169 command line arguments, which you can then do using %run.
2168
2170
2169
2171
2170 Arguments:
2172 Arguments:
2171
2173
2172 If arguments are given, the following possibilites exist:
2174 If arguments are given, the following possibilites exist:
2173
2175
2174 - The arguments are numbers or pairs of colon-separated numbers (like
2176 - The arguments are numbers or pairs of colon-separated numbers (like
2175 1 4:8 9). These are interpreted as lines of previous input to be
2177 1 4:8 9). These are interpreted as lines of previous input to be
2176 loaded into the editor. The syntax is the same of the %macro command.
2178 loaded into the editor. The syntax is the same of the %macro command.
2177
2179
2178 - If the argument doesn't start with a number, it is evaluated as a
2180 - If the argument doesn't start with a number, it is evaluated as a
2179 variable and its contents loaded into the editor. You can thus edit
2181 variable and its contents loaded into the editor. You can thus edit
2180 any string which contains python code (including the result of
2182 any string which contains python code (including the result of
2181 previous edits).
2183 previous edits).
2182
2184
2183 - If the argument is the name of an object (other than a string),
2185 - If the argument is the name of an object (other than a string),
2184 IPython will try to locate the file where it was defined and open the
2186 IPython will try to locate the file where it was defined and open the
2185 editor at the point where it is defined. You can use `%edit function`
2187 editor at the point where it is defined. You can use `%edit function`
2186 to load an editor exactly at the point where 'function' is defined,
2188 to load an editor exactly at the point where 'function' is defined,
2187 edit it and have the file be executed automatically.
2189 edit it and have the file be executed automatically.
2188
2190
2189 If the object is a macro (see %macro for details), this opens up your
2191 If the object is a macro (see %macro for details), this opens up your
2190 specified editor with a temporary file containing the macro's data.
2192 specified editor with a temporary file containing the macro's data.
2191 Upon exit, the macro is reloaded with the contents of the file.
2193 Upon exit, the macro is reloaded with the contents of the file.
2192
2194
2193 Note: opening at an exact line is only supported under Unix, and some
2195 Note: opening at an exact line is only supported under Unix, and some
2194 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2196 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2195 '+NUMBER' parameter necessary for this feature. Good editors like
2197 '+NUMBER' parameter necessary for this feature. Good editors like
2196 (X)Emacs, vi, jed, pico and joe all do.
2198 (X)Emacs, vi, jed, pico and joe all do.
2197
2199
2198 - If the argument is not found as a variable, IPython will look for a
2200 - If the argument is not found as a variable, IPython will look for a
2199 file with that name (adding .py if necessary) and load it into the
2201 file with that name (adding .py if necessary) and load it into the
2200 editor. It will execute its contents with execfile() when you exit,
2202 editor. It will execute its contents with execfile() when you exit,
2201 loading any code in the file into your interactive namespace.
2203 loading any code in the file into your interactive namespace.
2202
2204
2203 After executing your code, %edit will return as output the code you
2205 After executing your code, %edit will return as output the code you
2204 typed in the editor (except when it was an existing file). This way
2206 typed in the editor (except when it was an existing file). This way
2205 you can reload the code in further invocations of %edit as a variable,
2207 you can reload the code in further invocations of %edit as a variable,
2206 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2208 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2207 the output.
2209 the output.
2208
2210
2209 Note that %edit is also available through the alias %ed.
2211 Note that %edit is also available through the alias %ed.
2210
2212
2211 This is an example of creating a simple function inside the editor and
2213 This is an example of creating a simple function inside the editor and
2212 then modifying it. First, start up the editor:
2214 then modifying it. First, start up the editor:
2213
2215
2214 In [1]: ed
2216 In [1]: ed
2215 Editing... done. Executing edited code...
2217 Editing... done. Executing edited code...
2216 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2218 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2217
2219
2218 We can then call the function foo():
2220 We can then call the function foo():
2219
2221
2220 In [2]: foo()
2222 In [2]: foo()
2221 foo() was defined in an editing session
2223 foo() was defined in an editing session
2222
2224
2223 Now we edit foo. IPython automatically loads the editor with the
2225 Now we edit foo. IPython automatically loads the editor with the
2224 (temporary) file where foo() was previously defined:
2226 (temporary) file where foo() was previously defined:
2225
2227
2226 In [3]: ed foo
2228 In [3]: ed foo
2227 Editing... done. Executing edited code...
2229 Editing... done. Executing edited code...
2228
2230
2229 And if we call foo() again we get the modified version:
2231 And if we call foo() again we get the modified version:
2230
2232
2231 In [4]: foo()
2233 In [4]: foo()
2232 foo() has now been changed!
2234 foo() has now been changed!
2233
2235
2234 Here is an example of how to edit a code snippet successive
2236 Here is an example of how to edit a code snippet successive
2235 times. First we call the editor:
2237 times. First we call the editor:
2236
2238
2237 In [5]: ed
2239 In [5]: ed
2238 Editing... done. Executing edited code...
2240 Editing... done. Executing edited code...
2239 hello
2241 hello
2240 Out[5]: "print 'hello'n"
2242 Out[5]: "print 'hello'n"
2241
2243
2242 Now we call it again with the previous output (stored in _):
2244 Now we call it again with the previous output (stored in _):
2243
2245
2244 In [6]: ed _
2246 In [6]: ed _
2245 Editing... done. Executing edited code...
2247 Editing... done. Executing edited code...
2246 hello world
2248 hello world
2247 Out[6]: "print 'hello world'n"
2249 Out[6]: "print 'hello world'n"
2248
2250
2249 Now we call it with the output #8 (stored in _8, also as Out[8]):
2251 Now we call it with the output #8 (stored in _8, also as Out[8]):
2250
2252
2251 In [7]: ed _8
2253 In [7]: ed _8
2252 Editing... done. Executing edited code...
2254 Editing... done. Executing edited code...
2253 hello again
2255 hello again
2254 Out[7]: "print 'hello again'n"
2256 Out[7]: "print 'hello again'n"
2255
2257
2256
2258
2257 Changing the default editor hook:
2259 Changing the default editor hook:
2258
2260
2259 If you wish to write your own editor hook, you can put it in a
2261 If you wish to write your own editor hook, you can put it in a
2260 configuration file which you load at startup time. The default hook
2262 configuration file which you load at startup time. The default hook
2261 is defined in the IPython.core.hooks module, and you can use that as a
2263 is defined in the IPython.core.hooks module, and you can use that as a
2262 starting example for further modifications. That file also has
2264 starting example for further modifications. That file also has
2263 general instructions on how to set a new hook for use once you've
2265 general instructions on how to set a new hook for use once you've
2264 defined it."""
2266 defined it."""
2265
2267
2266 # FIXME: This function has become a convoluted mess. It needs a
2268 # FIXME: This function has become a convoluted mess. It needs a
2267 # ground-up rewrite with clean, simple logic.
2269 # ground-up rewrite with clean, simple logic.
2268
2270
2269 def make_filename(arg):
2271 def make_filename(arg):
2270 "Make a filename from the given args"
2272 "Make a filename from the given args"
2271 try:
2273 try:
2272 filename = get_py_filename(arg)
2274 filename = get_py_filename(arg)
2273 except IOError:
2275 except IOError:
2274 if args.endswith('.py'):
2276 if args.endswith('.py'):
2275 filename = arg
2277 filename = arg
2276 else:
2278 else:
2277 filename = None
2279 filename = None
2278 return filename
2280 return filename
2279
2281
2280 # custom exceptions
2282 # custom exceptions
2281 class DataIsObject(Exception): pass
2283 class DataIsObject(Exception): pass
2282
2284
2283 opts,args = self.parse_options(parameter_s,'prxn:')
2285 opts,args = self.parse_options(parameter_s,'prxn:')
2284 # Set a few locals from the options for convenience:
2286 # Set a few locals from the options for convenience:
2285 opts_p = opts.has_key('p')
2287 opts_p = opts.has_key('p')
2286 opts_r = opts.has_key('r')
2288 opts_r = opts.has_key('r')
2287
2289
2288 # Default line number value
2290 # Default line number value
2289 lineno = opts.get('n',None)
2291 lineno = opts.get('n',None)
2290
2292
2291 if opts_p:
2293 if opts_p:
2292 args = '_%s' % last_call[0]
2294 args = '_%s' % last_call[0]
2293 if not self.shell.user_ns.has_key(args):
2295 if not self.shell.user_ns.has_key(args):
2294 args = last_call[1]
2296 args = last_call[1]
2295
2297
2296 # use last_call to remember the state of the previous call, but don't
2298 # use last_call to remember the state of the previous call, but don't
2297 # let it be clobbered by successive '-p' calls.
2299 # let it be clobbered by successive '-p' calls.
2298 try:
2300 try:
2299 last_call[0] = self.shell.outputcache.prompt_count
2301 last_call[0] = self.shell.outputcache.prompt_count
2300 if not opts_p:
2302 if not opts_p:
2301 last_call[1] = parameter_s
2303 last_call[1] = parameter_s
2302 except:
2304 except:
2303 pass
2305 pass
2304
2306
2305 # by default this is done with temp files, except when the given
2307 # by default this is done with temp files, except when the given
2306 # arg is a filename
2308 # arg is a filename
2307 use_temp = 1
2309 use_temp = 1
2308
2310
2309 if re.match(r'\d',args):
2311 if re.match(r'\d',args):
2310 # Mode where user specifies ranges of lines, like in %macro.
2312 # Mode where user specifies ranges of lines, like in %macro.
2311 # This means that you can't edit files whose names begin with
2313 # This means that you can't edit files whose names begin with
2312 # numbers this way. Tough.
2314 # numbers this way. Tough.
2313 ranges = args.split()
2315 ranges = args.split()
2314 data = ''.join(self.extract_input_slices(ranges,opts_r))
2316 data = ''.join(self.extract_input_slices(ranges,opts_r))
2315 elif args.endswith('.py'):
2317 elif args.endswith('.py'):
2316 filename = make_filename(args)
2318 filename = make_filename(args)
2317 data = ''
2319 data = ''
2318 use_temp = 0
2320 use_temp = 0
2319 elif args:
2321 elif args:
2320 try:
2322 try:
2321 # Load the parameter given as a variable. If not a string,
2323 # Load the parameter given as a variable. If not a string,
2322 # process it as an object instead (below)
2324 # process it as an object instead (below)
2323
2325
2324 #print '*** args',args,'type',type(args) # dbg
2326 #print '*** args',args,'type',type(args) # dbg
2325 data = eval(args,self.shell.user_ns)
2327 data = eval(args,self.shell.user_ns)
2326 if not type(data) in StringTypes:
2328 if not type(data) in StringTypes:
2327 raise DataIsObject
2329 raise DataIsObject
2328
2330
2329 except (NameError,SyntaxError):
2331 except (NameError,SyntaxError):
2330 # given argument is not a variable, try as a filename
2332 # given argument is not a variable, try as a filename
2331 filename = make_filename(args)
2333 filename = make_filename(args)
2332 if filename is None:
2334 if filename is None:
2333 warn("Argument given (%s) can't be found as a variable "
2335 warn("Argument given (%s) can't be found as a variable "
2334 "or as a filename." % args)
2336 "or as a filename." % args)
2335 return
2337 return
2336
2338
2337 data = ''
2339 data = ''
2338 use_temp = 0
2340 use_temp = 0
2339 except DataIsObject:
2341 except DataIsObject:
2340
2342
2341 # macros have a special edit function
2343 # macros have a special edit function
2342 if isinstance(data,Macro):
2344 if isinstance(data,Macro):
2343 self._edit_macro(args,data)
2345 self._edit_macro(args,data)
2344 return
2346 return
2345
2347
2346 # For objects, try to edit the file where they are defined
2348 # For objects, try to edit the file where they are defined
2347 try:
2349 try:
2348 filename = inspect.getabsfile(data)
2350 filename = inspect.getabsfile(data)
2349 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2351 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2350 # class created by %edit? Try to find source
2352 # class created by %edit? Try to find source
2351 # by looking for method definitions instead, the
2353 # by looking for method definitions instead, the
2352 # __module__ in those classes is FakeModule.
2354 # __module__ in those classes is FakeModule.
2353 attrs = [getattr(data, aname) for aname in dir(data)]
2355 attrs = [getattr(data, aname) for aname in dir(data)]
2354 for attr in attrs:
2356 for attr in attrs:
2355 if not inspect.ismethod(attr):
2357 if not inspect.ismethod(attr):
2356 continue
2358 continue
2357 filename = inspect.getabsfile(attr)
2359 filename = inspect.getabsfile(attr)
2358 if filename and 'fakemodule' not in filename.lower():
2360 if filename and 'fakemodule' not in filename.lower():
2359 # change the attribute to be the edit target instead
2361 # change the attribute to be the edit target instead
2360 data = attr
2362 data = attr
2361 break
2363 break
2362
2364
2363 datafile = 1
2365 datafile = 1
2364 except TypeError:
2366 except TypeError:
2365 filename = make_filename(args)
2367 filename = make_filename(args)
2366 datafile = 1
2368 datafile = 1
2367 warn('Could not find file where `%s` is defined.\n'
2369 warn('Could not find file where `%s` is defined.\n'
2368 'Opening a file named `%s`' % (args,filename))
2370 'Opening a file named `%s`' % (args,filename))
2369 # Now, make sure we can actually read the source (if it was in
2371 # Now, make sure we can actually read the source (if it was in
2370 # a temp file it's gone by now).
2372 # a temp file it's gone by now).
2371 if datafile:
2373 if datafile:
2372 try:
2374 try:
2373 if lineno is None:
2375 if lineno is None:
2374 lineno = inspect.getsourcelines(data)[1]
2376 lineno = inspect.getsourcelines(data)[1]
2375 except IOError:
2377 except IOError:
2376 filename = make_filename(args)
2378 filename = make_filename(args)
2377 if filename is None:
2379 if filename is None:
2378 warn('The file `%s` where `%s` was defined cannot '
2380 warn('The file `%s` where `%s` was defined cannot '
2379 'be read.' % (filename,data))
2381 'be read.' % (filename,data))
2380 return
2382 return
2381 use_temp = 0
2383 use_temp = 0
2382 else:
2384 else:
2383 data = ''
2385 data = ''
2384
2386
2385 if use_temp:
2387 if use_temp:
2386 filename = self.shell.mktempfile(data)
2388 filename = self.shell.mktempfile(data)
2387 print 'IPython will make a temporary file named:',filename
2389 print 'IPython will make a temporary file named:',filename
2388
2390
2389 # do actual editing here
2391 # do actual editing here
2390 print 'Editing...',
2392 print 'Editing...',
2391 sys.stdout.flush()
2393 sys.stdout.flush()
2392 try:
2394 try:
2393 self.shell.hooks.editor(filename,lineno)
2395 self.shell.hooks.editor(filename,lineno)
2394 except ipapi.TryNext:
2396 except ipapi.TryNext:
2395 warn('Could not open editor')
2397 warn('Could not open editor')
2396 return
2398 return
2397
2399
2398 # XXX TODO: should this be generalized for all string vars?
2400 # XXX TODO: should this be generalized for all string vars?
2399 # For now, this is special-cased to blocks created by cpaste
2401 # For now, this is special-cased to blocks created by cpaste
2400 if args.strip() == 'pasted_block':
2402 if args.strip() == 'pasted_block':
2401 self.shell.user_ns['pasted_block'] = file_read(filename)
2403 self.shell.user_ns['pasted_block'] = file_read(filename)
2402
2404
2403 if opts.has_key('x'): # -x prevents actual execution
2405 if opts.has_key('x'): # -x prevents actual execution
2404 print
2406 print
2405 else:
2407 else:
2406 print 'done. Executing edited code...'
2408 print 'done. Executing edited code...'
2407 if opts_r:
2409 if opts_r:
2408 self.shell.runlines(file_read(filename))
2410 self.shell.runlines(file_read(filename))
2409 else:
2411 else:
2410 self.shell.safe_execfile(filename,self.shell.user_ns,
2412 self.shell.safe_execfile(filename,self.shell.user_ns,
2411 self.shell.user_ns)
2413 self.shell.user_ns)
2412
2414
2413
2415
2414 if use_temp:
2416 if use_temp:
2415 try:
2417 try:
2416 return open(filename).read()
2418 return open(filename).read()
2417 except IOError,msg:
2419 except IOError,msg:
2418 if msg.filename == filename:
2420 if msg.filename == filename:
2419 warn('File not found. Did you forget to save?')
2421 warn('File not found. Did you forget to save?')
2420 return
2422 return
2421 else:
2423 else:
2422 self.shell.showtraceback()
2424 self.shell.showtraceback()
2423
2425
2424 def magic_xmode(self,parameter_s = ''):
2426 def magic_xmode(self,parameter_s = ''):
2425 """Switch modes for the exception handlers.
2427 """Switch modes for the exception handlers.
2426
2428
2427 Valid modes: Plain, Context and Verbose.
2429 Valid modes: Plain, Context and Verbose.
2428
2430
2429 If called without arguments, acts as a toggle."""
2431 If called without arguments, acts as a toggle."""
2430
2432
2431 def xmode_switch_err(name):
2433 def xmode_switch_err(name):
2432 warn('Error changing %s exception modes.\n%s' %
2434 warn('Error changing %s exception modes.\n%s' %
2433 (name,sys.exc_info()[1]))
2435 (name,sys.exc_info()[1]))
2434
2436
2435 shell = self.shell
2437 shell = self.shell
2436 new_mode = parameter_s.strip().capitalize()
2438 new_mode = parameter_s.strip().capitalize()
2437 try:
2439 try:
2438 shell.InteractiveTB.set_mode(mode=new_mode)
2440 shell.InteractiveTB.set_mode(mode=new_mode)
2439 print 'Exception reporting mode:',shell.InteractiveTB.mode
2441 print 'Exception reporting mode:',shell.InteractiveTB.mode
2440 except:
2442 except:
2441 xmode_switch_err('user')
2443 xmode_switch_err('user')
2442
2444
2443 # threaded shells use a special handler in sys.excepthook
2445 # threaded shells use a special handler in sys.excepthook
2444 if shell.isthreaded:
2446 if shell.isthreaded:
2445 try:
2447 try:
2446 shell.sys_excepthook.set_mode(mode=new_mode)
2448 shell.sys_excepthook.set_mode(mode=new_mode)
2447 except:
2449 except:
2448 xmode_switch_err('threaded')
2450 xmode_switch_err('threaded')
2449
2451
2450 def magic_colors(self,parameter_s = ''):
2452 def magic_colors(self,parameter_s = ''):
2451 """Switch color scheme for prompts, info system and exception handlers.
2453 """Switch color scheme for prompts, info system and exception handlers.
2452
2454
2453 Currently implemented schemes: NoColor, Linux, LightBG.
2455 Currently implemented schemes: NoColor, Linux, LightBG.
2454
2456
2455 Color scheme names are not case-sensitive."""
2457 Color scheme names are not case-sensitive."""
2456
2458
2457 def color_switch_err(name):
2459 def color_switch_err(name):
2458 warn('Error changing %s color schemes.\n%s' %
2460 warn('Error changing %s color schemes.\n%s' %
2459 (name,sys.exc_info()[1]))
2461 (name,sys.exc_info()[1]))
2460
2462
2461
2463
2462 new_scheme = parameter_s.strip()
2464 new_scheme = parameter_s.strip()
2463 if not new_scheme:
2465 if not new_scheme:
2464 raise UsageError(
2466 raise UsageError(
2465 "%colors: you must specify a color scheme. See '%colors?'")
2467 "%colors: you must specify a color scheme. See '%colors?'")
2466 return
2468 return
2467 # local shortcut
2469 # local shortcut
2468 shell = self.shell
2470 shell = self.shell
2469
2471
2470 import IPython.utils.rlineimpl as readline
2472 import IPython.utils.rlineimpl as readline
2471
2473
2472 if not readline.have_readline and sys.platform == "win32":
2474 if not readline.have_readline and sys.platform == "win32":
2473 msg = """\
2475 msg = """\
2474 Proper color support under MS Windows requires the pyreadline library.
2476 Proper color support under MS Windows requires the pyreadline library.
2475 You can find it at:
2477 You can find it at:
2476 http://ipython.scipy.org/moin/PyReadline/Intro
2478 http://ipython.scipy.org/moin/PyReadline/Intro
2477 Gary's readline needs the ctypes module, from:
2479 Gary's readline needs the ctypes module, from:
2478 http://starship.python.net/crew/theller/ctypes
2480 http://starship.python.net/crew/theller/ctypes
2479 (Note that ctypes is already part of Python versions 2.5 and newer).
2481 (Note that ctypes is already part of Python versions 2.5 and newer).
2480
2482
2481 Defaulting color scheme to 'NoColor'"""
2483 Defaulting color scheme to 'NoColor'"""
2482 new_scheme = 'NoColor'
2484 new_scheme = 'NoColor'
2483 warn(msg)
2485 warn(msg)
2484
2486
2485 # readline option is 0
2487 # readline option is 0
2486 if not shell.has_readline:
2488 if not shell.has_readline:
2487 new_scheme = 'NoColor'
2489 new_scheme = 'NoColor'
2488
2490
2489 # Set prompt colors
2491 # Set prompt colors
2490 try:
2492 try:
2491 shell.outputcache.set_colors(new_scheme)
2493 shell.outputcache.set_colors(new_scheme)
2492 except:
2494 except:
2493 color_switch_err('prompt')
2495 color_switch_err('prompt')
2494 else:
2496 else:
2495 shell.rc.colors = \
2497 shell.colors = \
2496 shell.outputcache.color_table.active_scheme_name
2498 shell.outputcache.color_table.active_scheme_name
2497 # Set exception colors
2499 # Set exception colors
2498 try:
2500 try:
2499 shell.InteractiveTB.set_colors(scheme = new_scheme)
2501 shell.InteractiveTB.set_colors(scheme = new_scheme)
2500 shell.SyntaxTB.set_colors(scheme = new_scheme)
2502 shell.SyntaxTB.set_colors(scheme = new_scheme)
2501 except:
2503 except:
2502 color_switch_err('exception')
2504 color_switch_err('exception')
2503
2505
2504 # threaded shells use a verbose traceback in sys.excepthook
2506 # threaded shells use a verbose traceback in sys.excepthook
2505 if shell.isthreaded:
2507 if shell.isthreaded:
2506 try:
2508 try:
2507 shell.sys_excepthook.set_colors(scheme=new_scheme)
2509 shell.sys_excepthook.set_colors(scheme=new_scheme)
2508 except:
2510 except:
2509 color_switch_err('system exception handler')
2511 color_switch_err('system exception handler')
2510
2512
2511 # Set info (for 'object?') colors
2513 # Set info (for 'object?') colors
2512 if shell.rc.color_info:
2514 if shell.color_info:
2513 try:
2515 try:
2514 shell.inspector.set_active_scheme(new_scheme)
2516 shell.inspector.set_active_scheme(new_scheme)
2515 except:
2517 except:
2516 color_switch_err('object inspector')
2518 color_switch_err('object inspector')
2517 else:
2519 else:
2518 shell.inspector.set_active_scheme('NoColor')
2520 shell.inspector.set_active_scheme('NoColor')
2519
2521
2520 def magic_color_info(self,parameter_s = ''):
2522 def magic_color_info(self,parameter_s = ''):
2521 """Toggle color_info.
2523 """Toggle color_info.
2522
2524
2523 The color_info configuration parameter controls whether colors are
2525 The color_info configuration parameter controls whether colors are
2524 used for displaying object details (by things like %psource, %pfile or
2526 used for displaying object details (by things like %psource, %pfile or
2525 the '?' system). This function toggles this value with each call.
2527 the '?' system). This function toggles this value with each call.
2526
2528
2527 Note that unless you have a fairly recent pager (less works better
2529 Note that unless you have a fairly recent pager (less works better
2528 than more) in your system, using colored object information displays
2530 than more) in your system, using colored object information displays
2529 will not work properly. Test it and see."""
2531 will not work properly. Test it and see."""
2530
2532
2531 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2533 self.shell.color_info = 1 - self.shell.color_info
2532 self.magic_colors(self.shell.rc.colors)
2534 self.magic_colors(self.shell.colors)
2533 print 'Object introspection functions have now coloring:',
2535 print 'Object introspection functions have now coloring:',
2534 print ['OFF','ON'][self.shell.rc.color_info]
2536 print ['OFF','ON'][self.shell.color_info]
2535
2537
2536 def magic_Pprint(self, parameter_s=''):
2538 def magic_Pprint(self, parameter_s=''):
2537 """Toggle pretty printing on/off."""
2539 """Toggle pretty printing on/off."""
2538
2540
2539 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2541 self.shell.pprint = 1 - self.shell.pprint
2540 print 'Pretty printing has been turned', \
2542 print 'Pretty printing has been turned', \
2541 ['OFF','ON'][self.shell.rc.pprint]
2543 ['OFF','ON'][self.shell.pprint]
2542
2544
2543 def magic_exit(self, parameter_s=''):
2545 def magic_exit(self, parameter_s=''):
2544 """Exit IPython, confirming if configured to do so.
2546 """Exit IPython, confirming if configured to do so.
2545
2547
2546 You can configure whether IPython asks for confirmation upon exit by
2548 You can configure whether IPython asks for confirmation upon exit by
2547 setting the confirm_exit flag in the ipythonrc file."""
2549 setting the confirm_exit flag in the ipythonrc file."""
2548
2550
2549 self.shell.exit()
2551 self.shell.exit()
2550
2552
2551 def magic_quit(self, parameter_s=''):
2553 def magic_quit(self, parameter_s=''):
2552 """Exit IPython, confirming if configured to do so (like %exit)"""
2554 """Exit IPython, confirming if configured to do so (like %exit)"""
2553
2555
2554 self.shell.exit()
2556 self.shell.exit()
2555
2557
2556 def magic_Exit(self, parameter_s=''):
2558 def magic_Exit(self, parameter_s=''):
2557 """Exit IPython without confirmation."""
2559 """Exit IPython without confirmation."""
2558
2560
2559 self.shell.ask_exit()
2561 self.shell.ask_exit()
2560
2562
2561 #......................................................................
2563 #......................................................................
2562 # Functions to implement unix shell-type things
2564 # Functions to implement unix shell-type things
2563
2565
2564 @testdec.skip_doctest
2566 @testdec.skip_doctest
2565 def magic_alias(self, parameter_s = ''):
2567 def magic_alias(self, parameter_s = ''):
2566 """Define an alias for a system command.
2568 """Define an alias for a system command.
2567
2569
2568 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2570 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2569
2571
2570 Then, typing 'alias_name params' will execute the system command 'cmd
2572 Then, typing 'alias_name params' will execute the system command 'cmd
2571 params' (from your underlying operating system).
2573 params' (from your underlying operating system).
2572
2574
2573 Aliases have lower precedence than magic functions and Python normal
2575 Aliases have lower precedence than magic functions and Python normal
2574 variables, so if 'foo' is both a Python variable and an alias, the
2576 variables, so if 'foo' is both a Python variable and an alias, the
2575 alias can not be executed until 'del foo' removes the Python variable.
2577 alias can not be executed until 'del foo' removes the Python variable.
2576
2578
2577 You can use the %l specifier in an alias definition to represent the
2579 You can use the %l specifier in an alias definition to represent the
2578 whole line when the alias is called. For example:
2580 whole line when the alias is called. For example:
2579
2581
2580 In [2]: alias all echo "Input in brackets: <%l>"
2582 In [2]: alias all echo "Input in brackets: <%l>"
2581 In [3]: all hello world
2583 In [3]: all hello world
2582 Input in brackets: <hello world>
2584 Input in brackets: <hello world>
2583
2585
2584 You can also define aliases with parameters using %s specifiers (one
2586 You can also define aliases with parameters using %s specifiers (one
2585 per parameter):
2587 per parameter):
2586
2588
2587 In [1]: alias parts echo first %s second %s
2589 In [1]: alias parts echo first %s second %s
2588 In [2]: %parts A B
2590 In [2]: %parts A B
2589 first A second B
2591 first A second B
2590 In [3]: %parts A
2592 In [3]: %parts A
2591 Incorrect number of arguments: 2 expected.
2593 Incorrect number of arguments: 2 expected.
2592 parts is an alias to: 'echo first %s second %s'
2594 parts is an alias to: 'echo first %s second %s'
2593
2595
2594 Note that %l and %s are mutually exclusive. You can only use one or
2596 Note that %l and %s are mutually exclusive. You can only use one or
2595 the other in your aliases.
2597 the other in your aliases.
2596
2598
2597 Aliases expand Python variables just like system calls using ! or !!
2599 Aliases expand Python variables just like system calls using ! or !!
2598 do: all expressions prefixed with '$' get expanded. For details of
2600 do: all expressions prefixed with '$' get expanded. For details of
2599 the semantic rules, see PEP-215:
2601 the semantic rules, see PEP-215:
2600 http://www.python.org/peps/pep-0215.html. This is the library used by
2602 http://www.python.org/peps/pep-0215.html. This is the library used by
2601 IPython for variable expansion. If you want to access a true shell
2603 IPython for variable expansion. If you want to access a true shell
2602 variable, an extra $ is necessary to prevent its expansion by IPython:
2604 variable, an extra $ is necessary to prevent its expansion by IPython:
2603
2605
2604 In [6]: alias show echo
2606 In [6]: alias show echo
2605 In [7]: PATH='A Python string'
2607 In [7]: PATH='A Python string'
2606 In [8]: show $PATH
2608 In [8]: show $PATH
2607 A Python string
2609 A Python string
2608 In [9]: show $$PATH
2610 In [9]: show $$PATH
2609 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2611 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2610
2612
2611 You can use the alias facility to acess all of $PATH. See the %rehash
2613 You can use the alias facility to acess all of $PATH. See the %rehash
2612 and %rehashx functions, which automatically create aliases for the
2614 and %rehashx functions, which automatically create aliases for the
2613 contents of your $PATH.
2615 contents of your $PATH.
2614
2616
2615 If called with no parameters, %alias prints the current alias table."""
2617 If called with no parameters, %alias prints the current alias table."""
2616
2618
2617 par = parameter_s.strip()
2619 par = parameter_s.strip()
2618 if not par:
2620 if not par:
2619 stored = self.db.get('stored_aliases', {} )
2621 stored = self.db.get('stored_aliases', {} )
2620 atab = self.shell.alias_table
2622 atab = self.shell.alias_table
2621 aliases = atab.keys()
2623 aliases = atab.keys()
2622 aliases.sort()
2624 aliases.sort()
2623 res = []
2625 res = []
2624 showlast = []
2626 showlast = []
2625 for alias in aliases:
2627 for alias in aliases:
2626 special = False
2628 special = False
2627 try:
2629 try:
2628 tgt = atab[alias][1]
2630 tgt = atab[alias][1]
2629 except (TypeError, AttributeError):
2631 except (TypeError, AttributeError):
2630 # unsubscriptable? probably a callable
2632 # unsubscriptable? probably a callable
2631 tgt = atab[alias]
2633 tgt = atab[alias]
2632 special = True
2634 special = True
2633 # 'interesting' aliases
2635 # 'interesting' aliases
2634 if (alias in stored or
2636 if (alias in stored or
2635 special or
2637 special or
2636 alias.lower() != os.path.splitext(tgt)[0].lower() or
2638 alias.lower() != os.path.splitext(tgt)[0].lower() or
2637 ' ' in tgt):
2639 ' ' in tgt):
2638 showlast.append((alias, tgt))
2640 showlast.append((alias, tgt))
2639 else:
2641 else:
2640 res.append((alias, tgt ))
2642 res.append((alias, tgt ))
2641
2643
2642 # show most interesting aliases last
2644 # show most interesting aliases last
2643 res.extend(showlast)
2645 res.extend(showlast)
2644 print "Total number of aliases:",len(aliases)
2646 print "Total number of aliases:",len(aliases)
2645 return res
2647 return res
2646 try:
2648 try:
2647 alias,cmd = par.split(None,1)
2649 alias,cmd = par.split(None,1)
2648 except:
2650 except:
2649 print oinspect.getdoc(self.magic_alias)
2651 print oinspect.getdoc(self.magic_alias)
2650 else:
2652 else:
2651 nargs = cmd.count('%s')
2653 nargs = cmd.count('%s')
2652 if nargs>0 and cmd.find('%l')>=0:
2654 if nargs>0 and cmd.find('%l')>=0:
2653 error('The %s and %l specifiers are mutually exclusive '
2655 error('The %s and %l specifiers are mutually exclusive '
2654 'in alias definitions.')
2656 'in alias definitions.')
2655 else: # all looks OK
2657 else: # all looks OK
2656 self.shell.alias_table[alias] = (nargs,cmd)
2658 self.shell.alias_table[alias] = (nargs,cmd)
2657 self.shell.alias_table_validate(verbose=0)
2659 self.shell.alias_table_validate(verbose=0)
2658 # end magic_alias
2660 # end magic_alias
2659
2661
2660 def magic_unalias(self, parameter_s = ''):
2662 def magic_unalias(self, parameter_s = ''):
2661 """Remove an alias"""
2663 """Remove an alias"""
2662
2664
2663 aname = parameter_s.strip()
2665 aname = parameter_s.strip()
2664 if aname in self.shell.alias_table:
2666 if aname in self.shell.alias_table:
2665 del self.shell.alias_table[aname]
2667 del self.shell.alias_table[aname]
2666 stored = self.db.get('stored_aliases', {} )
2668 stored = self.db.get('stored_aliases', {} )
2667 if aname in stored:
2669 if aname in stored:
2668 print "Removing %stored alias",aname
2670 print "Removing %stored alias",aname
2669 del stored[aname]
2671 del stored[aname]
2670 self.db['stored_aliases'] = stored
2672 self.db['stored_aliases'] = stored
2671
2673
2672
2674
2673 def magic_rehashx(self, parameter_s = ''):
2675 def magic_rehashx(self, parameter_s = ''):
2674 """Update the alias table with all executable files in $PATH.
2676 """Update the alias table with all executable files in $PATH.
2675
2677
2676 This version explicitly checks that every entry in $PATH is a file
2678 This version explicitly checks that every entry in $PATH is a file
2677 with execute access (os.X_OK), so it is much slower than %rehash.
2679 with execute access (os.X_OK), so it is much slower than %rehash.
2678
2680
2679 Under Windows, it checks executability as a match agains a
2681 Under Windows, it checks executability as a match agains a
2680 '|'-separated string of extensions, stored in the IPython config
2682 '|'-separated string of extensions, stored in the IPython config
2681 variable win_exec_ext. This defaults to 'exe|com|bat'.
2683 variable win_exec_ext. This defaults to 'exe|com|bat'.
2682
2684
2683 This function also resets the root module cache of module completer,
2685 This function also resets the root module cache of module completer,
2684 used on slow filesystems.
2686 used on slow filesystems.
2685 """
2687 """
2686
2688
2687
2689
2688 ip = self.api
2690 ip = self.api
2689
2691
2690 # for the benefit of module completer in ipy_completers.py
2692 # for the benefit of module completer in ipy_completers.py
2691 del ip.db['rootmodules']
2693 del ip.db['rootmodules']
2692
2694
2693 path = [os.path.abspath(os.path.expanduser(p)) for p in
2695 path = [os.path.abspath(os.path.expanduser(p)) for p in
2694 os.environ.get('PATH','').split(os.pathsep)]
2696 os.environ.get('PATH','').split(os.pathsep)]
2695 path = filter(os.path.isdir,path)
2697 path = filter(os.path.isdir,path)
2696
2698
2697 alias_table = self.shell.alias_table
2699 alias_table = self.shell.alias_table
2698 syscmdlist = []
2700 syscmdlist = []
2699 if os.name == 'posix':
2701 if os.name == 'posix':
2700 isexec = lambda fname:os.path.isfile(fname) and \
2702 isexec = lambda fname:os.path.isfile(fname) and \
2701 os.access(fname,os.X_OK)
2703 os.access(fname,os.X_OK)
2702 else:
2704 else:
2703
2705
2704 try:
2706 try:
2705 winext = os.environ['pathext'].replace(';','|').replace('.','')
2707 winext = os.environ['pathext'].replace(';','|').replace('.','')
2706 except KeyError:
2708 except KeyError:
2707 winext = 'exe|com|bat|py'
2709 winext = 'exe|com|bat|py'
2708 if 'py' not in winext:
2710 if 'py' not in winext:
2709 winext += '|py'
2711 winext += '|py'
2710 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2712 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2711 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2713 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2712 savedir = os.getcwd()
2714 savedir = os.getcwd()
2713 try:
2715 try:
2714 # write the whole loop for posix/Windows so we don't have an if in
2716 # write the whole loop for posix/Windows so we don't have an if in
2715 # the innermost part
2717 # the innermost part
2716 if os.name == 'posix':
2718 if os.name == 'posix':
2717 for pdir in path:
2719 for pdir in path:
2718 os.chdir(pdir)
2720 os.chdir(pdir)
2719 for ff in os.listdir(pdir):
2721 for ff in os.listdir(pdir):
2720 if isexec(ff) and ff not in self.shell.no_alias:
2722 if isexec(ff) and ff not in self.shell.no_alias:
2721 # each entry in the alias table must be (N,name),
2723 # each entry in the alias table must be (N,name),
2722 # where N is the number of positional arguments of the
2724 # where N is the number of positional arguments of the
2723 # alias.
2725 # alias.
2724 # Dots will be removed from alias names, since ipython
2726 # Dots will be removed from alias names, since ipython
2725 # assumes names with dots to be python code
2727 # assumes names with dots to be python code
2726 alias_table[ff.replace('.','')] = (0,ff)
2728 alias_table[ff.replace('.','')] = (0,ff)
2727 syscmdlist.append(ff)
2729 syscmdlist.append(ff)
2728 else:
2730 else:
2729 for pdir in path:
2731 for pdir in path:
2730 os.chdir(pdir)
2732 os.chdir(pdir)
2731 for ff in os.listdir(pdir):
2733 for ff in os.listdir(pdir):
2732 base, ext = os.path.splitext(ff)
2734 base, ext = os.path.splitext(ff)
2733 if isexec(ff) and base.lower() not in self.shell.no_alias:
2735 if isexec(ff) and base.lower() not in self.shell.no_alias:
2734 if ext.lower() == '.exe':
2736 if ext.lower() == '.exe':
2735 ff = base
2737 ff = base
2736 alias_table[base.lower().replace('.','')] = (0,ff)
2738 alias_table[base.lower().replace('.','')] = (0,ff)
2737 syscmdlist.append(ff)
2739 syscmdlist.append(ff)
2738 # Make sure the alias table doesn't contain keywords or builtins
2740 # Make sure the alias table doesn't contain keywords or builtins
2739 self.shell.alias_table_validate()
2741 self.shell.alias_table_validate()
2740 # Call again init_auto_alias() so we get 'rm -i' and other
2742 # Call again init_auto_alias() so we get 'rm -i' and other
2741 # modified aliases since %rehashx will probably clobber them
2743 # modified aliases since %rehashx will probably clobber them
2742
2744
2743 # no, we don't want them. if %rehashx clobbers them, good,
2745 # no, we don't want them. if %rehashx clobbers them, good,
2744 # we'll probably get better versions
2746 # we'll probably get better versions
2745 # self.shell.init_auto_alias()
2747 # self.shell.init_auto_alias()
2746 db = ip.db
2748 db = ip.db
2747 db['syscmdlist'] = syscmdlist
2749 db['syscmdlist'] = syscmdlist
2748 finally:
2750 finally:
2749 os.chdir(savedir)
2751 os.chdir(savedir)
2750
2752
2751 def magic_pwd(self, parameter_s = ''):
2753 def magic_pwd(self, parameter_s = ''):
2752 """Return the current working directory path."""
2754 """Return the current working directory path."""
2753 return os.getcwd()
2755 return os.getcwd()
2754
2756
2755 def magic_cd(self, parameter_s=''):
2757 def magic_cd(self, parameter_s=''):
2756 """Change the current working directory.
2758 """Change the current working directory.
2757
2759
2758 This command automatically maintains an internal list of directories
2760 This command automatically maintains an internal list of directories
2759 you visit during your IPython session, in the variable _dh. The
2761 you visit during your IPython session, in the variable _dh. The
2760 command %dhist shows this history nicely formatted. You can also
2762 command %dhist shows this history nicely formatted. You can also
2761 do 'cd -<tab>' to see directory history conveniently.
2763 do 'cd -<tab>' to see directory history conveniently.
2762
2764
2763 Usage:
2765 Usage:
2764
2766
2765 cd 'dir': changes to directory 'dir'.
2767 cd 'dir': changes to directory 'dir'.
2766
2768
2767 cd -: changes to the last visited directory.
2769 cd -: changes to the last visited directory.
2768
2770
2769 cd -<n>: changes to the n-th directory in the directory history.
2771 cd -<n>: changes to the n-th directory in the directory history.
2770
2772
2771 cd --foo: change to directory that matches 'foo' in history
2773 cd --foo: change to directory that matches 'foo' in history
2772
2774
2773 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2775 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2774 (note: cd <bookmark_name> is enough if there is no
2776 (note: cd <bookmark_name> is enough if there is no
2775 directory <bookmark_name>, but a bookmark with the name exists.)
2777 directory <bookmark_name>, but a bookmark with the name exists.)
2776 'cd -b <tab>' allows you to tab-complete bookmark names.
2778 'cd -b <tab>' allows you to tab-complete bookmark names.
2777
2779
2778 Options:
2780 Options:
2779
2781
2780 -q: quiet. Do not print the working directory after the cd command is
2782 -q: quiet. Do not print the working directory after the cd command is
2781 executed. By default IPython's cd command does print this directory,
2783 executed. By default IPython's cd command does print this directory,
2782 since the default prompts do not display path information.
2784 since the default prompts do not display path information.
2783
2785
2784 Note that !cd doesn't work for this purpose because the shell where
2786 Note that !cd doesn't work for this purpose because the shell where
2785 !command runs is immediately discarded after executing 'command'."""
2787 !command runs is immediately discarded after executing 'command'."""
2786
2788
2787 parameter_s = parameter_s.strip()
2789 parameter_s = parameter_s.strip()
2788 #bkms = self.shell.persist.get("bookmarks",{})
2790 #bkms = self.shell.persist.get("bookmarks",{})
2789
2791
2790 oldcwd = os.getcwd()
2792 oldcwd = os.getcwd()
2791 numcd = re.match(r'(-)(\d+)$',parameter_s)
2793 numcd = re.match(r'(-)(\d+)$',parameter_s)
2792 # jump in directory history by number
2794 # jump in directory history by number
2793 if numcd:
2795 if numcd:
2794 nn = int(numcd.group(2))
2796 nn = int(numcd.group(2))
2795 try:
2797 try:
2796 ps = self.shell.user_ns['_dh'][nn]
2798 ps = self.shell.user_ns['_dh'][nn]
2797 except IndexError:
2799 except IndexError:
2798 print 'The requested directory does not exist in history.'
2800 print 'The requested directory does not exist in history.'
2799 return
2801 return
2800 else:
2802 else:
2801 opts = {}
2803 opts = {}
2802 elif parameter_s.startswith('--'):
2804 elif parameter_s.startswith('--'):
2803 ps = None
2805 ps = None
2804 fallback = None
2806 fallback = None
2805 pat = parameter_s[2:]
2807 pat = parameter_s[2:]
2806 dh = self.shell.user_ns['_dh']
2808 dh = self.shell.user_ns['_dh']
2807 # first search only by basename (last component)
2809 # first search only by basename (last component)
2808 for ent in reversed(dh):
2810 for ent in reversed(dh):
2809 if pat in os.path.basename(ent) and os.path.isdir(ent):
2811 if pat in os.path.basename(ent) and os.path.isdir(ent):
2810 ps = ent
2812 ps = ent
2811 break
2813 break
2812
2814
2813 if fallback is None and pat in ent and os.path.isdir(ent):
2815 if fallback is None and pat in ent and os.path.isdir(ent):
2814 fallback = ent
2816 fallback = ent
2815
2817
2816 # if we have no last part match, pick the first full path match
2818 # if we have no last part match, pick the first full path match
2817 if ps is None:
2819 if ps is None:
2818 ps = fallback
2820 ps = fallback
2819
2821
2820 if ps is None:
2822 if ps is None:
2821 print "No matching entry in directory history"
2823 print "No matching entry in directory history"
2822 return
2824 return
2823 else:
2825 else:
2824 opts = {}
2826 opts = {}
2825
2827
2826
2828
2827 else:
2829 else:
2828 #turn all non-space-escaping backslashes to slashes,
2830 #turn all non-space-escaping backslashes to slashes,
2829 # for c:\windows\directory\names\
2831 # for c:\windows\directory\names\
2830 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2832 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2831 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2833 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2832 # jump to previous
2834 # jump to previous
2833 if ps == '-':
2835 if ps == '-':
2834 try:
2836 try:
2835 ps = self.shell.user_ns['_dh'][-2]
2837 ps = self.shell.user_ns['_dh'][-2]
2836 except IndexError:
2838 except IndexError:
2837 raise UsageError('%cd -: No previous directory to change to.')
2839 raise UsageError('%cd -: No previous directory to change to.')
2838 # jump to bookmark if needed
2840 # jump to bookmark if needed
2839 else:
2841 else:
2840 if not os.path.isdir(ps) or opts.has_key('b'):
2842 if not os.path.isdir(ps) or opts.has_key('b'):
2841 bkms = self.db.get('bookmarks', {})
2843 bkms = self.db.get('bookmarks', {})
2842
2844
2843 if bkms.has_key(ps):
2845 if bkms.has_key(ps):
2844 target = bkms[ps]
2846 target = bkms[ps]
2845 print '(bookmark:%s) -> %s' % (ps,target)
2847 print '(bookmark:%s) -> %s' % (ps,target)
2846 ps = target
2848 ps = target
2847 else:
2849 else:
2848 if opts.has_key('b'):
2850 if opts.has_key('b'):
2849 raise UsageError("Bookmark '%s' not found. "
2851 raise UsageError("Bookmark '%s' not found. "
2850 "Use '%%bookmark -l' to see your bookmarks." % ps)
2852 "Use '%%bookmark -l' to see your bookmarks." % ps)
2851
2853
2852 # at this point ps should point to the target dir
2854 # at this point ps should point to the target dir
2853 if ps:
2855 if ps:
2854 try:
2856 try:
2855 os.chdir(os.path.expanduser(ps))
2857 os.chdir(os.path.expanduser(ps))
2856 if self.shell.rc.term_title:
2858 if self.shell.term_title:
2857 #print 'set term title:',self.shell.rc.term_title # dbg
2859 #print 'set term title:',self.shell.term_title # dbg
2858 platutils.set_term_title('IPy ' + abbrev_cwd())
2860 platutils.set_term_title('IPy ' + abbrev_cwd())
2859 except OSError:
2861 except OSError:
2860 print sys.exc_info()[1]
2862 print sys.exc_info()[1]
2861 else:
2863 else:
2862 cwd = os.getcwd()
2864 cwd = os.getcwd()
2863 dhist = self.shell.user_ns['_dh']
2865 dhist = self.shell.user_ns['_dh']
2864 if oldcwd != cwd:
2866 if oldcwd != cwd:
2865 dhist.append(cwd)
2867 dhist.append(cwd)
2866 self.db['dhist'] = compress_dhist(dhist)[-100:]
2868 self.db['dhist'] = compress_dhist(dhist)[-100:]
2867
2869
2868 else:
2870 else:
2869 os.chdir(self.shell.home_dir)
2871 os.chdir(self.shell.home_dir)
2870 if self.shell.rc.term_title:
2872 if self.shell.term_title:
2871 platutils.set_term_title("IPy ~")
2873 platutils.set_term_title("IPy ~")
2872 cwd = os.getcwd()
2874 cwd = os.getcwd()
2873 dhist = self.shell.user_ns['_dh']
2875 dhist = self.shell.user_ns['_dh']
2874
2876
2875 if oldcwd != cwd:
2877 if oldcwd != cwd:
2876 dhist.append(cwd)
2878 dhist.append(cwd)
2877 self.db['dhist'] = compress_dhist(dhist)[-100:]
2879 self.db['dhist'] = compress_dhist(dhist)[-100:]
2878 if not 'q' in opts and self.shell.user_ns['_dh']:
2880 if not 'q' in opts and self.shell.user_ns['_dh']:
2879 print self.shell.user_ns['_dh'][-1]
2881 print self.shell.user_ns['_dh'][-1]
2880
2882
2881
2883
2882 def magic_env(self, parameter_s=''):
2884 def magic_env(self, parameter_s=''):
2883 """List environment variables."""
2885 """List environment variables."""
2884
2886
2885 return os.environ.data
2887 return os.environ.data
2886
2888
2887 def magic_pushd(self, parameter_s=''):
2889 def magic_pushd(self, parameter_s=''):
2888 """Place the current dir on stack and change directory.
2890 """Place the current dir on stack and change directory.
2889
2891
2890 Usage:\\
2892 Usage:\\
2891 %pushd ['dirname']
2893 %pushd ['dirname']
2892 """
2894 """
2893
2895
2894 dir_s = self.shell.dir_stack
2896 dir_s = self.shell.dir_stack
2895 tgt = os.path.expanduser(parameter_s)
2897 tgt = os.path.expanduser(parameter_s)
2896 cwd = os.getcwd().replace(self.home_dir,'~')
2898 cwd = os.getcwd().replace(self.home_dir,'~')
2897 if tgt:
2899 if tgt:
2898 self.magic_cd(parameter_s)
2900 self.magic_cd(parameter_s)
2899 dir_s.insert(0,cwd)
2901 dir_s.insert(0,cwd)
2900 return self.magic_dirs()
2902 return self.magic_dirs()
2901
2903
2902 def magic_popd(self, parameter_s=''):
2904 def magic_popd(self, parameter_s=''):
2903 """Change to directory popped off the top of the stack.
2905 """Change to directory popped off the top of the stack.
2904 """
2906 """
2905 if not self.shell.dir_stack:
2907 if not self.shell.dir_stack:
2906 raise UsageError("%popd on empty stack")
2908 raise UsageError("%popd on empty stack")
2907 top = self.shell.dir_stack.pop(0)
2909 top = self.shell.dir_stack.pop(0)
2908 self.magic_cd(top)
2910 self.magic_cd(top)
2909 print "popd ->",top
2911 print "popd ->",top
2910
2912
2911 def magic_dirs(self, parameter_s=''):
2913 def magic_dirs(self, parameter_s=''):
2912 """Return the current directory stack."""
2914 """Return the current directory stack."""
2913
2915
2914 return self.shell.dir_stack
2916 return self.shell.dir_stack
2915
2917
2916 def magic_dhist(self, parameter_s=''):
2918 def magic_dhist(self, parameter_s=''):
2917 """Print your history of visited directories.
2919 """Print your history of visited directories.
2918
2920
2919 %dhist -> print full history\\
2921 %dhist -> print full history\\
2920 %dhist n -> print last n entries only\\
2922 %dhist n -> print last n entries only\\
2921 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2923 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2922
2924
2923 This history is automatically maintained by the %cd command, and
2925 This history is automatically maintained by the %cd command, and
2924 always available as the global list variable _dh. You can use %cd -<n>
2926 always available as the global list variable _dh. You can use %cd -<n>
2925 to go to directory number <n>.
2927 to go to directory number <n>.
2926
2928
2927 Note that most of time, you should view directory history by entering
2929 Note that most of time, you should view directory history by entering
2928 cd -<TAB>.
2930 cd -<TAB>.
2929
2931
2930 """
2932 """
2931
2933
2932 dh = self.shell.user_ns['_dh']
2934 dh = self.shell.user_ns['_dh']
2933 if parameter_s:
2935 if parameter_s:
2934 try:
2936 try:
2935 args = map(int,parameter_s.split())
2937 args = map(int,parameter_s.split())
2936 except:
2938 except:
2937 self.arg_err(Magic.magic_dhist)
2939 self.arg_err(Magic.magic_dhist)
2938 return
2940 return
2939 if len(args) == 1:
2941 if len(args) == 1:
2940 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2942 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2941 elif len(args) == 2:
2943 elif len(args) == 2:
2942 ini,fin = args
2944 ini,fin = args
2943 else:
2945 else:
2944 self.arg_err(Magic.magic_dhist)
2946 self.arg_err(Magic.magic_dhist)
2945 return
2947 return
2946 else:
2948 else:
2947 ini,fin = 0,len(dh)
2949 ini,fin = 0,len(dh)
2948 nlprint(dh,
2950 nlprint(dh,
2949 header = 'Directory history (kept in _dh)',
2951 header = 'Directory history (kept in _dh)',
2950 start=ini,stop=fin)
2952 start=ini,stop=fin)
2951
2953
2952 @testdec.skip_doctest
2954 @testdec.skip_doctest
2953 def magic_sc(self, parameter_s=''):
2955 def magic_sc(self, parameter_s=''):
2954 """Shell capture - execute a shell command and capture its output.
2956 """Shell capture - execute a shell command and capture its output.
2955
2957
2956 DEPRECATED. Suboptimal, retained for backwards compatibility.
2958 DEPRECATED. Suboptimal, retained for backwards compatibility.
2957
2959
2958 You should use the form 'var = !command' instead. Example:
2960 You should use the form 'var = !command' instead. Example:
2959
2961
2960 "%sc -l myfiles = ls ~" should now be written as
2962 "%sc -l myfiles = ls ~" should now be written as
2961
2963
2962 "myfiles = !ls ~"
2964 "myfiles = !ls ~"
2963
2965
2964 myfiles.s, myfiles.l and myfiles.n still apply as documented
2966 myfiles.s, myfiles.l and myfiles.n still apply as documented
2965 below.
2967 below.
2966
2968
2967 --
2969 --
2968 %sc [options] varname=command
2970 %sc [options] varname=command
2969
2971
2970 IPython will run the given command using commands.getoutput(), and
2972 IPython will run the given command using commands.getoutput(), and
2971 will then update the user's interactive namespace with a variable
2973 will then update the user's interactive namespace with a variable
2972 called varname, containing the value of the call. Your command can
2974 called varname, containing the value of the call. Your command can
2973 contain shell wildcards, pipes, etc.
2975 contain shell wildcards, pipes, etc.
2974
2976
2975 The '=' sign in the syntax is mandatory, and the variable name you
2977 The '=' sign in the syntax is mandatory, and the variable name you
2976 supply must follow Python's standard conventions for valid names.
2978 supply must follow Python's standard conventions for valid names.
2977
2979
2978 (A special format without variable name exists for internal use)
2980 (A special format without variable name exists for internal use)
2979
2981
2980 Options:
2982 Options:
2981
2983
2982 -l: list output. Split the output on newlines into a list before
2984 -l: list output. Split the output on newlines into a list before
2983 assigning it to the given variable. By default the output is stored
2985 assigning it to the given variable. By default the output is stored
2984 as a single string.
2986 as a single string.
2985
2987
2986 -v: verbose. Print the contents of the variable.
2988 -v: verbose. Print the contents of the variable.
2987
2989
2988 In most cases you should not need to split as a list, because the
2990 In most cases you should not need to split as a list, because the
2989 returned value is a special type of string which can automatically
2991 returned value is a special type of string which can automatically
2990 provide its contents either as a list (split on newlines) or as a
2992 provide its contents either as a list (split on newlines) or as a
2991 space-separated string. These are convenient, respectively, either
2993 space-separated string. These are convenient, respectively, either
2992 for sequential processing or to be passed to a shell command.
2994 for sequential processing or to be passed to a shell command.
2993
2995
2994 For example:
2996 For example:
2995
2997
2996 # all-random
2998 # all-random
2997
2999
2998 # Capture into variable a
3000 # Capture into variable a
2999 In [1]: sc a=ls *py
3001 In [1]: sc a=ls *py
3000
3002
3001 # a is a string with embedded newlines
3003 # a is a string with embedded newlines
3002 In [2]: a
3004 In [2]: a
3003 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3005 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3004
3006
3005 # which can be seen as a list:
3007 # which can be seen as a list:
3006 In [3]: a.l
3008 In [3]: a.l
3007 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3009 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3008
3010
3009 # or as a whitespace-separated string:
3011 # or as a whitespace-separated string:
3010 In [4]: a.s
3012 In [4]: a.s
3011 Out[4]: 'setup.py win32_manual_post_install.py'
3013 Out[4]: 'setup.py win32_manual_post_install.py'
3012
3014
3013 # a.s is useful to pass as a single command line:
3015 # a.s is useful to pass as a single command line:
3014 In [5]: !wc -l $a.s
3016 In [5]: !wc -l $a.s
3015 146 setup.py
3017 146 setup.py
3016 130 win32_manual_post_install.py
3018 130 win32_manual_post_install.py
3017 276 total
3019 276 total
3018
3020
3019 # while the list form is useful to loop over:
3021 # while the list form is useful to loop over:
3020 In [6]: for f in a.l:
3022 In [6]: for f in a.l:
3021 ...: !wc -l $f
3023 ...: !wc -l $f
3022 ...:
3024 ...:
3023 146 setup.py
3025 146 setup.py
3024 130 win32_manual_post_install.py
3026 130 win32_manual_post_install.py
3025
3027
3026 Similiarly, the lists returned by the -l option are also special, in
3028 Similiarly, the lists returned by the -l option are also special, in
3027 the sense that you can equally invoke the .s attribute on them to
3029 the sense that you can equally invoke the .s attribute on them to
3028 automatically get a whitespace-separated string from their contents:
3030 automatically get a whitespace-separated string from their contents:
3029
3031
3030 In [7]: sc -l b=ls *py
3032 In [7]: sc -l b=ls *py
3031
3033
3032 In [8]: b
3034 In [8]: b
3033 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3035 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3034
3036
3035 In [9]: b.s
3037 In [9]: b.s
3036 Out[9]: 'setup.py win32_manual_post_install.py'
3038 Out[9]: 'setup.py win32_manual_post_install.py'
3037
3039
3038 In summary, both the lists and strings used for ouptut capture have
3040 In summary, both the lists and strings used for ouptut capture have
3039 the following special attributes:
3041 the following special attributes:
3040
3042
3041 .l (or .list) : value as list.
3043 .l (or .list) : value as list.
3042 .n (or .nlstr): value as newline-separated string.
3044 .n (or .nlstr): value as newline-separated string.
3043 .s (or .spstr): value as space-separated string.
3045 .s (or .spstr): value as space-separated string.
3044 """
3046 """
3045
3047
3046 opts,args = self.parse_options(parameter_s,'lv')
3048 opts,args = self.parse_options(parameter_s,'lv')
3047 # Try to get a variable name and command to run
3049 # Try to get a variable name and command to run
3048 try:
3050 try:
3049 # the variable name must be obtained from the parse_options
3051 # the variable name must be obtained from the parse_options
3050 # output, which uses shlex.split to strip options out.
3052 # output, which uses shlex.split to strip options out.
3051 var,_ = args.split('=',1)
3053 var,_ = args.split('=',1)
3052 var = var.strip()
3054 var = var.strip()
3053 # But the the command has to be extracted from the original input
3055 # But the the command has to be extracted from the original input
3054 # parameter_s, not on what parse_options returns, to avoid the
3056 # parameter_s, not on what parse_options returns, to avoid the
3055 # quote stripping which shlex.split performs on it.
3057 # quote stripping which shlex.split performs on it.
3056 _,cmd = parameter_s.split('=',1)
3058 _,cmd = parameter_s.split('=',1)
3057 except ValueError:
3059 except ValueError:
3058 var,cmd = '',''
3060 var,cmd = '',''
3059 # If all looks ok, proceed
3061 # If all looks ok, proceed
3060 out,err = self.shell.getoutputerror(cmd)
3062 out,err = self.shell.getoutputerror(cmd)
3061 if err:
3063 if err:
3062 print >> Term.cerr,err
3064 print >> Term.cerr,err
3063 if opts.has_key('l'):
3065 if opts.has_key('l'):
3064 out = SList(out.split('\n'))
3066 out = SList(out.split('\n'))
3065 else:
3067 else:
3066 out = LSString(out)
3068 out = LSString(out)
3067 if opts.has_key('v'):
3069 if opts.has_key('v'):
3068 print '%s ==\n%s' % (var,pformat(out))
3070 print '%s ==\n%s' % (var,pformat(out))
3069 if var:
3071 if var:
3070 self.shell.user_ns.update({var:out})
3072 self.shell.user_ns.update({var:out})
3071 else:
3073 else:
3072 return out
3074 return out
3073
3075
3074 def magic_sx(self, parameter_s=''):
3076 def magic_sx(self, parameter_s=''):
3075 """Shell execute - run a shell command and capture its output.
3077 """Shell execute - run a shell command and capture its output.
3076
3078
3077 %sx command
3079 %sx command
3078
3080
3079 IPython will run the given command using commands.getoutput(), and
3081 IPython will run the given command using commands.getoutput(), and
3080 return the result formatted as a list (split on '\\n'). Since the
3082 return the result formatted as a list (split on '\\n'). Since the
3081 output is _returned_, it will be stored in ipython's regular output
3083 output is _returned_, it will be stored in ipython's regular output
3082 cache Out[N] and in the '_N' automatic variables.
3084 cache Out[N] and in the '_N' automatic variables.
3083
3085
3084 Notes:
3086 Notes:
3085
3087
3086 1) If an input line begins with '!!', then %sx is automatically
3088 1) If an input line begins with '!!', then %sx is automatically
3087 invoked. That is, while:
3089 invoked. That is, while:
3088 !ls
3090 !ls
3089 causes ipython to simply issue system('ls'), typing
3091 causes ipython to simply issue system('ls'), typing
3090 !!ls
3092 !!ls
3091 is a shorthand equivalent to:
3093 is a shorthand equivalent to:
3092 %sx ls
3094 %sx ls
3093
3095
3094 2) %sx differs from %sc in that %sx automatically splits into a list,
3096 2) %sx differs from %sc in that %sx automatically splits into a list,
3095 like '%sc -l'. The reason for this is to make it as easy as possible
3097 like '%sc -l'. The reason for this is to make it as easy as possible
3096 to process line-oriented shell output via further python commands.
3098 to process line-oriented shell output via further python commands.
3097 %sc is meant to provide much finer control, but requires more
3099 %sc is meant to provide much finer control, but requires more
3098 typing.
3100 typing.
3099
3101
3100 3) Just like %sc -l, this is a list with special attributes:
3102 3) Just like %sc -l, this is a list with special attributes:
3101
3103
3102 .l (or .list) : value as list.
3104 .l (or .list) : value as list.
3103 .n (or .nlstr): value as newline-separated string.
3105 .n (or .nlstr): value as newline-separated string.
3104 .s (or .spstr): value as whitespace-separated string.
3106 .s (or .spstr): value as whitespace-separated string.
3105
3107
3106 This is very useful when trying to use such lists as arguments to
3108 This is very useful when trying to use such lists as arguments to
3107 system commands."""
3109 system commands."""
3108
3110
3109 if parameter_s:
3111 if parameter_s:
3110 out,err = self.shell.getoutputerror(parameter_s)
3112 out,err = self.shell.getoutputerror(parameter_s)
3111 if err:
3113 if err:
3112 print >> Term.cerr,err
3114 print >> Term.cerr,err
3113 return SList(out.split('\n'))
3115 return SList(out.split('\n'))
3114
3116
3115 def magic_bg(self, parameter_s=''):
3117 def magic_bg(self, parameter_s=''):
3116 """Run a job in the background, in a separate thread.
3118 """Run a job in the background, in a separate thread.
3117
3119
3118 For example,
3120 For example,
3119
3121
3120 %bg myfunc(x,y,z=1)
3122 %bg myfunc(x,y,z=1)
3121
3123
3122 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3124 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3123 execution starts, a message will be printed indicating the job
3125 execution starts, a message will be printed indicating the job
3124 number. If your job number is 5, you can use
3126 number. If your job number is 5, you can use
3125
3127
3126 myvar = jobs.result(5) or myvar = jobs[5].result
3128 myvar = jobs.result(5) or myvar = jobs[5].result
3127
3129
3128 to assign this result to variable 'myvar'.
3130 to assign this result to variable 'myvar'.
3129
3131
3130 IPython has a job manager, accessible via the 'jobs' object. You can
3132 IPython has a job manager, accessible via the 'jobs' object. You can
3131 type jobs? to get more information about it, and use jobs.<TAB> to see
3133 type jobs? to get more information about it, and use jobs.<TAB> to see
3132 its attributes. All attributes not starting with an underscore are
3134 its attributes. All attributes not starting with an underscore are
3133 meant for public use.
3135 meant for public use.
3134
3136
3135 In particular, look at the jobs.new() method, which is used to create
3137 In particular, look at the jobs.new() method, which is used to create
3136 new jobs. This magic %bg function is just a convenience wrapper
3138 new jobs. This magic %bg function is just a convenience wrapper
3137 around jobs.new(), for expression-based jobs. If you want to create a
3139 around jobs.new(), for expression-based jobs. If you want to create a
3138 new job with an explicit function object and arguments, you must call
3140 new job with an explicit function object and arguments, you must call
3139 jobs.new() directly.
3141 jobs.new() directly.
3140
3142
3141 The jobs.new docstring also describes in detail several important
3143 The jobs.new docstring also describes in detail several important
3142 caveats associated with a thread-based model for background job
3144 caveats associated with a thread-based model for background job
3143 execution. Type jobs.new? for details.
3145 execution. Type jobs.new? for details.
3144
3146
3145 You can check the status of all jobs with jobs.status().
3147 You can check the status of all jobs with jobs.status().
3146
3148
3147 The jobs variable is set by IPython into the Python builtin namespace.
3149 The jobs variable is set by IPython into the Python builtin namespace.
3148 If you ever declare a variable named 'jobs', you will shadow this
3150 If you ever declare a variable named 'jobs', you will shadow this
3149 name. You can either delete your global jobs variable to regain
3151 name. You can either delete your global jobs variable to regain
3150 access to the job manager, or make a new name and assign it manually
3152 access to the job manager, or make a new name and assign it manually
3151 to the manager (stored in IPython's namespace). For example, to
3153 to the manager (stored in IPython's namespace). For example, to
3152 assign the job manager to the Jobs name, use:
3154 assign the job manager to the Jobs name, use:
3153
3155
3154 Jobs = __builtins__.jobs"""
3156 Jobs = __builtins__.jobs"""
3155
3157
3156 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3158 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3157
3159
3158 def magic_r(self, parameter_s=''):
3160 def magic_r(self, parameter_s=''):
3159 """Repeat previous input.
3161 """Repeat previous input.
3160
3162
3161 Note: Consider using the more powerfull %rep instead!
3163 Note: Consider using the more powerfull %rep instead!
3162
3164
3163 If given an argument, repeats the previous command which starts with
3165 If given an argument, repeats the previous command which starts with
3164 the same string, otherwise it just repeats the previous input.
3166 the same string, otherwise it just repeats the previous input.
3165
3167
3166 Shell escaped commands (with ! as first character) are not recognized
3168 Shell escaped commands (with ! as first character) are not recognized
3167 by this system, only pure python code and magic commands.
3169 by this system, only pure python code and magic commands.
3168 """
3170 """
3169
3171
3170 start = parameter_s.strip()
3172 start = parameter_s.strip()
3171 esc_magic = self.shell.ESC_MAGIC
3173 esc_magic = self.shell.ESC_MAGIC
3172 # Identify magic commands even if automagic is on (which means
3174 # Identify magic commands even if automagic is on (which means
3173 # the in-memory version is different from that typed by the user).
3175 # the in-memory version is different from that typed by the user).
3174 if self.shell.rc.automagic:
3176 if self.shell.automagic:
3175 start_magic = esc_magic+start
3177 start_magic = esc_magic+start
3176 else:
3178 else:
3177 start_magic = start
3179 start_magic = start
3178 # Look through the input history in reverse
3180 # Look through the input history in reverse
3179 for n in range(len(self.shell.input_hist)-2,0,-1):
3181 for n in range(len(self.shell.input_hist)-2,0,-1):
3180 input = self.shell.input_hist[n]
3182 input = self.shell.input_hist[n]
3181 # skip plain 'r' lines so we don't recurse to infinity
3183 # skip plain 'r' lines so we don't recurse to infinity
3182 if input != '_ip.magic("r")\n' and \
3184 if input != '_ip.magic("r")\n' and \
3183 (input.startswith(start) or input.startswith(start_magic)):
3185 (input.startswith(start) or input.startswith(start_magic)):
3184 #print 'match',`input` # dbg
3186 #print 'match',`input` # dbg
3185 print 'Executing:',input,
3187 print 'Executing:',input,
3186 self.shell.runlines(input)
3188 self.shell.runlines(input)
3187 return
3189 return
3188 print 'No previous input matching `%s` found.' % start
3190 print 'No previous input matching `%s` found.' % start
3189
3191
3190
3192
3191 def magic_bookmark(self, parameter_s=''):
3193 def magic_bookmark(self, parameter_s=''):
3192 """Manage IPython's bookmark system.
3194 """Manage IPython's bookmark system.
3193
3195
3194 %bookmark <name> - set bookmark to current dir
3196 %bookmark <name> - set bookmark to current dir
3195 %bookmark <name> <dir> - set bookmark to <dir>
3197 %bookmark <name> <dir> - set bookmark to <dir>
3196 %bookmark -l - list all bookmarks
3198 %bookmark -l - list all bookmarks
3197 %bookmark -d <name> - remove bookmark
3199 %bookmark -d <name> - remove bookmark
3198 %bookmark -r - remove all bookmarks
3200 %bookmark -r - remove all bookmarks
3199
3201
3200 You can later on access a bookmarked folder with:
3202 You can later on access a bookmarked folder with:
3201 %cd -b <name>
3203 %cd -b <name>
3202 or simply '%cd <name>' if there is no directory called <name> AND
3204 or simply '%cd <name>' if there is no directory called <name> AND
3203 there is such a bookmark defined.
3205 there is such a bookmark defined.
3204
3206
3205 Your bookmarks persist through IPython sessions, but they are
3207 Your bookmarks persist through IPython sessions, but they are
3206 associated with each profile."""
3208 associated with each profile."""
3207
3209
3208 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3210 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3209 if len(args) > 2:
3211 if len(args) > 2:
3210 raise UsageError("%bookmark: too many arguments")
3212 raise UsageError("%bookmark: too many arguments")
3211
3213
3212 bkms = self.db.get('bookmarks',{})
3214 bkms = self.db.get('bookmarks',{})
3213
3215
3214 if opts.has_key('d'):
3216 if opts.has_key('d'):
3215 try:
3217 try:
3216 todel = args[0]
3218 todel = args[0]
3217 except IndexError:
3219 except IndexError:
3218 raise UsageError(
3220 raise UsageError(
3219 "%bookmark -d: must provide a bookmark to delete")
3221 "%bookmark -d: must provide a bookmark to delete")
3220 else:
3222 else:
3221 try:
3223 try:
3222 del bkms[todel]
3224 del bkms[todel]
3223 except KeyError:
3225 except KeyError:
3224 raise UsageError(
3226 raise UsageError(
3225 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3227 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3226
3228
3227 elif opts.has_key('r'):
3229 elif opts.has_key('r'):
3228 bkms = {}
3230 bkms = {}
3229 elif opts.has_key('l'):
3231 elif opts.has_key('l'):
3230 bks = bkms.keys()
3232 bks = bkms.keys()
3231 bks.sort()
3233 bks.sort()
3232 if bks:
3234 if bks:
3233 size = max(map(len,bks))
3235 size = max(map(len,bks))
3234 else:
3236 else:
3235 size = 0
3237 size = 0
3236 fmt = '%-'+str(size)+'s -> %s'
3238 fmt = '%-'+str(size)+'s -> %s'
3237 print 'Current bookmarks:'
3239 print 'Current bookmarks:'
3238 for bk in bks:
3240 for bk in bks:
3239 print fmt % (bk,bkms[bk])
3241 print fmt % (bk,bkms[bk])
3240 else:
3242 else:
3241 if not args:
3243 if not args:
3242 raise UsageError("%bookmark: You must specify the bookmark name")
3244 raise UsageError("%bookmark: You must specify the bookmark name")
3243 elif len(args)==1:
3245 elif len(args)==1:
3244 bkms[args[0]] = os.getcwd()
3246 bkms[args[0]] = os.getcwd()
3245 elif len(args)==2:
3247 elif len(args)==2:
3246 bkms[args[0]] = args[1]
3248 bkms[args[0]] = args[1]
3247 self.db['bookmarks'] = bkms
3249 self.db['bookmarks'] = bkms
3248
3250
3249 def magic_pycat(self, parameter_s=''):
3251 def magic_pycat(self, parameter_s=''):
3250 """Show a syntax-highlighted file through a pager.
3252 """Show a syntax-highlighted file through a pager.
3251
3253
3252 This magic is similar to the cat utility, but it will assume the file
3254 This magic is similar to the cat utility, but it will assume the file
3253 to be Python source and will show it with syntax highlighting. """
3255 to be Python source and will show it with syntax highlighting. """
3254
3256
3255 try:
3257 try:
3256 filename = get_py_filename(parameter_s)
3258 filename = get_py_filename(parameter_s)
3257 cont = file_read(filename)
3259 cont = file_read(filename)
3258 except IOError:
3260 except IOError:
3259 try:
3261 try:
3260 cont = eval(parameter_s,self.user_ns)
3262 cont = eval(parameter_s,self.user_ns)
3261 except NameError:
3263 except NameError:
3262 cont = None
3264 cont = None
3263 if cont is None:
3265 if cont is None:
3264 print "Error: no such file or variable"
3266 print "Error: no such file or variable"
3265 return
3267 return
3266
3268
3267 page(self.shell.pycolorize(cont),
3269 page(self.shell.pycolorize(cont),
3268 screen_lines=self.shell.rc.screen_length)
3270 screen_lines=self.shell.screen_length)
3269
3271
3270 def _rerun_pasted(self):
3272 def _rerun_pasted(self):
3271 """ Rerun a previously pasted command.
3273 """ Rerun a previously pasted command.
3272 """
3274 """
3273 b = self.user_ns.get('pasted_block', None)
3275 b = self.user_ns.get('pasted_block', None)
3274 if b is None:
3276 if b is None:
3275 raise UsageError('No previous pasted block available')
3277 raise UsageError('No previous pasted block available')
3276 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3278 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3277 exec b in self.user_ns
3279 exec b in self.user_ns
3278
3280
3279 def _get_pasted_lines(self, sentinel):
3281 def _get_pasted_lines(self, sentinel):
3280 """ Yield pasted lines until the user enters the given sentinel value.
3282 """ Yield pasted lines until the user enters the given sentinel value.
3281 """
3283 """
3282 from IPython.core import iplib
3284 from IPython.core import iplib
3283 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3285 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3284 while True:
3286 while True:
3285 l = iplib.raw_input_original(':')
3287 l = iplib.raw_input_original(':')
3286 if l == sentinel:
3288 if l == sentinel:
3287 return
3289 return
3288 else:
3290 else:
3289 yield l
3291 yield l
3290
3292
3291 def _strip_pasted_lines_for_code(self, raw_lines):
3293 def _strip_pasted_lines_for_code(self, raw_lines):
3292 """ Strip non-code parts of a sequence of lines to return a block of
3294 """ Strip non-code parts of a sequence of lines to return a block of
3293 code.
3295 code.
3294 """
3296 """
3295 # Regular expressions that declare text we strip from the input:
3297 # Regular expressions that declare text we strip from the input:
3296 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3298 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3297 r'^\s*(\s?>)+', # Python input prompt
3299 r'^\s*(\s?>)+', # Python input prompt
3298 r'^\s*\.{3,}', # Continuation prompts
3300 r'^\s*\.{3,}', # Continuation prompts
3299 r'^\++',
3301 r'^\++',
3300 ]
3302 ]
3301
3303
3302 strip_from_start = map(re.compile,strip_re)
3304 strip_from_start = map(re.compile,strip_re)
3303
3305
3304 lines = []
3306 lines = []
3305 for l in raw_lines:
3307 for l in raw_lines:
3306 for pat in strip_from_start:
3308 for pat in strip_from_start:
3307 l = pat.sub('',l)
3309 l = pat.sub('',l)
3308 lines.append(l)
3310 lines.append(l)
3309
3311
3310 block = "\n".join(lines) + '\n'
3312 block = "\n".join(lines) + '\n'
3311 #print "block:\n",block
3313 #print "block:\n",block
3312 return block
3314 return block
3313
3315
3314 def _execute_block(self, block, par):
3316 def _execute_block(self, block, par):
3315 """ Execute a block, or store it in a variable, per the user's request.
3317 """ Execute a block, or store it in a variable, per the user's request.
3316 """
3318 """
3317 if not par:
3319 if not par:
3318 b = textwrap.dedent(block)
3320 b = textwrap.dedent(block)
3319 self.user_ns['pasted_block'] = b
3321 self.user_ns['pasted_block'] = b
3320 exec b in self.user_ns
3322 exec b in self.user_ns
3321 else:
3323 else:
3322 self.user_ns[par] = SList(block.splitlines())
3324 self.user_ns[par] = SList(block.splitlines())
3323 print "Block assigned to '%s'" % par
3325 print "Block assigned to '%s'" % par
3324
3326
3325 def magic_cpaste(self, parameter_s=''):
3327 def magic_cpaste(self, parameter_s=''):
3326 """Allows you to paste & execute a pre-formatted code block from clipboard.
3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3327
3329
3328 You must terminate the block with '--' (two minus-signs) alone on the
3330 You must terminate the block with '--' (two minus-signs) alone on the
3329 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3331 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3330 is the new sentinel for this operation)
3332 is the new sentinel for this operation)
3331
3333
3332 The block is dedented prior to execution to enable execution of method
3334 The block is dedented prior to execution to enable execution of method
3333 definitions. '>' and '+' characters at the beginning of a line are
3335 definitions. '>' and '+' characters at the beginning of a line are
3334 ignored, to allow pasting directly from e-mails, diff files and
3336 ignored, to allow pasting directly from e-mails, diff files and
3335 doctests (the '...' continuation prompt is also stripped). The
3337 doctests (the '...' continuation prompt is also stripped). The
3336 executed block is also assigned to variable named 'pasted_block' for
3338 executed block is also assigned to variable named 'pasted_block' for
3337 later editing with '%edit pasted_block'.
3339 later editing with '%edit pasted_block'.
3338
3340
3339 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3341 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3340 This assigns the pasted block to variable 'foo' as string, without
3342 This assigns the pasted block to variable 'foo' as string, without
3341 dedenting or executing it (preceding >>> and + is still stripped)
3343 dedenting or executing it (preceding >>> and + is still stripped)
3342
3344
3343 '%cpaste -r' re-executes the block previously entered by cpaste.
3345 '%cpaste -r' re-executes the block previously entered by cpaste.
3344
3346
3345 Do not be alarmed by garbled output on Windows (it's a readline bug).
3347 Do not be alarmed by garbled output on Windows (it's a readline bug).
3346 Just press enter and type -- (and press enter again) and the block
3348 Just press enter and type -- (and press enter again) and the block
3347 will be what was just pasted.
3349 will be what was just pasted.
3348
3350
3349 IPython statements (magics, shell escapes) are not supported (yet).
3351 IPython statements (magics, shell escapes) are not supported (yet).
3350
3352
3351 See also
3353 See also
3352 --------
3354 --------
3353 paste: automatically pull code from clipboard.
3355 paste: automatically pull code from clipboard.
3354 """
3356 """
3355
3357
3356 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3358 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3357 par = args.strip()
3359 par = args.strip()
3358 if opts.has_key('r'):
3360 if opts.has_key('r'):
3359 self._rerun_pasted()
3361 self._rerun_pasted()
3360 return
3362 return
3361
3363
3362 sentinel = opts.get('s','--')
3364 sentinel = opts.get('s','--')
3363
3365
3364 block = self._strip_pasted_lines_for_code(
3366 block = self._strip_pasted_lines_for_code(
3365 self._get_pasted_lines(sentinel))
3367 self._get_pasted_lines(sentinel))
3366
3368
3367 self._execute_block(block, par)
3369 self._execute_block(block, par)
3368
3370
3369 def magic_paste(self, parameter_s=''):
3371 def magic_paste(self, parameter_s=''):
3370 """Allows you to paste & execute a pre-formatted code block from clipboard.
3372 """Allows you to paste & execute a pre-formatted code block from clipboard.
3371
3373
3372 The text is pulled directly from the clipboard without user
3374 The text is pulled directly from the clipboard without user
3373 intervention and printed back on the screen before execution (unless
3375 intervention and printed back on the screen before execution (unless
3374 the -q flag is given to force quiet mode).
3376 the -q flag is given to force quiet mode).
3375
3377
3376 The block is dedented prior to execution to enable execution of method
3378 The block is dedented prior to execution to enable execution of method
3377 definitions. '>' and '+' characters at the beginning of a line are
3379 definitions. '>' and '+' characters at the beginning of a line are
3378 ignored, to allow pasting directly from e-mails, diff files and
3380 ignored, to allow pasting directly from e-mails, diff files and
3379 doctests (the '...' continuation prompt is also stripped). The
3381 doctests (the '...' continuation prompt is also stripped). The
3380 executed block is also assigned to variable named 'pasted_block' for
3382 executed block is also assigned to variable named 'pasted_block' for
3381 later editing with '%edit pasted_block'.
3383 later editing with '%edit pasted_block'.
3382
3384
3383 You can also pass a variable name as an argument, e.g. '%paste foo'.
3385 You can also pass a variable name as an argument, e.g. '%paste foo'.
3384 This assigns the pasted block to variable 'foo' as string, without
3386 This assigns the pasted block to variable 'foo' as string, without
3385 dedenting or executing it (preceding >>> and + is still stripped)
3387 dedenting or executing it (preceding >>> and + is still stripped)
3386
3388
3387 Options
3389 Options
3388 -------
3390 -------
3389
3391
3390 -r: re-executes the block previously entered by cpaste.
3392 -r: re-executes the block previously entered by cpaste.
3391
3393
3392 -q: quiet mode: do not echo the pasted text back to the terminal.
3394 -q: quiet mode: do not echo the pasted text back to the terminal.
3393
3395
3394 IPython statements (magics, shell escapes) are not supported (yet).
3396 IPython statements (magics, shell escapes) are not supported (yet).
3395
3397
3396 See also
3398 See also
3397 --------
3399 --------
3398 cpaste: manually paste code into terminal until you mark its end.
3400 cpaste: manually paste code into terminal until you mark its end.
3399 """
3401 """
3400 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3402 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3401 par = args.strip()
3403 par = args.strip()
3402 if opts.has_key('r'):
3404 if opts.has_key('r'):
3403 self._rerun_pasted()
3405 self._rerun_pasted()
3404 return
3406 return
3405
3407
3406 text = self.shell.hooks.clipboard_get()
3408 text = self.shell.hooks.clipboard_get()
3407 block = self._strip_pasted_lines_for_code(text.splitlines())
3409 block = self._strip_pasted_lines_for_code(text.splitlines())
3408
3410
3409 # By default, echo back to terminal unless quiet mode is requested
3411 # By default, echo back to terminal unless quiet mode is requested
3410 if not opts.has_key('q'):
3412 if not opts.has_key('q'):
3411 write = self.shell.write
3413 write = self.shell.write
3412 write(block)
3414 write(block)
3413 if not block.endswith('\n'):
3415 if not block.endswith('\n'):
3414 write('\n')
3416 write('\n')
3415 write("## -- End pasted text --\n")
3417 write("## -- End pasted text --\n")
3416
3418
3417 self._execute_block(block, par)
3419 self._execute_block(block, par)
3418
3420
3419 def magic_quickref(self,arg):
3421 def magic_quickref(self,arg):
3420 """ Show a quick reference sheet """
3422 """ Show a quick reference sheet """
3421 import IPython.core.usage
3423 import IPython.core.usage
3422 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3424 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3423
3425
3424 page(qr)
3426 page(qr)
3425
3427
3426 def magic_upgrade(self,arg):
3428 def magic_upgrade(self,arg):
3427 """ Upgrade your IPython installation
3429 """ Upgrade your IPython installation
3428
3430
3429 This will copy the config files that don't yet exist in your
3431 This will copy the config files that don't yet exist in your
3430 ipython dir from the system config dir. Use this after upgrading
3432 ipython dir from the system config dir. Use this after upgrading
3431 IPython if you don't wish to delete your .ipython dir.
3433 IPython if you don't wish to delete your .ipython dir.
3432
3434
3433 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3435 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3434 new users)
3436 new users)
3435
3437
3436 """
3438 """
3437 ip = self.getapi()
3439 ip = self.getapi()
3438 ipinstallation = path(IPython.__file__).dirname()
3440 ipinstallation = path(IPython.__file__).dirname()
3439 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3441 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3440 src_config = ipinstallation / 'config' / 'userconfig'
3442 src_config = ipinstallation / 'config' / 'userconfig'
3441 userdir = path(ip.options.ipythondir)
3443 userdir = path(ip.options.IPYTHONDIR)
3442 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3444 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3443 print ">",cmd
3445 print ">",cmd
3444 shell(cmd)
3446 shell(cmd)
3445 if arg == '-nolegacy':
3447 if arg == '-nolegacy':
3446 legacy = userdir.files('ipythonrc*')
3448 legacy = userdir.files('ipythonrc*')
3447 print "Nuking legacy files:",legacy
3449 print "Nuking legacy files:",legacy
3448
3450
3449 [p.remove() for p in legacy]
3451 [p.remove() for p in legacy]
3450 suffix = (sys.platform == 'win32' and '.ini' or '')
3452 suffix = (sys.platform == 'win32' and '.ini' or '')
3451 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3453 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3452
3454
3453
3455
3454 def magic_doctest_mode(self,parameter_s=''):
3456 def magic_doctest_mode(self,parameter_s=''):
3455 """Toggle doctest mode on and off.
3457 """Toggle doctest mode on and off.
3456
3458
3457 This mode allows you to toggle the prompt behavior between normal
3459 This mode allows you to toggle the prompt behavior between normal
3458 IPython prompts and ones that are as similar to the default IPython
3460 IPython prompts and ones that are as similar to the default IPython
3459 interpreter as possible.
3461 interpreter as possible.
3460
3462
3461 It also supports the pasting of code snippets that have leading '>>>'
3463 It also supports the pasting of code snippets that have leading '>>>'
3462 and '...' prompts in them. This means that you can paste doctests from
3464 and '...' prompts in them. This means that you can paste doctests from
3463 files or docstrings (even if they have leading whitespace), and the
3465 files or docstrings (even if they have leading whitespace), and the
3464 code will execute correctly. You can then use '%history -tn' to see
3466 code will execute correctly. You can then use '%history -tn' to see
3465 the translated history without line numbers; this will give you the
3467 the translated history without line numbers; this will give you the
3466 input after removal of all the leading prompts and whitespace, which
3468 input after removal of all the leading prompts and whitespace, which
3467 can be pasted back into an editor.
3469 can be pasted back into an editor.
3468
3470
3469 With these features, you can switch into this mode easily whenever you
3471 With these features, you can switch into this mode easily whenever you
3470 need to do testing and changes to doctests, without having to leave
3472 need to do testing and changes to doctests, without having to leave
3471 your existing IPython session.
3473 your existing IPython session.
3472 """
3474 """
3473
3475
3474 # XXX - Fix this to have cleaner activate/deactivate calls.
3476 # XXX - Fix this to have cleaner activate/deactivate calls.
3475 from IPython.extensions import InterpreterPasteInput as ipaste
3477 from IPython.extensions import InterpreterPasteInput as ipaste
3476 from IPython.utils.ipstruct import Struct
3478 from IPython.utils.ipstruct import Struct
3477
3479
3478 # Shorthands
3480 # Shorthands
3479 shell = self.shell
3481 shell = self.shell
3480 oc = shell.outputcache
3482 oc = shell.outputcache
3481 rc = shell.rc
3482 meta = shell.meta
3483 meta = shell.meta
3483 # dstore is a data store kept in the instance metadata bag to track any
3484 # dstore is a data store kept in the instance metadata bag to track any
3484 # changes we make, so we can undo them later.
3485 # changes we make, so we can undo them later.
3485 dstore = meta.setdefault('doctest_mode',Struct())
3486 dstore = meta.setdefault('doctest_mode',Struct())
3486 save_dstore = dstore.setdefault
3487 save_dstore = dstore.setdefault
3487
3488
3488 # save a few values we'll need to recover later
3489 # save a few values we'll need to recover later
3489 mode = save_dstore('mode',False)
3490 mode = save_dstore('mode',False)
3490 save_dstore('rc_pprint',rc.pprint)
3491 save_dstore('rc_pprint',shell.pprint)
3491 save_dstore('xmode',shell.InteractiveTB.mode)
3492 save_dstore('xmode',shell.InteractiveTB.mode)
3492 save_dstore('rc_separate_out',rc.separate_out)
3493 save_dstore('rc_separate_out',shell.separate_out)
3493 save_dstore('rc_separate_out2',rc.separate_out2)
3494 save_dstore('rc_separate_out2',shell.separate_out2)
3494 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3495 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3495 save_dstore('rc_separate_in',rc.separate_in)
3496 save_dstore('rc_separate_in',shell.separate_in)
3496
3497
3497 if mode == False:
3498 if mode == False:
3498 # turn on
3499 # turn on
3499 ipaste.activate_prefilter()
3500 ipaste.activate_prefilter()
3500
3501
3501 oc.prompt1.p_template = '>>> '
3502 oc.prompt1.p_template = '>>> '
3502 oc.prompt2.p_template = '... '
3503 oc.prompt2.p_template = '... '
3503 oc.prompt_out.p_template = ''
3504 oc.prompt_out.p_template = ''
3504
3505
3505 # Prompt separators like plain python
3506 # Prompt separators like plain python
3506 oc.input_sep = oc.prompt1.sep = ''
3507 oc.input_sep = oc.prompt1.sep = ''
3507 oc.output_sep = ''
3508 oc.output_sep = ''
3508 oc.output_sep2 = ''
3509 oc.output_sep2 = ''
3509
3510
3510 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3511 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3511 oc.prompt_out.pad_left = False
3512 oc.prompt_out.pad_left = False
3512
3513
3513 rc.pprint = False
3514 shell.pprint = False
3514
3515
3515 shell.magic_xmode('Plain')
3516 shell.magic_xmode('Plain')
3516
3517
3517 else:
3518 else:
3518 # turn off
3519 # turn off
3519 ipaste.deactivate_prefilter()
3520 ipaste.deactivate_prefilter()
3520
3521
3521 oc.prompt1.p_template = rc.prompt_in1
3522 oc.prompt1.p_template = shell.prompt_in1
3522 oc.prompt2.p_template = rc.prompt_in2
3523 oc.prompt2.p_template = shell.prompt_in2
3523 oc.prompt_out.p_template = rc.prompt_out
3524 oc.prompt_out.p_template = shell.prompt_out
3524
3525
3525 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3526 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3526
3527
3527 oc.output_sep = dstore.rc_separate_out
3528 oc.output_sep = dstore.rc_separate_out
3528 oc.output_sep2 = dstore.rc_separate_out2
3529 oc.output_sep2 = dstore.rc_separate_out2
3529
3530
3530 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3531 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3531 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3532 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3532
3533
3533 rc.pprint = dstore.rc_pprint
3534 rc.pprint = dstore.rc_pprint
3534
3535
3535 shell.magic_xmode(dstore.xmode)
3536 shell.magic_xmode(dstore.xmode)
3536
3537
3537 # Store new mode and inform
3538 # Store new mode and inform
3538 dstore.mode = bool(1-int(mode))
3539 dstore.mode = bool(1-int(mode))
3539 print 'Doctest mode is:',
3540 print 'Doctest mode is:',
3540 print ['OFF','ON'][dstore.mode]
3541 print ['OFF','ON'][dstore.mode]
3541
3542
3542 def magic_gui(self, parameter_s=''):
3543 def magic_gui(self, parameter_s=''):
3543 """Enable or disable IPython GUI event loop integration.
3544 """Enable or disable IPython GUI event loop integration.
3544
3545
3545 %gui [-a] [GUINAME]
3546 %gui [-a] [GUINAME]
3546
3547
3547 This magic replaces IPython's threaded shells that were activated
3548 This magic replaces IPython's threaded shells that were activated
3548 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3549 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3549 can now be enabled, disabled and swtiched at runtime and keyboard
3550 can now be enabled, disabled and swtiched at runtime and keyboard
3550 interrupts should work without any problems. The following toolkits
3551 interrupts should work without any problems. The following toolkits
3551 are supports: wxPython, PyQt4, PyGTK, and Tk::
3552 are supports: wxPython, PyQt4, PyGTK, and Tk::
3552
3553
3553 %gui wx # enable wxPython event loop integration
3554 %gui wx # enable wxPython event loop integration
3554 %gui qt4 # enable PyQt4 event loop integration
3555 %gui qt4 # enable PyQt4 event loop integration
3555 %gui gtk # enable PyGTK event loop integration
3556 %gui gtk # enable PyGTK event loop integration
3556 %gui tk # enable Tk event loop integration
3557 %gui tk # enable Tk event loop integration
3557 %gui # disable all event loop integration
3558 %gui # disable all event loop integration
3558
3559
3559 WARNING: after any of these has been called you can simply create
3560 WARNING: after any of these has been called you can simply create
3560 an application object, but DO NOT start the event loop yourself, as
3561 an application object, but DO NOT start the event loop yourself, as
3561 we have already handled that.
3562 we have already handled that.
3562
3563
3563 If you want us to create an appropriate application object add the
3564 If you want us to create an appropriate application object add the
3564 "-a" flag to your command::
3565 "-a" flag to your command::
3565
3566
3566 %gui -a wx
3567 %gui -a wx
3567
3568
3568 This is highly recommended for most users.
3569 This is highly recommended for most users.
3569 """
3570 """
3570 from IPython.lib import inputhook
3571 from IPython.lib import inputhook
3571 if "-a" in parameter_s:
3572 if "-a" in parameter_s:
3572 app = True
3573 app = True
3573 else:
3574 else:
3574 app = False
3575 app = False
3575 if not parameter_s:
3576 if not parameter_s:
3576 inputhook.clear_inputhook()
3577 inputhook.clear_inputhook()
3577 elif 'wx' in parameter_s:
3578 elif 'wx' in parameter_s:
3578 return inputhook.enable_wx(app)
3579 return inputhook.enable_wx(app)
3579 elif 'qt4' in parameter_s:
3580 elif 'qt4' in parameter_s:
3580 return inputhook.enable_qt4(app)
3581 return inputhook.enable_qt4(app)
3581 elif 'gtk' in parameter_s:
3582 elif 'gtk' in parameter_s:
3582 return inputhook.enable_gtk(app)
3583 return inputhook.enable_gtk(app)
3583 elif 'tk' in parameter_s:
3584 elif 'tk' in parameter_s:
3584 return inputhook.enable_tk(app)
3585 return inputhook.enable_tk(app)
3585
3586
3586
3587
3587 # end Magic
3588 # end Magic
@@ -1,320 +1,320 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes and functions for prefiltering (transforming) a line of user input.
3 Classes and functions for prefiltering (transforming) a line of user input.
4 This module is responsible, primarily, for breaking the line up into useful
4 This module is responsible, primarily, for breaking the line up into useful
5 pieces and triggering the appropriate handlers in iplib to do the actual
5 pieces and triggering the appropriate handlers in iplib to do the actual
6 transforming work.
6 transforming work.
7 """
7 """
8 __docformat__ = "restructuredtext en"
8 __docformat__ = "restructuredtext en"
9
9
10 import re
10 import re
11 from IPython.core import ipapi
11 from IPython.core import ipapi
12
12
13 class LineInfo(object):
13 class LineInfo(object):
14 """A single line of input and associated info.
14 """A single line of input and associated info.
15
15
16 Includes the following as properties:
16 Includes the following as properties:
17
17
18 line
18 line
19 The original, raw line
19 The original, raw line
20
20
21 continue_prompt
21 continue_prompt
22 Is this line a continuation in a sequence of multiline input?
22 Is this line a continuation in a sequence of multiline input?
23
23
24 pre
24 pre
25 The initial esc character or whitespace.
25 The initial esc character or whitespace.
26
26
27 preChar
27 preChar
28 The escape character(s) in pre or the empty string if there isn't one.
28 The escape character(s) in pre or the empty string if there isn't one.
29 Note that '!!' is a possible value for preChar. Otherwise it will
29 Note that '!!' is a possible value for preChar. Otherwise it will
30 always be a single character.
30 always be a single character.
31
31
32 preWhitespace
32 preWhitespace
33 The leading whitespace from pre if it exists. If there is a preChar,
33 The leading whitespace from pre if it exists. If there is a preChar,
34 this is just ''.
34 this is just ''.
35
35
36 iFun
36 iFun
37 The 'function part', which is basically the maximal initial sequence
37 The 'function part', which is basically the maximal initial sequence
38 of valid python identifiers and the '.' character. This is what is
38 of valid python identifiers and the '.' character. This is what is
39 checked for alias and magic transformations, used for auto-calling,
39 checked for alias and magic transformations, used for auto-calling,
40 etc.
40 etc.
41
41
42 theRest
42 theRest
43 Everything else on the line.
43 Everything else on the line.
44 """
44 """
45 def __init__(self, line, continue_prompt):
45 def __init__(self, line, continue_prompt):
46 self.line = line
46 self.line = line
47 self.continue_prompt = continue_prompt
47 self.continue_prompt = continue_prompt
48 self.pre, self.iFun, self.theRest = splitUserInput(line)
48 self.pre, self.iFun, self.theRest = splitUserInput(line)
49
49
50 self.preChar = self.pre.strip()
50 self.preChar = self.pre.strip()
51 if self.preChar:
51 if self.preChar:
52 self.preWhitespace = '' # No whitespace allowd before esc chars
52 self.preWhitespace = '' # No whitespace allowd before esc chars
53 else:
53 else:
54 self.preWhitespace = self.pre
54 self.preWhitespace = self.pre
55
55
56 self._oinfo = None
56 self._oinfo = None
57
57
58 def ofind(self, ip):
58 def ofind(self, ip):
59 """Do a full, attribute-walking lookup of the iFun in the various
59 """Do a full, attribute-walking lookup of the iFun in the various
60 namespaces for the given IPython InteractiveShell instance.
60 namespaces for the given IPython InteractiveShell instance.
61
61
62 Return a dict with keys: found,obj,ospace,ismagic
62 Return a dict with keys: found,obj,ospace,ismagic
63
63
64 Note: can cause state changes because of calling getattr, but should
64 Note: can cause state changes because of calling getattr, but should
65 only be run if autocall is on and if the line hasn't matched any
65 only be run if autocall is on and if the line hasn't matched any
66 other, less dangerous handlers.
66 other, less dangerous handlers.
67
67
68 Does cache the results of the call, so can be called multiple times
68 Does cache the results of the call, so can be called multiple times
69 without worrying about *further* damaging state.
69 without worrying about *further* damaging state.
70 """
70 """
71 if not self._oinfo:
71 if not self._oinfo:
72 self._oinfo = ip._ofind(self.iFun)
72 self._oinfo = ip._ofind(self.iFun)
73 return self._oinfo
73 return self._oinfo
74 def __str__(self):
74 def __str__(self):
75 return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest)
75 return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest)
76
76
77 def splitUserInput(line, pattern=None):
77 def splitUserInput(line, pattern=None):
78 """Split user input into pre-char/whitespace, function part and rest.
78 """Split user input into pre-char/whitespace, function part and rest.
79
79
80 Mostly internal to this module, but also used by iplib.expand_aliases,
80 Mostly internal to this module, but also used by iplib.expand_aliases,
81 which passes in a shell pattern.
81 which passes in a shell pattern.
82 """
82 """
83 # It seems to me that the shell splitting should be a separate method.
83 # It seems to me that the shell splitting should be a separate method.
84
84
85 if not pattern:
85 if not pattern:
86 pattern = line_split
86 pattern = line_split
87 match = pattern.match(line)
87 match = pattern.match(line)
88 if not match:
88 if not match:
89 #print "match failed for line '%s'" % line
89 #print "match failed for line '%s'" % line
90 try:
90 try:
91 iFun,theRest = line.split(None,1)
91 iFun,theRest = line.split(None,1)
92 except ValueError:
92 except ValueError:
93 #print "split failed for line '%s'" % line
93 #print "split failed for line '%s'" % line
94 iFun,theRest = line,''
94 iFun,theRest = line,''
95 pre = re.match('^(\s*)(.*)',line).groups()[0]
95 pre = re.match('^(\s*)(.*)',line).groups()[0]
96 else:
96 else:
97 pre,iFun,theRest = match.groups()
97 pre,iFun,theRest = match.groups()
98
98
99 # iFun has to be a valid python identifier, so it better be only pure
99 # iFun has to be a valid python identifier, so it better be only pure
100 # ascii, no unicode:
100 # ascii, no unicode:
101 try:
101 try:
102 iFun = iFun.encode('ascii')
102 iFun = iFun.encode('ascii')
103 except UnicodeEncodeError:
103 except UnicodeEncodeError:
104 theRest = iFun + u' ' + theRest
104 theRest = iFun + u' ' + theRest
105 iFun = u''
105 iFun = u''
106
106
107 #print 'line:<%s>' % line # dbg
107 #print 'line:<%s>' % line # dbg
108 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
108 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
109 return pre,iFun.strip(),theRest.lstrip()
109 return pre,iFun.strip(),theRest.lstrip()
110
110
111
111
112 # RegExp for splitting line contents into pre-char//first word-method//rest.
112 # RegExp for splitting line contents into pre-char//first word-method//rest.
113 # For clarity, each group in on one line.
113 # For clarity, each group in on one line.
114
114
115 # WARNING: update the regexp if the escapes in iplib are changed, as they
115 # WARNING: update the regexp if the escapes in iplib are changed, as they
116 # are hardwired in.
116 # are hardwired in.
117
117
118 # Although it's not solely driven by the regex, note that:
118 # Although it's not solely driven by the regex, note that:
119 # ,;/% only trigger if they are the first character on the line
119 # ,;/% only trigger if they are the first character on the line
120 # ! and !! trigger if they are first char(s) *or* follow an indent
120 # ! and !! trigger if they are first char(s) *or* follow an indent
121 # ? triggers as first or last char.
121 # ? triggers as first or last char.
122
122
123 # The three parts of the regex are:
123 # The three parts of the regex are:
124 # 1) pre: pre_char *or* initial whitespace
124 # 1) pre: pre_char *or* initial whitespace
125 # 2) iFun: first word/method (mix of \w and '.')
125 # 2) iFun: first word/method (mix of \w and '.')
126 # 3) theRest: rest of line (separated from iFun by space if non-empty)
126 # 3) theRest: rest of line (separated from iFun by space if non-empty)
127 line_split = re.compile(r'^([,;/%?]|!!?|\s*)'
127 line_split = re.compile(r'^([,;/%?]|!!?|\s*)'
128 r'\s*([\w\.]+)'
128 r'\s*([\w\.]+)'
129 r'(\s+.*$|$)')
129 r'(\s+.*$|$)')
130
130
131 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
131 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
132
132
133 def prefilter(line_info, ip):
133 def prefilter(line_info, ip):
134 """Call one of the passed-in InteractiveShell's handler preprocessors,
134 """Call one of the passed-in InteractiveShell's handler preprocessors,
135 depending on the form of the line. Return the results, which must be a
135 depending on the form of the line. Return the results, which must be a
136 value, even if it's a blank ('')."""
136 value, even if it's a blank ('')."""
137 # Note: the order of these checks does matter.
137 # Note: the order of these checks does matter.
138 for check in [ checkEmacs,
138 for check in [ checkEmacs,
139 checkShellEscape,
139 checkShellEscape,
140 checkIPyAutocall,
140 checkIPyAutocall,
141 checkMultiLineMagic,
141 checkMultiLineMagic,
142 checkEscChars,
142 checkEscChars,
143 checkAssignment,
143 checkAssignment,
144 checkAutomagic,
144 checkAutomagic,
145 checkAlias,
145 checkAlias,
146 checkPythonOps,
146 checkPythonOps,
147 checkAutocall,
147 checkAutocall,
148 ]:
148 ]:
149 handler = check(line_info, ip)
149 handler = check(line_info, ip)
150 if handler:
150 if handler:
151 return handler(line_info)
151 return handler(line_info)
152
152
153 return ip.handle_normal(line_info)
153 return ip.handle_normal(line_info)
154
154
155 # Handler checks
155 # Handler checks
156 #
156 #
157 # All have the same interface: they take a LineInfo object and a ref to the
157 # All have the same interface: they take a LineInfo object and a ref to the
158 # iplib.InteractiveShell object. They check the line to see if a particular
158 # iplib.InteractiveShell object. They check the line to see if a particular
159 # handler should be called, and return either a handler or None. The
159 # handler should be called, and return either a handler or None. The
160 # handlers which they return are *bound* methods of the InteractiveShell
160 # handlers which they return are *bound* methods of the InteractiveShell
161 # object.
161 # object.
162 #
162 #
163 # In general, these checks should only take responsibility for their 'own'
163 # In general, these checks should only take responsibility for their 'own'
164 # handler. If it doesn't get triggered, they should just return None and
164 # handler. If it doesn't get triggered, they should just return None and
165 # let the rest of the check sequence run.
165 # let the rest of the check sequence run.
166
166
167 def checkShellEscape(l_info,ip):
167 def checkShellEscape(l_info,ip):
168 if l_info.line.lstrip().startswith(ip.ESC_SHELL):
168 if l_info.line.lstrip().startswith(ip.ESC_SHELL):
169 return ip.handle_shell_escape
169 return ip.handle_shell_escape
170
170
171 def checkEmacs(l_info,ip):
171 def checkEmacs(l_info,ip):
172 "Emacs ipython-mode tags certain input lines."
172 "Emacs ipython-mode tags certain input lines."
173 if l_info.line.endswith('# PYTHON-MODE'):
173 if l_info.line.endswith('# PYTHON-MODE'):
174 return ip.handle_emacs
174 return ip.handle_emacs
175 else:
175 else:
176 return None
176 return None
177
177
178 def checkIPyAutocall(l_info,ip):
178 def checkIPyAutocall(l_info,ip):
179 "Instances of IPyAutocall in user_ns get autocalled immediately"
179 "Instances of IPyAutocall in user_ns get autocalled immediately"
180 obj = ip.user_ns.get(l_info.iFun, None)
180 obj = ip.user_ns.get(l_info.iFun, None)
181 if isinstance(obj, ipapi.IPyAutocall):
181 if isinstance(obj, ipapi.IPyAutocall):
182 obj.set_ip(ip.api)
182 obj.set_ip(ip.api)
183 return ip.handle_auto
183 return ip.handle_auto
184 else:
184 else:
185 return None
185 return None
186
186
187
187
188 def checkMultiLineMagic(l_info,ip):
188 def checkMultiLineMagic(l_info,ip):
189 "Allow ! and !! in multi-line statements if multi_line_specials is on"
189 "Allow ! and !! in multi-line statements if multi_line_specials is on"
190 # Note that this one of the only places we check the first character of
190 # Note that this one of the only places we check the first character of
191 # iFun and *not* the preChar. Also note that the below test matches
191 # iFun and *not* the preChar. Also note that the below test matches
192 # both ! and !!.
192 # both ! and !!.
193 if l_info.continue_prompt \
193 if l_info.continue_prompt \
194 and ip.rc.multi_line_specials:
194 and ip.multi_line_specials:
195 if l_info.iFun.startswith(ip.ESC_MAGIC):
195 if l_info.iFun.startswith(ip.ESC_MAGIC):
196 return ip.handle_magic
196 return ip.handle_magic
197 else:
197 else:
198 return None
198 return None
199
199
200 def checkEscChars(l_info,ip):
200 def checkEscChars(l_info,ip):
201 """Check for escape character and return either a handler to handle it,
201 """Check for escape character and return either a handler to handle it,
202 or None if there is no escape char."""
202 or None if there is no escape char."""
203 if l_info.line[-1] == ip.ESC_HELP \
203 if l_info.line[-1] == ip.ESC_HELP \
204 and l_info.preChar != ip.ESC_SHELL \
204 and l_info.preChar != ip.ESC_SHELL \
205 and l_info.preChar != ip.ESC_SH_CAP:
205 and l_info.preChar != ip.ESC_SH_CAP:
206 # the ? can be at the end, but *not* for either kind of shell escape,
206 # the ? can be at the end, but *not* for either kind of shell escape,
207 # because a ? can be a vaild final char in a shell cmd
207 # because a ? can be a vaild final char in a shell cmd
208 return ip.handle_help
208 return ip.handle_help
209 elif l_info.preChar in ip.esc_handlers:
209 elif l_info.preChar in ip.esc_handlers:
210 return ip.esc_handlers[l_info.preChar]
210 return ip.esc_handlers[l_info.preChar]
211 else:
211 else:
212 return None
212 return None
213
213
214
214
215 def checkAssignment(l_info,ip):
215 def checkAssignment(l_info,ip):
216 """Check to see if user is assigning to a var for the first time, in
216 """Check to see if user is assigning to a var for the first time, in
217 which case we want to avoid any sort of automagic / autocall games.
217 which case we want to avoid any sort of automagic / autocall games.
218
218
219 This allows users to assign to either alias or magic names true python
219 This allows users to assign to either alias or magic names true python
220 variables (the magic/alias systems always take second seat to true
220 variables (the magic/alias systems always take second seat to true
221 python code). E.g. ls='hi', or ls,that=1,2"""
221 python code). E.g. ls='hi', or ls,that=1,2"""
222 if l_info.theRest and l_info.theRest[0] in '=,':
222 if l_info.theRest and l_info.theRest[0] in '=,':
223 return ip.handle_normal
223 return ip.handle_normal
224 else:
224 else:
225 return None
225 return None
226
226
227
227
228 def checkAutomagic(l_info,ip):
228 def checkAutomagic(l_info,ip):
229 """If the iFun is magic, and automagic is on, run it. Note: normal,
229 """If the iFun is magic, and automagic is on, run it. Note: normal,
230 non-auto magic would already have been triggered via '%' in
230 non-auto magic would already have been triggered via '%' in
231 check_esc_chars. This just checks for automagic. Also, before
231 check_esc_chars. This just checks for automagic. Also, before
232 triggering the magic handler, make sure that there is nothing in the
232 triggering the magic handler, make sure that there is nothing in the
233 user namespace which could shadow it."""
233 user namespace which could shadow it."""
234 if not ip.rc.automagic or not hasattr(ip,'magic_'+l_info.iFun):
234 if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun):
235 return None
235 return None
236
236
237 # We have a likely magic method. Make sure we should actually call it.
237 # We have a likely magic method. Make sure we should actually call it.
238 if l_info.continue_prompt and not ip.rc.multi_line_specials:
238 if l_info.continue_prompt and not ip.multi_line_specials:
239 return None
239 return None
240
240
241 head = l_info.iFun.split('.',1)[0]
241 head = l_info.iFun.split('.',1)[0]
242 if isShadowed(head,ip):
242 if isShadowed(head,ip):
243 return None
243 return None
244
244
245 return ip.handle_magic
245 return ip.handle_magic
246
246
247
247
248 def checkAlias(l_info,ip):
248 def checkAlias(l_info,ip):
249 "Check if the initital identifier on the line is an alias."
249 "Check if the initital identifier on the line is an alias."
250 # Note: aliases can not contain '.'
250 # Note: aliases can not contain '.'
251 head = l_info.iFun.split('.',1)[0]
251 head = l_info.iFun.split('.',1)[0]
252
252
253 if l_info.iFun not in ip.alias_table \
253 if l_info.iFun not in ip.alias_table \
254 or head not in ip.alias_table \
254 or head not in ip.alias_table \
255 or isShadowed(head,ip):
255 or isShadowed(head,ip):
256 return None
256 return None
257
257
258 return ip.handle_alias
258 return ip.handle_alias
259
259
260
260
261 def checkPythonOps(l_info,ip):
261 def checkPythonOps(l_info,ip):
262 """If the 'rest' of the line begins with a function call or pretty much
262 """If the 'rest' of the line begins with a function call or pretty much
263 any python operator, we should simply execute the line (regardless of
263 any python operator, we should simply execute the line (regardless of
264 whether or not there's a possible autocall expansion). This avoids
264 whether or not there's a possible autocall expansion). This avoids
265 spurious (and very confusing) geattr() accesses."""
265 spurious (and very confusing) geattr() accesses."""
266 if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|':
266 if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|':
267 return ip.handle_normal
267 return ip.handle_normal
268 else:
268 else:
269 return None
269 return None
270
270
271
271
272 def checkAutocall(l_info,ip):
272 def checkAutocall(l_info,ip):
273 "Check if the initial word/function is callable and autocall is on."
273 "Check if the initial word/function is callable and autocall is on."
274 if not ip.rc.autocall:
274 if not ip.autocall:
275 return None
275 return None
276
276
277 oinfo = l_info.ofind(ip) # This can mutate state via getattr
277 oinfo = l_info.ofind(ip) # This can mutate state via getattr
278 if not oinfo['found']:
278 if not oinfo['found']:
279 return None
279 return None
280
280
281 if callable(oinfo['obj']) \
281 if callable(oinfo['obj']) \
282 and (not re_exclude_auto.match(l_info.theRest)) \
282 and (not re_exclude_auto.match(l_info.theRest)) \
283 and re_fun_name.match(l_info.iFun):
283 and re_fun_name.match(l_info.iFun):
284 #print 'going auto' # dbg
284 #print 'going auto' # dbg
285 return ip.handle_auto
285 return ip.handle_auto
286 else:
286 else:
287 #print 'was callable?', callable(l_info.oinfo['obj']) # dbg
287 #print 'was callable?', callable(l_info.oinfo['obj']) # dbg
288 return None
288 return None
289
289
290 # RegExp to identify potential function names
290 # RegExp to identify potential function names
291 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
291 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
292
292
293 # RegExp to exclude strings with this start from autocalling. In
293 # RegExp to exclude strings with this start from autocalling. In
294 # particular, all binary operators should be excluded, so that if foo is
294 # particular, all binary operators should be excluded, so that if foo is
295 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
295 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
296 # characters '!=()' don't need to be checked for, as the checkPythonChars
296 # characters '!=()' don't need to be checked for, as the checkPythonChars
297 # routine explicitely does so, to catch direct calls and rebindings of
297 # routine explicitely does so, to catch direct calls and rebindings of
298 # existing names.
298 # existing names.
299
299
300 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
300 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
301 # it affects the rest of the group in square brackets.
301 # it affects the rest of the group in square brackets.
302 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
302 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
303 r'|^is |^not |^in |^and |^or ')
303 r'|^is |^not |^in |^and |^or ')
304
304
305 # try to catch also methods for stuff in lists/tuples/dicts: off
305 # try to catch also methods for stuff in lists/tuples/dicts: off
306 # (experimental). For this to work, the line_split regexp would need
306 # (experimental). For this to work, the line_split regexp would need
307 # to be modified so it wouldn't break things at '['. That line is
307 # to be modified so it wouldn't break things at '['. That line is
308 # nasty enough that I shouldn't change it until I can test it _well_.
308 # nasty enough that I shouldn't change it until I can test it _well_.
309 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
309 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
310
310
311 # Handler Check Utilities
311 # Handler Check Utilities
312 def isShadowed(identifier,ip):
312 def isShadowed(identifier,ip):
313 """Is the given identifier defined in one of the namespaces which shadow
313 """Is the given identifier defined in one of the namespaces which shadow
314 the alias and magic namespaces? Note that an identifier is different
314 the alias and magic namespaces? Note that an identifier is different
315 than iFun, because it can not contain a '.' character."""
315 than iFun, because it can not contain a '.' character."""
316 # This is much safer than calling ofind, which can change state
316 # This is much safer than calling ofind, which can change state
317 return (identifier in ip.user_ns \
317 return (identifier in ip.user_ns \
318 or identifier in ip.internal_ns \
318 or identifier in ip.internal_ns \
319 or identifier in ip.ns_table['builtin'])
319 or identifier in ip.ns_table['builtin'])
320
320
@@ -1,274 +1,274 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """IPython Shell classes.
3 """IPython Shell classes.
4
4
5 Originally, this module was horribly complicated because of the need to
5 Originally, this module was horribly complicated because of the need to
6 use threads to integrate with GUI toolkit event loops. Now, we are using
6 use threads to integrate with GUI toolkit event loops. Now, we are using
7 the :mod:`IPython.lib.inputhook`, which is based on PyOS_InputHook. This
7 the :mod:`IPython.lib.inputhook`, which is based on PyOS_InputHook. This
8 dramatically simplifies this logic and allow 3rd party packages (such as
8 dramatically simplifies this logic and allow 3rd party packages (such as
9 matplotlib) to handle these things by themselves.
9 matplotlib) to handle these things by themselves.
10
10
11 This new approach also allows projects like matplotlib to work interactively
11 This new approach also allows projects like matplotlib to work interactively
12 in the standard python shell.
12 in the standard python shell.
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import sys
26 import sys
27
27
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.core import ipapi
29 from IPython.core import ipapi
30 from IPython.utils.genutils import ask_yes_no
30 from IPython.utils.genutils import ask_yes_no
31 from IPython.core.iplib import InteractiveShell
31 from IPython.core.iplib import InteractiveShell
32 from IPython.core.ipmaker import make_IPython
32 from IPython.core.ipmaker import make_IPython
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Code
35 # Code
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class IPShell:
39 class IPShell:
40 """Create an IPython instance.
40 """Create an IPython instance.
41
41
42 This calls the factory :func:`make_IPython`, which creates a configured
42 This calls the factory :func:`make_IPython`, which creates a configured
43 :class:`InteractiveShell` object, and presents the result as a simple
43 :class:`InteractiveShell` object, and presents the result as a simple
44 class with a :meth:`mainloop` method.
44 class with a :meth:`mainloop` method.
45 """
45 """
46
46
47 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
47 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
48 debug=1, shell_class=InteractiveShell):
48 debug=1, shell_class=InteractiveShell):
49 self.IP = make_IPython(argv, user_ns=user_ns,
49 self.IP = make_IPython(argv, user_ns=user_ns,
50 user_global_ns=user_global_ns,
50 user_global_ns=user_global_ns,
51 debug=debug, shell_class=shell_class)
51 debug=debug, shell_class=shell_class)
52
52
53 def mainloop(self,sys_exit=0,banner=None):
53 def mainloop(self,sys_exit=0,banner=None):
54 self.IP.mainloop(banner)
54 self.IP.mainloop(banner)
55 if sys_exit:
55 if sys_exit:
56 sys.exit()
56 sys.exit()
57
57
58
58
59 # This is an additional magic that is exposed in embedded shells.
59 # This is an additional magic that is exposed in embedded shells.
60 def kill_embedded(self,parameter_s=''):
60 def kill_embedded(self,parameter_s=''):
61 """%kill_embedded : deactivate for good the current embedded IPython.
61 """%kill_embedded : deactivate for good the current embedded IPython.
62
62
63 This function (after asking for confirmation) sets an internal flag so that
63 This function (after asking for confirmation) sets an internal flag so that
64 an embedded IPython will never activate again. This is useful to
64 an embedded IPython will never activate again. This is useful to
65 permanently disable a shell that is being called inside a loop: once you've
65 permanently disable a shell that is being called inside a loop: once you've
66 figured out what you needed from it, you may then kill it and the program
66 figured out what you needed from it, you may then kill it and the program
67 will then continue to run without the interactive shell interfering again.
67 will then continue to run without the interactive shell interfering again.
68 """
68 """
69
69
70 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
70 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
71 "(y/n)? [y/N] ",'n')
71 "(y/n)? [y/N] ",'n')
72 if kill:
72 if kill:
73 self.shell.embedded_active = False
73 self.shell.embedded_active = False
74 print "This embedded IPython will not reactivate anymore once you exit."
74 print "This embedded IPython will not reactivate anymore once you exit."
75
75
76
76
77 class IPShellEmbed:
77 class IPShellEmbed:
78 """Allow embedding an IPython shell into a running program.
78 """Allow embedding an IPython shell into a running program.
79
79
80 Instances of this class are callable, with the __call__ method being an
80 Instances of this class are callable, with the __call__ method being an
81 alias to the embed() method of an InteractiveShell instance.
81 alias to the embed() method of an InteractiveShell instance.
82
82
83 Usage (see also the example-embed.py file for a running example)::
83 Usage (see also the example-embed.py file for a running example)::
84
84
85 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
85 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
86
86
87 * argv: list containing valid command-line options for IPython, as they
87 * argv: list containing valid command-line options for IPython, as they
88 would appear in sys.argv[1:].
88 would appear in sys.argv[1:].
89
89
90 For example, the following command-line options::
90 For example, the following command-line options::
91
91
92 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
92 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
93
93
94 would be passed in the argv list as::
94 would be passed in the argv list as::
95
95
96 ['-prompt_in1','Input <\\#>','-colors','LightBG']
96 ['-prompt_in1','Input <\\#>','-colors','LightBG']
97
97
98 * banner: string which gets printed every time the interpreter starts.
98 * banner: string which gets printed every time the interpreter starts.
99
99
100 * exit_msg: string which gets printed every time the interpreter exits.
100 * exit_msg: string which gets printed every time the interpreter exits.
101
101
102 * rc_override: a dict or Struct of configuration options such as those
102 * rc_override: a dict or Struct of configuration options such as those
103 used by IPython. These options are read from your ~/.ipython/ipythonrc
103 used by IPython. These options are read from your ~/.ipython/ipythonrc
104 file when the Shell object is created. Passing an explicit rc_override
104 file when the Shell object is created. Passing an explicit rc_override
105 dict with any options you want allows you to override those values at
105 dict with any options you want allows you to override those values at
106 creation time without having to modify the file. This way you can create
106 creation time without having to modify the file. This way you can create
107 embeddable instances configured in any way you want without editing any
107 embeddable instances configured in any way you want without editing any
108 global files (thus keeping your interactive IPython configuration
108 global files (thus keeping your interactive IPython configuration
109 unchanged).
109 unchanged).
110
110
111 Then the ipshell instance can be called anywhere inside your code::
111 Then the ipshell instance can be called anywhere inside your code::
112
112
113 ipshell(header='') -> Opens up an IPython shell.
113 ipshell(header='') -> Opens up an IPython shell.
114
114
115 * header: string printed by the IPython shell upon startup. This can let
115 * header: string printed by the IPython shell upon startup. This can let
116 you know where in your code you are when dropping into the shell. Note
116 you know where in your code you are when dropping into the shell. Note
117 that 'banner' gets prepended to all calls, so header is used for
117 that 'banner' gets prepended to all calls, so header is used for
118 location-specific information.
118 location-specific information.
119
119
120 For more details, see the __call__ method below.
120 For more details, see the __call__ method below.
121
121
122 When the IPython shell is exited with Ctrl-D, normal program execution
122 When the IPython shell is exited with Ctrl-D, normal program execution
123 resumes.
123 resumes.
124
124
125 This functionality was inspired by a posting on comp.lang.python by cmkl
125 This functionality was inspired by a posting on comp.lang.python by cmkl
126 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
126 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
127 by the IDL stop/continue commands.
127 by the IDL stop/continue commands.
128 """
128 """
129
129
130 def __init__(self, argv=None, banner='', exit_msg=None,
130 def __init__(self, argv=None, banner='', exit_msg=None,
131 rc_override=None, user_ns=None):
131 rc_override=None, user_ns=None):
132 """Note that argv here is a string, NOT a list."""
132 """Note that argv here is a string, NOT a list."""
133
133
134 self.set_banner(banner)
134 self.set_banner(banner)
135 self.set_exit_msg(exit_msg)
135 self.set_exit_msg(exit_msg)
136 self.set_dummy_mode(0)
136 self.set_dummy_mode(0)
137
137
138 # sys.displayhook is a global, we need to save the user's original
138 # sys.displayhook is a global, we need to save the user's original
139 # Don't rely on __displayhook__, as the user may have changed that.
139 # Don't rely on __displayhook__, as the user may have changed that.
140 self.sys_displayhook_ori = sys.displayhook
140 self.sys_displayhook_ori = sys.displayhook
141
141
142 # save readline completer status
142 # save readline completer status
143 try:
143 try:
144 #print 'Save completer',sys.ipcompleter # dbg
144 #print 'Save completer',sys.ipcompleter # dbg
145 self.sys_ipcompleter_ori = sys.ipcompleter
145 self.sys_ipcompleter_ori = sys.ipcompleter
146 except:
146 except:
147 pass # not nested with IPython
147 pass # not nested with IPython
148
148
149 self.IP = make_IPython(argv,rc_override=rc_override,
149 self.IP = make_IPython(argv,rc_override=rc_override,
150 embedded=True,
150 embedded=True,
151 user_ns=user_ns)
151 user_ns=user_ns)
152
152
153 ip = ipapi.IPApi(self.IP)
153 ip = ipapi.IPApi(self.IP)
154 ip.expose_magic("kill_embedded",kill_embedded)
154 ip.expose_magic("kill_embedded",kill_embedded)
155
155
156 # copy our own displayhook also
156 # copy our own displayhook also
157 self.sys_displayhook_embed = sys.displayhook
157 self.sys_displayhook_embed = sys.displayhook
158 # and leave the system's display hook clean
158 # and leave the system's display hook clean
159 sys.displayhook = self.sys_displayhook_ori
159 sys.displayhook = self.sys_displayhook_ori
160 # don't use the ipython crash handler so that user exceptions aren't
160 # don't use the ipython crash handler so that user exceptions aren't
161 # trapped
161 # trapped
162 sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.rc.colors,
162 sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.colors,
163 mode = self.IP.rc.xmode,
163 mode = self.IP.xmode,
164 call_pdb = self.IP.rc.pdb)
164 call_pdb = self.IP.pdb)
165 self.restore_system_completer()
165 self.restore_system_completer()
166
166
167 def restore_system_completer(self):
167 def restore_system_completer(self):
168 """Restores the readline completer which was in place.
168 """Restores the readline completer which was in place.
169
169
170 This allows embedded IPython within IPython not to disrupt the
170 This allows embedded IPython within IPython not to disrupt the
171 parent's completion.
171 parent's completion.
172 """
172 """
173
173
174 try:
174 try:
175 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
175 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
176 sys.ipcompleter = self.sys_ipcompleter_ori
176 sys.ipcompleter = self.sys_ipcompleter_ori
177 except:
177 except:
178 pass
178 pass
179
179
180 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None):
180 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None):
181 """Activate the interactive interpreter.
181 """Activate the interactive interpreter.
182
182
183 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
183 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
184 the interpreter shell with the given local and global namespaces, and
184 the interpreter shell with the given local and global namespaces, and
185 optionally print a header string at startup.
185 optionally print a header string at startup.
186
186
187 The shell can be globally activated/deactivated using the
187 The shell can be globally activated/deactivated using the
188 set/get_dummy_mode methods. This allows you to turn off a shell used
188 set/get_dummy_mode methods. This allows you to turn off a shell used
189 for debugging globally.
189 for debugging globally.
190
190
191 However, *each* time you call the shell you can override the current
191 However, *each* time you call the shell you can override the current
192 state of dummy_mode with the optional keyword parameter 'dummy'. For
192 state of dummy_mode with the optional keyword parameter 'dummy'. For
193 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
193 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
194 can still have a specific call work by making it as IPShell(dummy=0).
194 can still have a specific call work by making it as IPShell(dummy=0).
195
195
196 The optional keyword parameter dummy controls whether the call
196 The optional keyword parameter dummy controls whether the call
197 actually does anything.
197 actually does anything.
198 """
198 """
199
199
200 # If the user has turned it off, go away
200 # If the user has turned it off, go away
201 if not self.IP.embedded_active:
201 if not self.IP.embedded_active:
202 return
202 return
203
203
204 # Normal exits from interactive mode set this flag, so the shell can't
204 # Normal exits from interactive mode set this flag, so the shell can't
205 # re-enter (it checks this variable at the start of interactive mode).
205 # re-enter (it checks this variable at the start of interactive mode).
206 self.IP.exit_now = False
206 self.IP.exit_now = False
207
207
208 # Allow the dummy parameter to override the global __dummy_mode
208 # Allow the dummy parameter to override the global __dummy_mode
209 if dummy or (dummy != 0 and self.__dummy_mode):
209 if dummy or (dummy != 0 and self.__dummy_mode):
210 return
210 return
211
211
212 # Set global subsystems (display,completions) to our values
212 # Set global subsystems (display,completions) to our values
213 sys.displayhook = self.sys_displayhook_embed
213 sys.displayhook = self.sys_displayhook_embed
214 if self.IP.has_readline:
214 if self.IP.has_readline:
215 self.IP.set_completer()
215 self.IP.set_completer()
216
216
217 if self.banner and header:
217 if self.banner and header:
218 format = '%s\n%s\n'
218 format = '%s\n%s\n'
219 else:
219 else:
220 format = '%s%s\n'
220 format = '%s%s\n'
221 banner = format % (self.banner,header)
221 banner = format % (self.banner,header)
222
222
223 # Call the embedding code with a stack depth of 1 so it can skip over
223 # Call the embedding code with a stack depth of 1 so it can skip over
224 # our call and get the original caller's namespaces.
224 # our call and get the original caller's namespaces.
225 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
225 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
226
226
227 if self.exit_msg:
227 if self.exit_msg:
228 print self.exit_msg
228 print self.exit_msg
229
229
230 # Restore global systems (display, completion)
230 # Restore global systems (display, completion)
231 sys.displayhook = self.sys_displayhook_ori
231 sys.displayhook = self.sys_displayhook_ori
232 self.restore_system_completer()
232 self.restore_system_completer()
233
233
234 def set_dummy_mode(self, dummy):
234 def set_dummy_mode(self, dummy):
235 """Sets the embeddable shell's dummy mode parameter.
235 """Sets the embeddable shell's dummy mode parameter.
236
236
237 set_dummy_mode(dummy): dummy = 0 or 1.
237 set_dummy_mode(dummy): dummy = 0 or 1.
238
238
239 This parameter is persistent and makes calls to the embeddable shell
239 This parameter is persistent and makes calls to the embeddable shell
240 silently return without performing any action. This allows you to
240 silently return without performing any action. This allows you to
241 globally activate or deactivate a shell you're using with a single call.
241 globally activate or deactivate a shell you're using with a single call.
242
242
243 If you need to manually"""
243 If you need to manually"""
244
244
245 if dummy not in [0,1,False,True]:
245 if dummy not in [0,1,False,True]:
246 raise ValueError,'dummy parameter must be boolean'
246 raise ValueError,'dummy parameter must be boolean'
247 self.__dummy_mode = dummy
247 self.__dummy_mode = dummy
248
248
249 def get_dummy_mode(self):
249 def get_dummy_mode(self):
250 """Return the current value of the dummy mode parameter.
250 """Return the current value of the dummy mode parameter.
251 """
251 """
252 return self.__dummy_mode
252 return self.__dummy_mode
253
253
254 def set_banner(self, banner):
254 def set_banner(self, banner):
255 """Sets the global banner.
255 """Sets the global banner.
256
256
257 This banner gets prepended to every header printed when the shell
257 This banner gets prepended to every header printed when the shell
258 instance is called."""
258 instance is called."""
259
259
260 self.banner = banner
260 self.banner = banner
261
261
262 def set_exit_msg(self, exit_msg):
262 def set_exit_msg(self, exit_msg):
263 """Sets the global exit_msg.
263 """Sets the global exit_msg.
264
264
265 This exit message gets printed upon exiting every time the embedded
265 This exit message gets printed upon exiting every time the embedded
266 shell is called. It is None by default. """
266 shell is called. It is None by default. """
267
267
268 self.exit_msg = exit_msg
268 self.exit_msg = exit_msg
269
269
270 # This is the one which should be called by external code.
270 # This is the one which should be called by external code.
271 def start(user_ns = None):
271 def start(user_ns = None):
272 """Return a running shell instance of :class:`IPShell`."""
272 """Return a running shell instance of :class:`IPShell`."""
273 return IPShell(user_ns = user_ns)
273 return IPShell(user_ns = user_ns)
274
274
@@ -1,81 +1,82 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
1 """Tests for the key iplib module, where the main ipython class is defined.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import shutil
9 import shutil
10 import tempfile
10 import tempfile
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.core import iplib
16 from IPython.core import iplib
17 from IPython.core import ipapi
17 from IPython.core import ipapi
18 from IPython.core.oldusersetup import user_setup
18
19
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20 # Globals
21 # Globals
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22
23
23 # Useful global ipapi object and main IPython one. Unfortunately we have a
24 # Useful global ipapi object and main IPython one. Unfortunately we have a
24 # long precedent of carrying the 'ipapi' global object which is injected into
25 # long precedent of carrying the 'ipapi' global object which is injected into
25 # the system namespace as _ip, but that keeps a pointer to the actual IPython
26 # the system namespace as _ip, but that keeps a pointer to the actual IPython
26 # InteractiveShell instance, which is named IP. Since in testing we do need
27 # InteractiveShell instance, which is named IP. Since in testing we do need
27 # access to the real thing (we want to probe beyond what ipapi exposes), make
28 # access to the real thing (we want to probe beyond what ipapi exposes), make
28 # here a global reference to each. In general, things that are exposed by the
29 # here a global reference to each. In general, things that are exposed by the
29 # ipapi instance should be read from there, but we also will often need to use
30 # ipapi instance should be read from there, but we also will often need to use
30 # the actual IPython one.
31 # the actual IPython one.
31
32
32 # Get the public instance of IPython, and if it's None, make one so we can use
33 # Get the public instance of IPython, and if it's None, make one so we can use
33 # it for testing
34 # it for testing
34 ip = ipapi.get()
35 ip = ipapi.get()
35 if ip is None:
36 if ip is None:
36 # IPython not running yet, make one from the testing machinery for
37 # IPython not running yet, make one from the testing machinery for
37 # consistency when the test suite is being run via iptest
38 # consistency when the test suite is being run via iptest
38 from IPython.testing.plugin import ipdoctest
39 from IPython.testing.plugin import ipdoctest
39 ip = ipapi.get()
40 ip = ipapi.get()
40
41
41 IP = ip.IP # This is the actual IPython shell 'raw' object.
42 IP = ip.IP # This is the actual IPython shell 'raw' object.
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44 # Test functions
45 # Test functions
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46
47
47 def test_reset():
48 def test_reset():
48 """reset must clear most namespaces."""
49 """reset must clear most namespaces."""
49 IP.reset() # first, it should run without error
50 IP.reset() # first, it should run without error
50 # Then, check that most namespaces end up empty
51 # Then, check that most namespaces end up empty
51 for ns in IP.ns_refs_table:
52 for ns in IP.ns_refs_table:
52 if ns is IP.user_ns:
53 if ns is IP.user_ns:
53 # The user namespace is reset with some data, so we can't check for
54 # The user namespace is reset with some data, so we can't check for
54 # it being empty
55 # it being empty
55 continue
56 continue
56 nt.assert_equals(len(ns),0)
57 nt.assert_equals(len(ns),0)
57
58
58
59
59 # make sure that user_setup can be run re-entrantly in 'install' mode.
60 # make sure that user_setup can be run re-entrantly in 'install' mode.
60 def test_user_setup():
61 def test_user_setup():
61 # use a lambda to pass kwargs to the generator
62 # use a lambda to pass kwargs to the generator
62 user_setup = lambda a,k: iplib.user_setup(*a,**k)
63 user_setup = lambda a,k: user_setup(*a,**k)
63 kw = dict(mode='install', interactive=False)
64 kw = dict(mode='install', interactive=False)
64
65
65 # Call the user setup and verify that the directory exists
66 # Call the user setup and verify that the directory exists
66 yield user_setup, (ip.options.ipythondir,''), kw
67 yield user_setup, (ip.options.IPYTHONDIR,''), kw
67 yield os.path.isdir, ip.options.ipythondir
68 yield os.path.isdir, ip.options.IPYTHONDIR
68
69
69 # Now repeat the operation with a non-existent directory. Check both that
70 # Now repeat the operation with a non-existent directory. Check both that
70 # the call succeeds and that the directory is created.
71 # the call succeeds and that the directory is created.
71 tmpdir = tempfile.mktemp(prefix='ipython-test-')
72 tmpdir = tempfile.mktemp(prefix='ipython-test-')
72 # Use a try with an empty except because try/finally doesn't work with a
73 # Use a try with an empty except because try/finally doesn't work with a
73 # yield in Python 2.4.
74 # yield in Python 2.4.
74 try:
75 try:
75 yield user_setup, (tmpdir,''), kw
76 yield user_setup, (tmpdir,''), kw
76 yield os.path.isdir, tmpdir
77 yield os.path.isdir, tmpdir
77 except:
78 except:
78 pass
79 pass
79 # Clean up the temp dir once done
80 # Clean up the temp dir once done
80 shutil.rmtree(tmpdir)
81 shutil.rmtree(tmpdir)
81 No newline at end of file
82
@@ -1,1063 +1,1063 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultratb.py -- Spice up your tracebacks!
3 ultratb.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultratb
12 import sys,ultratb
13 sys.excepthook = ultratb.ColorTB()
13 sys.excepthook = ultratb.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultratb
40 import sys,ultratb
41 sys.excepthook = ultratb.VerboseTB()
41 sys.excepthook = ultratb.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62 """
62 """
63
63
64 #*****************************************************************************
64 #*****************************************************************************
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 #
67 #
68 # Distributed under the terms of the BSD License. The full license is in
68 # Distributed under the terms of the BSD License. The full license is in
69 # the file COPYING, distributed as part of this software.
69 # the file COPYING, distributed as part of this software.
70 #*****************************************************************************
70 #*****************************************************************************
71
71
72 # Required modules
72 # Required modules
73 import inspect
73 import inspect
74 import keyword
74 import keyword
75 import linecache
75 import linecache
76 import os
76 import os
77 import pydoc
77 import pydoc
78 import re
78 import re
79 import string
79 import string
80 import sys
80 import sys
81 import time
81 import time
82 import tokenize
82 import tokenize
83 import traceback
83 import traceback
84 import types
84 import types
85
85
86 # For purposes of monkeypatching inspect to fix a bug in it.
86 # For purposes of monkeypatching inspect to fix a bug in it.
87 from inspect import getsourcefile, getfile, getmodule,\
87 from inspect import getsourcefile, getfile, getmodule,\
88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
89
89
90
90
91 # IPython's own modules
91 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython.utils import PyColorize
93 from IPython.utils import PyColorize
94 from IPython.core import debugger, ipapi
94 from IPython.core import debugger, ipapi
95 from IPython.utils.ipstruct import Struct
95 from IPython.utils.ipstruct import Struct
96 from IPython.core.excolors import exception_colors
96 from IPython.core.excolors import exception_colors
97 from IPython.utils.genutils import Term,uniq_stable,error,info
97 from IPython.utils.genutils import Term,uniq_stable,error,info
98
98
99 # Globals
99 # Globals
100 # amount of space to put line numbers before verbose tracebacks
100 # amount of space to put line numbers before verbose tracebacks
101 INDENT_SIZE = 8
101 INDENT_SIZE = 8
102
102
103 # Default color scheme. This is used, for example, by the traceback
103 # Default color scheme. This is used, for example, by the traceback
104 # formatter. When running in an actual IPython instance, the user's rc.colors
104 # formatter. When running in an actual IPython instance, the user's rc.colors
105 # value is used, but havinga module global makes this functionality available
105 # value is used, but havinga module global makes this functionality available
106 # to users of ultratb who are NOT running inside ipython.
106 # to users of ultratb who are NOT running inside ipython.
107 DEFAULT_SCHEME = 'NoColor'
107 DEFAULT_SCHEME = 'NoColor'
108
108
109 #---------------------------------------------------------------------------
109 #---------------------------------------------------------------------------
110 # Code begins
110 # Code begins
111
111
112 # Utility functions
112 # Utility functions
113 def inspect_error():
113 def inspect_error():
114 """Print a message about internal inspect errors.
114 """Print a message about internal inspect errors.
115
115
116 These are unfortunately quite common."""
116 These are unfortunately quite common."""
117
117
118 error('Internal Python error in the inspect module.\n'
118 error('Internal Python error in the inspect module.\n'
119 'Below is the traceback from this internal error.\n')
119 'Below is the traceback from this internal error.\n')
120
120
121
121
122 def findsource(object):
122 def findsource(object):
123 """Return the entire source file and starting line number for an object.
123 """Return the entire source file and starting line number for an object.
124
124
125 The argument may be a module, class, method, function, traceback, frame,
125 The argument may be a module, class, method, function, traceback, frame,
126 or code object. The source code is returned as a list of all the lines
126 or code object. The source code is returned as a list of all the lines
127 in the file and the line number indexes a line in that list. An IOError
127 in the file and the line number indexes a line in that list. An IOError
128 is raised if the source code cannot be retrieved.
128 is raised if the source code cannot be retrieved.
129
129
130 FIXED version with which we monkeypatch the stdlib to work around a bug."""
130 FIXED version with which we monkeypatch the stdlib to work around a bug."""
131
131
132 file = getsourcefile(object) or getfile(object)
132 file = getsourcefile(object) or getfile(object)
133 # If the object is a frame, then trying to get the globals dict from its
133 # If the object is a frame, then trying to get the globals dict from its
134 # module won't work. Instead, the frame object itself has the globals
134 # module won't work. Instead, the frame object itself has the globals
135 # dictionary.
135 # dictionary.
136 globals_dict = None
136 globals_dict = None
137 if inspect.isframe(object):
137 if inspect.isframe(object):
138 # XXX: can this ever be false?
138 # XXX: can this ever be false?
139 globals_dict = object.f_globals
139 globals_dict = object.f_globals
140 else:
140 else:
141 module = getmodule(object, file)
141 module = getmodule(object, file)
142 if module:
142 if module:
143 globals_dict = module.__dict__
143 globals_dict = module.__dict__
144 lines = linecache.getlines(file, globals_dict)
144 lines = linecache.getlines(file, globals_dict)
145 if not lines:
145 if not lines:
146 raise IOError('could not get source code')
146 raise IOError('could not get source code')
147
147
148 if ismodule(object):
148 if ismodule(object):
149 return lines, 0
149 return lines, 0
150
150
151 if isclass(object):
151 if isclass(object):
152 name = object.__name__
152 name = object.__name__
153 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
153 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
154 # make some effort to find the best matching class definition:
154 # make some effort to find the best matching class definition:
155 # use the one with the least indentation, which is the one
155 # use the one with the least indentation, which is the one
156 # that's most probably not inside a function definition.
156 # that's most probably not inside a function definition.
157 candidates = []
157 candidates = []
158 for i in range(len(lines)):
158 for i in range(len(lines)):
159 match = pat.match(lines[i])
159 match = pat.match(lines[i])
160 if match:
160 if match:
161 # if it's at toplevel, it's already the best one
161 # if it's at toplevel, it's already the best one
162 if lines[i][0] == 'c':
162 if lines[i][0] == 'c':
163 return lines, i
163 return lines, i
164 # else add whitespace to candidate list
164 # else add whitespace to candidate list
165 candidates.append((match.group(1), i))
165 candidates.append((match.group(1), i))
166 if candidates:
166 if candidates:
167 # this will sort by whitespace, and by line number,
167 # this will sort by whitespace, and by line number,
168 # less whitespace first
168 # less whitespace first
169 candidates.sort()
169 candidates.sort()
170 return lines, candidates[0][1]
170 return lines, candidates[0][1]
171 else:
171 else:
172 raise IOError('could not find class definition')
172 raise IOError('could not find class definition')
173
173
174 if ismethod(object):
174 if ismethod(object):
175 object = object.im_func
175 object = object.im_func
176 if isfunction(object):
176 if isfunction(object):
177 object = object.func_code
177 object = object.func_code
178 if istraceback(object):
178 if istraceback(object):
179 object = object.tb_frame
179 object = object.tb_frame
180 if isframe(object):
180 if isframe(object):
181 object = object.f_code
181 object = object.f_code
182 if iscode(object):
182 if iscode(object):
183 if not hasattr(object, 'co_firstlineno'):
183 if not hasattr(object, 'co_firstlineno'):
184 raise IOError('could not find function definition')
184 raise IOError('could not find function definition')
185 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
185 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
186 pmatch = pat.match
186 pmatch = pat.match
187 # fperez - fix: sometimes, co_firstlineno can give a number larger than
187 # fperez - fix: sometimes, co_firstlineno can give a number larger than
188 # the length of lines, which causes an error. Safeguard against that.
188 # the length of lines, which causes an error. Safeguard against that.
189 lnum = min(object.co_firstlineno,len(lines))-1
189 lnum = min(object.co_firstlineno,len(lines))-1
190 while lnum > 0:
190 while lnum > 0:
191 if pmatch(lines[lnum]): break
191 if pmatch(lines[lnum]): break
192 lnum -= 1
192 lnum -= 1
193
193
194 return lines, lnum
194 return lines, lnum
195 raise IOError('could not find code object')
195 raise IOError('could not find code object')
196
196
197 # Monkeypatch inspect to apply our bugfix. This code only works with py25
197 # Monkeypatch inspect to apply our bugfix. This code only works with py25
198 if sys.version_info[:2] >= (2,5):
198 if sys.version_info[:2] >= (2,5):
199 inspect.findsource = findsource
199 inspect.findsource = findsource
200
200
201 def fix_frame_records_filenames(records):
201 def fix_frame_records_filenames(records):
202 """Try to fix the filenames in each record from inspect.getinnerframes().
202 """Try to fix the filenames in each record from inspect.getinnerframes().
203
203
204 Particularly, modules loaded from within zip files have useless filenames
204 Particularly, modules loaded from within zip files have useless filenames
205 attached to their code object, and inspect.getinnerframes() just uses it.
205 attached to their code object, and inspect.getinnerframes() just uses it.
206 """
206 """
207 fixed_records = []
207 fixed_records = []
208 for frame, filename, line_no, func_name, lines, index in records:
208 for frame, filename, line_no, func_name, lines, index in records:
209 # Look inside the frame's globals dictionary for __file__, which should
209 # Look inside the frame's globals dictionary for __file__, which should
210 # be better.
210 # be better.
211 better_fn = frame.f_globals.get('__file__', None)
211 better_fn = frame.f_globals.get('__file__', None)
212 if isinstance(better_fn, str):
212 if isinstance(better_fn, str):
213 # Check the type just in case someone did something weird with
213 # Check the type just in case someone did something weird with
214 # __file__. It might also be None if the error occurred during
214 # __file__. It might also be None if the error occurred during
215 # import.
215 # import.
216 filename = better_fn
216 filename = better_fn
217 fixed_records.append((frame, filename, line_no, func_name, lines, index))
217 fixed_records.append((frame, filename, line_no, func_name, lines, index))
218 return fixed_records
218 return fixed_records
219
219
220
220
221 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
221 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
222 import linecache
222 import linecache
223 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
223 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
224
224
225 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
225 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
226
226
227 # If the error is at the console, don't build any context, since it would
227 # If the error is at the console, don't build any context, since it would
228 # otherwise produce 5 blank lines printed out (there is no file at the
228 # otherwise produce 5 blank lines printed out (there is no file at the
229 # console)
229 # console)
230 rec_check = records[tb_offset:]
230 rec_check = records[tb_offset:]
231 try:
231 try:
232 rname = rec_check[0][1]
232 rname = rec_check[0][1]
233 if rname == '<ipython console>' or rname.endswith('<string>'):
233 if rname == '<ipython console>' or rname.endswith('<string>'):
234 return rec_check
234 return rec_check
235 except IndexError:
235 except IndexError:
236 pass
236 pass
237
237
238 aux = traceback.extract_tb(etb)
238 aux = traceback.extract_tb(etb)
239 assert len(records) == len(aux)
239 assert len(records) == len(aux)
240 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
240 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
241 maybeStart = lnum-1 - context//2
241 maybeStart = lnum-1 - context//2
242 start = max(maybeStart, 0)
242 start = max(maybeStart, 0)
243 end = start + context
243 end = start + context
244 lines = linecache.getlines(file)[start:end]
244 lines = linecache.getlines(file)[start:end]
245 # pad with empty lines if necessary
245 # pad with empty lines if necessary
246 if maybeStart < 0:
246 if maybeStart < 0:
247 lines = (['\n'] * -maybeStart) + lines
247 lines = (['\n'] * -maybeStart) + lines
248 if len(lines) < context:
248 if len(lines) < context:
249 lines += ['\n'] * (context - len(lines))
249 lines += ['\n'] * (context - len(lines))
250 buf = list(records[i])
250 buf = list(records[i])
251 buf[LNUM_POS] = lnum
251 buf[LNUM_POS] = lnum
252 buf[INDEX_POS] = lnum - 1 - start
252 buf[INDEX_POS] = lnum - 1 - start
253 buf[LINES_POS] = lines
253 buf[LINES_POS] = lines
254 records[i] = tuple(buf)
254 records[i] = tuple(buf)
255 return records[tb_offset:]
255 return records[tb_offset:]
256
256
257 # Helper function -- largely belongs to VerboseTB, but we need the same
257 # Helper function -- largely belongs to VerboseTB, but we need the same
258 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
258 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
259 # can be recognized properly by ipython.el's py-traceback-line-re
259 # can be recognized properly by ipython.el's py-traceback-line-re
260 # (SyntaxErrors have to be treated specially because they have no traceback)
260 # (SyntaxErrors have to be treated specially because they have no traceback)
261
261
262 _parser = PyColorize.Parser()
262 _parser = PyColorize.Parser()
263
263
264 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):
264 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):
265 numbers_width = INDENT_SIZE - 1
265 numbers_width = INDENT_SIZE - 1
266 res = []
266 res = []
267 i = lnum - index
267 i = lnum - index
268
268
269 # This lets us get fully syntax-highlighted tracebacks.
269 # This lets us get fully syntax-highlighted tracebacks.
270 if scheme is None:
270 if scheme is None:
271 ipinst = ipapi.get()
271 ipinst = ipapi.get()
272 if ipinst is not None:
272 if ipinst is not None:
273 scheme = ipinst.IP.rc.colors
273 scheme = ipinst.IP.colors
274 else:
274 else:
275 scheme = DEFAULT_SCHEME
275 scheme = DEFAULT_SCHEME
276
276
277 _line_format = _parser.format2
277 _line_format = _parser.format2
278
278
279 for line in lines:
279 for line in lines:
280 new_line, err = _line_format(line,'str',scheme)
280 new_line, err = _line_format(line,'str',scheme)
281 if not err: line = new_line
281 if not err: line = new_line
282
282
283 if i == lnum:
283 if i == lnum:
284 # This is the line with the error
284 # This is the line with the error
285 pad = numbers_width - len(str(i))
285 pad = numbers_width - len(str(i))
286 if pad >= 3:
286 if pad >= 3:
287 marker = '-'*(pad-3) + '-> '
287 marker = '-'*(pad-3) + '-> '
288 elif pad == 2:
288 elif pad == 2:
289 marker = '> '
289 marker = '> '
290 elif pad == 1:
290 elif pad == 1:
291 marker = '>'
291 marker = '>'
292 else:
292 else:
293 marker = ''
293 marker = ''
294 num = marker + str(i)
294 num = marker + str(i)
295 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
295 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
296 Colors.line, line, Colors.Normal)
296 Colors.line, line, Colors.Normal)
297 else:
297 else:
298 num = '%*s' % (numbers_width,i)
298 num = '%*s' % (numbers_width,i)
299 line = '%s%s%s %s' %(Colors.lineno, num,
299 line = '%s%s%s %s' %(Colors.lineno, num,
300 Colors.Normal, line)
300 Colors.Normal, line)
301
301
302 res.append(line)
302 res.append(line)
303 if lvals and i == lnum:
303 if lvals and i == lnum:
304 res.append(lvals + '\n')
304 res.append(lvals + '\n')
305 i = i + 1
305 i = i + 1
306 return res
306 return res
307
307
308
308
309 #---------------------------------------------------------------------------
309 #---------------------------------------------------------------------------
310 # Module classes
310 # Module classes
311 class TBTools:
311 class TBTools:
312 """Basic tools used by all traceback printer classes."""
312 """Basic tools used by all traceback printer classes."""
313
313
314 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
314 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
315 # Whether to call the interactive pdb debugger after printing
315 # Whether to call the interactive pdb debugger after printing
316 # tracebacks or not
316 # tracebacks or not
317 self.call_pdb = call_pdb
317 self.call_pdb = call_pdb
318
318
319 # Create color table
319 # Create color table
320 self.color_scheme_table = exception_colors()
320 self.color_scheme_table = exception_colors()
321
321
322 self.set_colors(color_scheme)
322 self.set_colors(color_scheme)
323 self.old_scheme = color_scheme # save initial value for toggles
323 self.old_scheme = color_scheme # save initial value for toggles
324
324
325 if call_pdb:
325 if call_pdb:
326 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
326 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
327 else:
327 else:
328 self.pdb = None
328 self.pdb = None
329
329
330 def set_colors(self,*args,**kw):
330 def set_colors(self,*args,**kw):
331 """Shorthand access to the color table scheme selector method."""
331 """Shorthand access to the color table scheme selector method."""
332
332
333 # Set own color table
333 # Set own color table
334 self.color_scheme_table.set_active_scheme(*args,**kw)
334 self.color_scheme_table.set_active_scheme(*args,**kw)
335 # for convenience, set Colors to the active scheme
335 # for convenience, set Colors to the active scheme
336 self.Colors = self.color_scheme_table.active_colors
336 self.Colors = self.color_scheme_table.active_colors
337 # Also set colors of debugger
337 # Also set colors of debugger
338 if hasattr(self,'pdb') and self.pdb is not None:
338 if hasattr(self,'pdb') and self.pdb is not None:
339 self.pdb.set_colors(*args,**kw)
339 self.pdb.set_colors(*args,**kw)
340
340
341 def color_toggle(self):
341 def color_toggle(self):
342 """Toggle between the currently active color scheme and NoColor."""
342 """Toggle between the currently active color scheme and NoColor."""
343
343
344 if self.color_scheme_table.active_scheme_name == 'NoColor':
344 if self.color_scheme_table.active_scheme_name == 'NoColor':
345 self.color_scheme_table.set_active_scheme(self.old_scheme)
345 self.color_scheme_table.set_active_scheme(self.old_scheme)
346 self.Colors = self.color_scheme_table.active_colors
346 self.Colors = self.color_scheme_table.active_colors
347 else:
347 else:
348 self.old_scheme = self.color_scheme_table.active_scheme_name
348 self.old_scheme = self.color_scheme_table.active_scheme_name
349 self.color_scheme_table.set_active_scheme('NoColor')
349 self.color_scheme_table.set_active_scheme('NoColor')
350 self.Colors = self.color_scheme_table.active_colors
350 self.Colors = self.color_scheme_table.active_colors
351
351
352 #---------------------------------------------------------------------------
352 #---------------------------------------------------------------------------
353 class ListTB(TBTools):
353 class ListTB(TBTools):
354 """Print traceback information from a traceback list, with optional color.
354 """Print traceback information from a traceback list, with optional color.
355
355
356 Calling: requires 3 arguments:
356 Calling: requires 3 arguments:
357 (etype, evalue, elist)
357 (etype, evalue, elist)
358 as would be obtained by:
358 as would be obtained by:
359 etype, evalue, tb = sys.exc_info()
359 etype, evalue, tb = sys.exc_info()
360 if tb:
360 if tb:
361 elist = traceback.extract_tb(tb)
361 elist = traceback.extract_tb(tb)
362 else:
362 else:
363 elist = None
363 elist = None
364
364
365 It can thus be used by programs which need to process the traceback before
365 It can thus be used by programs which need to process the traceback before
366 printing (such as console replacements based on the code module from the
366 printing (such as console replacements based on the code module from the
367 standard library).
367 standard library).
368
368
369 Because they are meant to be called without a full traceback (only a
369 Because they are meant to be called without a full traceback (only a
370 list), instances of this class can't call the interactive pdb debugger."""
370 list), instances of this class can't call the interactive pdb debugger."""
371
371
372 def __init__(self,color_scheme = 'NoColor'):
372 def __init__(self,color_scheme = 'NoColor'):
373 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
373 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
374
374
375 def __call__(self, etype, value, elist):
375 def __call__(self, etype, value, elist):
376 Term.cout.flush()
376 Term.cout.flush()
377 print >> Term.cerr, self.text(etype,value,elist)
377 print >> Term.cerr, self.text(etype,value,elist)
378 Term.cerr.flush()
378 Term.cerr.flush()
379
379
380 def text(self,etype, value, elist,context=5):
380 def text(self,etype, value, elist,context=5):
381 """Return a color formatted string with the traceback info."""
381 """Return a color formatted string with the traceback info."""
382
382
383 Colors = self.Colors
383 Colors = self.Colors
384 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
384 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
385 if elist:
385 if elist:
386 out_string.append('Traceback %s(most recent call last)%s:' % \
386 out_string.append('Traceback %s(most recent call last)%s:' % \
387 (Colors.normalEm, Colors.Normal) + '\n')
387 (Colors.normalEm, Colors.Normal) + '\n')
388 out_string.extend(self._format_list(elist))
388 out_string.extend(self._format_list(elist))
389 lines = self._format_exception_only(etype, value)
389 lines = self._format_exception_only(etype, value)
390 for line in lines[:-1]:
390 for line in lines[:-1]:
391 out_string.append(" "+line)
391 out_string.append(" "+line)
392 out_string.append(lines[-1])
392 out_string.append(lines[-1])
393 return ''.join(out_string)
393 return ''.join(out_string)
394
394
395 def _format_list(self, extracted_list):
395 def _format_list(self, extracted_list):
396 """Format a list of traceback entry tuples for printing.
396 """Format a list of traceback entry tuples for printing.
397
397
398 Given a list of tuples as returned by extract_tb() or
398 Given a list of tuples as returned by extract_tb() or
399 extract_stack(), return a list of strings ready for printing.
399 extract_stack(), return a list of strings ready for printing.
400 Each string in the resulting list corresponds to the item with the
400 Each string in the resulting list corresponds to the item with the
401 same index in the argument list. Each string ends in a newline;
401 same index in the argument list. Each string ends in a newline;
402 the strings may contain internal newlines as well, for those items
402 the strings may contain internal newlines as well, for those items
403 whose source text line is not None.
403 whose source text line is not None.
404
404
405 Lifted almost verbatim from traceback.py
405 Lifted almost verbatim from traceback.py
406 """
406 """
407
407
408 Colors = self.Colors
408 Colors = self.Colors
409 list = []
409 list = []
410 for filename, lineno, name, line in extracted_list[:-1]:
410 for filename, lineno, name, line in extracted_list[:-1]:
411 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
411 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
412 (Colors.filename, filename, Colors.Normal,
412 (Colors.filename, filename, Colors.Normal,
413 Colors.lineno, lineno, Colors.Normal,
413 Colors.lineno, lineno, Colors.Normal,
414 Colors.name, name, Colors.Normal)
414 Colors.name, name, Colors.Normal)
415 if line:
415 if line:
416 item = item + ' %s\n' % line.strip()
416 item = item + ' %s\n' % line.strip()
417 list.append(item)
417 list.append(item)
418 # Emphasize the last entry
418 # Emphasize the last entry
419 filename, lineno, name, line = extracted_list[-1]
419 filename, lineno, name, line = extracted_list[-1]
420 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
420 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
421 (Colors.normalEm,
421 (Colors.normalEm,
422 Colors.filenameEm, filename, Colors.normalEm,
422 Colors.filenameEm, filename, Colors.normalEm,
423 Colors.linenoEm, lineno, Colors.normalEm,
423 Colors.linenoEm, lineno, Colors.normalEm,
424 Colors.nameEm, name, Colors.normalEm,
424 Colors.nameEm, name, Colors.normalEm,
425 Colors.Normal)
425 Colors.Normal)
426 if line:
426 if line:
427 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
427 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
428 Colors.Normal)
428 Colors.Normal)
429 list.append(item)
429 list.append(item)
430 return list
430 return list
431
431
432 def _format_exception_only(self, etype, value):
432 def _format_exception_only(self, etype, value):
433 """Format the exception part of a traceback.
433 """Format the exception part of a traceback.
434
434
435 The arguments are the exception type and value such as given by
435 The arguments are the exception type and value such as given by
436 sys.exc_info()[:2]. The return value is a list of strings, each ending
436 sys.exc_info()[:2]. The return value is a list of strings, each ending
437 in a newline. Normally, the list contains a single string; however,
437 in a newline. Normally, the list contains a single string; however,
438 for SyntaxError exceptions, it contains several lines that (when
438 for SyntaxError exceptions, it contains several lines that (when
439 printed) display detailed information about where the syntax error
439 printed) display detailed information about where the syntax error
440 occurred. The message indicating which exception occurred is the
440 occurred. The message indicating which exception occurred is the
441 always last string in the list.
441 always last string in the list.
442
442
443 Also lifted nearly verbatim from traceback.py
443 Also lifted nearly verbatim from traceback.py
444 """
444 """
445
445
446 have_filedata = False
446 have_filedata = False
447 Colors = self.Colors
447 Colors = self.Colors
448 list = []
448 list = []
449 try:
449 try:
450 stype = Colors.excName + etype.__name__ + Colors.Normal
450 stype = Colors.excName + etype.__name__ + Colors.Normal
451 except AttributeError:
451 except AttributeError:
452 stype = etype # String exceptions don't get special coloring
452 stype = etype # String exceptions don't get special coloring
453 if value is None:
453 if value is None:
454 list.append( str(stype) + '\n')
454 list.append( str(stype) + '\n')
455 else:
455 else:
456 if etype is SyntaxError:
456 if etype is SyntaxError:
457 try:
457 try:
458 msg, (filename, lineno, offset, line) = value
458 msg, (filename, lineno, offset, line) = value
459 except:
459 except:
460 have_filedata = False
460 have_filedata = False
461 else:
461 else:
462 have_filedata = True
462 have_filedata = True
463 #print 'filename is',filename # dbg
463 #print 'filename is',filename # dbg
464 if not filename: filename = "<string>"
464 if not filename: filename = "<string>"
465 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
465 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
466 (Colors.normalEm,
466 (Colors.normalEm,
467 Colors.filenameEm, filename, Colors.normalEm,
467 Colors.filenameEm, filename, Colors.normalEm,
468 Colors.linenoEm, lineno, Colors.Normal ))
468 Colors.linenoEm, lineno, Colors.Normal ))
469 if line is not None:
469 if line is not None:
470 i = 0
470 i = 0
471 while i < len(line) and line[i].isspace():
471 while i < len(line) and line[i].isspace():
472 i = i+1
472 i = i+1
473 list.append('%s %s%s\n' % (Colors.line,
473 list.append('%s %s%s\n' % (Colors.line,
474 line.strip(),
474 line.strip(),
475 Colors.Normal))
475 Colors.Normal))
476 if offset is not None:
476 if offset is not None:
477 s = ' '
477 s = ' '
478 for c in line[i:offset-1]:
478 for c in line[i:offset-1]:
479 if c.isspace():
479 if c.isspace():
480 s = s + c
480 s = s + c
481 else:
481 else:
482 s = s + ' '
482 s = s + ' '
483 list.append('%s%s^%s\n' % (Colors.caret, s,
483 list.append('%s%s^%s\n' % (Colors.caret, s,
484 Colors.Normal) )
484 Colors.Normal) )
485 value = msg
485 value = msg
486 s = self._some_str(value)
486 s = self._some_str(value)
487 if s:
487 if s:
488 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
488 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
489 Colors.Normal, s))
489 Colors.Normal, s))
490 else:
490 else:
491 list.append('%s\n' % str(stype))
491 list.append('%s\n' % str(stype))
492
492
493 # vds:>>
493 # vds:>>
494 if have_filedata:
494 if have_filedata:
495 ipinst = ipapi.get()
495 ipinst = ipapi.get()
496 if ipinst is not None:
496 if ipinst is not None:
497 ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0)
497 ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0)
498 # vds:<<
498 # vds:<<
499
499
500 return list
500 return list
501
501
502 def _some_str(self, value):
502 def _some_str(self, value):
503 # Lifted from traceback.py
503 # Lifted from traceback.py
504 try:
504 try:
505 return str(value)
505 return str(value)
506 except:
506 except:
507 return '<unprintable %s object>' % type(value).__name__
507 return '<unprintable %s object>' % type(value).__name__
508
508
509 #----------------------------------------------------------------------------
509 #----------------------------------------------------------------------------
510 class VerboseTB(TBTools):
510 class VerboseTB(TBTools):
511 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
511 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
512 of HTML. Requires inspect and pydoc. Crazy, man.
512 of HTML. Requires inspect and pydoc. Crazy, man.
513
513
514 Modified version which optionally strips the topmost entries from the
514 Modified version which optionally strips the topmost entries from the
515 traceback, to be used with alternate interpreters (because their own code
515 traceback, to be used with alternate interpreters (because their own code
516 would appear in the traceback)."""
516 would appear in the traceback)."""
517
517
518 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
518 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
519 call_pdb = 0, include_vars=1):
519 call_pdb = 0, include_vars=1):
520 """Specify traceback offset, headers and color scheme.
520 """Specify traceback offset, headers and color scheme.
521
521
522 Define how many frames to drop from the tracebacks. Calling it with
522 Define how many frames to drop from the tracebacks. Calling it with
523 tb_offset=1 allows use of this handler in interpreters which will have
523 tb_offset=1 allows use of this handler in interpreters which will have
524 their own code at the top of the traceback (VerboseTB will first
524 their own code at the top of the traceback (VerboseTB will first
525 remove that frame before printing the traceback info)."""
525 remove that frame before printing the traceback info)."""
526 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
526 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
527 self.tb_offset = tb_offset
527 self.tb_offset = tb_offset
528 self.long_header = long_header
528 self.long_header = long_header
529 self.include_vars = include_vars
529 self.include_vars = include_vars
530
530
531 def text(self, etype, evalue, etb, context=5):
531 def text(self, etype, evalue, etb, context=5):
532 """Return a nice text document describing the traceback."""
532 """Return a nice text document describing the traceback."""
533
533
534 # some locals
534 # some locals
535 try:
535 try:
536 etype = etype.__name__
536 etype = etype.__name__
537 except AttributeError:
537 except AttributeError:
538 pass
538 pass
539 Colors = self.Colors # just a shorthand + quicker name lookup
539 Colors = self.Colors # just a shorthand + quicker name lookup
540 ColorsNormal = Colors.Normal # used a lot
540 ColorsNormal = Colors.Normal # used a lot
541 col_scheme = self.color_scheme_table.active_scheme_name
541 col_scheme = self.color_scheme_table.active_scheme_name
542 indent = ' '*INDENT_SIZE
542 indent = ' '*INDENT_SIZE
543 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
543 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
544 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
544 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
545 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
545 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
546
546
547 # some internal-use functions
547 # some internal-use functions
548 def text_repr(value):
548 def text_repr(value):
549 """Hopefully pretty robust repr equivalent."""
549 """Hopefully pretty robust repr equivalent."""
550 # this is pretty horrible but should always return *something*
550 # this is pretty horrible but should always return *something*
551 try:
551 try:
552 return pydoc.text.repr(value)
552 return pydoc.text.repr(value)
553 except KeyboardInterrupt:
553 except KeyboardInterrupt:
554 raise
554 raise
555 except:
555 except:
556 try:
556 try:
557 return repr(value)
557 return repr(value)
558 except KeyboardInterrupt:
558 except KeyboardInterrupt:
559 raise
559 raise
560 except:
560 except:
561 try:
561 try:
562 # all still in an except block so we catch
562 # all still in an except block so we catch
563 # getattr raising
563 # getattr raising
564 name = getattr(value, '__name__', None)
564 name = getattr(value, '__name__', None)
565 if name:
565 if name:
566 # ick, recursion
566 # ick, recursion
567 return text_repr(name)
567 return text_repr(name)
568 klass = getattr(value, '__class__', None)
568 klass = getattr(value, '__class__', None)
569 if klass:
569 if klass:
570 return '%s instance' % text_repr(klass)
570 return '%s instance' % text_repr(klass)
571 except KeyboardInterrupt:
571 except KeyboardInterrupt:
572 raise
572 raise
573 except:
573 except:
574 return 'UNRECOVERABLE REPR FAILURE'
574 return 'UNRECOVERABLE REPR FAILURE'
575 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
575 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
576 def nullrepr(value, repr=text_repr): return ''
576 def nullrepr(value, repr=text_repr): return ''
577
577
578 # meat of the code begins
578 # meat of the code begins
579 try:
579 try:
580 etype = etype.__name__
580 etype = etype.__name__
581 except AttributeError:
581 except AttributeError:
582 pass
582 pass
583
583
584 if self.long_header:
584 if self.long_header:
585 # Header with the exception type, python version, and date
585 # Header with the exception type, python version, and date
586 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
586 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
587 date = time.ctime(time.time())
587 date = time.ctime(time.time())
588
588
589 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
589 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
590 exc, ' '*(75-len(str(etype))-len(pyver)),
590 exc, ' '*(75-len(str(etype))-len(pyver)),
591 pyver, string.rjust(date, 75) )
591 pyver, string.rjust(date, 75) )
592 head += "\nA problem occured executing Python code. Here is the sequence of function"\
592 head += "\nA problem occured executing Python code. Here is the sequence of function"\
593 "\ncalls leading up to the error, with the most recent (innermost) call last."
593 "\ncalls leading up to the error, with the most recent (innermost) call last."
594 else:
594 else:
595 # Simplified header
595 # Simplified header
596 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
596 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
597 string.rjust('Traceback (most recent call last)',
597 string.rjust('Traceback (most recent call last)',
598 75 - len(str(etype)) ) )
598 75 - len(str(etype)) ) )
599 frames = []
599 frames = []
600 # Flush cache before calling inspect. This helps alleviate some of the
600 # Flush cache before calling inspect. This helps alleviate some of the
601 # problems with python 2.3's inspect.py.
601 # problems with python 2.3's inspect.py.
602 linecache.checkcache()
602 linecache.checkcache()
603 # Drop topmost frames if requested
603 # Drop topmost frames if requested
604 try:
604 try:
605 # Try the default getinnerframes and Alex's: Alex's fixes some
605 # Try the default getinnerframes and Alex's: Alex's fixes some
606 # problems, but it generates empty tracebacks for console errors
606 # problems, but it generates empty tracebacks for console errors
607 # (5 blanks lines) where none should be returned.
607 # (5 blanks lines) where none should be returned.
608 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
608 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
609 #print 'python records:', records # dbg
609 #print 'python records:', records # dbg
610 records = _fixed_getinnerframes(etb, context,self.tb_offset)
610 records = _fixed_getinnerframes(etb, context,self.tb_offset)
611 #print 'alex records:', records # dbg
611 #print 'alex records:', records # dbg
612 except:
612 except:
613
613
614 # FIXME: I've been getting many crash reports from python 2.3
614 # FIXME: I've been getting many crash reports from python 2.3
615 # users, traceable to inspect.py. If I can find a small test-case
615 # users, traceable to inspect.py. If I can find a small test-case
616 # to reproduce this, I should either write a better workaround or
616 # to reproduce this, I should either write a better workaround or
617 # file a bug report against inspect (if that's the real problem).
617 # file a bug report against inspect (if that's the real problem).
618 # So far, I haven't been able to find an isolated example to
618 # So far, I haven't been able to find an isolated example to
619 # reproduce the problem.
619 # reproduce the problem.
620 inspect_error()
620 inspect_error()
621 traceback.print_exc(file=Term.cerr)
621 traceback.print_exc(file=Term.cerr)
622 info('\nUnfortunately, your original traceback can not be constructed.\n')
622 info('\nUnfortunately, your original traceback can not be constructed.\n')
623 return ''
623 return ''
624
624
625 # build some color string templates outside these nested loops
625 # build some color string templates outside these nested loops
626 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
626 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
627 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
627 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
628 ColorsNormal)
628 ColorsNormal)
629 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
629 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
630 (Colors.vName, Colors.valEm, ColorsNormal)
630 (Colors.vName, Colors.valEm, ColorsNormal)
631 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
631 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
632 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
632 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
633 Colors.vName, ColorsNormal)
633 Colors.vName, ColorsNormal)
634 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
634 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
635 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
635 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
636 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
636 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
637 ColorsNormal)
637 ColorsNormal)
638
638
639 # now, loop over all records printing context and info
639 # now, loop over all records printing context and info
640 abspath = os.path.abspath
640 abspath = os.path.abspath
641 for frame, file, lnum, func, lines, index in records:
641 for frame, file, lnum, func, lines, index in records:
642 #print '*** record:',file,lnum,func,lines,index # dbg
642 #print '*** record:',file,lnum,func,lines,index # dbg
643 try:
643 try:
644 file = file and abspath(file) or '?'
644 file = file and abspath(file) or '?'
645 except OSError:
645 except OSError:
646 # if file is '<console>' or something not in the filesystem,
646 # if file is '<console>' or something not in the filesystem,
647 # the abspath call will throw an OSError. Just ignore it and
647 # the abspath call will throw an OSError. Just ignore it and
648 # keep the original file string.
648 # keep the original file string.
649 pass
649 pass
650 link = tpl_link % file
650 link = tpl_link % file
651 try:
651 try:
652 args, varargs, varkw, locals = inspect.getargvalues(frame)
652 args, varargs, varkw, locals = inspect.getargvalues(frame)
653 except:
653 except:
654 # This can happen due to a bug in python2.3. We should be
654 # This can happen due to a bug in python2.3. We should be
655 # able to remove this try/except when 2.4 becomes a
655 # able to remove this try/except when 2.4 becomes a
656 # requirement. Bug details at http://python.org/sf/1005466
656 # requirement. Bug details at http://python.org/sf/1005466
657 inspect_error()
657 inspect_error()
658 traceback.print_exc(file=Term.cerr)
658 traceback.print_exc(file=Term.cerr)
659 info("\nIPython's exception reporting continues...\n")
659 info("\nIPython's exception reporting continues...\n")
660
660
661 if func == '?':
661 if func == '?':
662 call = ''
662 call = ''
663 else:
663 else:
664 # Decide whether to include variable details or not
664 # Decide whether to include variable details or not
665 var_repr = self.include_vars and eqrepr or nullrepr
665 var_repr = self.include_vars and eqrepr or nullrepr
666 try:
666 try:
667 call = tpl_call % (func,inspect.formatargvalues(args,
667 call = tpl_call % (func,inspect.formatargvalues(args,
668 varargs, varkw,
668 varargs, varkw,
669 locals,formatvalue=var_repr))
669 locals,formatvalue=var_repr))
670 except KeyError:
670 except KeyError:
671 # Very odd crash from inspect.formatargvalues(). The
671 # Very odd crash from inspect.formatargvalues(). The
672 # scenario under which it appeared was a call to
672 # scenario under which it appeared was a call to
673 # view(array,scale) in NumTut.view.view(), where scale had
673 # view(array,scale) in NumTut.view.view(), where scale had
674 # been defined as a scalar (it should be a tuple). Somehow
674 # been defined as a scalar (it should be a tuple). Somehow
675 # inspect messes up resolving the argument list of view()
675 # inspect messes up resolving the argument list of view()
676 # and barfs out. At some point I should dig into this one
676 # and barfs out. At some point I should dig into this one
677 # and file a bug report about it.
677 # and file a bug report about it.
678 inspect_error()
678 inspect_error()
679 traceback.print_exc(file=Term.cerr)
679 traceback.print_exc(file=Term.cerr)
680 info("\nIPython's exception reporting continues...\n")
680 info("\nIPython's exception reporting continues...\n")
681 call = tpl_call_fail % func
681 call = tpl_call_fail % func
682
682
683 # Initialize a list of names on the current line, which the
683 # Initialize a list of names on the current line, which the
684 # tokenizer below will populate.
684 # tokenizer below will populate.
685 names = []
685 names = []
686
686
687 def tokeneater(token_type, token, start, end, line):
687 def tokeneater(token_type, token, start, end, line):
688 """Stateful tokeneater which builds dotted names.
688 """Stateful tokeneater which builds dotted names.
689
689
690 The list of names it appends to (from the enclosing scope) can
690 The list of names it appends to (from the enclosing scope) can
691 contain repeated composite names. This is unavoidable, since
691 contain repeated composite names. This is unavoidable, since
692 there is no way to disambguate partial dotted structures until
692 there is no way to disambguate partial dotted structures until
693 the full list is known. The caller is responsible for pruning
693 the full list is known. The caller is responsible for pruning
694 the final list of duplicates before using it."""
694 the final list of duplicates before using it."""
695
695
696 # build composite names
696 # build composite names
697 if token == '.':
697 if token == '.':
698 try:
698 try:
699 names[-1] += '.'
699 names[-1] += '.'
700 # store state so the next token is added for x.y.z names
700 # store state so the next token is added for x.y.z names
701 tokeneater.name_cont = True
701 tokeneater.name_cont = True
702 return
702 return
703 except IndexError:
703 except IndexError:
704 pass
704 pass
705 if token_type == tokenize.NAME and token not in keyword.kwlist:
705 if token_type == tokenize.NAME and token not in keyword.kwlist:
706 if tokeneater.name_cont:
706 if tokeneater.name_cont:
707 # Dotted names
707 # Dotted names
708 names[-1] += token
708 names[-1] += token
709 tokeneater.name_cont = False
709 tokeneater.name_cont = False
710 else:
710 else:
711 # Regular new names. We append everything, the caller
711 # Regular new names. We append everything, the caller
712 # will be responsible for pruning the list later. It's
712 # will be responsible for pruning the list later. It's
713 # very tricky to try to prune as we go, b/c composite
713 # very tricky to try to prune as we go, b/c composite
714 # names can fool us. The pruning at the end is easy
714 # names can fool us. The pruning at the end is easy
715 # to do (or the caller can print a list with repeated
715 # to do (or the caller can print a list with repeated
716 # names if so desired.
716 # names if so desired.
717 names.append(token)
717 names.append(token)
718 elif token_type == tokenize.NEWLINE:
718 elif token_type == tokenize.NEWLINE:
719 raise IndexError
719 raise IndexError
720 # we need to store a bit of state in the tokenizer to build
720 # we need to store a bit of state in the tokenizer to build
721 # dotted names
721 # dotted names
722 tokeneater.name_cont = False
722 tokeneater.name_cont = False
723
723
724 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
724 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
725 line = getline(file, lnum[0])
725 line = getline(file, lnum[0])
726 lnum[0] += 1
726 lnum[0] += 1
727 return line
727 return line
728
728
729 # Build the list of names on this line of code where the exception
729 # Build the list of names on this line of code where the exception
730 # occurred.
730 # occurred.
731 try:
731 try:
732 # This builds the names list in-place by capturing it from the
732 # This builds the names list in-place by capturing it from the
733 # enclosing scope.
733 # enclosing scope.
734 tokenize.tokenize(linereader, tokeneater)
734 tokenize.tokenize(linereader, tokeneater)
735 except IndexError:
735 except IndexError:
736 # signals exit of tokenizer
736 # signals exit of tokenizer
737 pass
737 pass
738 except tokenize.TokenError,msg:
738 except tokenize.TokenError,msg:
739 _m = ("An unexpected error occurred while tokenizing input\n"
739 _m = ("An unexpected error occurred while tokenizing input\n"
740 "The following traceback may be corrupted or invalid\n"
740 "The following traceback may be corrupted or invalid\n"
741 "The error message is: %s\n" % msg)
741 "The error message is: %s\n" % msg)
742 error(_m)
742 error(_m)
743
743
744 # prune names list of duplicates, but keep the right order
744 # prune names list of duplicates, but keep the right order
745 unique_names = uniq_stable(names)
745 unique_names = uniq_stable(names)
746
746
747 # Start loop over vars
747 # Start loop over vars
748 lvals = []
748 lvals = []
749 if self.include_vars:
749 if self.include_vars:
750 for name_full in unique_names:
750 for name_full in unique_names:
751 name_base = name_full.split('.',1)[0]
751 name_base = name_full.split('.',1)[0]
752 if name_base in frame.f_code.co_varnames:
752 if name_base in frame.f_code.co_varnames:
753 if locals.has_key(name_base):
753 if locals.has_key(name_base):
754 try:
754 try:
755 value = repr(eval(name_full,locals))
755 value = repr(eval(name_full,locals))
756 except:
756 except:
757 value = undefined
757 value = undefined
758 else:
758 else:
759 value = undefined
759 value = undefined
760 name = tpl_local_var % name_full
760 name = tpl_local_var % name_full
761 else:
761 else:
762 if frame.f_globals.has_key(name_base):
762 if frame.f_globals.has_key(name_base):
763 try:
763 try:
764 value = repr(eval(name_full,frame.f_globals))
764 value = repr(eval(name_full,frame.f_globals))
765 except:
765 except:
766 value = undefined
766 value = undefined
767 else:
767 else:
768 value = undefined
768 value = undefined
769 name = tpl_global_var % name_full
769 name = tpl_global_var % name_full
770 lvals.append(tpl_name_val % (name,value))
770 lvals.append(tpl_name_val % (name,value))
771 if lvals:
771 if lvals:
772 lvals = '%s%s' % (indent,em_normal.join(lvals))
772 lvals = '%s%s' % (indent,em_normal.join(lvals))
773 else:
773 else:
774 lvals = ''
774 lvals = ''
775
775
776 level = '%s %s\n' % (link,call)
776 level = '%s %s\n' % (link,call)
777
777
778 if index is None:
778 if index is None:
779 frames.append(level)
779 frames.append(level)
780 else:
780 else:
781 frames.append('%s%s' % (level,''.join(
781 frames.append('%s%s' % (level,''.join(
782 _formatTracebackLines(lnum,index,lines,Colors,lvals,
782 _formatTracebackLines(lnum,index,lines,Colors,lvals,
783 col_scheme))))
783 col_scheme))))
784
784
785 # Get (safely) a string form of the exception info
785 # Get (safely) a string form of the exception info
786 try:
786 try:
787 etype_str,evalue_str = map(str,(etype,evalue))
787 etype_str,evalue_str = map(str,(etype,evalue))
788 except:
788 except:
789 # User exception is improperly defined.
789 # User exception is improperly defined.
790 etype,evalue = str,sys.exc_info()[:2]
790 etype,evalue = str,sys.exc_info()[:2]
791 etype_str,evalue_str = map(str,(etype,evalue))
791 etype_str,evalue_str = map(str,(etype,evalue))
792 # ... and format it
792 # ... and format it
793 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
793 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
794 ColorsNormal, evalue_str)]
794 ColorsNormal, evalue_str)]
795 if type(evalue) is types.InstanceType:
795 if type(evalue) is types.InstanceType:
796 try:
796 try:
797 names = [w for w in dir(evalue) if isinstance(w, basestring)]
797 names = [w for w in dir(evalue) if isinstance(w, basestring)]
798 except:
798 except:
799 # Every now and then, an object with funny inernals blows up
799 # Every now and then, an object with funny inernals blows up
800 # when dir() is called on it. We do the best we can to report
800 # when dir() is called on it. We do the best we can to report
801 # the problem and continue
801 # the problem and continue
802 _m = '%sException reporting error (object with broken dir())%s:'
802 _m = '%sException reporting error (object with broken dir())%s:'
803 exception.append(_m % (Colors.excName,ColorsNormal))
803 exception.append(_m % (Colors.excName,ColorsNormal))
804 etype_str,evalue_str = map(str,sys.exc_info()[:2])
804 etype_str,evalue_str = map(str,sys.exc_info()[:2])
805 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
805 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
806 ColorsNormal, evalue_str))
806 ColorsNormal, evalue_str))
807 names = []
807 names = []
808 for name in names:
808 for name in names:
809 value = text_repr(getattr(evalue, name))
809 value = text_repr(getattr(evalue, name))
810 exception.append('\n%s%s = %s' % (indent, name, value))
810 exception.append('\n%s%s = %s' % (indent, name, value))
811
811
812 # vds: >>
812 # vds: >>
813 if records:
813 if records:
814 filepath, lnum = records[-1][1:3]
814 filepath, lnum = records[-1][1:3]
815 #print "file:", str(file), "linenb", str(lnum) # dbg
815 #print "file:", str(file), "linenb", str(lnum) # dbg
816 filepath = os.path.abspath(filepath)
816 filepath = os.path.abspath(filepath)
817 ipinst = ipapi.get()
817 ipinst = ipapi.get()
818 if ipinst is not None:
818 if ipinst is not None:
819 ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0)
819 ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0)
820 # vds: <<
820 # vds: <<
821
821
822 # return all our info assembled as a single string
822 # return all our info assembled as a single string
823 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
823 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
824
824
825 def debugger(self,force=False):
825 def debugger(self,force=False):
826 """Call up the pdb debugger if desired, always clean up the tb
826 """Call up the pdb debugger if desired, always clean up the tb
827 reference.
827 reference.
828
828
829 Keywords:
829 Keywords:
830
830
831 - force(False): by default, this routine checks the instance call_pdb
831 - force(False): by default, this routine checks the instance call_pdb
832 flag and does not actually invoke the debugger if the flag is false.
832 flag and does not actually invoke the debugger if the flag is false.
833 The 'force' option forces the debugger to activate even if the flag
833 The 'force' option forces the debugger to activate even if the flag
834 is false.
834 is false.
835
835
836 If the call_pdb flag is set, the pdb interactive debugger is
836 If the call_pdb flag is set, the pdb interactive debugger is
837 invoked. In all cases, the self.tb reference to the current traceback
837 invoked. In all cases, the self.tb reference to the current traceback
838 is deleted to prevent lingering references which hamper memory
838 is deleted to prevent lingering references which hamper memory
839 management.
839 management.
840
840
841 Note that each call to pdb() does an 'import readline', so if your app
841 Note that each call to pdb() does an 'import readline', so if your app
842 requires a special setup for the readline completers, you'll have to
842 requires a special setup for the readline completers, you'll have to
843 fix that by hand after invoking the exception handler."""
843 fix that by hand after invoking the exception handler."""
844
844
845 if force or self.call_pdb:
845 if force or self.call_pdb:
846 if self.pdb is None:
846 if self.pdb is None:
847 self.pdb = debugger.Pdb(
847 self.pdb = debugger.Pdb(
848 self.color_scheme_table.active_scheme_name)
848 self.color_scheme_table.active_scheme_name)
849 # the system displayhook may have changed, restore the original
849 # the system displayhook may have changed, restore the original
850 # for pdb
850 # for pdb
851 dhook = sys.displayhook
851 dhook = sys.displayhook
852 sys.displayhook = sys.__displayhook__
852 sys.displayhook = sys.__displayhook__
853 self.pdb.reset()
853 self.pdb.reset()
854 # Find the right frame so we don't pop up inside ipython itself
854 # Find the right frame so we don't pop up inside ipython itself
855 if hasattr(self,'tb'):
855 if hasattr(self,'tb'):
856 etb = self.tb
856 etb = self.tb
857 else:
857 else:
858 etb = self.tb = sys.last_traceback
858 etb = self.tb = sys.last_traceback
859 while self.tb.tb_next is not None:
859 while self.tb.tb_next is not None:
860 self.tb = self.tb.tb_next
860 self.tb = self.tb.tb_next
861 try:
861 try:
862 if etb and etb.tb_next:
862 if etb and etb.tb_next:
863 etb = etb.tb_next
863 etb = etb.tb_next
864 self.pdb.botframe = etb.tb_frame
864 self.pdb.botframe = etb.tb_frame
865 self.pdb.interaction(self.tb.tb_frame, self.tb)
865 self.pdb.interaction(self.tb.tb_frame, self.tb)
866 finally:
866 finally:
867 sys.displayhook = dhook
867 sys.displayhook = dhook
868
868
869 if hasattr(self,'tb'):
869 if hasattr(self,'tb'):
870 del self.tb
870 del self.tb
871
871
872 def handler(self, info=None):
872 def handler(self, info=None):
873 (etype, evalue, etb) = info or sys.exc_info()
873 (etype, evalue, etb) = info or sys.exc_info()
874 self.tb = etb
874 self.tb = etb
875 Term.cout.flush()
875 Term.cout.flush()
876 print >> Term.cerr, self.text(etype, evalue, etb)
876 print >> Term.cerr, self.text(etype, evalue, etb)
877 Term.cerr.flush()
877 Term.cerr.flush()
878
878
879 # Changed so an instance can just be called as VerboseTB_inst() and print
879 # Changed so an instance can just be called as VerboseTB_inst() and print
880 # out the right info on its own.
880 # out the right info on its own.
881 def __call__(self, etype=None, evalue=None, etb=None):
881 def __call__(self, etype=None, evalue=None, etb=None):
882 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
882 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
883 if etb is None:
883 if etb is None:
884 self.handler()
884 self.handler()
885 else:
885 else:
886 self.handler((etype, evalue, etb))
886 self.handler((etype, evalue, etb))
887 try:
887 try:
888 self.debugger()
888 self.debugger()
889 except KeyboardInterrupt:
889 except KeyboardInterrupt:
890 print "\nKeyboardInterrupt"
890 print "\nKeyboardInterrupt"
891
891
892 #----------------------------------------------------------------------------
892 #----------------------------------------------------------------------------
893 class FormattedTB(VerboseTB,ListTB):
893 class FormattedTB(VerboseTB,ListTB):
894 """Subclass ListTB but allow calling with a traceback.
894 """Subclass ListTB but allow calling with a traceback.
895
895
896 It can thus be used as a sys.excepthook for Python > 2.1.
896 It can thus be used as a sys.excepthook for Python > 2.1.
897
897
898 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
898 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
899
899
900 Allows a tb_offset to be specified. This is useful for situations where
900 Allows a tb_offset to be specified. This is useful for situations where
901 one needs to remove a number of topmost frames from the traceback (such as
901 one needs to remove a number of topmost frames from the traceback (such as
902 occurs with python programs that themselves execute other python code,
902 occurs with python programs that themselves execute other python code,
903 like Python shells). """
903 like Python shells). """
904
904
905 def __init__(self, mode = 'Plain', color_scheme='Linux',
905 def __init__(self, mode = 'Plain', color_scheme='Linux',
906 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
906 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
907
907
908 # NEVER change the order of this list. Put new modes at the end:
908 # NEVER change the order of this list. Put new modes at the end:
909 self.valid_modes = ['Plain','Context','Verbose']
909 self.valid_modes = ['Plain','Context','Verbose']
910 self.verbose_modes = self.valid_modes[1:3]
910 self.verbose_modes = self.valid_modes[1:3]
911
911
912 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
912 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
913 call_pdb=call_pdb,include_vars=include_vars)
913 call_pdb=call_pdb,include_vars=include_vars)
914 self.set_mode(mode)
914 self.set_mode(mode)
915
915
916 def _extract_tb(self,tb):
916 def _extract_tb(self,tb):
917 if tb:
917 if tb:
918 return traceback.extract_tb(tb)
918 return traceback.extract_tb(tb)
919 else:
919 else:
920 return None
920 return None
921
921
922 def text(self, etype, value, tb,context=5,mode=None):
922 def text(self, etype, value, tb,context=5,mode=None):
923 """Return formatted traceback.
923 """Return formatted traceback.
924
924
925 If the optional mode parameter is given, it overrides the current
925 If the optional mode parameter is given, it overrides the current
926 mode."""
926 mode."""
927
927
928 if mode is None:
928 if mode is None:
929 mode = self.mode
929 mode = self.mode
930 if mode in self.verbose_modes:
930 if mode in self.verbose_modes:
931 # verbose modes need a full traceback
931 # verbose modes need a full traceback
932 return VerboseTB.text(self,etype, value, tb,context=5)
932 return VerboseTB.text(self,etype, value, tb,context=5)
933 else:
933 else:
934 # We must check the source cache because otherwise we can print
934 # We must check the source cache because otherwise we can print
935 # out-of-date source code.
935 # out-of-date source code.
936 linecache.checkcache()
936 linecache.checkcache()
937 # Now we can extract and format the exception
937 # Now we can extract and format the exception
938 elist = self._extract_tb(tb)
938 elist = self._extract_tb(tb)
939 if len(elist) > self.tb_offset:
939 if len(elist) > self.tb_offset:
940 del elist[:self.tb_offset]
940 del elist[:self.tb_offset]
941 return ListTB.text(self,etype,value,elist)
941 return ListTB.text(self,etype,value,elist)
942
942
943 def set_mode(self,mode=None):
943 def set_mode(self,mode=None):
944 """Switch to the desired mode.
944 """Switch to the desired mode.
945
945
946 If mode is not specified, cycles through the available modes."""
946 If mode is not specified, cycles through the available modes."""
947
947
948 if not mode:
948 if not mode:
949 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
949 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
950 len(self.valid_modes)
950 len(self.valid_modes)
951 self.mode = self.valid_modes[new_idx]
951 self.mode = self.valid_modes[new_idx]
952 elif mode not in self.valid_modes:
952 elif mode not in self.valid_modes:
953 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
953 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
954 'Valid modes: '+str(self.valid_modes)
954 'Valid modes: '+str(self.valid_modes)
955 else:
955 else:
956 self.mode = mode
956 self.mode = mode
957 # include variable details only in 'Verbose' mode
957 # include variable details only in 'Verbose' mode
958 self.include_vars = (self.mode == self.valid_modes[2])
958 self.include_vars = (self.mode == self.valid_modes[2])
959
959
960 # some convenient shorcuts
960 # some convenient shorcuts
961 def plain(self):
961 def plain(self):
962 self.set_mode(self.valid_modes[0])
962 self.set_mode(self.valid_modes[0])
963
963
964 def context(self):
964 def context(self):
965 self.set_mode(self.valid_modes[1])
965 self.set_mode(self.valid_modes[1])
966
966
967 def verbose(self):
967 def verbose(self):
968 self.set_mode(self.valid_modes[2])
968 self.set_mode(self.valid_modes[2])
969
969
970 #----------------------------------------------------------------------------
970 #----------------------------------------------------------------------------
971 class AutoFormattedTB(FormattedTB):
971 class AutoFormattedTB(FormattedTB):
972 """A traceback printer which can be called on the fly.
972 """A traceback printer which can be called on the fly.
973
973
974 It will find out about exceptions by itself.
974 It will find out about exceptions by itself.
975
975
976 A brief example:
976 A brief example:
977
977
978 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
978 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
979 try:
979 try:
980 ...
980 ...
981 except:
981 except:
982 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
982 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
983 """
983 """
984 def __call__(self,etype=None,evalue=None,etb=None,
984 def __call__(self,etype=None,evalue=None,etb=None,
985 out=None,tb_offset=None):
985 out=None,tb_offset=None):
986 """Print out a formatted exception traceback.
986 """Print out a formatted exception traceback.
987
987
988 Optional arguments:
988 Optional arguments:
989 - out: an open file-like object to direct output to.
989 - out: an open file-like object to direct output to.
990
990
991 - tb_offset: the number of frames to skip over in the stack, on a
991 - tb_offset: the number of frames to skip over in the stack, on a
992 per-call basis (this overrides temporarily the instance's tb_offset
992 per-call basis (this overrides temporarily the instance's tb_offset
993 given at initialization time. """
993 given at initialization time. """
994
994
995 if out is None:
995 if out is None:
996 out = Term.cerr
996 out = Term.cerr
997 Term.cout.flush()
997 Term.cout.flush()
998 if tb_offset is not None:
998 if tb_offset is not None:
999 tb_offset, self.tb_offset = self.tb_offset, tb_offset
999 tb_offset, self.tb_offset = self.tb_offset, tb_offset
1000 print >> out, self.text(etype, evalue, etb)
1000 print >> out, self.text(etype, evalue, etb)
1001 self.tb_offset = tb_offset
1001 self.tb_offset = tb_offset
1002 else:
1002 else:
1003 print >> out, self.text(etype, evalue, etb)
1003 print >> out, self.text(etype, evalue, etb)
1004 out.flush()
1004 out.flush()
1005 try:
1005 try:
1006 self.debugger()
1006 self.debugger()
1007 except KeyboardInterrupt:
1007 except KeyboardInterrupt:
1008 print "\nKeyboardInterrupt"
1008 print "\nKeyboardInterrupt"
1009
1009
1010 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1010 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1011 if etype is None:
1011 if etype is None:
1012 etype,value,tb = sys.exc_info()
1012 etype,value,tb = sys.exc_info()
1013 self.tb = tb
1013 self.tb = tb
1014 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1014 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1015
1015
1016 #---------------------------------------------------------------------------
1016 #---------------------------------------------------------------------------
1017 # A simple class to preserve Nathan's original functionality.
1017 # A simple class to preserve Nathan's original functionality.
1018 class ColorTB(FormattedTB):
1018 class ColorTB(FormattedTB):
1019 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1019 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1020 def __init__(self,color_scheme='Linux',call_pdb=0):
1020 def __init__(self,color_scheme='Linux',call_pdb=0):
1021 FormattedTB.__init__(self,color_scheme=color_scheme,
1021 FormattedTB.__init__(self,color_scheme=color_scheme,
1022 call_pdb=call_pdb)
1022 call_pdb=call_pdb)
1023
1023
1024 #----------------------------------------------------------------------------
1024 #----------------------------------------------------------------------------
1025 # module testing (minimal)
1025 # module testing (minimal)
1026 if __name__ == "__main__":
1026 if __name__ == "__main__":
1027 def spam(c, (d, e)):
1027 def spam(c, (d, e)):
1028 x = c + d
1028 x = c + d
1029 y = c * d
1029 y = c * d
1030 foo(x, y)
1030 foo(x, y)
1031
1031
1032 def foo(a, b, bar=1):
1032 def foo(a, b, bar=1):
1033 eggs(a, b + bar)
1033 eggs(a, b + bar)
1034
1034
1035 def eggs(f, g, z=globals()):
1035 def eggs(f, g, z=globals()):
1036 h = f + g
1036 h = f + g
1037 i = f - g
1037 i = f - g
1038 return h / i
1038 return h / i
1039
1039
1040 print ''
1040 print ''
1041 print '*** Before ***'
1041 print '*** Before ***'
1042 try:
1042 try:
1043 print spam(1, (2, 3))
1043 print spam(1, (2, 3))
1044 except:
1044 except:
1045 traceback.print_exc()
1045 traceback.print_exc()
1046 print ''
1046 print ''
1047
1047
1048 handler = ColorTB()
1048 handler = ColorTB()
1049 print '*** ColorTB ***'
1049 print '*** ColorTB ***'
1050 try:
1050 try:
1051 print spam(1, (2, 3))
1051 print spam(1, (2, 3))
1052 except:
1052 except:
1053 apply(handler, sys.exc_info() )
1053 apply(handler, sys.exc_info() )
1054 print ''
1054 print ''
1055
1055
1056 handler = VerboseTB()
1056 handler = VerboseTB()
1057 print '*** VerboseTB ***'
1057 print '*** VerboseTB ***'
1058 try:
1058 try:
1059 print spam(1, (2, 3))
1059 print spam(1, (2, 3))
1060 except:
1060 except:
1061 apply(handler, sys.exc_info() )
1061 apply(handler, sys.exc_info() )
1062 print ''
1062 print ''
1063
1063
@@ -1,558 +1,586 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 import sys
10 from IPython.core import release
11
9 __doc__ = """
12 __doc__ = """
10 IPython -- An enhanced Interactive Python
13 IPython -- An enhanced Interactive Python
11 =========================================
14 =========================================
12
15
13 A Python shell with automatic history (input and output), dynamic object
16 A Python shell with automatic history (input and output), dynamic object
14 introspection, easier configuration, command completion, access to the system
17 introspection, easier configuration, command completion, access to the system
15 shell and more.
18 shell and more.
16
19
17 IPython can also be embedded in running programs. See EMBEDDING below.
20 IPython can also be embedded in running programs. See EMBEDDING below.
18
21
19
22
20 USAGE
23 USAGE
21 ipython [options] files
24 ipython [options] files
22
25
23 If invoked with no options, it executes all the files listed in
26 If invoked with no options, it executes all the files listed in
24 sequence and drops you into the interpreter while still acknowledging
27 sequence and drops you into the interpreter while still acknowledging
25 any options you may have set in your ipythonrc file. This behavior is
28 any options you may have set in your ipythonrc file. This behavior is
26 different from standard Python, which when called as python -i will
29 different from standard Python, which when called as python -i will
27 only execute one file and will ignore your configuration setup.
30 only execute one file and will ignore your configuration setup.
28
31
29 Please note that some of the configuration options are not available at
32 Please note that some of the configuration options are not available at
30 the command line, simply because they are not practical here. Look into
33 the command line, simply because they are not practical here. Look into
31 your ipythonrc configuration file for details on those. This file
34 your ipythonrc configuration file for details on those. This file
32 typically installed in the $HOME/.ipython directory.
35 typically installed in the $HOME/.ipython directory.
33
36
34 For Windows users, $HOME resolves to C:\\Documents and
37 For Windows users, $HOME resolves to C:\\Documents and
35 Settings\\YourUserName in most instances, and _ipython is used instead
38 Settings\\YourUserName in most instances, and _ipython is used instead
36 of .ipython, since some Win32 programs have problems with dotted names
39 of .ipython, since some Win32 programs have problems with dotted names
37 in directories.
40 in directories.
38
41
39 In the rest of this text, we will refer to this directory as
42 In the rest of this text, we will refer to this directory as
40 IPYTHONDIR.
43 IPYTHONDIR.
41
44
42 REGULAR OPTIONS
45 REGULAR OPTIONS
43 After the above threading options have been given, regular options can
46 After the above threading options have been given, regular options can
44 follow in any order. All options can be abbreviated to their shortest
47 follow in any order. All options can be abbreviated to their shortest
45 non-ambiguous form and are case-sensitive. One or two dashes can be
48 non-ambiguous form and are case-sensitive. One or two dashes can be
46 used. Some options have an alternate short form, indicated after a |.
49 used. Some options have an alternate short form, indicated after a |.
47
50
48 Most options can also be set from your ipythonrc configuration file.
51 Most options can also be set from your ipythonrc configuration file.
49 See the provided examples for assistance. Options given on the comman-
52 See the provided examples for assistance. Options given on the comman-
50 dline override the values set in the ipythonrc file.
53 dline override the values set in the ipythonrc file.
51
54
52 All options with a [no] prepended can be specified in negated form
55 All options with a [no] prepended can be specified in negated form
53 (using -nooption instead of -option) to turn the feature off.
56 (using -nooption instead of -option) to turn the feature off.
54
57
55 -h, --help
58 -h, --help
56 Show summary of options.
59 Show summary of options.
57
60
58 -autocall <val>
61 -autocall <val>
59 Make IPython automatically call any callable object even if you
62 Make IPython automatically call any callable object even if you
60 didn't type explicit parentheses. For example, 'str 43' becomes
63 didn't type explicit parentheses. For example, 'str 43' becomes
61 'str(43)' automatically. The value can be '0' to disable the
64 'str(43)' automatically. The value can be '0' to disable the
62 feature, '1' for 'smart' autocall, where it is not applied if
65 feature, '1' for 'smart' autocall, where it is not applied if
63 there are no more arguments on the line, and '2' for 'full'
66 there are no more arguments on the line, and '2' for 'full'
64 autocall, where all callable objects are automatically called
67 autocall, where all callable objects are automatically called
65 (even if no arguments are present). The default is '1'.
68 (even if no arguments are present). The default is '1'.
66
69
67 -[no]autoindent
70 -[no]autoindent
68 Turn automatic indentation on/off.
71 Turn automatic indentation on/off.
69
72
70 -[no]automagic
73 -[no]automagic
71 Make magic commands automatic (without needing their first char-
74 Make magic commands automatic (without needing their first char-
72 acter to be %). Type %magic at the IPython prompt for more
75 acter to be %). Type %magic at the IPython prompt for more
73 information.
76 information.
74
77
75 -[no]autoedit_syntax
78 -[no]autoedit_syntax
76 When a syntax error occurs after editing a file, automatically
79 When a syntax error occurs after editing a file, automatically
77 open the file to the trouble causing line for convenient fixing.
80 open the file to the trouble causing line for convenient fixing.
78
81
79 -[no]banner
82 -[no]banner
80 Print the intial information banner (default on).
83 Print the intial information banner (default on).
81
84
82 -c <command>
85 -c <command>
83 Execute the given command string, and set sys.argv to ['c'].
86 Execute the given command string, and set sys.argv to ['c'].
84 This is similar to the -c option in the normal Python inter-
87 This is similar to the -c option in the normal Python inter-
85 preter.
88 preter.
86
89
87 -cache_size|cs <n>
90 -cache_size|cs <n>
88 Size of the output cache (maximum number of entries to hold in
91 Size of the output cache (maximum number of entries to hold in
89 memory). The default is 1000, you can change it permanently in
92 memory). The default is 1000, you can change it permanently in
90 your config file. Setting it to 0 completely disables the
93 your config file. Setting it to 0 completely disables the
91 caching system, and the minimum value accepted is 20 (if you
94 caching system, and the minimum value accepted is 20 (if you
92 provide a value less than 20, it is reset to 0 and a warning is
95 provide a value less than 20, it is reset to 0 and a warning is
93 issued). This limit is defined because otherwise you'll spend
96 issued). This limit is defined because otherwise you'll spend
94 more time re-flushing a too small cache than working.
97 more time re-flushing a too small cache than working.
95
98
96 -classic|cl
99 -classic|cl
97 Gives IPython a similar feel to the classic Python prompt.
100 Gives IPython a similar feel to the classic Python prompt.
98
101
99 -colors <scheme>
102 -colors <scheme>
100 Color scheme for prompts and exception reporting. Currently
103 Color scheme for prompts and exception reporting. Currently
101 implemented: NoColor, Linux, and LightBG.
104 implemented: NoColor, Linux, and LightBG.
102
105
103 -[no]color_info
106 -[no]color_info
104 IPython can display information about objects via a set of func-
107 IPython can display information about objects via a set of func-
105 tions, and optionally can use colors for this, syntax highlight-
108 tions, and optionally can use colors for this, syntax highlight-
106 ing source code and various other elements. However, because
109 ing source code and various other elements. However, because
107 this information is passed through a pager (like 'less') and
110 this information is passed through a pager (like 'less') and
108 many pagers get confused with color codes, this option is off by
111 many pagers get confused with color codes, this option is off by
109 default. You can test it and turn it on permanently in your
112 default. You can test it and turn it on permanently in your
110 ipythonrc file if it works for you. As a reference, the 'less'
113 ipythonrc file if it works for you. As a reference, the 'less'
111 pager supplied with Mandrake 8.2 works ok, but that in RedHat
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
112 7.2 doesn't.
115 7.2 doesn't.
113
116
114 Test it and turn it on permanently if it works with your system.
117 Test it and turn it on permanently if it works with your system.
115 The magic function @color_info allows you to toggle this inter-
118 The magic function @color_info allows you to toggle this inter-
116 actively for testing.
119 actively for testing.
117
120
118 -[no]confirm_exit
121 -[no]confirm_exit
119 Set to confirm when you try to exit IPython with an EOF (Con-
122 Set to confirm when you try to exit IPython with an EOF (Con-
120 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
121 magic functions @Exit or @Quit you can force a direct exit,
124 magic functions @Exit or @Quit you can force a direct exit,
122 bypassing any confirmation.
125 bypassing any confirmation.
123
126
124 -[no]debug
127 -[no]debug
125 Show information about the loading process. Very useful to pin
128 Show information about the loading process. Very useful to pin
126 down problems with your configuration files or to get details
129 down problems with your configuration files or to get details
127 about session restores.
130 about session restores.
128
131
129 -[no]deep_reload
132 -[no]deep_reload
130 IPython can use the deep_reload module which reloads changes in
133 IPython can use the deep_reload module which reloads changes in
131 modules recursively (it replaces the reload() function, so you
134 modules recursively (it replaces the reload() function, so you
132 don't need to change anything to use it). deep_reload() forces a
135 don't need to change anything to use it). deep_reload() forces a
133 full reload of modules whose code may have changed, which the
136 full reload of modules whose code may have changed, which the
134 default reload() function does not.
137 default reload() function does not.
135
138
136 When deep_reload is off, IPython will use the normal reload(),
139 When deep_reload is off, IPython will use the normal reload(),
137 but deep_reload will still be available as dreload(). This fea-
140 but deep_reload will still be available as dreload(). This fea-
138 ture is off by default [which means that you have both normal
141 ture is off by default [which means that you have both normal
139 reload() and dreload()].
142 reload() and dreload()].
140
143
141 -editor <name>
144 -editor <name>
142 Which editor to use with the @edit command. By default, IPython
145 Which editor to use with the @edit command. By default, IPython
143 will honor your EDITOR environment variable (if not set, vi is
146 will honor your EDITOR environment variable (if not set, vi is
144 the Unix default and notepad the Windows one). Since this editor
147 the Unix default and notepad the Windows one). Since this editor
145 is invoked on the fly by IPython and is meant for editing small
148 is invoked on the fly by IPython and is meant for editing small
146 code snippets, you may want to use a small, lightweight editor
149 code snippets, you may want to use a small, lightweight editor
147 here (in case your default EDITOR is something like Emacs).
150 here (in case your default EDITOR is something like Emacs).
148
151
149 -ipythondir <name>
152 -ipythondir <name>
150 The name of your IPython configuration directory IPYTHONDIR.
153 The name of your IPython configuration directory IPYTHONDIR.
151 This can also be specified through the environment variable
154 This can also be specified through the environment variable
152 IPYTHONDIR.
155 IPYTHONDIR.
153
156
154 -log|l Generate a log file of all input. The file is named
157 -log|l Generate a log file of all input. The file is named
155 ipython_log.py in your current directory (which prevents logs
158 ipython_log.py in your current directory (which prevents logs
156 from multiple IPython sessions from trampling each other). You
159 from multiple IPython sessions from trampling each other). You
157 can use this to later restore a session by loading your logfile
160 can use this to later restore a session by loading your logfile
158 as a file to be executed with option -logplay (see below).
161 as a file to be executed with option -logplay (see below).
159
162
160 -logfile|lf
163 -logfile|lf
161 Specify the name of your logfile.
164 Specify the name of your logfile.
162
165
163 -logplay|lp
166 -logplay|lp
164 Replay a previous log. For restoring a session as close as pos-
167 Replay a previous log. For restoring a session as close as pos-
165 sible to the state you left it in, use this option (don't just
168 sible to the state you left it in, use this option (don't just
166 run the logfile). With -logplay, IPython will try to reconstruct
169 run the logfile). With -logplay, IPython will try to reconstruct
167 the previous working environment in full, not just execute the
170 the previous working environment in full, not just execute the
168 commands in the logfile.
171 commands in the logfile.
169 When a session is restored, logging is automatically turned on
172 When a session is restored, logging is automatically turned on
170 again with the name of the logfile it was invoked with (it is
173 again with the name of the logfile it was invoked with (it is
171 read from the log header). So once you've turned logging on for
174 read from the log header). So once you've turned logging on for
172 a session, you can quit IPython and reload it as many times as
175 a session, you can quit IPython and reload it as many times as
173 you want and it will continue to log its history and restore
176 you want and it will continue to log its history and restore
174 from the beginning every time.
177 from the beginning every time.
175
178
176 Caveats: there are limitations in this option. The history vari-
179 Caveats: there are limitations in this option. The history vari-
177 ables _i*,_* and _dh don't get restored properly. In the future
180 ables _i*,_* and _dh don't get restored properly. In the future
178 we will try to implement full session saving by writing and
181 we will try to implement full session saving by writing and
179 retrieving a failed because of inherent limitations of Python's
182 retrieving a failed because of inherent limitations of Python's
180 Pickle module, so this may have to wait.
183 Pickle module, so this may have to wait.
181
184
182 -[no]messages
185 -[no]messages
183 Print messages which IPython collects about its startup process
186 Print messages which IPython collects about its startup process
184 (default on).
187 (default on).
185
188
186 -[no]pdb
189 -[no]pdb
187 Automatically call the pdb debugger after every uncaught excep-
190 Automatically call the pdb debugger after every uncaught excep-
188 tion. If you are used to debugging using pdb, this puts you
191 tion. If you are used to debugging using pdb, this puts you
189 automatically inside of it after any call (either in IPython or
192 automatically inside of it after any call (either in IPython or
190 in code called by it) which triggers an exception which goes
193 in code called by it) which triggers an exception which goes
191 uncaught.
194 uncaught.
192
195
193 -[no]pprint
196 -[no]pprint
194 IPython can optionally use the pprint (pretty printer) module
197 IPython can optionally use the pprint (pretty printer) module
195 for displaying results. pprint tends to give a nicer display of
198 for displaying results. pprint tends to give a nicer display of
196 nested data structures. If you like it, you can turn it on per-
199 nested data structures. If you like it, you can turn it on per-
197 manently in your config file (default off).
200 manently in your config file (default off).
198
201
199 -profile|p <name>
202 -profile|p <name>
200 Assume that your config file is ipythonrc-<name> (looks in cur-
203 Assume that your config file is ipythonrc-<name> (looks in cur-
201 rent dir first, then in IPYTHONDIR). This is a quick way to keep
204 rent dir first, then in IPYTHONDIR). This is a quick way to keep
202 and load multiple config files for different tasks, especially
205 and load multiple config files for different tasks, especially
203 if you use the include option of config files. You can keep a
206 if you use the include option of config files. You can keep a
204 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
207 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
205 which include this one and load extra things for particular
208 which include this one and load extra things for particular
206 tasks. For example:
209 tasks. For example:
207
210
208 1) $HOME/.ipython/ipythonrc : load basic things you always want.
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
209 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
210 related modules.
213 related modules.
211 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
212 plotting modules.
215 plotting modules.
213
216
214 Since it is possible to create an endless loop by having circu-
217 Since it is possible to create an endless loop by having circu-
215 lar file inclusions, IPython will stop if it reaches 15 recur-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
216 sive inclusions.
219 sive inclusions.
217
220
218 -prompt_in1|pi1 <string>
221 -prompt_in1|pi1 <string>
219 Specify the string used for input prompts. Note that if you are
222 Specify the string used for input prompts. Note that if you are
220 using numbered prompts, the number is represented with a '\#' in
223 using numbered prompts, the number is represented with a '\#' in
221 the string. Don't forget to quote strings with spaces embedded
224 the string. Don't forget to quote strings with spaces embedded
222 in them. Default: 'In [\#]: '.
225 in them. Default: 'In [\#]: '.
223
226
224 Most bash-like escapes can be used to customize IPython's
227 Most bash-like escapes can be used to customize IPython's
225 prompts, as well as a few additional ones which are IPython-spe-
228 prompts, as well as a few additional ones which are IPython-spe-
226 cific. All valid prompt escapes are described in detail in the
229 cific. All valid prompt escapes are described in detail in the
227 Customization section of the IPython HTML/PDF manual.
230 Customization section of the IPython HTML/PDF manual.
228
231
229 -prompt_in2|pi2 <string>
232 -prompt_in2|pi2 <string>
230 Similar to the previous option, but used for the continuation
233 Similar to the previous option, but used for the continuation
231 prompts. The special sequence '\D' is similar to '\#', but with
234 prompts. The special sequence '\D' is similar to '\#', but with
232 all digits replaced dots (so you can have your continuation
235 all digits replaced dots (so you can have your continuation
233 prompt aligned with your input prompt). Default: ' .\D.: '
236 prompt aligned with your input prompt). Default: ' .\D.: '
234 (note three spaces at the start for alignment with 'In [\#]').
237 (note three spaces at the start for alignment with 'In [\#]').
235
238
236 -prompt_out|po <string>
239 -prompt_out|po <string>
237 String used for output prompts, also uses numbers like
240 String used for output prompts, also uses numbers like
238 prompt_in1. Default: 'Out[\#]:'.
241 prompt_in1. Default: 'Out[\#]:'.
239
242
240 -quick Start in bare bones mode (no config file loaded).
243 -quick Start in bare bones mode (no config file loaded).
241
244
242 -rcfile <name>
245 -rcfile <name>
243 Name of your IPython resource configuration file. normally
246 Name of your IPython resource configuration file. normally
244 IPython loads ipythonrc (from current directory) or
247 IPython loads ipythonrc (from current directory) or
245 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
248 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
246 IPython starts with a bare bones configuration (no modules
249 IPython starts with a bare bones configuration (no modules
247 loaded at all).
250 loaded at all).
248
251
249 -[no]readline
252 -[no]readline
250 Use the readline library, which is needed to support name com-
253 Use the readline library, which is needed to support name com-
251 pletion and command history, among other things. It is enabled
254 pletion and command history, among other things. It is enabled
252 by default, but may cause problems for users of X/Emacs in
255 by default, but may cause problems for users of X/Emacs in
253 Python comint or shell buffers.
256 Python comint or shell buffers.
254
257
255 Note that emacs 'eterm' buffers (opened with M-x term) support
258 Note that emacs 'eterm' buffers (opened with M-x term) support
256 IPython's readline and syntax coloring fine, only 'emacs' (M-x
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
257 shell and C-c !) buffers do not.
260 shell and C-c !) buffers do not.
258
261
259 -screen_length|sl <n>
262 -screen_length|sl <n>
260 Number of lines of your screen. This is used to control print-
263 Number of lines of your screen. This is used to control print-
261 ing of very long strings. Strings longer than this number of
264 ing of very long strings. Strings longer than this number of
262 lines will be sent through a pager instead of directly printed.
265 lines will be sent through a pager instead of directly printed.
263
266
264 The default value for this is 0, which means IPython will auto-
267 The default value for this is 0, which means IPython will auto-
265 detect your screen size every time it needs to print certain
268 detect your screen size every time it needs to print certain
266 potentially long strings (this doesn't change the behavior of
269 potentially long strings (this doesn't change the behavior of
267 the 'print' keyword, it's only triggered internally). If for
270 the 'print' keyword, it's only triggered internally). If for
268 some reason this isn't working well (it needs curses support),
271 some reason this isn't working well (it needs curses support),
269 specify it yourself. Otherwise don't change the default.
272 specify it yourself. Otherwise don't change the default.
270
273
271 -separate_in|si <string>
274 -separate_in|si <string>
272 Separator before input prompts. Default '0.
275 Separator before input prompts. Default '0.
273
276
274 -separate_out|so <string>
277 -separate_out|so <string>
275 Separator before output prompts. Default: 0 (nothing).
278 Separator before output prompts. Default: 0 (nothing).
276
279
277 -separate_out2|so2 <string>
280 -separate_out2|so2 <string>
278 Separator after output prompts. Default: 0 (nothing).
281 Separator after output prompts. Default: 0 (nothing).
279
282
280 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
281 Simply removes all input/output separators.
284 Simply removes all input/output separators.
282
285
283 -upgrade
286 -upgrade
284 Allows you to upgrade your IPYTHONDIR configuration when you
287 Allows you to upgrade your IPYTHONDIR configuration when you
285 install a new version of IPython. Since new versions may
288 install a new version of IPython. Since new versions may
286 include new command lines options or example files, this copies
289 include new command lines options or example files, this copies
287 updated ipythonrc-type files. However, it backs up (with a .old
290 updated ipythonrc-type files. However, it backs up (with a .old
288 extension) all files which it overwrites so that you can merge
291 extension) all files which it overwrites so that you can merge
289 back any custimizations you might have in your personal files.
292 back any custimizations you might have in your personal files.
290
293
291 -Version
294 -Version
292 Print version information and exit.
295 Print version information and exit.
293
296
294 -wxversion <string>
297 -wxversion <string>
295 Select a specific version of wxPython (used in conjunction with
298 Select a specific version of wxPython (used in conjunction with
296 -wthread). Requires the wxversion module, part of recent
299 -wthread). Requires the wxversion module, part of recent
297 wxPython distributions.
300 wxPython distributions.
298
301
299 -xmode <modename>
302 -xmode <modename>
300 Mode for exception reporting. The valid modes are Plain, Con-
303 Mode for exception reporting. The valid modes are Plain, Con-
301 text, and Verbose.
304 text, and Verbose.
302
305
303 - Plain: similar to python's normal traceback printing.
306 - Plain: similar to python's normal traceback printing.
304
307
305 - Context: prints 5 lines of context source code around each
308 - Context: prints 5 lines of context source code around each
306 line in the traceback.
309 line in the traceback.
307
310
308 - Verbose: similar to Context, but additionally prints the vari-
311 - Verbose: similar to Context, but additionally prints the vari-
309 ables currently visible where the exception happened (shortening
312 ables currently visible where the exception happened (shortening
310 their strings if too long). This can potentially be very slow,
313 their strings if too long). This can potentially be very slow,
311 if you happen to have a huge data structure whose string repre-
314 if you happen to have a huge data structure whose string repre-
312 sentation is complex to compute. Your computer may appear to
315 sentation is complex to compute. Your computer may appear to
313 freeze for a while with cpu usage at 100%. If this occurs, you
316 freeze for a while with cpu usage at 100%. If this occurs, you
314 can cancel the traceback with Ctrl-C (maybe hitting it more than
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
315 once).
318 once).
316
319
317
320
318 EMBEDDING
321 EMBEDDING
319 It is possible to start an IPython instance inside your own Python pro-
322 It is possible to start an IPython instance inside your own Python pro-
320 grams. In the documentation example files there are some illustrations
323 grams. In the documentation example files there are some illustrations
321 on how to do this.
324 on how to do this.
322
325
323 This feature allows you to evalutate dynamically the state of your
326 This feature allows you to evalutate dynamically the state of your
324 code, operate with your variables, analyze them, etc. Note however
327 code, operate with your variables, analyze them, etc. Note however
325 that any changes you make to values while in the shell do NOT propagate
328 that any changes you make to values while in the shell do NOT propagate
326 back to the running code, so it is safe to modify your values because
329 back to the running code, so it is safe to modify your values because
327 you won't break your code in bizarre ways by doing so.
330 you won't break your code in bizarre ways by doing so.
328 """
331 """
329
332
330 cmd_line_usage = __doc__
333 cmd_line_usage = __doc__
331
334
332 #---------------------------------------------------------------------------
335 #---------------------------------------------------------------------------
333 interactive_usage = """
336 interactive_usage = """
334 IPython -- An enhanced Interactive Python
337 IPython -- An enhanced Interactive Python
335 =========================================
338 =========================================
336
339
337 IPython offers a combination of convenient shell features, special commands
340 IPython offers a combination of convenient shell features, special commands
338 and a history mechanism for both input (command history) and output (results
341 and a history mechanism for both input (command history) and output (results
339 caching, similar to Mathematica). It is intended to be a fully compatible
342 caching, similar to Mathematica). It is intended to be a fully compatible
340 replacement for the standard Python interpreter, while offering vastly
343 replacement for the standard Python interpreter, while offering vastly
341 improved functionality and flexibility.
344 improved functionality and flexibility.
342
345
343 At your system command line, type 'ipython -help' to see the command line
346 At your system command line, type 'ipython -help' to see the command line
344 options available. This document only describes interactive features.
347 options available. This document only describes interactive features.
345
348
346 Warning: IPython relies on the existence of a global variable called __IP which
349 Warning: IPython relies on the existence of a global variable called __IP which
347 controls the shell itself. If you redefine __IP to anything, bizarre behavior
350 controls the shell itself. If you redefine __IP to anything, bizarre behavior
348 will quickly occur.
351 will quickly occur.
349
352
350 MAIN FEATURES
353 MAIN FEATURES
351
354
352 * Access to the standard Python help. As of Python 2.1, a help system is
355 * Access to the standard Python help. As of Python 2.1, a help system is
353 available with access to object docstrings and the Python manuals. Simply
356 available with access to object docstrings and the Python manuals. Simply
354 type 'help' (no quotes) to access it.
357 type 'help' (no quotes) to access it.
355
358
356 * Magic commands: type %magic for information on the magic subsystem.
359 * Magic commands: type %magic for information on the magic subsystem.
357
360
358 * System command aliases, via the %alias command or the ipythonrc config file.
361 * System command aliases, via the %alias command or the ipythonrc config file.
359
362
360 * Dynamic object information:
363 * Dynamic object information:
361
364
362 Typing ?word or word? prints detailed information about an object. If
365 Typing ?word or word? prints detailed information about an object. If
363 certain strings in the object are too long (docstrings, code, etc.) they get
366 certain strings in the object are too long (docstrings, code, etc.) they get
364 snipped in the center for brevity.
367 snipped in the center for brevity.
365
368
366 Typing ??word or word?? gives access to the full information without
369 Typing ??word or word?? gives access to the full information without
367 snipping long strings. Long strings are sent to the screen through the less
370 snipping long strings. Long strings are sent to the screen through the less
368 pager if longer than the screen, printed otherwise.
371 pager if longer than the screen, printed otherwise.
369
372
370 The ?/?? system gives access to the full source code for any object (if
373 The ?/?? system gives access to the full source code for any object (if
371 available), shows function prototypes and other useful information.
374 available), shows function prototypes and other useful information.
372
375
373 If you just want to see an object's docstring, type '%pdoc object' (without
376 If you just want to see an object's docstring, type '%pdoc object' (without
374 quotes, and without % if you have automagic on).
377 quotes, and without % if you have automagic on).
375
378
376 Both %pdoc and ?/?? give you access to documentation even on things which are
379 Both %pdoc and ?/?? give you access to documentation even on things which are
377 not explicitely defined. Try for example typing {}.get? or after import os,
380 not explicitely defined. Try for example typing {}.get? or after import os,
378 type os.path.abspath??. The magic functions %pdef, %source and %file operate
381 type os.path.abspath??. The magic functions %pdef, %source and %file operate
379 similarly.
382 similarly.
380
383
381 * Completion in the local namespace, by typing TAB at the prompt.
384 * Completion in the local namespace, by typing TAB at the prompt.
382
385
383 At any time, hitting tab will complete any available python commands or
386 At any time, hitting tab will complete any available python commands or
384 variable names, and show you a list of the possible completions if there's
387 variable names, and show you a list of the possible completions if there's
385 no unambiguous one. It will also complete filenames in the current directory.
388 no unambiguous one. It will also complete filenames in the current directory.
386
389
387 This feature requires the readline and rlcomplete modules, so it won't work
390 This feature requires the readline and rlcomplete modules, so it won't work
388 if your Python lacks readline support (such as under Windows).
391 if your Python lacks readline support (such as under Windows).
389
392
390 * Search previous command history in two ways (also requires readline):
393 * Search previous command history in two ways (also requires readline):
391
394
392 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
395 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
393 search through only the history items that match what you've typed so
396 search through only the history items that match what you've typed so
394 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
397 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
395 normal arrow keys.
398 normal arrow keys.
396
399
397 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
400 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
398 your history for lines that match what you've typed so far, completing as
401 your history for lines that match what you've typed so far, completing as
399 much as it can.
402 much as it can.
400
403
401 * Persistent command history across sessions (readline required).
404 * Persistent command history across sessions (readline required).
402
405
403 * Logging of input with the ability to save and restore a working session.
406 * Logging of input with the ability to save and restore a working session.
404
407
405 * System escape with !. Typing !ls will run 'ls' in the current directory.
408 * System escape with !. Typing !ls will run 'ls' in the current directory.
406
409
407 * The reload command does a 'deep' reload of a module: changes made to the
410 * The reload command does a 'deep' reload of a module: changes made to the
408 module since you imported will actually be available without having to exit.
411 module since you imported will actually be available without having to exit.
409
412
410 * Verbose and colored exception traceback printouts. See the magic xmode and
413 * Verbose and colored exception traceback printouts. See the magic xmode and
411 xcolor functions for details (just type %magic).
414 xcolor functions for details (just type %magic).
412
415
413 * Input caching system:
416 * Input caching system:
414
417
415 IPython offers numbered prompts (In/Out) with input and output caching. All
418 IPython offers numbered prompts (In/Out) with input and output caching. All
416 input is saved and can be retrieved as variables (besides the usual arrow
419 input is saved and can be retrieved as variables (besides the usual arrow
417 key recall).
420 key recall).
418
421
419 The following GLOBAL variables always exist (so don't overwrite them!):
422 The following GLOBAL variables always exist (so don't overwrite them!):
420 _i: stores previous input.
423 _i: stores previous input.
421 _ii: next previous.
424 _ii: next previous.
422 _iii: next-next previous.
425 _iii: next-next previous.
423 _ih : a list of all input _ih[n] is the input from line n.
426 _ih : a list of all input _ih[n] is the input from line n.
424
427
425 Additionally, global variables named _i<n> are dynamically created (<n>
428 Additionally, global variables named _i<n> are dynamically created (<n>
426 being the prompt counter), such that _i<n> == _ih[<n>]
429 being the prompt counter), such that _i<n> == _ih[<n>]
427
430
428 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
431 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
429
432
430 You can create macros which contain multiple input lines from this history,
433 You can create macros which contain multiple input lines from this history,
431 for later re-execution, with the %macro function.
434 for later re-execution, with the %macro function.
432
435
433 The history function %hist allows you to see any part of your input history
436 The history function %hist allows you to see any part of your input history
434 by printing a range of the _i variables. Note that inputs which contain
437 by printing a range of the _i variables. Note that inputs which contain
435 magic functions (%) appear in the history with a prepended comment. This is
438 magic functions (%) appear in the history with a prepended comment. This is
436 because they aren't really valid Python code, so you can't exec them.
439 because they aren't really valid Python code, so you can't exec them.
437
440
438 * Output caching system:
441 * Output caching system:
439
442
440 For output that is returned from actions, a system similar to the input
443 For output that is returned from actions, a system similar to the input
441 cache exists but using _ instead of _i. Only actions that produce a result
444 cache exists but using _ instead of _i. Only actions that produce a result
442 (NOT assignments, for example) are cached. If you are familiar with
445 (NOT assignments, for example) are cached. If you are familiar with
443 Mathematica, IPython's _ variables behave exactly like Mathematica's %
446 Mathematica, IPython's _ variables behave exactly like Mathematica's %
444 variables.
447 variables.
445
448
446 The following GLOBAL variables always exist (so don't overwrite them!):
449 The following GLOBAL variables always exist (so don't overwrite them!):
447 _ (one underscore): previous output.
450 _ (one underscore): previous output.
448 __ (two underscores): next previous.
451 __ (two underscores): next previous.
449 ___ (three underscores): next-next previous.
452 ___ (three underscores): next-next previous.
450
453
451 Global variables named _<n> are dynamically created (<n> being the prompt
454 Global variables named _<n> are dynamically created (<n> being the prompt
452 counter), such that the result of output <n> is always available as _<n>.
455 counter), such that the result of output <n> is always available as _<n>.
453
456
454 Finally, a global dictionary named _oh exists with entries for all lines
457 Finally, a global dictionary named _oh exists with entries for all lines
455 which generated output.
458 which generated output.
456
459
457 * Directory history:
460 * Directory history:
458
461
459 Your history of visited directories is kept in the global list _dh, and the
462 Your history of visited directories is kept in the global list _dh, and the
460 magic %cd command can be used to go to any entry in that list.
463 magic %cd command can be used to go to any entry in that list.
461
464
462 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
465 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
463
466
464 1. Auto-parentheses
467 1. Auto-parentheses
465 Callable objects (i.e. functions, methods, etc) can be invoked like
468 Callable objects (i.e. functions, methods, etc) can be invoked like
466 this (notice the commas between the arguments):
469 this (notice the commas between the arguments):
467 >>> callable_ob arg1, arg2, arg3
470 >>> callable_ob arg1, arg2, arg3
468 and the input will be translated to this:
471 and the input will be translated to this:
469 --> callable_ob(arg1, arg2, arg3)
472 --> callable_ob(arg1, arg2, arg3)
470 You can force auto-parentheses by using '/' as the first character
473 You can force auto-parentheses by using '/' as the first character
471 of a line. For example:
474 of a line. For example:
472 >>> /globals # becomes 'globals()'
475 >>> /globals # becomes 'globals()'
473 Note that the '/' MUST be the first character on the line! This
476 Note that the '/' MUST be the first character on the line! This
474 won't work:
477 won't work:
475 >>> print /globals # syntax error
478 >>> print /globals # syntax error
476
479
477 In most cases the automatic algorithm should work, so you should
480 In most cases the automatic algorithm should work, so you should
478 rarely need to explicitly invoke /. One notable exception is if you
481 rarely need to explicitly invoke /. One notable exception is if you
479 are trying to call a function with a list of tuples as arguments (the
482 are trying to call a function with a list of tuples as arguments (the
480 parenthesis will confuse IPython):
483 parenthesis will confuse IPython):
481 In [1]: zip (1,2,3),(4,5,6) # won't work
484 In [1]: zip (1,2,3),(4,5,6) # won't work
482 but this will work:
485 but this will work:
483 In [2]: /zip (1,2,3),(4,5,6)
486 In [2]: /zip (1,2,3),(4,5,6)
484 ------> zip ((1,2,3),(4,5,6))
487 ------> zip ((1,2,3),(4,5,6))
485 Out[2]= [(1, 4), (2, 5), (3, 6)]
488 Out[2]= [(1, 4), (2, 5), (3, 6)]
486
489
487 IPython tells you that it has altered your command line by
490 IPython tells you that it has altered your command line by
488 displaying the new command line preceded by -->. e.g.:
491 displaying the new command line preceded by -->. e.g.:
489 In [18]: callable list
492 In [18]: callable list
490 -------> callable (list)
493 -------> callable (list)
491
494
492 2. Auto-Quoting
495 2. Auto-Quoting
493 You can force auto-quoting of a function's arguments by using ',' as
496 You can force auto-quoting of a function's arguments by using ',' as
494 the first character of a line. For example:
497 the first character of a line. For example:
495 >>> ,my_function /home/me # becomes my_function("/home/me")
498 >>> ,my_function /home/me # becomes my_function("/home/me")
496
499
497 If you use ';' instead, the whole argument is quoted as a single
500 If you use ';' instead, the whole argument is quoted as a single
498 string (while ',' splits on whitespace):
501 string (while ',' splits on whitespace):
499 >>> ,my_function a b c # becomes my_function("a","b","c")
502 >>> ,my_function a b c # becomes my_function("a","b","c")
500 >>> ;my_function a b c # becomes my_function("a b c")
503 >>> ;my_function a b c # becomes my_function("a b c")
501
504
502 Note that the ',' MUST be the first character on the line! This
505 Note that the ',' MUST be the first character on the line! This
503 won't work:
506 won't work:
504 >>> x = ,my_function /home/me # syntax error
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 quick_reference = r"""
522 quick_reference = r"""
508 IPython -- An enhanced Interactive Python - Quick Reference Card
523 IPython -- An enhanced Interactive Python - Quick Reference Card
509 ================================================================
524 ================================================================
510
525
511 obj?, obj?? : Get help, or more help for object (also works as
526 obj?, obj?? : Get help, or more help for object (also works as
512 ?obj, ??obj).
527 ?obj, ??obj).
513 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
528 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
514 %magic : Information about IPython's 'magic' % functions.
529 %magic : Information about IPython's 'magic' % functions.
515
530
516 Magic functions are prefixed by %, and typically take their arguments without
531 Magic functions are prefixed by %, and typically take their arguments without
517 parentheses, quotes or even commas for convenience.
532 parentheses, quotes or even commas for convenience.
518
533
519 Example magic function calls:
534 Example magic function calls:
520
535
521 %alias d ls -F : 'd' is now an alias for 'ls -F'
536 %alias d ls -F : 'd' is now an alias for 'ls -F'
522 alias d ls -F : Works if 'alias' not a python name
537 alias d ls -F : Works if 'alias' not a python name
523 alist = %alias : Get list of aliases to 'alist'
538 alist = %alias : Get list of aliases to 'alist'
524 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
539 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
525 %cd?? : See help AND source for magic %cd
540 %cd?? : See help AND source for magic %cd
526
541
527 System commands:
542 System commands:
528
543
529 !cp a.txt b/ : System command escape, calls os.system()
544 !cp a.txt b/ : System command escape, calls os.system()
530 cp a.txt b/ : after %rehashx, most system commands work without !
545 cp a.txt b/ : after %rehashx, most system commands work without !
531 cp ${f}.txt $bar : Variable expansion in magics and system commands
546 cp ${f}.txt $bar : Variable expansion in magics and system commands
532 files = !ls /usr : Capture sytem command output
547 files = !ls /usr : Capture sytem command output
533 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
548 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
534
549
535 History:
550 History:
536
551
537 _i, _ii, _iii : Previous, next previous, next next previous input
552 _i, _ii, _iii : Previous, next previous, next next previous input
538 _i4, _ih[2:5] : Input history line 4, lines 2-4
553 _i4, _ih[2:5] : Input history line 4, lines 2-4
539 exec _i81 : Execute input history line #81 again
554 exec _i81 : Execute input history line #81 again
540 %rep 81 : Edit input history line #81
555 %rep 81 : Edit input history line #81
541 _, __, ___ : previous, next previous, next next previous output
556 _, __, ___ : previous, next previous, next next previous output
542 _dh : Directory history
557 _dh : Directory history
543 _oh : Output history
558 _oh : Output history
544 %hist : Command history. '%hist -g foo' search history for 'foo'
559 %hist : Command history. '%hist -g foo' search history for 'foo'
545
560
546 Autocall:
561 Autocall:
547
562
548 f 1,2 : f(1,2)
563 f 1,2 : f(1,2)
549 /f 1,2 : f(1,2) (forced autoparen)
564 /f 1,2 : f(1,2) (forced autoparen)
550 ,f 1 2 : f("1","2")
565 ,f 1 2 : f("1","2")
551 ;f 1 2 : f("1 2")
566 ;f 1 2 : f("1 2")
552
567
553 Remember: TAB completion works in many contexts, not just file names
568 Remember: TAB completion works in many contexts, not just file names
554 or python names.
569 or python names.
555
570
556 The following magic functions are currently available:
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 """ File system operations
1 """ File system operations
2
2
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
4 imkdir, igrep).
4 imkdir, igrep).
5
5
6 Some "otherwise handy" utils ('collect' for gathering files to
6 Some "otherwise handy" utils ('collect' for gathering files to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
8 ~/_ipython/note.txt)
8 ~/_ipython/note.txt)
9
9
10 Mostly of use for bare windows installations where cygwin/equivalent is not
10 Mostly of use for bare windows installations where cygwin/equivalent is not
11 installed and you would otherwise need to deal with dos versions of the
11 installed and you would otherwise need to deal with dos versions of the
12 commands (that e.g. don't understand / as path separator). These can
12 commands (that e.g. don't understand / as path separator). These can
13 do some useful tricks on their own, though (like use 'mglob' patterns).
13 do some useful tricks on their own, though (like use 'mglob' patterns).
14
14
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
16 """
16 """
17
17
18 from IPython.core import ipapi
18 from IPython.core import ipapi
19 ip = ipapi.get()
19 ip = ipapi.get()
20
20
21 import shutil,os,shlex
21 import shutil,os,shlex
22 from IPython.external import mglob
22 from IPython.external import mglob
23 from IPython.external.path import path
23 from IPython.external.path import path
24 from IPython.core.ipapi import UsageError
24 from IPython.core.ipapi import UsageError
25 import IPython.utils.generics
25 import IPython.utils.generics
26
26
27 def parse_args(args):
27 def parse_args(args):
28 """ Given arg string 'CMD files... target', return ([files], target) """
28 """ Given arg string 'CMD files... target', return ([files], target) """
29
29
30 tup = args.split(None, 1)
30 tup = args.split(None, 1)
31 if len(tup) == 1:
31 if len(tup) == 1:
32 raise UsageError("Expected arguments for " + tup[0])
32 raise UsageError("Expected arguments for " + tup[0])
33
33
34 tup2 = shlex.split(tup[1])
34 tup2 = shlex.split(tup[1])
35
35
36 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
36 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
37 if not flist:
37 if not flist:
38 raise UsageError("No files found:" + str(tup2[0:-1]))
38 raise UsageError("No files found:" + str(tup2[0:-1]))
39 return flist, trg
39 return flist, trg
40
40
41 def icp(ip,arg):
41 def icp(ip,arg):
42 """ icp files... targetdir
42 """ icp files... targetdir
43
43
44 Copy all files to target, creating dirs for target if necessary
44 Copy all files to target, creating dirs for target if necessary
45
45
46 icp srcdir dstdir
46 icp srcdir dstdir
47
47
48 Copy srcdir to distdir
48 Copy srcdir to distdir
49
49
50 """
50 """
51 import distutils.dir_util
51 import distutils.dir_util
52
52
53 fs, targetdir = parse_args(arg)
53 fs, targetdir = parse_args(arg)
54 if not os.path.isdir(targetdir) and len(fs) > 1:
54 if not os.path.isdir(targetdir) and len(fs) > 1:
55 distutils.dir_util.mkpath(targetdir,verbose =1)
55 distutils.dir_util.mkpath(targetdir,verbose =1)
56 for f in fs:
56 for f in fs:
57 if os.path.isdir(f):
57 if os.path.isdir(f):
58 shutil.copytree(f, targetdir)
58 shutil.copytree(f, targetdir)
59 else:
59 else:
60 shutil.copy2(f,targetdir)
60 shutil.copy2(f,targetdir)
61 return fs
61 return fs
62 ip.defalias("icp",icp)
62 ip.defalias("icp",icp)
63
63
64 def imv(ip,arg):
64 def imv(ip,arg):
65 """ imv src tgt
65 """ imv src tgt
66
66
67 Move source to target.
67 Move source to target.
68 """
68 """
69
69
70 fs, target = parse_args(arg)
70 fs, target = parse_args(arg)
71 if len(fs) > 1:
71 if len(fs) > 1:
72 assert os.path.isdir(target)
72 assert os.path.isdir(target)
73 for f in fs:
73 for f in fs:
74 shutil.move(f, target)
74 shutil.move(f, target)
75 return fs
75 return fs
76 ip.defalias("imv",imv)
76 ip.defalias("imv",imv)
77
77
78 def irm(ip,arg):
78 def irm(ip,arg):
79 """ irm path[s]...
79 """ irm path[s]...
80
80
81 Remove file[s] or dir[s] path. Dirs are deleted recursively.
81 Remove file[s] or dir[s] path. Dirs are deleted recursively.
82 """
82 """
83 try:
83 try:
84 paths = mglob.expand(arg.split(None,1)[1])
84 paths = mglob.expand(arg.split(None,1)[1])
85 except IndexError:
85 except IndexError:
86 raise UsageError("%irm paths...")
86 raise UsageError("%irm paths...")
87 import distutils.dir_util
87 import distutils.dir_util
88 for p in paths:
88 for p in paths:
89 print "rm",p
89 print "rm",p
90 if os.path.isdir(p):
90 if os.path.isdir(p):
91 distutils.dir_util.remove_tree(p, verbose = 1)
91 distutils.dir_util.remove_tree(p, verbose = 1)
92 else:
92 else:
93 os.remove(p)
93 os.remove(p)
94
94
95 ip.defalias("irm",irm)
95 ip.defalias("irm",irm)
96
96
97 def imkdir(ip,arg):
97 def imkdir(ip,arg):
98 """ imkdir path
98 """ imkdir path
99
99
100 Creates dir path, and all dirs on the road
100 Creates dir path, and all dirs on the road
101 """
101 """
102 import distutils.dir_util
102 import distutils.dir_util
103 targetdir = arg.split(None,1)[1]
103 targetdir = arg.split(None,1)[1]
104 distutils.dir_util.mkpath(targetdir,verbose =1)
104 distutils.dir_util.mkpath(targetdir,verbose =1)
105
105
106 ip.defalias("imkdir",imkdir)
106 ip.defalias("imkdir",imkdir)
107
107
108 def igrep(ip,arg):
108 def igrep(ip,arg):
109 """ igrep PAT files...
109 """ igrep PAT files...
110
110
111 Very dumb file scan, case-insensitive.
111 Very dumb file scan, case-insensitive.
112
112
113 e.g.
113 e.g.
114
114
115 igrep "test this" rec:*.py
115 igrep "test this" rec:*.py
116
116
117 """
117 """
118 elems = shlex.split(arg)
118 elems = shlex.split(arg)
119 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
119 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
120 res = []
120 res = []
121 for f in fs:
121 for f in fs:
122 found = False
122 found = False
123 for l in open(f):
123 for l in open(f):
124 if pat.lower() in l.lower():
124 if pat.lower() in l.lower():
125 if not found:
125 if not found:
126 print "[[",f,"]]"
126 print "[[",f,"]]"
127 found = True
127 found = True
128 res.append(f)
128 res.append(f)
129 print l.rstrip()
129 print l.rstrip()
130 return res
130 return res
131
131
132 ip.defalias("igrep",igrep)
132 ip.defalias("igrep",igrep)
133
133
134 def collect(ip,arg):
134 def collect(ip,arg):
135 """ collect foo/a.txt rec:bar=*.py
135 """ collect foo/a.txt rec:bar=*.py
136
136
137 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
137 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
138 likewise
138 likewise
139
139
140 Without args, try to open ~/_ipython/collect dir (in win32 at least).
140 Without args, try to open ~/_ipython/collect dir (in win32 at least).
141 """
141 """
142 from IPython.external.path import path
142 from IPython.external.path import path
143 basedir = path(ip.options.ipythondir + '/collect')
143 basedir = path(ip.options.IPYTHONDIR + '/collect')
144 try:
144 try:
145 fs = mglob.expand(arg.split(None,1)[1])
145 fs = mglob.expand(arg.split(None,1)[1])
146 except IndexError:
146 except IndexError:
147 os.startfile(basedir)
147 os.startfile(basedir)
148 return
148 return
149 for f in fs:
149 for f in fs:
150 f = path(f)
150 f = path(f)
151 trg = basedir / f.splitdrive()[1].lstrip('/\\')
151 trg = basedir / f.splitdrive()[1].lstrip('/\\')
152 if f.isdir():
152 if f.isdir():
153 print "mkdir",trg
153 print "mkdir",trg
154 trg.makedirs()
154 trg.makedirs()
155 continue
155 continue
156 dname = trg.dirname()
156 dname = trg.dirname()
157 if not dname.isdir():
157 if not dname.isdir():
158 dname.makedirs()
158 dname.makedirs()
159 print f,"=>",trg
159 print f,"=>",trg
160 shutil.copy2(f,trg)
160 shutil.copy2(f,trg)
161
161
162 ip.defalias("collect",collect)
162 ip.defalias("collect",collect)
163
163
164 def inote(ip,arg):
164 def inote(ip,arg):
165 """ inote Hello world
165 """ inote Hello world
166
166
167 Adds timestamp and Hello world to ~/_ipython/notes.txt
167 Adds timestamp and Hello world to ~/_ipython/notes.txt
168
168
169 Without args, opens notes.txt for editing.
169 Without args, opens notes.txt for editing.
170 """
170 """
171 import time
171 import time
172 fname = ip.options.ipythondir + '/notes.txt'
172 fname = ip.options.IPYTHONDIR + '/notes.txt'
173
173
174 try:
174 try:
175 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
175 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
176 f= open(fname, 'a').write(entry)
176 f= open(fname, 'a').write(entry)
177 except IndexError:
177 except IndexError:
178 ip.IP.hooks.editor(fname)
178 ip.IP.hooks.editor(fname)
179
179
180 ip.defalias("inote",inote)
180 ip.defalias("inote",inote)
181
181
182 def pathobj_mangle(p):
182 def pathobj_mangle(p):
183 return p.replace(' ', '__').replace('.','DOT')
183 return p.replace(' ', '__').replace('.','DOT')
184 def pathobj_unmangle(s):
184 def pathobj_unmangle(s):
185 return s.replace('__',' ').replace('DOT','.')
185 return s.replace('__',' ').replace('DOT','.')
186
186
187
187
188
188
189 class PathObj(path):
189 class PathObj(path):
190 def __init__(self,p):
190 def __init__(self,p):
191 self.path = p
191 self.path = p
192 if p != '.':
192 if p != '.':
193 self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)]
193 self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)]
194 else:
194 else:
195 self.ents = None
195 self.ents = None
196 def __complete__(self):
196 def __complete__(self):
197 if self.path != '.':
197 if self.path != '.':
198 return self.ents
198 return self.ents
199 self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')]
199 self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')]
200 return self.ents
200 return self.ents
201 def __getattr__(self,name):
201 def __getattr__(self,name):
202 if name in self.ents:
202 if name in self.ents:
203 if self.path.endswith('/'):
203 if self.path.endswith('/'):
204 sep = ''
204 sep = ''
205 else:
205 else:
206 sep = '/'
206 sep = '/'
207
207
208 tgt = self.path + sep + pathobj_unmangle(name)
208 tgt = self.path + sep + pathobj_unmangle(name)
209 #print "tgt",tgt
209 #print "tgt",tgt
210 if os.path.isdir(tgt):
210 if os.path.isdir(tgt):
211 return PathObj(tgt)
211 return PathObj(tgt)
212 if os.path.isfile(tgt):
212 if os.path.isfile(tgt):
213 return path(tgt)
213 return path(tgt)
214
214
215 raise AttributeError, name # <<< DON'T FORGET THIS LINE !!
215 raise AttributeError, name # <<< DON'T FORGET THIS LINE !!
216 def __str__(self):
216 def __str__(self):
217 return self.path
217 return self.path
218
218
219 def __repr__(self):
219 def __repr__(self):
220 return "<PathObj to %s>" % self.path
220 return "<PathObj to %s>" % self.path
221
221
222 def __call__(self):
222 def __call__(self):
223 print "cd:",self.path
223 print "cd:",self.path
224 os.chdir(self.path)
224 os.chdir(self.path)
225
225
226 def complete_pathobj(obj, prev_completions):
226 def complete_pathobj(obj, prev_completions):
227 if hasattr(obj,'__complete__'):
227 if hasattr(obj,'__complete__'):
228 res = obj.__complete__()
228 res = obj.__complete__()
229 if res:
229 if res:
230 return res
230 return res
231 # just return normal attributes of 'path' object if the dir is empty
231 # just return normal attributes of 'path' object if the dir is empty
232 raise ipapi.TryNext
232 raise ipapi.TryNext
233
233
234 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
234 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
235
235
236 def test_pathobj():
236 def test_pathobj():
237 #p = PathObj('c:/prj')
237 #p = PathObj('c:/prj')
238 #p2 = p.cgi
238 #p2 = p.cgi
239 #print p,p2
239 #print p,p2
240 rootdir = PathObj("/")
240 rootdir = PathObj("/")
241 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
241 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
242 cwd = PathObj('.')
242 cwd = PathObj('.')
243 ip.to_user_ns("rootdir startmenu cwd")
243 ip.to_user_ns("rootdir startmenu cwd")
244
244
245 #test_pathobj() No newline at end of file
245 #test_pathobj()
@@ -1,31 +1,31 b''
1 import inspect
1 import inspect
2 from IPython.core import ipapi
2 from IPython.core import ipapi
3 from IPython.utils.genutils import arg_split
3 from IPython.utils.genutils import arg_split
4 ip = ipapi.get()
4 ip = ipapi.get()
5
5
6 from IPython.core import debugger
6 from IPython.core import debugger
7
7
8 def call_pydb(self, args):
8 def call_pydb(self, args):
9 """Invoke pydb with the supplied parameters."""
9 """Invoke pydb with the supplied parameters."""
10 try:
10 try:
11 import pydb
11 import pydb
12 except ImportError:
12 except ImportError:
13 raise ImportError("pydb doesn't seem to be installed.")
13 raise ImportError("pydb doesn't seem to be installed.")
14
14
15 if not hasattr(pydb.pydb, "runv"):
15 if not hasattr(pydb.pydb, "runv"):
16 raise ImportError("You need pydb version 1.19 or later installed.")
16 raise ImportError("You need pydb version 1.19 or later installed.")
17
17
18 argl = arg_split(args)
18 argl = arg_split(args)
19 # print argl # dbg
19 # print argl # dbg
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = debugger.Pdb(color_scheme=self.rc.colors)
21 pdb = debugger.Pdb(color_scheme=self.colors)
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 else:
23 else:
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
25
25
26
26
27 ip.expose_magic("pydb",call_pydb)
27 ip.expose_magic("pydb",call_pydb)
28
28
29
29
30
30
31
31
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now