##// END OF EJS Templates
Massive, crazy refactoring of everything....
Brian Granger -
Show More
@@ -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
@@ -163,7 +163,7 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
163 163 self._add_arguments()
164 164 self._add_other_arguments()
165 165
166 def _add_other_arguments():
166 def _add_other_arguments(self):
167 167 pass
168 168
169 169 def _add_arguments(self):
@@ -241,7 +241,7 b' class IPCompleter(Completer):'
241 241 self.get_line_buffer = self.readline.get_line_buffer
242 242 self.get_endidx = self.readline.get_endidx
243 243 self.omit__names = omit__names
244 self.merge_completions = shell.rc.readline_merge_completions
244 self.merge_completions = shell.readline_merge_completions
245 245 if alias_table is None:
246 246 alias_table = {}
247 247 self.alias_table = alias_table
@@ -124,7 +124,7 b' $self.bug_tracker'
124 124 #color_scheme = 'Linux' # dbg
125 125
126 126 try:
127 rptdir = self.IP.rc.ipythondir
127 rptdir = self.IP.config.IPYTHONDIR
128 128 except:
129 129 rptdir = os.getcwd()
130 130 if not os.path.isdir(rptdir):
@@ -171,7 +171,7 b' $self.bug_tracker'
171 171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 172 (os.name,sys.platform) )
173 173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.rc.dict()))
174 rpt_add(pformat(self.IP.dict()))
175 175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 176 try:
177 177 rpt_add(sec_sep+"History of session input:")
@@ -215,7 +215,7 b' class IPythonCrashHandler(CrashHandler):'
215 215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 216 (os.name,sys.platform) )
217 217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 rpt_add(pformat(self.IP.rc.dict()))
218 rpt_add(pformat(self.IP.dict()))
219 219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 220 try:
221 221 rpt_add(sec_sep+"History of session input:")
@@ -69,7 +69,7 b' def editor(self,filename, linenum=None):'
69 69
70 70 # IPython configures a default editor at startup by reading $EDITOR from
71 71 # the environment, and falling back on vi (unix) or notepad (win32).
72 editor = self.rc.editor
72 editor = self.editor
73 73
74 74 # marker for at which line to open the file (for existing objects)
75 75 if linenum is None or editor=='notepad':
@@ -99,7 +99,7 b' def fix_error_editor(self,filename,linenum,column,msg):'
99 99 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
100 100 t.flush()
101 101 return t
102 if os.path.basename(self.rc.editor) != 'vim':
102 if os.path.basename(self.editor) != 'vim':
103 103 self.hooks.editor(filename,linenum)
104 104 return
105 105 t = vim_quickfix_file()
@@ -167,7 +167,7 b' def result_display(self,arg):'
167 167 Called for displaying the result to the user.
168 168 """
169 169
170 if self.rc.pprint:
170 if self.pprint:
171 171 out = pformat(arg)
172 172 if '\n' in out:
173 173 # So that multi-line strings line up with the left column of
@@ -226,7 +226,7 b' def generate_output_prompt(self):'
226 226 def shell_hook(self,cmd):
227 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 231 def show_in_pager(self,s):
232 232 """ Run a string through pager """
@@ -219,8 +219,7 b' class IPApi(object):'
219 219 # is in fact wanted (e.g. when exposing new options), do
220 220 # allow_new_attr(True) for the received rc struct.
221 221
222 self.IP.rc.allow_new_attr(False)
223 return self.IP.rc
222 return self.IP
224 223
225 224 options = property(get_options,None,None,get_options.__doc__)
226 225
@@ -609,7 +608,7 b' _make_user_ns = make_user_ns'
609 608 _make_user_global_ns = make_user_global_ns
610 609
611 610
612 def make_user_namespaces(user_ns = None,user_global_ns = None):
611 def make_user_namespaces(user_ns = None, user_global_ns = None):
613 612 """Return a valid local and global user interactive namespaces.
614 613
615 614 This builds a dict with the minimal information needed to operate as a
This diff has been collapsed as it changes many lines, (862 lines changed) Show them Hide them
@@ -1,32 +1,21 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 IPython -- An enhanced Interactive Python
4
5 Requires Python 2.4 or newer.
6
7 This file contains all the classes and helper functions specific to IPython.
3 Main IPython Component
8 4 """
9 5
10 #*****************************************************************************
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
13 10 #
14 11 # Distributed under the terms of the BSD License. The full license is in
15 12 # the file COPYING, distributed as part of this software.
16 #
17 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Python standard library. Over time, all of that class has been copied
19 # verbatim here for modifications which could not be accomplished by
20 # subclassing. At this point, there are no dependencies at all on the code
21 # module anymore (it is not even imported). The Python License (sec. 2)
22 # allows for this, but it's always nice to acknowledge credit where credit is
23 # due.
24 #*****************************************************************************
25
26 #****************************************************************************
27 # Modules and globals
28
29 # Python standard modules
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18
30 19 import __main__
31 20 import __builtin__
32 21 import StringIO
@@ -43,26 +32,36 b' import string'
43 32 import sys
44 33 import tempfile
45 34
46 # IPython's own modules
47 #import IPython
48 35 from IPython.core import ultratb
49 from IPython.utils import PyColorize
50 36 from IPython.core import debugger, oinspect
51 from IPython.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 41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
53 from IPython.external.Itpl import ItplNS
54 42 from IPython.core.logger import Logger
55 43 from IPython.core.magic import Magic
56 44 from IPython.core.prompts import CachedOutput
57 from IPython.utils.ipstruct import Struct
45 from IPython.core.component import Component
46 from IPython.core.oldusersetup import user_setup
47 from IPython.core.usage import interactive_usage, banner_parts
48
49 from IPython.extensions import pickleshare
50 from IPython.external.Itpl import ItplNS
58 51 from IPython.lib.backgroundjobs import BackgroundJobManager
52 from IPython.utils.ipstruct import Struct
53 from IPython.utils import PyColorize
59 54 from IPython.utils.genutils import *
60 55 from IPython.utils.strdispatch import StrDispatch
61 from IPython.core import ipapi
62 import IPython.core.history
63 import IPython.core.prefilter as prefilter
64 from IPython.core import shadowns
56
57 from IPython.utils.traitlets import (
58 Int, Float, Str, Bool
59 )
60
61 #-----------------------------------------------------------------------------
65 62 # Globals
63 #-----------------------------------------------------------------------------
64
66 65
67 66 # store the builtin raw_input globally, and use this always, in case user code
68 67 # overwrites it (like wx.py.PyShell does)
@@ -72,11 +71,14 b' raw_input_original = raw_input'
72 71 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
73 72
74 73
75 #****************************************************************************
76 # Some utility function definitions
74 #-----------------------------------------------------------------------------
75 # Utilities
76 #-----------------------------------------------------------------------------
77
77 78
78 79 ini_spaces_re = re.compile(r'^(\s+)')
79 80
81
80 82 def num_ini_spaces(strng):
81 83 """Return the number of initial spaces in a string"""
82 84
@@ -86,6 +88,7 b' def num_ini_spaces(strng):'
86 88 else:
87 89 return 0
88 90
91
89 92 def softspace(file, newvalue):
90 93 """Copied from code.py, to remove the dependency"""
91 94
@@ -102,208 +105,8 b' def softspace(file, newvalue):'
102 105 return oldvalue
103 106
104 107
105 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
106 """Install or upgrade the user configuration directory.
107
108 Can be called when running for the first time or to upgrade the user's
109 .ipython/ directory.
110
111 Parameters
112 ----------
113 ipythondir : path
114 The directory to be used for installation/upgrade. In 'install' mode,
115 if this path already exists, the function exits immediately.
116
117 rc_suffix : str
118 Extension for the config files. On *nix platforms it is typically the
119 empty string, while Windows normally uses '.ini'.
120
121 mode : str, optional
122 Valid modes are 'install' and 'upgrade'.
123
124 interactive : bool, optional
125 If False, do not wait for user input on any errors. Normally after
126 printing its status information, this function waits for the user to
127 hit Return before proceeding. This is because the default use case is
128 when first installing the IPython configuration, so we want the user to
129 acknowledge the initial message, which contains some useful
130 information.
131 """
132
133 # For automatic use, deactivate all i/o
134 if interactive:
135 def wait():
136 try:
137 raw_input("Please press <RETURN> to start IPython.")
138 except EOFError:
139 print >> Term.cout
140 print '*'*70
141
142 def printf(s):
143 print s
144 else:
145 wait = lambda : None
146 printf = lambda s : None
147
148 # Install mode should be re-entrant: if the install dir already exists,
149 # bail out cleanly.
150 # XXX. This is too hasty to return. We need to check to make sure that
151 # all the expected config files and directories are actually there. We
152 # currently have a failure mode if someone deletes a needed config file
153 # but still has the ipythondir.
154 if mode == 'install' and os.path.isdir(ipythondir):
155 return
156
157 cwd = os.getcwd() # remember where we started
158 glb = glob.glob
159
160 printf('*'*70)
161 if mode == 'install':
162 printf(
163 """Welcome to IPython. I will try to create a personal configuration directory
164 where you can customize many aspects of IPython's functionality in:\n""")
165 else:
166 printf('I am going to upgrade your configuration in:')
167
168 printf(ipythondir)
169
170 rcdirend = os.path.join('IPython','config','userconfig')
171 cfg = lambda d: os.path.join(d,rcdirend)
172 try:
173 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
174 printf("Initializing from configuration: %s" % rcdir)
175 except IndexError:
176 warning = """
177 Installation error. IPython's directory was not found.
178
179 Check the following:
180
181 The ipython/IPython directory should be in a directory belonging to your
182 PYTHONPATH environment variable (that is, it should be in a directory
183 belonging to sys.path). You can copy it explicitly there or just link to it.
184
185 IPython will create a minimal default configuration for you.
186
187 """
188 warn(warning)
189 wait()
190
191 if sys.platform =='win32':
192 inif = 'ipythonrc.ini'
193 else:
194 inif = 'ipythonrc'
195 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
196 inif : '# intentionally left blank' }
197 os.makedirs(ipythondir, mode = 0777)
198 for f, cont in minimal_setup.items():
199 # In 2.5, this can be more cleanly done using 'with'
200 fobj = file(ipythondir + '/' + f,'w')
201 fobj.write(cont)
202 fobj.close()
203
204 return
205
206 if mode == 'install':
207 try:
208 shutil.copytree(rcdir,ipythondir)
209 os.chdir(ipythondir)
210 rc_files = glb("ipythonrc*")
211 for rc_file in rc_files:
212 os.rename(rc_file,rc_file+rc_suffix)
213 except:
214 warning = """
215
216 There was a problem with the installation:
217 %s
218 Try to correct it or contact the developers if you think it's a bug.
219 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
220 warn(warning)
221 wait()
222 return
223
224 elif mode == 'upgrade':
225 try:
226 os.chdir(ipythondir)
227 except:
228 printf("""
229 Can not upgrade: changing to directory %s failed. Details:
230 %s
231 """ % (ipythondir,sys.exc_info()[1]) )
232 wait()
233 return
234 else:
235 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
236 for new_full_path in sources:
237 new_filename = os.path.basename(new_full_path)
238 if new_filename.startswith('ipythonrc'):
239 new_filename = new_filename + rc_suffix
240 # The config directory should only contain files, skip any
241 # directories which may be there (like CVS)
242 if os.path.isdir(new_full_path):
243 continue
244 if os.path.exists(new_filename):
245 old_file = new_filename+'.old'
246 if os.path.exists(old_file):
247 os.remove(old_file)
248 os.rename(new_filename,old_file)
249 shutil.copy(new_full_path,new_filename)
250 else:
251 raise ValueError('unrecognized mode for install: %r' % mode)
252
253 # Fix line-endings to those native to each platform in the config
254 # directory.
255 try:
256 os.chdir(ipythondir)
257 except:
258 printf("""
259 Problem: changing to directory %s failed.
260 Details:
261 %s
262
263 Some configuration files may have incorrect line endings. This should not
264 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
265 wait()
266 else:
267 for fname in glb('ipythonrc*'):
268 try:
269 native_line_ends(fname,backup=0)
270 except IOError:
271 pass
272
273 if mode == 'install':
274 printf("""
275 Successful installation!
276
277 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
278 IPython manual (there are both HTML and PDF versions supplied with the
279 distribution) to make sure that your system environment is properly configured
280 to take advantage of IPython's features.
281
282 Important note: the configuration system has changed! The old system is
283 still in place, but its setting may be partly overridden by the settings in
284 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
285 if some of the new settings bother you.
286
287 """)
288 else:
289 printf("""
290 Successful upgrade!
291
292 All files in your directory:
293 %(ipythondir)s
294 which would have been overwritten by the upgrade were backed up with a .old
295 extension. If you had made particular customizations in those files you may
296 want to merge them back into the new files.""" % locals() )
297 wait()
298 os.chdir(cwd)
299
300 #****************************************************************************
301 # Local use exceptions
302 108 class SpaceInInput(exceptions.Exception): pass
303 109
304
305 #****************************************************************************
306 # Local use classes
307 110 class Bunch: pass
308 111
309 112 class Undefined: pass
@@ -357,8 +160,10 b' class SyntaxTB(ultratb.ListTB):'
357 160 self.last_syntax_error = None
358 161 return e
359 162
360 #****************************************************************************
163
164 #-----------------------------------------------------------------------------
361 165 # Main IPython class
166 #-----------------------------------------------------------------------------
362 167
363 168 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
364 169 # until a full rewrite is made. I've cleaned all cross-class uses of
@@ -378,34 +183,122 b' class SyntaxTB(ultratb.ListTB):'
378 183 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
379 184 # 'self.value']
380 185
381 class InteractiveShell(object,Magic):
186 class InteractiveShell(Component, Magic):
382 187 """An enhanced console for Python."""
383 188
189 alias = []
190 autocall = Bool(True)
191 autoedit_syntax = Bool(False)
192 autoindent = Bool(False)
193 automagic = Bool(True)
194 autoexec = []
195 display_banner = Bool(True)
196 banner = Str('')
197 c = Str('')
198 cache_size = Int(1000)
199 classic = Bool(False)
200 color_info = Int(0)
201 colors = Str('LightBG')
202 confirm_exit = Bool(True)
203 debug = Bool(False)
204 deep_reload = Bool(False)
205 embedded = Bool(False)
206 editor = Str('0')
207 filename = Str("<ipython console>")
208 help = Bool(False)
209 interactive = Bool(False)
210 logstart = Bool(False, config_key='LOGSTART')
211 logfile = Str('')
212 logplay = Str('')
213 messages = Bool(True)
214 multi_line_specials = Bool(True)
215 nosep = Bool(False)
216 object_info_string_level = Int(0)
217 pager = Str('less')
218 pdb = Bool(False)
219 pprint = Bool(True)
220 profile = Str('')
221 prompt_in1 = Str('In [\\#]: ')
222 prompt_in2 = Str(' .\\D.: ')
223 prompt_out = Str('Out[\\#]: ')
224 prompts_pad_left = Bool(True)
225 pydb = Bool(False)
226 quick = Bool(False)
227 quiet = Bool(False)
228
229 readline_use = Bool(True)
230 readline_merge_completions = Bool(True)
231 readline_omit__names = Int(0)
232 readline_remove_delims = '-/~'
233 readline_parse_and_bind = [
234 'tab: complete',
235 '"\C-l": possible-completions',
236 'set show-all-if-ambiguous on',
237 '"\C-o": tab-insert',
238 '"\M-i": " "',
239 '"\M-o": "\d\d\d\d"',
240 '"\M-I": "\d\d\d\d"',
241 '"\C-r": reverse-search-history',
242 '"\C-s": forward-search-history',
243 '"\C-p": history-search-backward',
244 '"\C-n": history-search-forward',
245 '"\e[A": history-search-backward',
246 '"\e[B": history-search-forward',
247 '"\C-k": kill-line',
248 '"\C-u": unix-line-discard',
249 ]
250
251 screen_length = Int(0)
252 separate_in = Str('\n')
253 separate_out = Str('')
254 separate_out2 = Str('')
255 system_header = Str('IPython system call: ')
256 system_verbose = Bool(False)
257 term_title = Bool(True)
258 wildcards_case_sensitive = Bool(True)
259 xmode = Str('Context')
260 magic_docstrings = Bool(False)
261
384 262 # class attribute to indicate whether the class supports threads or not.
385 263 # Subclasses with thread support should override this as needed.
386 264 isthreaded = False
387 265
388 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
389 user_ns=None,user_global_ns=None,banner2='',
390 custom_exceptions=((),None),embedded=False):
266 def __init__(self, name, parent=None, config=None, usage=None,
267 user_ns=None, user_global_ns=None, banner2='',
268 custom_exceptions=((),None), embedded=False):
391 269
392 # log system
393 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
394
395 # Job manager (for jobs run as background threads)
396 self.jobs = BackgroundJobManager()
270 super(InteractiveShell, self).__init__(parent, config=config, name=name)
397 271
398 # Store the actual shell's name
399 self.name = name
400 self.more = False
272 self.init_instance_attrs()
273 self.init_usage(usage)
274 self.init_banner(banner2)
275 self.init_embedded(embedded)
276 self.init_create_namespaces(user_ns, user_global_ns)
277 self.init_history()
278 self.init_encoding()
279 self.init_handlers()
401 280
402 # We need to know whether the instance is meant for embedding, since
403 # global/local namespaces need to be handled differently in that case
404 self.embedded = embedded
405 if embedded:
406 # Control variable so users can, from within the embedded instance,
407 # permanently deactivate it.
408 self.embedded_active = True
281 Magic.__init__(self, self)
282
283 self.init_syntax_highlighting()
284 self.init_hooks()
285 self.init_pushd_popd_magic()
286 self.init_traceback_handlers(custom_exceptions)
287
288 # Produce a public API instance
289 self.api = ipapi.IPApi(self)
290
291 self.init_namespaces()
292 self.init_logger()
293 self.init_aliases()
294 self.init_builtins()
295 self.init_shadow_hist()
296 self.init_logstart()
297 self.post_config_initialization()
298
299 def init_instance_attrs(self):
300 self.jobs = BackgroundJobManager()
301 self.more = False
409 302
410 303 # command compiler
411 304 self.compile = codeop.CommandCompiler()
@@ -413,14 +306,6 b' class InteractiveShell(object,Magic):'
413 306 # User input buffer
414 307 self.buffer = []
415 308
416 # Default name given in compilation of code
417 self.filename = '<ipython console>'
418
419 # Install our own quitter instead of the builtins. For python2.3-2.4,
420 # this brings in behavior like 2.5, and for 2.5 it's identical.
421 __builtin__.exit = Quitter(self,'exit')
422 __builtin__.quit = Quitter(self,'quit')
423
424 309 # Make an empty namespace, which extension writers can rely on both
425 310 # existing and NEVER being used by ipython itself. This gives them a
426 311 # convenient location for storing additional information and state
@@ -428,6 +313,54 b' class InteractiveShell(object,Magic):'
428 313 # ipython names that may develop later.
429 314 self.meta = Struct()
430 315
316 # Object variable to store code object waiting execution. This is
317 # used mainly by the multithreaded shells, but it can come in handy in
318 # other situations. No need to use a Queue here, since it's a single
319 # item which gets cleared once run.
320 self.code_to_run = None
321
322 # Flag to mark unconditional exit
323 self.exit_now = False
324
325 # Temporary files used for various purposes. Deleted at exit.
326 self.tempfiles = []
327
328 # Keep track of readline usage (later set by init_readline)
329 self.has_readline = False
330
331 # keep track of where we started running (mainly for crash post-mortem)
332 # This is not being used anywhere currently.
333 self.starting_dir = os.getcwd()
334
335 # Indentation management
336 self.indent_current_nsp = 0
337
338 def init_usage(self, usage=None):
339 if usage is None:
340 self.usage = interactive_usage
341 else:
342 self.usage = usage
343
344 def init_banner(self, banner2):
345 if self.c: # regular python doesn't print the banner with -c
346 self.display_banner = False
347 bp = banner_parts
348 if self.profile:
349 bp.append('IPython profile: %s\n' % self.profile)
350 if banner2 is not None:
351 bp.append(banner2)
352 self.banner = '\n'.join(bp)
353
354 def init_embedded(self, embedded):
355 # We need to know whether the instance is meant for embedding, since
356 # global/local namespaces need to be handled differently in that case
357 self.embedded = embedded
358 if embedded:
359 # Control variable so users can, from within the embedded instance,
360 # permanently deactivate it.
361 self.embedded_active = True
362
363 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
431 364 # Create the namespace where the user will operate. user_ns is
432 365 # normally the only one used, and it is passed to the exec calls as
433 366 # the locals argument. But we do carry a user_global_ns namespace
@@ -547,16 +480,15 b' class InteractiveShell(object,Magic):'
547 480 # shouldn't overtake the execution environment of the script they're
548 481 # embedded in).
549 482
550 if not embedded:
483 if not self.embedded:
551 484 try:
552 485 main_name = self.user_ns['__name__']
553 486 except KeyError:
554 487 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
555 488 else:
556 #print "pickle hack in place" # dbg
557 #print 'main_name:',main_name # dbg
558 489 sys.modules[main_name] = FakeModule(self.user_ns)
559
490
491 def init_history(self):
560 492 # List of input with multi-line handling.
561 493 self.input_hist = InputList()
562 494 # This one will hold the 'raw' input history, without any
@@ -573,6 +505,14 b' class InteractiveShell(object,Magic):'
573 505 # dict of output history
574 506 self.output_hist = {}
575 507
508 # Now the history file
509 try:
510 histfname = 'history-%s' % self.config.PROFILE
511 except AttributeError:
512 histfname = 'history'
513 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
514
515 def init_encoding(self):
576 516 # Get system encoding at startup time. Certain terminals (like Emacs
577 517 # under Win32 have it set to None, and we need to have a known valid
578 518 # encoding to use in the raw_input() method
@@ -581,20 +521,7 b' class InteractiveShell(object,Magic):'
581 521 except AttributeError:
582 522 self.stdin_encoding = 'ascii'
583 523
584 # dict of things NOT to alias (keywords, builtins and some magics)
585 no_alias = {}
586 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
587 for key in keyword.kwlist + no_alias_magics:
588 no_alias[key] = 1
589 no_alias.update(__builtin__.__dict__)
590 self.no_alias = no_alias
591
592 # Object variable to store code object waiting execution. This is
593 # used mainly by the multithreaded shells, but it can come in handy in
594 # other situations. No need to use a Queue here, since it's a single
595 # item which gets cleared once run.
596 self.code_to_run = None
597
524 def init_handlers(self):
598 525 # escapes for automatic behavior on the command line
599 526 self.ESC_SHELL = '!'
600 527 self.ESC_SH_CAP = '!!'
@@ -614,13 +541,12 b' class InteractiveShell(object,Magic):'
614 541 self.ESC_SH_CAP : self.handle_shell_escape,
615 542 }
616 543
617 # class initializations
618 Magic.__init__(self,self)
619
544 def init_syntax_highlighting(self):
620 545 # Python source parser/formatter for syntax highlighting
621 546 pyformat = PyColorize.Parser().format
622 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
547 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
623 548
549 def init_hooks(self):
624 550 # hooks holds pointers used for user-side customizations
625 551 self.hooks = Struct()
626 552
@@ -633,81 +559,17 b' class InteractiveShell(object,Magic):'
633 559 # default hooks have priority 100, i.e. low; user hooks should have
634 560 # 0-100 priority
635 561 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
636 #print "bound hook",hook_name
637
638 # Flag to mark unconditional exit
639 self.exit_now = False
640
641 self.usage_min = """\
642 An enhanced console for Python.
643 Some of its features are:
644 - Readline support if the readline library is present.
645 - Tab completion in the local namespace.
646 - Logging of input, see command-line options.
647 - System shell escape via ! , eg !ls.
648 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
649 - Keeps track of locally defined variables via %who, %whos.
650 - Show object information with a ? eg ?x or x? (use ?? for more info).
651 """
652 if usage: self.usage = usage
653 else: self.usage = self.usage_min
654
655 # Storage
656 self.rc = rc # This will hold all configuration information
657 self.pager = 'less'
658 # temporary files used for various purposes. Deleted at exit.
659 self.tempfiles = []
660 562
661 # Keep track of readline usage (later set by init_readline)
662 self.has_readline = False
663
664 # template for logfile headers. It gets resolved at runtime by the
665 # logstart method.
666 self.loghead_tpl = \
667 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
668 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
669 #log# opts = %s
670 #log# args = %s
671 #log# It is safe to make manual edits below here.
672 #log#-----------------------------------------------------------------------
673 """
563 def init_pushd_popd_magic(self):
674 564 # for pushd/popd management
675 565 try:
676 566 self.home_dir = get_home_dir()
677 except HomeDirError,msg:
567 except HomeDirError, msg:
678 568 fatal(msg)
679 569
680 570 self.dir_stack = []
681 571
682 # Functions to call the underlying shell.
683
684 # The first is similar to os.system, but it doesn't return a value,
685 # and it allows interpolation of variables in the user's namespace.
686 self.system = lambda cmd: \
687 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
688
689 # These are for getoutput and getoutputerror:
690 self.getoutput = lambda cmd: \
691 getoutput(self.var_expand(cmd,depth=2),
692 header=self.rc.system_header,
693 verbose=self.rc.system_verbose)
694
695 self.getoutputerror = lambda cmd: \
696 getoutputerror(self.var_expand(cmd,depth=2),
697 header=self.rc.system_header,
698 verbose=self.rc.system_verbose)
699
700
701 # keep track of where we started running (mainly for crash post-mortem)
702 self.starting_dir = os.getcwd()
703
704 # Various switches which can be set
705 self.CACHELENGTH = 5000 # this is cheap, it's just text
706 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
707 self.banner2 = banner2
708
709 # TraceBack handlers:
710
572 def init_traceback_handlers(self, custom_exceptions):
711 573 # Syntax error handler.
712 574 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
713 575
@@ -734,9 +596,37 b' class InteractiveShell(object,Magic):'
734 596 # and add any custom exception handlers the user may have specified
735 597 self.set_custom_exc(*custom_exceptions)
736 598
737 # indentation management
738 self.autoindent = False
739 self.indent_current_nsp = 0
599 def init_logger(self):
600 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
601 # local shortcut, this is used a LOT
602 self.log = self.logger.log
603 # template for logfile headers. It gets resolved at runtime by the
604 # logstart method.
605 self.loghead_tpl = \
606 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
607 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
608 #log# opts = %s
609 #log# args = %s
610 #log# It is safe to make manual edits below here.
611 #log#-----------------------------------------------------------------------
612 """
613
614 def init_logstart(self):
615 if self.logplay:
616 IP.magic_logstart(self.logplay + ' append')
617 elif self.logfile:
618 IP.magic_logstart(self.logfile)
619 elif self.logstart:
620 self.magic_logstart()
621
622 def init_aliases(self):
623 # dict of things NOT to alias (keywords, builtins and some magics)
624 no_alias = {}
625 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
626 for key in keyword.kwlist + no_alias_magics:
627 no_alias[key] = 1
628 no_alias.update(__builtin__.__dict__)
629 self.no_alias = no_alias
740 630
741 631 # Make some aliases automatically
742 632 # Prepare list of shell aliases to auto-define
@@ -783,15 +673,15 b' class InteractiveShell(object,Magic):'
783 673 auto_alias = ()
784 674 self.auto_alias = [s.split(None,1) for s in auto_alias]
785 675
786 # Produce a public API instance
787 self.api = ipapi.IPApi(self)
676 # Load default aliases
677 for alias, cmd in self.auto_alias:
678 self.define_alias(alias,cmd)
788 679
789 # Initialize all user-visible namespaces
790 self.init_namespaces()
791
792 # Call the actual (public) initializer
793 self.init_auto_alias()
680 # Load user aliases
681 for alias in self.alias:
682 self.magic_alias(alias)
794 683
684 def init_builtins(self):
795 685 # track which builtins we add, so we can clean up later
796 686 self.builtins_added = {}
797 687 # This method will add the necessary builtins for operation, but
@@ -799,42 +689,17 b' class InteractiveShell(object,Magic):'
799 689
800 690 #TODO: remove this, redundant
801 691 self.add_builtins()
802 # end __init__
803 692
804 def var_expand(self,cmd,depth=0):
805 """Expand python variables in a string.
806
807 The depth argument indicates how many frames above the caller should
808 be walked to look for the local namespace where to expand variables.
809
810 The global namespace for expansion is always the user's interactive
811 namespace.
812 """
813
814 return str(ItplNS(cmd,
815 self.user_ns, # globals
816 # Skip our own frame in searching for locals:
817 sys._getframe(depth+1).f_locals # locals
818 ))
819
820 def pre_config_initialization(self):
821 """Pre-configuration init method
822
823 This is called before the configuration files are processed to
824 prepare the services the config files might need.
825
826 self.rc already has reasonable default values at this point.
827 """
828 rc = self.rc
693 def init_shadow_hist(self):
829 694 try:
830 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
695 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
831 696 except exceptions.UnicodeDecodeError:
832 697 print "Your ipythondir can't be decoded to unicode!"
833 698 print "Please set HOME environment variable to something that"
834 699 print r"only has ASCII characters, e.g. c:\home"
835 print "Now it is",rc.ipythondir
700 print "Now it is", self.config.IPYTHONDIR
836 701 sys.exit()
837 self.shadowhist = IPython.core.history.ShadowHist(self.db)
702 self.shadowhist = ipcorehist.ShadowHist(self.db)
838 703
839 704 def post_config_initialization(self):
840 705 """Post configuration init method
@@ -842,34 +707,29 b' class InteractiveShell(object,Magic):'
842 707 This is called after the configuration files have been processed to
843 708 'finalize' the initialization."""
844 709
845 rc = self.rc
846
847 710 # Object inspector
848 711 self.inspector = oinspect.Inspector(oinspect.InspectColors,
849 712 PyColorize.ANSICodeColors,
850 713 'NoColor',
851 rc.object_info_string_level)
714 self.object_info_string_level)
852 715
853 716 self.rl_next_input = None
854 717 self.rl_do_indent = False
855 718 # Load readline proper
856 if rc.readline:
719 if self.readline_use:
857 720 self.init_readline()
858
859 # local shortcut, this is used a LOT
860 self.log = self.logger.log
861 721
862 722 # Initialize cache, set in/out prompts and printing system
863 723 self.outputcache = CachedOutput(self,
864 rc.cache_size,
865 rc.pprint,
866 input_sep = rc.separate_in,
867 output_sep = rc.separate_out,
868 output_sep2 = rc.separate_out2,
869 ps1 = rc.prompt_in1,
870 ps2 = rc.prompt_in2,
871 ps_out = rc.prompt_out,
872 pad_left = rc.prompts_pad_left)
724 self.cache_size,
725 self.pprint,
726 input_sep = self.separate_in,
727 output_sep = self.separate_out,
728 output_sep2 = self.separate_out2,
729 ps1 = self.prompt_in1,
730 ps2 = self.prompt_in2,
731 ps_out = self.prompt_out,
732 pad_left = self.prompts_pad_left)
873 733
874 734 # user may have over-ridden the default print hook:
875 735 try:
@@ -894,31 +754,30 b' class InteractiveShell(object,Magic):'
894 754
895 755 # Set user colors (don't do it in the constructor above so that it
896 756 # doesn't crash if colors option is invalid)
897 self.magic_colors(rc.colors)
757 self.magic_colors(self.colors)
898 758
899 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 764 self.hooks.late_startup_hook()
907 765
908 for cmd in self.rc.autoexec:
766 for cmd in self.autoexec:
909 767 #print "autoexec>",cmd #dbg
910 768 self.api.runlines(cmd)
911 769
912 770 batchrun = False
913 for batchfile in [path(arg) for arg in self.rc.args
914 if arg.lower().endswith('.ipy')]:
915 if not batchfile.isfile():
916 print "No such batch file:", batchfile
917 continue
918 self.api.runlines(batchfile.text())
919 batchrun = True
771 if self.config.has_key('EXECFILE'):
772 for batchfile in [path(arg) for arg in self.config.EXECFILE
773 if arg.lower().endswith('.ipy')]:
774 if not batchfile.isfile():
775 print "No such batch file:", batchfile
776 continue
777 self.api.runlines(batchfile.text())
778 batchrun = True
920 779 # without -i option, exit after running the batch file
921 if batchrun and not self.rc.interact:
780 if batchrun and not self.interactive:
922 781 self.ask_exit()
923 782
924 783 def init_namespaces(self):
@@ -960,7 +819,14 b' class InteractiveShell(object,Magic):'
960 819 Some parts of ipython operate via builtins injected here, which hold a
961 820 reference to IPython itself."""
962 821
963 # TODO: deprecate all of these, they are unsafe
822 # Install our own quitter instead of the builtins.
823 # This used to be in the __init__ method, but this is a better
824 # place for it. These can be incorporated to the logic below
825 # when it is refactored.
826 __builtin__.exit = Quitter(self,'exit')
827 __builtin__.quit = Quitter(self,'quit')
828
829 # TODO: deprecate all of these, they are unsafe. Why though?
964 830 builtins_new = dict(__IPYTHON__ = self,
965 831 ip_set_hook = self.set_hook,
966 832 jobs = self.jobs,
@@ -1176,6 +1042,26 b' class InteractiveShell(object,Magic):'
1176 1042 magic_args = self.var_expand(magic_args,1)
1177 1043 return fn(magic_args)
1178 1044
1045 def define_alias(self, name, cmd):
1046 """ Define a new alias."""
1047
1048 if callable(cmd):
1049 self.alias_table[name] = cmd
1050 from IPython.core import shadowns
1051 setattr(shadowns, name, cmd)
1052 return
1053
1054 if isinstance(cmd, basestring):
1055 nargs = cmd.count('%s')
1056 if nargs>0 and cmd.find('%l')>=0:
1057 raise Exception('The %s and %l specifiers are mutually '
1058 'exclusive in alias definitions.')
1059
1060 self.alias_table[name] = (nargs,cmd)
1061 return
1062
1063 self.alias_table[name] = cmd
1064
1179 1065 def ipalias(self,arg_s):
1180 1066 """Call an alias by name.
1181 1067
@@ -1205,10 +1091,21 b' class InteractiveShell(object,Magic):'
1205 1091 else:
1206 1092 error("Alias `%s` not found." % alias_name)
1207 1093
1208 def ipsystem(self,arg_s):
1094 def system(self, cmd):
1209 1095 """Make a system call, using IPython."""
1096 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1097
1098 ipsystem = system
1210 1099
1211 self.system(arg_s)
1100 def getoutput(self, cmd):
1101 return getoutput(self.var_expand(cmd,depth=2),
1102 header=self.system_header,
1103 verbose=self.system_verbose)
1104
1105 def getoutputerror(self, cmd):
1106 return getoutputerror(self.var_expand(cmd,depth=2),
1107 header=self.system_header,
1108 verbose=self.system_verbose)
1212 1109
1213 1110 def complete(self,text):
1214 1111 """Return a sorted list of all possible completions on text.
@@ -1299,28 +1196,6 b' class InteractiveShell(object,Magic):'
1299 1196 else:
1300 1197 self.autoindent = value
1301 1198
1302 def rc_set_toggle(self,rc_field,value=None):
1303 """Set or toggle a field in IPython's rc config. structure.
1304
1305 If called with no arguments, it acts as a toggle.
1306
1307 If called with a non-existent field, the resulting AttributeError
1308 exception will propagate out."""
1309
1310 rc_val = getattr(self.rc,rc_field)
1311 if value is None:
1312 value = not rc_val
1313 setattr(self.rc,rc_field,value)
1314
1315 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1316 """Install the user configuration directory.
1317
1318 Notes
1319 -----
1320 DEPRECATED: use the top-level user_setup() function instead.
1321 """
1322 return user_setup(ipythondir,rc_suffix,mode)
1323
1324 1199 def atexit_operations(self):
1325 1200 """This will be executed at the time of exit.
1326 1201
@@ -1430,7 +1305,7 b' class InteractiveShell(object,Magic):'
1430 1305 self.Completer = IPCompleter(self,
1431 1306 self.user_ns,
1432 1307 self.user_global_ns,
1433 self.rc.readline_omit__names,
1308 self.readline_omit__names,
1434 1309 self.alias_table)
1435 1310 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1436 1311 self.strdispatchers['complete_command'] = sdisp
@@ -1469,7 +1344,7 b' class InteractiveShell(object,Magic):'
1469 1344 # is being used (as on Leopard) the readline config is
1470 1345 # not run as the syntax for libedit is different.
1471 1346 if not readline.uses_libedit:
1472 for rlcommand in self.rc.readline_parse_and_bind:
1347 for rlcommand in self.readline_parse_and_bind:
1473 1348 #print "loading rl:",rlcommand # dbg
1474 1349 readline.parse_and_bind(rlcommand)
1475 1350
@@ -1477,7 +1352,7 b' class InteractiveShell(object,Magic):'
1477 1352 # unicode chars, discard them.
1478 1353 delims = readline.get_completer_delims().encode("ascii", "ignore")
1479 1354 delims = delims.translate(string._idmap,
1480 self.rc.readline_remove_delims)
1355 self.readline_remove_delims)
1481 1356 readline.set_completer_delims(delims)
1482 1357 # otherwise we end up with a monster history after a while:
1483 1358 readline.set_history_length(1000)
@@ -1491,10 +1366,10 b' class InteractiveShell(object,Magic):'
1491 1366 del atexit
1492 1367
1493 1368 # Configure auto-indent for all platforms
1494 self.set_autoindent(self.rc.autoindent)
1369 self.set_autoindent(self.autoindent)
1495 1370
1496 1371 def ask_yes_no(self,prompt,default=True):
1497 if self.rc.quiet:
1372 if self.quiet:
1498 1373 return True
1499 1374 return ask_yes_no(prompt,default)
1500 1375
@@ -1577,7 +1452,7 b' class InteractiveShell(object,Magic):'
1577 1452
1578 1453 return False
1579 1454 try:
1580 if (self.rc.autoedit_syntax and
1455 if (self.autoedit_syntax and
1581 1456 not self.ask_yes_no('Return to editor to correct syntax error? '
1582 1457 '[Y/n] ','y')):
1583 1458 return False
@@ -1728,22 +1603,18 b' class InteractiveShell(object,Magic):'
1728 1603 except KeyboardInterrupt:
1729 1604 self.write("\nKeyboardInterrupt\n")
1730 1605
1731 def mainloop(self,banner=None):
1732 """Creates the local namespace and starts the mainloop.
1606 def mainloop(self, banner=None):
1607 """Start the mainloop.
1733 1608
1734 1609 If an optional banner argument is given, it will override the
1735 internally created default banner."""
1736
1737 if self.rc.c: # Emulate Python's -c option
1610 internally created default banner.
1611 """
1612 if self.c: # Emulate Python's -c option
1738 1613 self.exec_init_cmd()
1739 if banner is None:
1740 if not self.rc.banner:
1741 banner = ''
1742 # banner is string? Use it directly!
1743 elif isinstance(self.rc.banner,basestring):
1744 banner = self.rc.banner
1745 else:
1746 banner = self.BANNER+self.banner2
1614
1615 if self.display_banner:
1616 if banner is None:
1617 banner = self.banner
1747 1618
1748 1619 # if you run stuff with -c <cmd>, raw hist is not updated
1749 1620 # ensure that it's in sync
@@ -1752,12 +1623,10 b' class InteractiveShell(object,Magic):'
1752 1623
1753 1624 while 1:
1754 1625 try:
1755 self.interact(banner)
1626 self.interact()
1756 1627 #self.interact_with_readline()
1757
1758 1628 # XXX for testing of a readline-decoupled repl loop, call
1759 1629 # interact_with_readline above
1760
1761 1630 break
1762 1631 except KeyboardInterrupt:
1763 1632 # this should not be necessary, but KeyboardInterrupt
@@ -1770,8 +1639,8 b' class InteractiveShell(object,Magic):'
1770 1639 This emulates Python's -c option."""
1771 1640
1772 1641 #sys.argv = ['-c']
1773 self.push(self.prefilter(self.rc.c, False))
1774 if not self.rc.interact:
1642 self.push(self.prefilter(self.c, False))
1643 if not self.interactive:
1775 1644 self.ask_exit()
1776 1645
1777 1646 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
@@ -1885,7 +1754,7 b' class InteractiveShell(object,Magic):'
1885 1754
1886 1755 self.more = self.push(lineout)
1887 1756 if (self.SyntaxTB.last_syntax_error and
1888 self.rc.autoedit_syntax):
1757 self.autoedit_syntax):
1889 1758 self.edit_syntax_error()
1890 1759
1891 1760 def interact_with_readline(self):
@@ -1904,28 +1773,16 b' class InteractiveShell(object,Magic):'
1904 1773 line = raw_input_original().decode(self.stdin_encoding)
1905 1774 self.interact_handle_input(line)
1906 1775
1907
1908 1776 def interact(self, banner=None):
1909 """Closely emulate the interactive Python console.
1777 """Closely emulate the interactive Python console."""
1910 1778
1911 The optional banner argument specify the banner to print
1912 before the first interaction; by default it prints a banner
1913 similar to the one printed by the real Python interpreter,
1914 followed by the current class name in parentheses (so as not
1915 to confuse this with the real interpreter -- since it's so
1916 close!).
1917
1918 """
1919
1779 # batch run -> do not interact
1920 1780 if self.exit_now:
1921 # batch run -> do not interact
1922 1781 return
1923 cprt = 'Type "copyright", "credits" or "license" for more information.'
1924 if banner is None:
1925 self.write("Python %s on %s\n%s\n(%s)\n" %
1926 (sys.version, sys.platform, cprt,
1927 self.__class__.__name__))
1928 else:
1782
1783 if self.display_banner:
1784 if banner is None:
1785 banner = self.banner
1929 1786 self.write(banner)
1930 1787
1931 1788 more = 0
@@ -1954,7 +1811,7 b' class InteractiveShell(object,Magic):'
1954 1811 except:
1955 1812 self.showtraceback()
1956 1813 try:
1957 line = self.raw_input(prompt,more)
1814 line = self.raw_input(prompt, more)
1958 1815 if self.exit_now:
1959 1816 # quick exit on sys.std[in|out] close
1960 1817 break
@@ -1992,7 +1849,7 b' class InteractiveShell(object,Magic):'
1992 1849 else:
1993 1850 more = self.push(line)
1994 1851 if (self.SyntaxTB.last_syntax_error and
1995 self.rc.autoedit_syntax):
1852 self.autoedit_syntax):
1996 1853 self.edit_syntax_error()
1997 1854
1998 1855 # We are off again...
@@ -2419,7 +2276,7 b' class InteractiveShell(object,Magic):'
2419 2276
2420 2277 # print '***cont',continue_prompt # dbg
2421 2278 # special handlers are only allowed for single line statements
2422 if continue_prompt and not self.rc.multi_line_specials:
2279 if continue_prompt and not self.multi_line_specials:
2423 2280 return self.handle_normal(line_info)
2424 2281
2425 2282
@@ -2565,7 +2422,7 b' class InteractiveShell(object,Magic):'
2565 2422 # We only apply it to argument-less calls if the autocall
2566 2423 # parameter is set to 2. We only need to check that autocall is <
2567 2424 # 2, since this function isn't called unless it's at least 1.
2568 if not theRest and (self.rc.autocall < 2) and not force_auto:
2425 if not theRest and (self.autocall < 2) and not force_auto:
2569 2426 newcmd = '%s %s' % (iFun,theRest)
2570 2427 auto_rewrite = False
2571 2428 else:
@@ -2623,7 +2480,7 b' class InteractiveShell(object,Magic):'
2623 2480 #print 'line:<%r>' % line # dbg
2624 2481 self.magic_pinfo(line)
2625 2482 else:
2626 page(self.usage,screen_lines=self.rc.screen_length)
2483 page(self.usage,screen_lines=self.screen_length)
2627 2484 return '' # Empty string is needed here!
2628 2485 except:
2629 2486 # Pass any other exceptions through to the normal handler
@@ -2653,6 +2510,21 b' class InteractiveShell(object,Magic):'
2653 2510 # The input cache shouldn't be updated
2654 2511 return line_info.line
2655 2512
2513 def var_expand(self,cmd,depth=0):
2514 """Expand python variables in a string.
2515
2516 The depth argument indicates how many frames above the caller should
2517 be walked to look for the local namespace where to expand variables.
2518
2519 The global namespace for expansion is always the user's interactive
2520 namespace.
2521 """
2522
2523 return str(ItplNS(cmd,
2524 self.user_ns, # globals
2525 # Skip our own frame in searching for locals:
2526 sys._getframe(depth+1).f_locals # locals
2527 ))
2656 2528
2657 2529 def mktempfile(self,data=None):
2658 2530 """Make a new tempfile and return its filename.
@@ -2690,8 +2562,8 b' class InteractiveShell(object,Magic):'
2690 2562 """Handle interactive exit.
2691 2563
2692 2564 This method calls the ask_exit callback."""
2693
2694 if self.rc.confirm_exit:
2565 print "IN self.exit", self.confirm_exit
2566 if self.confirm_exit:
2695 2567 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2696 2568 self.ask_exit()
2697 2569 else:
@@ -47,6 +47,7 b' import warnings'
47 47 # Our own
48 48 from IPython.utils import DPyGetOpt
49 49 from IPython.core import release
50 from IPython.core.oldusersetup import user_setup
50 51 from IPython.utils.ipstruct import Struct
51 52 from IPython.core.outputtrap import OutputTrap
52 53 from IPython.config.configloader import ConfigLoader
@@ -356,11 +357,11 b" object? -> Details about 'object'. ?object also works, ?? prints more."
356 357 # Create user config directory if it doesn't exist. This must be done
357 358 # *after* getting the cmd line options.
358 359 if not os.path.isdir(opts_all.ipythondir):
359 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
360 user_setup(opts_all.ipythondir,rc_suffix,'install')
360 361
361 362 # upgrade user config files while preserving a copy of the originals
362 363 if opts_all.upgrade:
363 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
364 user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
364 365
365 366 # check mutually exclusive options in the *original* command line
366 367 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
@@ -378,7 +378,7 b' python-profiler package from non-free.""")'
378 378 mesc = self.shell.ESC_MAGIC
379 379 print 'Available magic functions:\n'+mesc+\
380 380 (' '+mesc).join(self.lsmagic())
381 print '\n' + Magic.auto_status[self.shell.rc.automagic]
381 print '\n' + Magic.auto_status[self.shell.automagic]
382 382 return None
383 383
384 384 def magic_magic(self, parameter_s = ''):
@@ -483,9 +483,9 b' Currently the magic system has the following functions:\\n"""'
483 483 "\n\n%s%s\n\n%s" % (outmsg,
484 484 magic_docs,mesc,mesc,
485 485 (' '+mesc).join(self.lsmagic()),
486 Magic.auto_status[self.shell.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 491 def magic_autoindent(self, parameter_s = ''):
@@ -512,15 +512,14 b' Currently the magic system has the following functions:\\n"""'
512 512 delete the variable (del var), the previously shadowed magic function
513 513 becomes visible to automagic again."""
514 514
515 rc = self.shell.rc
516 515 arg = parameter_s.lower()
517 516 if parameter_s in ('on','1','true'):
518 rc.automagic = True
517 self.shell.automagic = True
519 518 elif parameter_s in ('off','0','false'):
520 rc.automagic = False
519 self.shell.automagic = False
521 520 else:
522 rc.automagic = not rc.automagic
523 print '\n' + Magic.auto_status[rc.automagic]
521 self.shell.automagic = not self.shell.automagic
522 print '\n' + Magic.auto_status[self.shell.automagic]
524 523
525 524 @testdec.skip_doctest
526 525 def magic_autocall(self, parameter_s = ''):
@@ -566,8 +565,6 b' Currently the magic system has the following functions:\\n"""'
566 565 # all-random (note for auto-testing)
567 566 """
568 567
569 rc = self.shell.rc
570
571 568 if parameter_s:
572 569 arg = int(parameter_s)
573 570 else:
@@ -578,18 +575,18 b' Currently the magic system has the following functions:\\n"""'
578 575 return
579 576
580 577 if arg in (0,1,2):
581 rc.autocall = arg
578 self.shell.autocall = arg
582 579 else: # toggle
583 if rc.autocall:
584 self._magic_state.autocall_save = rc.autocall
585 rc.autocall = 0
580 if self.shell.autocall:
581 self._magic_state.autocall_save = self.shell.autocall
582 self.shell.autocall = 0
586 583 else:
587 584 try:
588 rc.autocall = self._magic_state.autocall_save
585 self.shell.autocall = self._magic_state.autocall_save
589 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 591 def magic_system_verbose(self, parameter_s = ''):
595 592 """Set verbose printing of system calls.
@@ -600,10 +597,13 b' Currently the magic system has the following functions:\\n"""'
600 597 val = bool(eval(parameter_s))
601 598 else:
602 599 val = None
603
604 self.shell.rc_set_toggle('system_verbose',val)
600
601 if self.shell.system_verbose:
602 self.shell.system_verbose = False
603 else:
604 self.shell.system_verbose = True
605 605 print "System verbose printing is:",\
606 ['OFF','ON'][self.shell.rc.system_verbose]
606 ['OFF','ON'][self.shell.system_verbose]
607 607
608 608
609 609 def magic_page(self, parameter_s=''):
@@ -633,8 +633,8 b' Currently the magic system has the following functions:\\n"""'
633 633
634 634 def magic_profile(self, parameter_s=''):
635 635 """Print your currently active IPyhton profile."""
636 if self.shell.rc.profile:
637 printpl('Current IPython profile: $self.shell.rc.profile.')
636 if self.shell.profile:
637 printpl('Current IPython profile: $self.shell.profile.')
638 638 else:
639 639 print 'No profile active.'
640 640
@@ -848,7 +848,7 b' Currently the magic system has the following functions:\\n"""'
848 848 elif opts.has_key('c'):
849 849 ignore_case = False
850 850 else:
851 ignore_case = not shell.rc.wildcards_case_sensitive
851 ignore_case = not shell.wildcards_case_sensitive
852 852
853 853 # Build list of namespaces to search from user options
854 854 def_search.extend(opt('s',[]))
@@ -1132,7 +1132,6 b' Currently the magic system has the following functions:\\n"""'
1132 1132 log_raw_input = 'r' in opts
1133 1133 timestamp = 't' in opts
1134 1134
1135 rc = self.shell.rc
1136 1135 logger = self.shell.logger
1137 1136
1138 1137 # if no args are given, the defaults set in the logger constructor by
@@ -1149,11 +1148,14 b' Currently the magic system has the following functions:\\n"""'
1149 1148 # put logfname into rc struct as if it had been called on the command
1150 1149 # line, so it ends up saved in the log header Save it in case we need
1151 1150 # to restore it...
1152 old_logfile = rc.opts.get('logfile','')
1151 old_logfile = self.shell.logfile
1153 1152 if logfname:
1154 1153 logfname = os.path.expanduser(logfname)
1155 rc.opts.logfile = logfname
1156 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1154 self.shell.logfile = logfname
1155 # TODO: we need to re-think how logs with args/opts are replayed
1156 # and tracked.
1157 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1158 loghead = self.shell.loghead_tpl % ('','')
1157 1159 try:
1158 1160 started = logger.logstart(logfname,loghead,logmode,
1159 1161 log_output,timestamp,log_raw_input)
@@ -1421,7 +1423,7 b' Currently the magic system has the following functions:\\n"""'
1421 1423 output = stdout_trap.getvalue()
1422 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 1427 print sys_exit,
1426 1428
1427 1429 dump_file = opts.D[0]
@@ -1622,7 +1624,7 b' Currently the magic system has the following functions:\\n"""'
1622 1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1623 1625 else:
1624 1626 if opts.has_key('d'):
1625 deb = debugger.Pdb(self.shell.rc.colors)
1627 deb = debugger.Pdb(self.shell.colors)
1626 1628 # reset Breakpoint state, which is moronically kept
1627 1629 # in a class
1628 1630 bdb.Breakpoint.next = 1
@@ -2492,7 +2494,7 b' Defaulting color scheme to \'NoColor\'"""'
2492 2494 except:
2493 2495 color_switch_err('prompt')
2494 2496 else:
2495 shell.rc.colors = \
2497 shell.colors = \
2496 2498 shell.outputcache.color_table.active_scheme_name
2497 2499 # Set exception colors
2498 2500 try:
@@ -2509,7 +2511,7 b' Defaulting color scheme to \'NoColor\'"""'
2509 2511 color_switch_err('system exception handler')
2510 2512
2511 2513 # Set info (for 'object?') colors
2512 if shell.rc.color_info:
2514 if shell.color_info:
2513 2515 try:
2514 2516 shell.inspector.set_active_scheme(new_scheme)
2515 2517 except:
@@ -2528,17 +2530,17 b' Defaulting color scheme to \'NoColor\'"""'
2528 2530 than more) in your system, using colored object information displays
2529 2531 will not work properly. Test it and see."""
2530 2532
2531 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2532 self.magic_colors(self.shell.rc.colors)
2533 self.shell.color_info = 1 - self.shell.color_info
2534 self.magic_colors(self.shell.colors)
2533 2535 print 'Object introspection functions have now coloring:',
2534 print ['OFF','ON'][self.shell.rc.color_info]
2536 print ['OFF','ON'][self.shell.color_info]
2535 2537
2536 2538 def magic_Pprint(self, parameter_s=''):
2537 2539 """Toggle pretty printing on/off."""
2538 2540
2539 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2541 self.shell.pprint = 1 - self.shell.pprint
2540 2542 print 'Pretty printing has been turned', \
2541 ['OFF','ON'][self.shell.rc.pprint]
2543 ['OFF','ON'][self.shell.pprint]
2542 2544
2543 2545 def magic_exit(self, parameter_s=''):
2544 2546 """Exit IPython, confirming if configured to do so.
@@ -2853,8 +2855,8 b' Defaulting color scheme to \'NoColor\'"""'
2853 2855 if ps:
2854 2856 try:
2855 2857 os.chdir(os.path.expanduser(ps))
2856 if self.shell.rc.term_title:
2857 #print 'set term title:',self.shell.rc.term_title # dbg
2858 if self.shell.term_title:
2859 #print 'set term title:',self.shell.term_title # dbg
2858 2860 platutils.set_term_title('IPy ' + abbrev_cwd())
2859 2861 except OSError:
2860 2862 print sys.exc_info()[1]
@@ -2867,7 +2869,7 b' Defaulting color scheme to \'NoColor\'"""'
2867 2869
2868 2870 else:
2869 2871 os.chdir(self.shell.home_dir)
2870 if self.shell.rc.term_title:
2872 if self.shell.term_title:
2871 2873 platutils.set_term_title("IPy ~")
2872 2874 cwd = os.getcwd()
2873 2875 dhist = self.shell.user_ns['_dh']
@@ -3171,7 +3173,7 b' Defaulting color scheme to \'NoColor\'"""'
3171 3173 esc_magic = self.shell.ESC_MAGIC
3172 3174 # Identify magic commands even if automagic is on (which means
3173 3175 # the in-memory version is different from that typed by the user).
3174 if self.shell.rc.automagic:
3176 if self.shell.automagic:
3175 3177 start_magic = esc_magic+start
3176 3178 else:
3177 3179 start_magic = start
@@ -3265,7 +3267,7 b' Defaulting color scheme to \'NoColor\'"""'
3265 3267 return
3266 3268
3267 3269 page(self.shell.pycolorize(cont),
3268 screen_lines=self.shell.rc.screen_length)
3270 screen_lines=self.shell.screen_length)
3269 3271
3270 3272 def _rerun_pasted(self):
3271 3273 """ Rerun a previously pasted command.
@@ -3438,7 +3440,7 b' Defaulting color scheme to \'NoColor\'"""'
3438 3440 ipinstallation = path(IPython.__file__).dirname()
3439 3441 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3440 3442 src_config = ipinstallation / 'config' / 'userconfig'
3441 userdir = path(ip.options.ipythondir)
3443 userdir = path(ip.options.IPYTHONDIR)
3442 3444 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3443 3445 print ">",cmd
3444 3446 shell(cmd)
@@ -3478,7 +3480,6 b' Defaulting color scheme to \'NoColor\'"""'
3478 3480 # Shorthands
3479 3481 shell = self.shell
3480 3482 oc = shell.outputcache
3481 rc = shell.rc
3482 3483 meta = shell.meta
3483 3484 # dstore is a data store kept in the instance metadata bag to track any
3484 3485 # changes we make, so we can undo them later.
@@ -3487,12 +3488,12 b' Defaulting color scheme to \'NoColor\'"""'
3487 3488
3488 3489 # save a few values we'll need to recover later
3489 3490 mode = save_dstore('mode',False)
3490 save_dstore('rc_pprint',rc.pprint)
3491 save_dstore('rc_pprint',shell.pprint)
3491 3492 save_dstore('xmode',shell.InteractiveTB.mode)
3492 save_dstore('rc_separate_out',rc.separate_out)
3493 save_dstore('rc_separate_out2',rc.separate_out2)
3494 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3495 save_dstore('rc_separate_in',rc.separate_in)
3493 save_dstore('rc_separate_out',shell.separate_out)
3494 save_dstore('rc_separate_out2',shell.separate_out2)
3495 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3496 save_dstore('rc_separate_in',shell.separate_in)
3496 3497
3497 3498 if mode == False:
3498 3499 # turn on
@@ -3510,7 +3511,7 b' Defaulting color scheme to \'NoColor\'"""'
3510 3511 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3511 3512 oc.prompt_out.pad_left = False
3512 3513
3513 rc.pprint = False
3514 shell.pprint = False
3514 3515
3515 3516 shell.magic_xmode('Plain')
3516 3517
@@ -3518,9 +3519,9 b' Defaulting color scheme to \'NoColor\'"""'
3518 3519 # turn off
3519 3520 ipaste.deactivate_prefilter()
3520 3521
3521 oc.prompt1.p_template = rc.prompt_in1
3522 oc.prompt2.p_template = rc.prompt_in2
3523 oc.prompt_out.p_template = rc.prompt_out
3522 oc.prompt1.p_template = shell.prompt_in1
3523 oc.prompt2.p_template = shell.prompt_in2
3524 oc.prompt_out.p_template = shell.prompt_out
3524 3525
3525 3526 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3526 3527
@@ -191,7 +191,7 b' def checkMultiLineMagic(l_info,ip):'
191 191 # iFun and *not* the preChar. Also note that the below test matches
192 192 # both ! and !!.
193 193 if l_info.continue_prompt \
194 and ip.rc.multi_line_specials:
194 and ip.multi_line_specials:
195 195 if l_info.iFun.startswith(ip.ESC_MAGIC):
196 196 return ip.handle_magic
197 197 else:
@@ -231,11 +231,11 b' def checkAutomagic(l_info,ip):'
231 231 check_esc_chars. This just checks for automagic. Also, before
232 232 triggering the magic handler, make sure that there is nothing in the
233 233 user namespace which could shadow it."""
234 if not ip.rc.automagic or not hasattr(ip,'magic_'+l_info.iFun):
234 if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun):
235 235 return None
236 236
237 237 # We have a likely magic method. Make sure we should actually call it.
238 if l_info.continue_prompt and not ip.rc.multi_line_specials:
238 if l_info.continue_prompt and not ip.multi_line_specials:
239 239 return None
240 240
241 241 head = l_info.iFun.split('.',1)[0]
@@ -271,7 +271,7 b' def checkPythonOps(l_info,ip):'
271 271
272 272 def checkAutocall(l_info,ip):
273 273 "Check if the initial word/function is callable and autocall is on."
274 if not ip.rc.autocall:
274 if not ip.autocall:
275 275 return None
276 276
277 277 oinfo = l_info.ofind(ip) # This can mutate state via getattr
@@ -159,9 +159,9 b' class IPShellEmbed:'
159 159 sys.displayhook = self.sys_displayhook_ori
160 160 # don't use the ipython crash handler so that user exceptions aren't
161 161 # trapped
162 sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.rc.colors,
163 mode = self.IP.rc.xmode,
164 call_pdb = self.IP.rc.pdb)
162 sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.colors,
163 mode = self.IP.xmode,
164 call_pdb = self.IP.pdb)
165 165 self.restore_system_completer()
166 166
167 167 def restore_system_completer(self):
@@ -15,6 +15,7 b' import nose.tools as nt'
15 15 # our own packages
16 16 from IPython.core import iplib
17 17 from IPython.core import ipapi
18 from IPython.core.oldusersetup import user_setup
18 19
19 20 #-----------------------------------------------------------------------------
20 21 # Globals
@@ -59,12 +60,12 b' def test_reset():'
59 60 # make sure that user_setup can be run re-entrantly in 'install' mode.
60 61 def test_user_setup():
61 62 # use a lambda to pass kwargs to the generator
62 user_setup = lambda a,k: iplib.user_setup(*a,**k)
63 user_setup = lambda a,k: user_setup(*a,**k)
63 64 kw = dict(mode='install', interactive=False)
64 65
65 66 # Call the user setup and verify that the directory exists
66 yield user_setup, (ip.options.ipythondir,''), kw
67 yield os.path.isdir, ip.options.ipythondir
67 yield user_setup, (ip.options.IPYTHONDIR,''), kw
68 yield os.path.isdir, ip.options.IPYTHONDIR
68 69
69 70 # Now repeat the operation with a non-existent directory. Check both that
70 71 # the call succeeds and that the directory is created.
@@ -270,7 +270,7 b' def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):'
270 270 if scheme is None:
271 271 ipinst = ipapi.get()
272 272 if ipinst is not None:
273 scheme = ipinst.IP.rc.colors
273 scheme = ipinst.IP.colors
274 274 else:
275 275 scheme = DEFAULT_SCHEME
276 276
@@ -6,6 +6,9 b''
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 import sys
10 from IPython.core import release
11
9 12 __doc__ = """
10 13 IPython -- An enhanced Interactive Python
11 14 =========================================
@@ -504,6 +507,18 b' MAIN FEATURES'
504 507 >>> x = ,my_function /home/me # syntax error
505 508 """
506 509
510 interactive_usage_min = """\
511 An enhanced console for Python.
512 Some of its features are:
513 - Readline support if the readline library is present.
514 - Tab completion in the local namespace.
515 - Logging of input, see command-line options.
516 - System shell escape via ! , eg !ls.
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
518 - Keeps track of locally defined variables via %who, %whos.
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
520 """
521
507 522 quick_reference = r"""
508 523 IPython -- An enhanced Interactive Python - Quick Reference Card
509 524 ================================================================
@@ -556,3 +571,16 b' or python names.'
556 571 The following magic functions are currently available:
557 572
558 573 """
574
575 quick_guide = """\
576 ? -> Introduction and overview of IPython's features.
577 %quickref -> Quick reference.
578 help -> Python's own help system.
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
580
581 banner_parts = [
582 'Python %s' % (sys.version.split('\n')[0],),
583 'Type "copyright", "credits" or "license" for more information.\n',
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 quick_guide
586 ]
@@ -140,7 +140,7 b' def collect(ip,arg):'
140 140 Without args, try to open ~/_ipython/collect dir (in win32 at least).
141 141 """
142 142 from IPython.external.path import path
143 basedir = path(ip.options.ipythondir + '/collect')
143 basedir = path(ip.options.IPYTHONDIR + '/collect')
144 144 try:
145 145 fs = mglob.expand(arg.split(None,1)[1])
146 146 except IndexError:
@@ -169,7 +169,7 b' def inote(ip,arg):'
169 169 Without args, opens notes.txt for editing.
170 170 """
171 171 import time
172 fname = ip.options.ipythondir + '/notes.txt'
172 fname = ip.options.IPYTHONDIR + '/notes.txt'
173 173
174 174 try:
175 175 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
@@ -18,7 +18,7 b' def call_pydb(self, args):'
18 18 argl = arg_split(args)
19 19 # print argl # dbg
20 20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = debugger.Pdb(color_scheme=self.rc.colors)
21 pdb = debugger.Pdb(color_scheme=self.colors)
22 22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 23 else:
24 24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
@@ -494,7 +494,7 b' class NonBlockingIPShell(object):'
494 494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
495 495 self._iter_more = self._IP.push(line)
496 496 if (self._IP.SyntaxTB.last_syntax_error and \
497 self._IP.rc.autoedit_syntax):
497 self._IP.autoedit_syntax):
498 498 self._IP.edit_syntax_error()
499 499 if self._iter_more:
500 500 self._prompt = str(self._IP.outputcache.prompt2).strip()
@@ -109,7 +109,7 b' class MyFrame(wx.Frame):'
109 109
110 110 def optionSave(self, name, value):
111 111 ip = get()
112 path = ip.IP.rc.ipythondir
112 path = ip.IP.config.IPYTHONDIR
113 113 opt = open(path + '/options.conf','w')
114 114
115 115 try:
@@ -126,7 +126,7 b' class MyFrame(wx.Frame):'
126 126 def optionLoad(self):
127 127 try:
128 128 ip = get()
129 path = ip.IP.rc.ipythondir
129 path = ip.IP.config.IPYTHONDIR
130 130 opt = open(path + '/options.conf','r')
131 131 lines = opt.readlines()
132 132 opt.close()
@@ -39,7 +39,7 b' from IPython.kernel.fcutil import have_crypto'
39 39
40 40 # Create various ipython directories if they don't exist.
41 41 # This must be done before IPython.kernel.config is imported.
42 from IPython.core.iplib import user_setup
42 from IPython.core.oldusersetup import user_setup
43 43 if os.name == 'posix':
44 44 rc_suffix = ''
45 45 else:
@@ -41,7 +41,7 b' from IPython.kernel.fcutil import check_furl_file_security'
41 41
42 42 # Create various ipython directories if they don't exist.
43 43 # This must be done before IPython.kernel.config is imported.
44 from IPython.core.iplib import user_setup
44 from IPython.core.oldusersetup import user_setup
45 45 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
46 46 if os.name == 'posix':
47 47 rc_suffix = ''
@@ -36,7 +36,7 b' from IPython.kernel.engineservice import EngineService'
36 36
37 37 # Create various ipython directories if they don't exist.
38 38 # This must be done before IPython.kernel.config is imported.
39 from IPython.core.iplib import user_setup
39 from IPython.core.oldusersetup import user_setup
40 40 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
41 41 if os.name == 'posix':
42 42 rc_suffix = ''
General Comments 0
You need to be logged in to leave comments. Login now