##// 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 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):
@@ -241,7 +241,7 b' class IPCompleter(Completer):'
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
@@ -124,7 +124,7 b' $self.bug_tracker'
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):
@@ -171,7 +171,7 b' $self.bug_tracker'
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:")
@@ -215,7 +215,7 b' class IPythonCrashHandler(CrashHandler):'
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:")
@@ -69,7 +69,7 b' def editor(self,filename, linenum=None):'
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':
@@ -99,7 +99,7 b' def fix_error_editor(self,filename,linenum,column,msg):'
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()
@@ -167,7 +167,7 b' def result_display(self,arg):'
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
@@ -226,7 +226,7 b' def generate_output_prompt(self):'
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 """
@@ -219,8 +219,7 b' class IPApi(object):'
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
@@ -609,7 +608,7 b' _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
This diff has been collapsed as it changes many lines, (862 lines changed) Show them Hide them
@@ -1,32 +1,21 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
@@ -43,26 +32,36 b' 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)
@@ -72,11 +71,14 b' raw_input_original = raw_input'
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
@@ -86,6 +88,7 b' def num_ini_spaces(strng):'
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
@@ -102,208 +105,8 b' def softspace(file, newvalue):'
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
@@ -357,8 +160,10 b' class SyntaxTB(ultratb.ListTB):'
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
@@ -378,34 +183,122 b' class SyntaxTB(ultratb.ListTB):'
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()
@@ -413,14 +306,6 b' class InteractiveShell(object,Magic):'
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
@@ -428,6 +313,54 b' class InteractiveShell(object,Magic):'
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
@@ -547,16 +480,15 b' class InteractiveShell(object,Magic):'
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
@@ -573,6 +505,14 b' class InteractiveShell(object,Magic):'
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
@@ -581,20 +521,7 b' class InteractiveShell(object,Magic):'
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 = '!!'
@@ -614,13 +541,12 b' class InteractiveShell(object,Magic):'
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
@@ -633,81 +559,17 b' class InteractiveShell(object,Magic):'
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
@@ -734,9 +596,37 b' class InteractiveShell(object,Magic):'
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
@@ -783,15 +673,15 b' class InteractiveShell(object,Magic):'
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
@@ -799,42 +689,17 b' class InteractiveShell(object,Magic):'
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
@@ -842,34 +707,29 b' class InteractiveShell(object,Magic):'
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:
@@ -894,31 +754,30 b' class InteractiveShell(object,Magic):'
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):
@@ -960,7 +819,14 b' class InteractiveShell(object,Magic):'
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,
@@ -1176,6 +1042,26 b' class InteractiveShell(object,Magic):'
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
@@ -1205,10 +1091,21 b' class InteractiveShell(object,Magic):'
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.
@@ -1299,28 +1196,6 b' class InteractiveShell(object,Magic):'
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
@@ -1430,7 +1305,7 b' class InteractiveShell(object,Magic):'
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
@@ -1469,7 +1344,7 b' class InteractiveShell(object,Magic):'
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
@@ -1477,7 +1352,7 b' class InteractiveShell(object,Magic):'
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)
@@ -1491,10 +1366,10 b' class InteractiveShell(object,Magic):'
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
@@ -1577,7 +1452,7 b' class InteractiveShell(object,Magic):'
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
@@ -1728,22 +1603,18 b' class InteractiveShell(object,Magic):'
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
@@ -1752,12 +1623,10 b' class InteractiveShell(object,Magic):'
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
@@ -1770,8 +1639,8 b' class InteractiveShell(object,Magic):'
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):
@@ -1885,7 +1754,7 b' class InteractiveShell(object,Magic):'
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):
@@ -1904,28 +1773,16 b' class InteractiveShell(object,Magic):'
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
@@ -1954,7 +1811,7 b' class InteractiveShell(object,Magic):'
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
@@ -1992,7 +1849,7 b' class InteractiveShell(object,Magic):'
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...
@@ -2419,7 +2276,7 b' class InteractiveShell(object,Magic):'
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
@@ -2565,7 +2422,7 b' class InteractiveShell(object,Magic):'
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:
@@ -2623,7 +2480,7 b' class InteractiveShell(object,Magic):'
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
@@ -2653,6 +2510,21 b' class InteractiveShell(object,Magic):'
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.
@@ -2690,8 +2562,8 b' class InteractiveShell(object,Magic):'
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:
@@ -47,6 +47,7 b' import warnings'
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
@@ -356,11 +357,11 b" object? -> Details about 'object'. ?object also works, ?? prints more."
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'),
@@ -378,7 +378,7 b' python-profiler package from non-free.""")'
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 = ''):
@@ -483,9 +483,9 b' Currently the magic system has the following functions:\\n"""'
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 = ''):
@@ -512,15 +512,14 b' Currently the magic system has the following functions:\\n"""'
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 = ''):
@@ -566,8 +565,6 b' Currently the magic system has the following functions:\\n"""'
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:
@@ -578,18 +575,18 b' Currently the magic system has the following functions:\\n"""'
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.
@@ -600,10 +597,13 b' Currently the magic system has the following functions:\\n"""'
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=''):
@@ -633,8 +633,8 b' Currently the magic system has the following functions:\\n"""'
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
@@ -848,7 +848,7 b' Currently the magic system has the following functions:\\n"""'
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',[]))
@@ -1132,7 +1132,6 b' Currently the magic system has the following functions:\\n"""'
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
@@ -1149,11 +1148,14 b' Currently the magic system has the following functions:\\n"""'
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)
@@ -1421,7 +1423,7 b' Currently the magic system has the following functions:\\n"""'
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]
@@ -1622,7 +1624,7 b' Currently the magic system has the following functions:\\n"""'
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
@@ -2492,7 +2494,7 b' Defaulting color scheme to \'NoColor\'"""'
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:
@@ -2509,7 +2511,7 b' Defaulting color scheme to \'NoColor\'"""'
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:
@@ -2528,17 +2530,17 b' Defaulting color scheme to \'NoColor\'"""'
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.
@@ -2853,8 +2855,8 b' Defaulting color scheme to \'NoColor\'"""'
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]
@@ -2867,7 +2869,7 b' Defaulting color scheme to \'NoColor\'"""'
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']
@@ -3171,7 +3173,7 b' Defaulting color scheme to \'NoColor\'"""'
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
@@ -3265,7 +3267,7 b' Defaulting color scheme to \'NoColor\'"""'
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.
@@ -3438,7 +3440,7 b' Defaulting color scheme to \'NoColor\'"""'
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)
@@ -3478,7 +3480,6 b' Defaulting color scheme to \'NoColor\'"""'
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.
@@ -3487,12 +3488,12 b' Defaulting color scheme to \'NoColor\'"""'
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
@@ -3510,7 +3511,7 b' Defaulting color scheme to \'NoColor\'"""'
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
@@ -3518,9 +3519,9 b' Defaulting color scheme to \'NoColor\'"""'
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
@@ -191,7 +191,7 b' def checkMultiLineMagic(l_info,ip):'
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:
@@ -231,11 +231,11 b' def checkAutomagic(l_info,ip):'
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]
@@ -271,7 +271,7 b' def checkPythonOps(l_info,ip):'
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
@@ -159,9 +159,9 b' class IPShellEmbed:'
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):
@@ -15,6 +15,7 b' import nose.tools as nt'
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
@@ -59,12 +60,12 b' def test_reset():'
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.
@@ -270,7 +270,7 b' def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):'
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
@@ -6,6 +6,9 b''
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 =========================================
@@ -504,6 +507,18 b' MAIN FEATURES'
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 ================================================================
@@ -556,3 +571,16 b' or python names.'
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 ]
@@ -140,7 +140,7 b' def collect(ip,arg):'
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:
@@ -169,7 +169,7 b' def inote(ip,arg):'
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'
@@ -18,7 +18,7 b' def call_pydb(self, args):'
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) )()
@@ -494,7 +494,7 b' class NonBlockingIPShell(object):'
494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
495 self._iter_more = self._IP.push(line)
495 self._iter_more = self._IP.push(line)
496 if (self._IP.SyntaxTB.last_syntax_error and \
496 if (self._IP.SyntaxTB.last_syntax_error and \
497 self._IP.rc.autoedit_syntax):
497 self._IP.autoedit_syntax):
498 self._IP.edit_syntax_error()
498 self._IP.edit_syntax_error()
499 if self._iter_more:
499 if self._iter_more:
500 self._prompt = str(self._IP.outputcache.prompt2).strip()
500 self._prompt = str(self._IP.outputcache.prompt2).strip()
@@ -109,7 +109,7 b' class MyFrame(wx.Frame):'
109
109
110 def optionSave(self, name, value):
110 def optionSave(self, name, value):
111 ip = get()
111 ip = get()
112 path = ip.IP.rc.ipythondir
112 path = ip.IP.config.IPYTHONDIR
113 opt = open(path + '/options.conf','w')
113 opt = open(path + '/options.conf','w')
114
114
115 try:
115 try:
@@ -126,7 +126,7 b' class MyFrame(wx.Frame):'
126 def optionLoad(self):
126 def optionLoad(self):
127 try:
127 try:
128 ip = get()
128 ip = get()
129 path = ip.IP.rc.ipythondir
129 path = ip.IP.config.IPYTHONDIR
130 opt = open(path + '/options.conf','r')
130 opt = open(path + '/options.conf','r')
131 lines = opt.readlines()
131 lines = opt.readlines()
132 opt.close()
132 opt.close()
@@ -39,7 +39,7 b' from IPython.kernel.fcutil import have_crypto'
39
39
40 # Create various ipython directories if they don't exist.
40 # Create various ipython directories if they don't exist.
41 # This must be done before IPython.kernel.config is imported.
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 if os.name == 'posix':
43 if os.name == 'posix':
44 rc_suffix = ''
44 rc_suffix = ''
45 else:
45 else:
@@ -41,7 +41,7 b' from IPython.kernel.fcutil import check_furl_file_security'
41
41
42 # Create various ipython directories if they don't exist.
42 # Create various ipython directories if they don't exist.
43 # This must be done before IPython.kernel.config is imported.
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 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
45 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
46 if os.name == 'posix':
46 if os.name == 'posix':
47 rc_suffix = ''
47 rc_suffix = ''
@@ -36,7 +36,7 b' from IPython.kernel.engineservice import EngineService'
36
36
37 # Create various ipython directories if they don't exist.
37 # Create various ipython directories if they don't exist.
38 # This must be done before IPython.kernel.config is imported.
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 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
40 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
41 if os.name == 'posix':
41 if os.name == 'posix':
42 rc_suffix = ''
42 rc_suffix = ''
General Comments 0
You need to be logged in to leave comments. Login now