##// END OF EJS Templates
config changes
vivainio -
Show More
@@ -0,0 +1,19 b''
1 """ System wide configuration file for IPython.
2
3 This will be imported by ipython for all users.
4
5 After this ipy_user_conf.py is imported, user specific configuration
6 should reside there.
7
8 """
9
10 import IPython.ipapi as ip
11
12 # add system wide configuration information, import extensions etc. here.
13 # nothing here is essential
14
15 import sys
16
17 if sys.version_info >= (2,4):
18 # rehashdir extension requires python 2.4
19 import ext_rehashdir No newline at end of file
@@ -0,0 +1,40 b''
1 """ User configuration file for IPython
2
3 This is a more flexible and safe way to configure ipython than *rc files
4 (ipythonrc, ipythonrc-pysh etc.)
5
6 This file is always imported on ipython startup. You should import all the
7 ipython extensions you need here (see IPython/Extensions directory).
8
9 """
10
11 # see IPython.ipapi for configuration tips
12
13 import IPython.ipapi as ip
14
15
16 o = ip.options()
17 # autocall 1 ('smart') is default anyway, this is just an
18 # example on how to set an option
19 o.autocall = 1
20
21 if o.profile == 'pysh':
22 # Jason Orendorff's path class is handy to have in user namespace
23 # if you are doing shell-like stuff
24 ip.ex("from IPython.path import path" )
25
26 # get pysh-like prompt for all profiles. Comment these out for "old style"
27 # prompts, as determined by *rc files
28
29 o.prompt_in1= '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
30 o.prompt_in2= '\C_Green|\C_LightGreen\D\C_Green> '
31 o.prompt_out= '<\#> '
32
33 # make 'd' an alias for ls -F
34
35 ip.magic('alias d ls -F --color=auto')
36
37 # Make available all system commands. Comment out to speed up
38 # startup os slow machines and conserve a bit of memory
39
40 ip.magic('rehashx') No newline at end of file
@@ -1,136 +1,143 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi as ip
28 import IPython.ipapi as ip
29
29
30 def ankka_f(self, arg):
30 def ankka_f(self, arg):
31 print "Ankka",self,"says uppercase:",arg.upper()
31 print "Ankka",self,"says uppercase:",arg.upper()
32
32
33 ip.expose_magic("ankka",ankka_f)
33 ip.expose_magic("ankka",ankka_f)
34
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
37 ip.system('pwd')
38
38
39 ip.ex('import re')
39 ip.ex('import re')
40 ip.ex("""
40 ip.ex("""
41 def funcci(a,b):
41 def funcci(a,b):
42 print a+b
42 print a+b
43 print funcci(3,4)
43 print funcci(3,4)
44 """)
44 """)
45 ip.ex("funcci(348,9)")
45 ip.ex("funcci(348,9)")
46
46
47 def jed_editor(self,filename, linenum=None):
47 def jed_editor(self,filename, linenum=None):
48 print "Calling my own editor, jed ... via hook!"
48 print "Calling my own editor, jed ... via hook!"
49 import os
49 import os
50 if linenum is None: linenum = 0
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
51 os.system('jed +%d %s' % (linenum, filename))
52 print "exiting jed"
52 print "exiting jed"
53
53
54 ip.set_hook('editor',jed_editor)
54 ip.set_hook('editor',jed_editor)
55
55
56 o = ip.options()
56 o = ip.options()
57 o.autocall = 2 # FULL autocall mode
57 o.autocall = 2 # FULL autocall mode
58
58
59 print "done!"
59 print "done!"
60
60
61 '''
61 '''
62
62
63 def _init_with_shell(ip):
63 def _init_with_shell(ip):
64 global magic
64 global magic
65 magic = ip.ipmagic
65 magic = ip.ipmagic
66 global system
66 global system
67 system = ip.ipsystem
67 system = ip.ipsystem
68 global set_hook
68 global set_hook
69 set_hook = ip.set_hook
69 set_hook = ip.set_hook
70
70
71 global __IP
71 global __IP
72 __IP = ip
72 __IP = ip
73
73
74 def options():
74 def options():
75 """ All configurable variables """
75 """ All configurable variables """
76 return __IP.rc
76 return __IP.rc
77
77
78 def user_ns():
78 def user_ns():
79 return __IP.user_ns
79 return __IP.user_ns
80
80
81 def expose_magic(magicname, func):
81 def expose_magic(magicname, func):
82 ''' Expose own function as magic function for ipython
82 ''' Expose own function as magic function for ipython
83
83
84 def foo_impl(self,parameter_s=''):
84 def foo_impl(self,parameter_s=''):
85 """My very own magic!. (Use docstrings, IPython reads them)."""
85 """My very own magic!. (Use docstrings, IPython reads them)."""
86 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
86 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
87 print 'The self object is:',self
87 print 'The self object is:',self
88
88
89 ipapi.expose_magic("foo",foo_impl)
89 ipapi.expose_magic("foo",foo_impl)
90 '''
90 '''
91
91
92 from IPython import Magic
92 from IPython import Magic
93 import new
93 import new
94 im = new.instancemethod(func,__IP, __IP.__class__)
94 im = new.instancemethod(func,__IP, __IP.__class__)
95 setattr(__IP, "magic_" + magicname, im)
95 setattr(__IP, "magic_" + magicname, im)
96
96
97 class asmagic:
97 class asmagic:
98 """ Decorator for exposing magics in a friendly 2.4 decorator form
98 """ Decorator for exposing magics in a friendly 2.4 decorator form
99
99
100 @ip.asmagic("foo")
100 @ip.asmagic("foo")
101 def f(self,arg):
101 def f(self,arg):
102 pring "arg given:",arg
102 pring "arg given:",arg
103
103
104 After this, %foo is a magic function.
104 After this, %foo is a magic function.
105 """
105 """
106
106
107 def __init__(self,magicname):
107 def __init__(self,magicname):
108 self.name = magicname
108 self.name = magicname
109
109
110 def __call__(self,f):
110 def __call__(self,f):
111 expose_magic(self.name, f)
111 expose_magic(self.name, f)
112 return f
112 return f
113
113
114 class ashook:
114 class ashook:
115 """ Decorator for exposing magics in a friendly 2.4 decorator form
115 """ Decorator for exposing magics in a friendly 2.4 decorator form
116
116
117 @ip.ashook("editor")
117 @ip.ashook("editor")
118 def jed_editor(self,filename, linenum=None):
118 def jed_editor(self,filename, linenum=None):
119 import os
119 import os
120 if linenum is None: linenum = 0
120 if linenum is None: linenum = 0
121 os.system('jed +%d %s' % (linenum, filename))
121 os.system('jed +%d %s' % (linenum, filename))
122
122
123 """
123 """
124
124
125 def __init__(self,name,priority=50):
125 def __init__(self,name,priority=50):
126 self.name = name
126 self.name = name
127 self.prio = priority
127 self.prio = priority
128
128
129 def __call__(self,f):
129 def __call__(self,f):
130 set_hook(self.name, f, self.prio)
130 set_hook(self.name, f, self.prio)
131 return f
131 return f
132
132
133
133
134 def ex(cmd):
134 def ex(cmd):
135 """ Execute a normal python statement """
135 """ Execute a normal python statement in user namespace """
136 exec cmd in user_ns() No newline at end of file
136 exec cmd in user_ns()
137
138 def ev(expr):
139 """ Evaluate python expression expr in user namespace
140
141 Returns the result """
142 return eval(expr,user_ns())
143 No newline at end of file
@@ -1,707 +1,715 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 1033 2006-01-20 10:41:20Z vivainio $"""
9 $Id: ipmaker.py 1037 2006-01-20 23:27:53Z vivainio $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.ipstruct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 # we need the directory where IPython itself is installed
130 # we need the directory where IPython itself is installed
131 import IPython
131 import IPython
132 IPython_dir = os.path.dirname(IPython.__file__)
132 IPython_dir = os.path.dirname(IPython.__file__)
133 del IPython
133 del IPython
134
134
135 #-------------------------------------------------------------------------
135 #-------------------------------------------------------------------------
136 # Command line handling
136 # Command line handling
137
137
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 # GetOpt::Long)
139 # GetOpt::Long)
140
140
141 # Any key not listed here gets deleted even if in the file (like session
141 # Any key not listed here gets deleted even if in the file (like session
142 # or profile). That's deliberate, to maintain the rc namespace clean.
142 # or profile). That's deliberate, to maintain the rc namespace clean.
143
143
144 # Each set of options appears twice: under _conv only the names are
144 # Each set of options appears twice: under _conv only the names are
145 # listed, indicating which type they must be converted to when reading the
145 # listed, indicating which type they must be converted to when reading the
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 # DPyGetOpt syntax (=s,=i,:f,etc).
147 # DPyGetOpt syntax (=s,=i,:f,etc).
148
148
149 # Make sure there's a space before each end of line (they get auto-joined!)
149 # Make sure there's a space before each end of line (they get auto-joined!)
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 'quick screen_length|sl=i prompts_pad_left=i '
154 'quick screen_length|sl=i prompts_pad_left=i '
155 'logfile|lf=s logplay|lp=s profile|p=s '
155 'logfile|lf=s logplay|lp=s profile|p=s '
156 'readline! readline_merge_completions! '
156 'readline! readline_merge_completions! '
157 'readline_omit__names! '
157 'readline_omit__names! '
158 'rcfile=s separate_in|si=s separate_out|so=s '
158 'rcfile=s separate_in|si=s separate_out|so=s '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 'magic_docstrings system_verbose! '
160 'magic_docstrings system_verbose! '
161 'multi_line_specials! '
161 'multi_line_specials! '
162 'wxversion=s '
162 'wxversion=s '
163 'autoedit_syntax!')
163 'autoedit_syntax!')
164
164
165 # Options that can *only* appear at the cmd line (not in rcfiles).
165 # Options that can *only* appear at the cmd line (not in rcfiles).
166
166
167 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
167 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
168 # the 'C-c !' command in emacs automatically appends a -i option at the end.
168 # the 'C-c !' command in emacs automatically appends a -i option at the end.
169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
170 'gthread! qthread! wthread! pylab! tk!')
170 'gthread! qthread! wthread! pylab! tk!')
171
171
172 # Build the actual name list to be used by DPyGetOpt
172 # Build the actual name list to be used by DPyGetOpt
173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
174
174
175 # Set sensible command line defaults.
175 # Set sensible command line defaults.
176 # This should have everything from cmdline_opts and cmdline_only
176 # This should have everything from cmdline_opts and cmdline_only
177 opts_def = Struct(autocall = 1,
177 opts_def = Struct(autocall = 1,
178 autoedit_syntax = 1,
178 autoedit_syntax = 1,
179 autoindent=0,
179 autoindent=0,
180 automagic = 1,
180 automagic = 1,
181 banner = 1,
181 banner = 1,
182 cache_size = 1000,
182 cache_size = 1000,
183 c = '',
183 c = '',
184 classic = 0,
184 classic = 0,
185 colors = 'NoColor',
185 colors = 'NoColor',
186 color_info = 0,
186 color_info = 0,
187 confirm_exit = 1,
187 confirm_exit = 1,
188 debug = 0,
188 debug = 0,
189 deep_reload = 0,
189 deep_reload = 0,
190 editor = '0',
190 editor = '0',
191 help = 0,
191 help = 0,
192 ignore = 0,
192 ignore = 0,
193 ipythondir = ipythondir,
193 ipythondir = ipythondir,
194 log = 0,
194 log = 0,
195 logfile = '',
195 logfile = '',
196 logplay = '',
196 logplay = '',
197 multi_line_specials = 1,
197 multi_line_specials = 1,
198 messages = 1,
198 messages = 1,
199 nosep = 0,
199 nosep = 0,
200 pdb = 0,
200 pdb = 0,
201 pprint = 0,
201 pprint = 0,
202 profile = '',
202 profile = '',
203 prompt_in1 = 'In [\\#]: ',
203 prompt_in1 = 'In [\\#]: ',
204 prompt_in2 = ' .\\D.: ',
204 prompt_in2 = ' .\\D.: ',
205 prompt_out = 'Out[\\#]: ',
205 prompt_out = 'Out[\\#]: ',
206 prompts_pad_left = 1,
206 prompts_pad_left = 1,
207 quick = 0,
207 quick = 0,
208 readline = 1,
208 readline = 1,
209 readline_merge_completions = 1,
209 readline_merge_completions = 1,
210 readline_omit__names = 0,
210 readline_omit__names = 0,
211 rcfile = 'ipythonrc' + rc_suffix,
211 rcfile = 'ipythonrc' + rc_suffix,
212 screen_length = 0,
212 screen_length = 0,
213 separate_in = '\n',
213 separate_in = '\n',
214 separate_out = '\n',
214 separate_out = '\n',
215 separate_out2 = '',
215 separate_out2 = '',
216 system_verbose = 0,
216 system_verbose = 0,
217 gthread = 0,
217 gthread = 0,
218 qthread = 0,
218 qthread = 0,
219 wthread = 0,
219 wthread = 0,
220 pylab = 0,
220 pylab = 0,
221 tk = 0,
221 tk = 0,
222 upgrade = 0,
222 upgrade = 0,
223 Version = 0,
223 Version = 0,
224 xmode = 'Verbose',
224 xmode = 'Verbose',
225 wildcards_case_sensitive = 1,
225 wildcards_case_sensitive = 1,
226 wxversion = '0',
226 wxversion = '0',
227 magic_docstrings = 0, # undocumented, for doc generation
227 magic_docstrings = 0, # undocumented, for doc generation
228 )
228 )
229
229
230 # Things that will *only* appear in rcfiles (not at the command line).
230 # Things that will *only* appear in rcfiles (not at the command line).
231 # Make sure there's a space before each end of line (they get auto-joined!)
231 # Make sure there's a space before each end of line (they get auto-joined!)
232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
233 qw_lol: 'import_some ',
233 qw_lol: 'import_some ',
234 # for things with embedded whitespace:
234 # for things with embedded whitespace:
235 list_strings:'execute alias readline_parse_and_bind ',
235 list_strings:'execute alias readline_parse_and_bind ',
236 # Regular strings need no conversion:
236 # Regular strings need no conversion:
237 None:'readline_remove_delims ',
237 None:'readline_remove_delims ',
238 }
238 }
239 # Default values for these
239 # Default values for these
240 rc_def = Struct(include = [],
240 rc_def = Struct(include = [],
241 import_mod = [],
241 import_mod = [],
242 import_all = [],
242 import_all = [],
243 import_some = [[]],
243 import_some = [[]],
244 execute = [],
244 execute = [],
245 execfile = [],
245 execfile = [],
246 alias = [],
246 alias = [],
247 readline_parse_and_bind = [],
247 readline_parse_and_bind = [],
248 readline_remove_delims = '',
248 readline_remove_delims = '',
249 )
249 )
250
250
251 # Build the type conversion dictionary from the above tables:
251 # Build the type conversion dictionary from the above tables:
252 typeconv = rcfile_opts.copy()
252 typeconv = rcfile_opts.copy()
253 typeconv.update(optstr2types(cmdline_opts))
253 typeconv.update(optstr2types(cmdline_opts))
254
254
255 # FIXME: the None key appears in both, put that back together by hand. Ugly!
255 # FIXME: the None key appears in both, put that back together by hand. Ugly!
256 typeconv[None] += ' ' + rcfile_opts[None]
256 typeconv[None] += ' ' + rcfile_opts[None]
257
257
258 # Remove quotes at ends of all strings (used to protect spaces)
258 # Remove quotes at ends of all strings (used to protect spaces)
259 typeconv[unquote_ends] = typeconv[None]
259 typeconv[unquote_ends] = typeconv[None]
260 del typeconv[None]
260 del typeconv[None]
261
261
262 # Build the list we'll use to make all config decisions with defaults:
262 # Build the list we'll use to make all config decisions with defaults:
263 opts_all = opts_def.copy()
263 opts_all = opts_def.copy()
264 opts_all.update(rc_def)
264 opts_all.update(rc_def)
265
265
266 # Build conflict resolver for recursive loading of config files:
266 # Build conflict resolver for recursive loading of config files:
267 # - preserve means the outermost file maintains the value, it is not
267 # - preserve means the outermost file maintains the value, it is not
268 # overwritten if an included file has the same key.
268 # overwritten if an included file has the same key.
269 # - add_flip applies + to the two values, so it better make sense to add
269 # - add_flip applies + to the two values, so it better make sense to add
270 # those types of keys. But it flips them first so that things loaded
270 # those types of keys. But it flips them first so that things loaded
271 # deeper in the inclusion chain have lower precedence.
271 # deeper in the inclusion chain have lower precedence.
272 conflict = {'preserve': ' '.join([ typeconv[int],
272 conflict = {'preserve': ' '.join([ typeconv[int],
273 typeconv[unquote_ends] ]),
273 typeconv[unquote_ends] ]),
274 'add_flip': ' '.join([ typeconv[qwflat],
274 'add_flip': ' '.join([ typeconv[qwflat],
275 typeconv[qw_lol],
275 typeconv[qw_lol],
276 typeconv[list_strings] ])
276 typeconv[list_strings] ])
277 }
277 }
278
278
279 # Now actually process the command line
279 # Now actually process the command line
280 getopt = DPyGetOpt.DPyGetOpt()
280 getopt = DPyGetOpt.DPyGetOpt()
281 getopt.setIgnoreCase(0)
281 getopt.setIgnoreCase(0)
282
282
283 getopt.parseConfiguration(opts_names)
283 getopt.parseConfiguration(opts_names)
284
284
285 try:
285 try:
286 getopt.processArguments(argv)
286 getopt.processArguments(argv)
287 except:
287 except:
288 print cmd_line_usage
288 print cmd_line_usage
289 warn('\nError in Arguments: ' + `sys.exc_value`)
289 warn('\nError in Arguments: ' + `sys.exc_value`)
290 sys.exit(1)
290 sys.exit(1)
291
291
292 # convert the options dict to a struct for much lighter syntax later
292 # convert the options dict to a struct for much lighter syntax later
293 opts = Struct(getopt.optionValues)
293 opts = Struct(getopt.optionValues)
294 args = getopt.freeValues
294 args = getopt.freeValues
295
295
296 # this is the struct (which has default values at this point) with which
296 # this is the struct (which has default values at this point) with which
297 # we make all decisions:
297 # we make all decisions:
298 opts_all.update(opts)
298 opts_all.update(opts)
299
299
300 # Options that force an immediate exit
300 # Options that force an immediate exit
301 if opts_all.help:
301 if opts_all.help:
302 page(cmd_line_usage)
302 page(cmd_line_usage)
303 sys.exit()
303 sys.exit()
304
304
305 if opts_all.Version:
305 if opts_all.Version:
306 print __version__
306 print __version__
307 sys.exit()
307 sys.exit()
308
308
309 if opts_all.magic_docstrings:
309 if opts_all.magic_docstrings:
310 IP.magic_magic('-latex')
310 IP.magic_magic('-latex')
311 sys.exit()
311 sys.exit()
312
312
313 # Create user config directory if it doesn't exist. This must be done
313 # Create user config directory if it doesn't exist. This must be done
314 # *after* getting the cmd line options.
314 # *after* getting the cmd line options.
315 if not os.path.isdir(opts_all.ipythondir):
315 if not os.path.isdir(opts_all.ipythondir):
316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
317
317
318 # upgrade user config files while preserving a copy of the originals
318 # upgrade user config files while preserving a copy of the originals
319 if opts_all.upgrade:
319 if opts_all.upgrade:
320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
321
321
322 # check mutually exclusive options in the *original* command line
322 # check mutually exclusive options in the *original* command line
323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
324 qw('classic profile'),qw('classic rcfile')])
324 qw('classic profile'),qw('classic rcfile')])
325
325
326 #---------------------------------------------------------------------------
326 #---------------------------------------------------------------------------
327 # Log replay
327 # Log replay
328
328
329 # if -logplay, we need to 'become' the other session. That basically means
329 # if -logplay, we need to 'become' the other session. That basically means
330 # replacing the current command line environment with that of the old
330 # replacing the current command line environment with that of the old
331 # session and moving on.
331 # session and moving on.
332
332
333 # this is needed so that later we know we're in session reload mode, as
333 # this is needed so that later we know we're in session reload mode, as
334 # opts_all will get overwritten:
334 # opts_all will get overwritten:
335 load_logplay = 0
335 load_logplay = 0
336
336
337 if opts_all.logplay:
337 if opts_all.logplay:
338 load_logplay = opts_all.logplay
338 load_logplay = opts_all.logplay
339 opts_debug_save = opts_all.debug
339 opts_debug_save = opts_all.debug
340 try:
340 try:
341 logplay = open(opts_all.logplay)
341 logplay = open(opts_all.logplay)
342 except IOError:
342 except IOError:
343 if opts_all.debug: IP.InteractiveTB()
343 if opts_all.debug: IP.InteractiveTB()
344 warn('Could not open logplay file '+`opts_all.logplay`)
344 warn('Could not open logplay file '+`opts_all.logplay`)
345 # restore state as if nothing had happened and move on, but make
345 # restore state as if nothing had happened and move on, but make
346 # sure that later we don't try to actually load the session file
346 # sure that later we don't try to actually load the session file
347 logplay = None
347 logplay = None
348 load_logplay = 0
348 load_logplay = 0
349 del opts_all.logplay
349 del opts_all.logplay
350 else:
350 else:
351 try:
351 try:
352 logplay.readline()
352 logplay.readline()
353 logplay.readline();
353 logplay.readline();
354 # this reloads that session's command line
354 # this reloads that session's command line
355 cmd = logplay.readline()[6:]
355 cmd = logplay.readline()[6:]
356 exec cmd
356 exec cmd
357 # restore the true debug flag given so that the process of
357 # restore the true debug flag given so that the process of
358 # session loading itself can be monitored.
358 # session loading itself can be monitored.
359 opts.debug = opts_debug_save
359 opts.debug = opts_debug_save
360 # save the logplay flag so later we don't overwrite the log
360 # save the logplay flag so later we don't overwrite the log
361 opts.logplay = load_logplay
361 opts.logplay = load_logplay
362 # now we must update our own structure with defaults
362 # now we must update our own structure with defaults
363 opts_all.update(opts)
363 opts_all.update(opts)
364 # now load args
364 # now load args
365 cmd = logplay.readline()[6:]
365 cmd = logplay.readline()[6:]
366 exec cmd
366 exec cmd
367 logplay.close()
367 logplay.close()
368 except:
368 except:
369 logplay.close()
369 logplay.close()
370 if opts_all.debug: IP.InteractiveTB()
370 if opts_all.debug: IP.InteractiveTB()
371 warn("Logplay file lacking full configuration information.\n"
371 warn("Logplay file lacking full configuration information.\n"
372 "I'll try to read it, but some things may not work.")
372 "I'll try to read it, but some things may not work.")
373
373
374 #-------------------------------------------------------------------------
374 #-------------------------------------------------------------------------
375 # set up output traps: catch all output from files, being run, modules
375 # set up output traps: catch all output from files, being run, modules
376 # loaded, etc. Then give it to the user in a clean form at the end.
376 # loaded, etc. Then give it to the user in a clean form at the end.
377
377
378 msg_out = 'Output messages. '
378 msg_out = 'Output messages. '
379 msg_err = 'Error messages. '
379 msg_err = 'Error messages. '
380 msg_sep = '\n'
380 msg_sep = '\n'
381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
382 msg_err,msg_sep,debug,
382 msg_err,msg_sep,debug,
383 quiet_out=1),
383 quiet_out=1),
384 user_exec = OutputTrap('User File Execution',msg_out,
384 user_exec = OutputTrap('User File Execution',msg_out,
385 msg_err,msg_sep,debug),
385 msg_err,msg_sep,debug),
386 logplay = OutputTrap('Log Loader',msg_out,
386 logplay = OutputTrap('Log Loader',msg_out,
387 msg_err,msg_sep,debug),
387 msg_err,msg_sep,debug),
388 summary = ''
388 summary = ''
389 )
389 )
390
390
391 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
392 # Process user ipythonrc-type configuration files
392 # Process user ipythonrc-type configuration files
393
393
394 # turn on output trapping and log to msg.config
394 # turn on output trapping and log to msg.config
395 # remember that with debug on, trapping is actually disabled
395 # remember that with debug on, trapping is actually disabled
396 msg.config.trap_all()
396 msg.config.trap_all()
397
397
398 # look for rcfile in current or default directory
398 # look for rcfile in current or default directory
399 try:
399 try:
400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
401 except IOError:
401 except IOError:
402 if opts_all.debug: IP.InteractiveTB()
402 if opts_all.debug: IP.InteractiveTB()
403 warn('Configuration file %s not found. Ignoring request.'
403 warn('Configuration file %s not found. Ignoring request.'
404 % (opts_all.rcfile) )
404 % (opts_all.rcfile) )
405
405
406 # 'profiles' are a shorthand notation for config filenames
406 # 'profiles' are a shorthand notation for config filenames
407 if opts_all.profile:
407 if opts_all.profile:
408 try:
408 try:
409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
410 + rc_suffix,
410 + rc_suffix,
411 opts_all.ipythondir)
411 opts_all.ipythondir)
412 except IOError:
412 except IOError:
413 if opts_all.debug: IP.InteractiveTB()
413 if opts_all.debug: IP.InteractiveTB()
414 opts.profile = '' # remove profile from options if invalid
414 opts.profile = '' # remove profile from options if invalid
415 warn('Profile configuration file %s not found. Ignoring request.'
415 warn('Profile configuration file %s not found. Ignoring request.'
416 % (opts_all.profile) )
416 % (opts_all.profile) )
417
417
418
418
419 # load the config file
419 # load the config file
420 rcfiledata = None
420 rcfiledata = None
421 if opts_all.quick:
421 if opts_all.quick:
422 print 'Launching IPython in quick mode. No config file read.'
422 print 'Launching IPython in quick mode. No config file read.'
423 elif opts_all.classic:
423 elif opts_all.classic:
424 print 'Launching IPython in classic mode. No config file read.'
424 print 'Launching IPython in classic mode. No config file read.'
425 elif opts_all.rcfile:
425 elif opts_all.rcfile:
426 try:
426 try:
427 cfg_loader = ConfigLoader(conflict)
427 cfg_loader = ConfigLoader(conflict)
428 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
428 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
429 'include',opts_all.ipythondir,
429 'include',opts_all.ipythondir,
430 purge = 1,
430 purge = 1,
431 unique = conflict['preserve'])
431 unique = conflict['preserve'])
432 except:
432 except:
433 IP.InteractiveTB()
433 IP.InteractiveTB()
434 warn('Problems loading configuration file '+
434 warn('Problems loading configuration file '+
435 `opts_all.rcfile`+
435 `opts_all.rcfile`+
436 '\nStarting with default -bare bones- configuration.')
436 '\nStarting with default -bare bones- configuration.')
437 else:
437 else:
438 warn('No valid configuration file found in either currrent directory\n'+
438 warn('No valid configuration file found in either currrent directory\n'+
439 'or in the IPython config. directory: '+`opts_all.ipythondir`+
439 'or in the IPython config. directory: '+`opts_all.ipythondir`+
440 '\nProceeding with internal defaults.')
440 '\nProceeding with internal defaults.')
441
441
442 #------------------------------------------------------------------------
442 #------------------------------------------------------------------------
443 # Set exception handlers in mode requested by user.
443 # Set exception handlers in mode requested by user.
444 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
444 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
445 IP.magic_xmode(opts_all.xmode)
445 IP.magic_xmode(opts_all.xmode)
446 otrap.release_out()
446 otrap.release_out()
447
447
448 #------------------------------------------------------------------------
448 #------------------------------------------------------------------------
449 # Execute user config
449 # Execute user config
450
450
451 # Create a valid config structure with the right precedence order:
451 # Create a valid config structure with the right precedence order:
452 # defaults < rcfile < command line. This needs to be in the instance, so
452 # defaults < rcfile < command line. This needs to be in the instance, so
453 # that method calls below that rely on it find it.
453 # that method calls below that rely on it find it.
454 IP.rc = rc_def.copy()
454 IP.rc = rc_def.copy()
455
455
456 # Work with a local alias inside this routine to avoid unnecessary
456 # Work with a local alias inside this routine to avoid unnecessary
457 # attribute lookups.
457 # attribute lookups.
458 IP_rc = IP.rc
458 IP_rc = IP.rc
459
459
460 IP_rc.update(opts_def)
460 IP_rc.update(opts_def)
461 if rcfiledata:
461 if rcfiledata:
462 # now we can update
462 # now we can update
463 IP_rc.update(rcfiledata)
463 IP_rc.update(rcfiledata)
464 IP_rc.update(opts)
464 IP_rc.update(opts)
465 IP_rc.update(rc_override)
465 IP_rc.update(rc_override)
466
466
467 # Store the original cmd line for reference:
467 # Store the original cmd line for reference:
468 IP_rc.opts = opts
468 IP_rc.opts = opts
469 IP_rc.args = args
469 IP_rc.args = args
470
470
471 # create a *runtime* Struct like rc for holding parameters which may be
471 # create a *runtime* Struct like rc for holding parameters which may be
472 # created and/or modified by runtime user extensions.
472 # created and/or modified by runtime user extensions.
473 IP.runtime_rc = Struct()
473 IP.runtime_rc = Struct()
474
474
475 # from this point on, all config should be handled through IP_rc,
475 # from this point on, all config should be handled through IP_rc,
476 # opts* shouldn't be used anymore.
476 # opts* shouldn't be used anymore.
477
477
478 # add personal .ipython dir to sys.path so that users can put things in
478 # add personal .ipython dir to sys.path so that users can put things in
479 # there for customization
479 # there for customization
480 sys.path.append(IP_rc.ipythondir)
480 sys.path.append(IP_rc.ipythondir)
481
481
482 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
482 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
483
483
484 # update IP_rc with some special things that need manual
484 # update IP_rc with some special things that need manual
485 # tweaks. Basically options which affect other options. I guess this
485 # tweaks. Basically options which affect other options. I guess this
486 # should just be written so that options are fully orthogonal and we
486 # should just be written so that options are fully orthogonal and we
487 # wouldn't worry about this stuff!
487 # wouldn't worry about this stuff!
488
488
489 if IP_rc.classic:
489 if IP_rc.classic:
490 IP_rc.quick = 1
490 IP_rc.quick = 1
491 IP_rc.cache_size = 0
491 IP_rc.cache_size = 0
492 IP_rc.pprint = 0
492 IP_rc.pprint = 0
493 IP_rc.prompt_in1 = '>>> '
493 IP_rc.prompt_in1 = '>>> '
494 IP_rc.prompt_in2 = '... '
494 IP_rc.prompt_in2 = '... '
495 IP_rc.prompt_out = ''
495 IP_rc.prompt_out = ''
496 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
496 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
497 IP_rc.colors = 'NoColor'
497 IP_rc.colors = 'NoColor'
498 IP_rc.xmode = 'Plain'
498 IP_rc.xmode = 'Plain'
499
499
500 # configure readline
500 # configure readline
501 # Define the history file for saving commands in between sessions
501 # Define the history file for saving commands in between sessions
502 if IP_rc.profile:
502 if IP_rc.profile:
503 histfname = 'history-%s' % IP_rc.profile
503 histfname = 'history-%s' % IP_rc.profile
504 else:
504 else:
505 histfname = 'history'
505 histfname = 'history'
506 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
506 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
507
507
508 # update exception handlers with rc file status
508 # update exception handlers with rc file status
509 otrap.trap_out() # I don't want these messages ever.
509 otrap.trap_out() # I don't want these messages ever.
510 IP.magic_xmode(IP_rc.xmode)
510 IP.magic_xmode(IP_rc.xmode)
511 otrap.release_out()
511 otrap.release_out()
512
512
513 # activate logging if requested and not reloading a log
513 # activate logging if requested and not reloading a log
514 if IP_rc.logplay:
514 if IP_rc.logplay:
515 IP.magic_logstart(IP_rc.logplay + ' append')
515 IP.magic_logstart(IP_rc.logplay + ' append')
516 elif IP_rc.logfile:
516 elif IP_rc.logfile:
517 IP.magic_logstart(IP_rc.logfile)
517 IP.magic_logstart(IP_rc.logfile)
518 elif IP_rc.log:
518 elif IP_rc.log:
519 IP.magic_logstart()
519 IP.magic_logstart()
520
520
521 # find user editor so that it we don't have to look it up constantly
521 # find user editor so that it we don't have to look it up constantly
522 if IP_rc.editor.strip()=='0':
522 if IP_rc.editor.strip()=='0':
523 try:
523 try:
524 ed = os.environ['EDITOR']
524 ed = os.environ['EDITOR']
525 except KeyError:
525 except KeyError:
526 if os.name == 'posix':
526 if os.name == 'posix':
527 ed = 'vi' # the only one guaranteed to be there!
527 ed = 'vi' # the only one guaranteed to be there!
528 else:
528 else:
529 ed = 'notepad' # same in Windows!
529 ed = 'notepad' # same in Windows!
530 IP_rc.editor = ed
530 IP_rc.editor = ed
531
531
532 # Keep track of whether this is an embedded instance or not (useful for
532 # Keep track of whether this is an embedded instance or not (useful for
533 # post-mortems).
533 # post-mortems).
534 IP_rc.embedded = IP.embedded
534 IP_rc.embedded = IP.embedded
535
535
536 # Recursive reload
536 # Recursive reload
537 try:
537 try:
538 from IPython import deep_reload
538 from IPython import deep_reload
539 if IP_rc.deep_reload:
539 if IP_rc.deep_reload:
540 __builtin__.reload = deep_reload.reload
540 __builtin__.reload = deep_reload.reload
541 else:
541 else:
542 __builtin__.dreload = deep_reload.reload
542 __builtin__.dreload = deep_reload.reload
543 del deep_reload
543 del deep_reload
544 except ImportError:
544 except ImportError:
545 pass
545 pass
546
546
547 # Save the current state of our namespace so that the interactive shell
547 # Save the current state of our namespace so that the interactive shell
548 # can later know which variables have been created by us from config files
548 # can later know which variables have been created by us from config files
549 # and loading. This way, loading a file (in any way) is treated just like
549 # and loading. This way, loading a file (in any way) is treated just like
550 # defining things on the command line, and %who works as expected.
550 # defining things on the command line, and %who works as expected.
551
551
552 # DON'T do anything that affects the namespace beyond this point!
552 # DON'T do anything that affects the namespace beyond this point!
553 IP.internal_ns.update(__main__.__dict__)
553 IP.internal_ns.update(__main__.__dict__)
554
554
555 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
555 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
556
556
557 # Now run through the different sections of the users's config
557 # Now run through the different sections of the users's config
558 if IP_rc.debug:
558 if IP_rc.debug:
559 print 'Trying to execute the following configuration structure:'
559 print 'Trying to execute the following configuration structure:'
560 print '(Things listed first are deeper in the inclusion tree and get'
560 print '(Things listed first are deeper in the inclusion tree and get'
561 print 'loaded first).\n'
561 print 'loaded first).\n'
562 pprint(IP_rc.__dict__)
562 pprint(IP_rc.__dict__)
563
563
564 # Make it easy to import extensions
564 # Make it easy to import extensions
565 sys.path.append(os.path.join(IPython_dir,"Extensions"))
565 sys.path.append(os.path.join(IPython_dir,"Extensions"))
566 for mod in IP_rc.import_mod:
566 for mod in IP_rc.import_mod:
567 try:
567 try:
568 exec 'import '+mod in IP.user_ns
568 exec 'import '+mod in IP.user_ns
569 except :
569 except :
570 IP.InteractiveTB()
570 IP.InteractiveTB()
571 import_fail_info(mod)
571 import_fail_info(mod)
572
572
573 for mod_fn in IP_rc.import_some:
573 for mod_fn in IP_rc.import_some:
574 if mod_fn == []: break
574 if mod_fn == []: break
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
576 try:
576 try:
577 exec 'from '+mod+' import '+fn in IP.user_ns
577 exec 'from '+mod+' import '+fn in IP.user_ns
578 except :
578 except :
579 IP.InteractiveTB()
579 IP.InteractiveTB()
580 import_fail_info(mod,fn)
580 import_fail_info(mod,fn)
581
581
582 for mod in IP_rc.import_all:
582 for mod in IP_rc.import_all:
583 try:
583 try:
584 exec 'from '+mod+' import *' in IP.user_ns
584 exec 'from '+mod+' import *' in IP.user_ns
585 except :
585 except :
586 IP.InteractiveTB()
586 IP.InteractiveTB()
587 import_fail_info(mod)
587 import_fail_info(mod)
588
588
589 for code in IP_rc.execute:
589 for code in IP_rc.execute:
590 try:
590 try:
591 exec code in IP.user_ns
591 exec code in IP.user_ns
592 except:
592 except:
593 IP.InteractiveTB()
593 IP.InteractiveTB()
594 warn('Failure executing code: ' + `code`)
594 warn('Failure executing code: ' + `code`)
595
595
596 # Execute the files the user wants in ipythonrc
596 # Execute the files the user wants in ipythonrc
597 for file in IP_rc.execfile:
597 for file in IP_rc.execfile:
598 try:
598 try:
599 file = filefind(file,sys.path+[IPython_dir])
599 file = filefind(file,sys.path+[IPython_dir])
600 except IOError:
600 except IOError:
601 warn(itpl('File $file not found. Skipping it.'))
601 warn(itpl('File $file not found. Skipping it.'))
602 else:
602 else:
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
604
604
605 # finally, try importing ipy_*_conf for final configuration
606 try:
607 import ipy_system_conf
608 import ipy_user_conf
609
610 except ImportError:
611 IP.InteractiveTB()
612
605 # release stdout and stderr and save config log into a global summary
613 # release stdout and stderr and save config log into a global summary
606 msg.config.release_all()
614 msg.config.release_all()
607 if IP_rc.messages:
615 if IP_rc.messages:
608 msg.summary += msg.config.summary_all()
616 msg.summary += msg.config.summary_all()
609
617
610 #------------------------------------------------------------------------
618 #------------------------------------------------------------------------
611 # Setup interactive session
619 # Setup interactive session
612
620
613 # Now we should be fully configured. We can then execute files or load
621 # Now we should be fully configured. We can then execute files or load
614 # things only needed for interactive use. Then we'll open the shell.
622 # things only needed for interactive use. Then we'll open the shell.
615
623
616 # Take a snapshot of the user namespace before opening the shell. That way
624 # Take a snapshot of the user namespace before opening the shell. That way
617 # we'll be able to identify which things were interactively defined and
625 # we'll be able to identify which things were interactively defined and
618 # which were defined through config files.
626 # which were defined through config files.
619 IP.user_config_ns = IP.user_ns.copy()
627 IP.user_config_ns = IP.user_ns.copy()
620
628
621 # Force reading a file as if it were a session log. Slower but safer.
629 # Force reading a file as if it were a session log. Slower but safer.
622 if load_logplay:
630 if load_logplay:
623 print 'Replaying log...'
631 print 'Replaying log...'
624 try:
632 try:
625 if IP_rc.debug:
633 if IP_rc.debug:
626 logplay_quiet = 0
634 logplay_quiet = 0
627 else:
635 else:
628 logplay_quiet = 1
636 logplay_quiet = 1
629
637
630 msg.logplay.trap_all()
638 msg.logplay.trap_all()
631 IP.safe_execfile(load_logplay,IP.user_ns,
639 IP.safe_execfile(load_logplay,IP.user_ns,
632 islog = 1, quiet = logplay_quiet)
640 islog = 1, quiet = logplay_quiet)
633 msg.logplay.release_all()
641 msg.logplay.release_all()
634 if IP_rc.messages:
642 if IP_rc.messages:
635 msg.summary += msg.logplay.summary_all()
643 msg.summary += msg.logplay.summary_all()
636 except:
644 except:
637 warn('Problems replaying logfile %s.' % load_logplay)
645 warn('Problems replaying logfile %s.' % load_logplay)
638 IP.InteractiveTB()
646 IP.InteractiveTB()
639
647
640 # Load remaining files in command line
648 # Load remaining files in command line
641 msg.user_exec.trap_all()
649 msg.user_exec.trap_all()
642
650
643 # Do NOT execute files named in the command line as scripts to be loaded
651 # Do NOT execute files named in the command line as scripts to be loaded
644 # by embedded instances. Doing so has the potential for an infinite
652 # by embedded instances. Doing so has the potential for an infinite
645 # recursion if there are exceptions thrown in the process.
653 # recursion if there are exceptions thrown in the process.
646
654
647 # XXX FIXME: the execution of user files should be moved out to after
655 # XXX FIXME: the execution of user files should be moved out to after
648 # ipython is fully initialized, just as if they were run via %run at the
656 # ipython is fully initialized, just as if they were run via %run at the
649 # ipython prompt. This would also give them the benefit of ipython's
657 # ipython prompt. This would also give them the benefit of ipython's
650 # nice tracebacks.
658 # nice tracebacks.
651
659
652 if not embedded and IP_rc.args:
660 if not embedded and IP_rc.args:
653 name_save = IP.user_ns['__name__']
661 name_save = IP.user_ns['__name__']
654 IP.user_ns['__name__'] = '__main__'
662 IP.user_ns['__name__'] = '__main__'
655 try:
663 try:
656 # Set our own excepthook in case the user code tries to call it
664 # Set our own excepthook in case the user code tries to call it
657 # directly. This prevents triggering the IPython crash handler.
665 # directly. This prevents triggering the IPython crash handler.
658 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
666 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
659 for run in args:
667 for run in args:
660 IP.safe_execfile(run,IP.user_ns)
668 IP.safe_execfile(run,IP.user_ns)
661 finally:
669 finally:
662 # Reset our crash handler in place
670 # Reset our crash handler in place
663 sys.excepthook = old_excepthook
671 sys.excepthook = old_excepthook
664
672
665 IP.user_ns['__name__'] = name_save
673 IP.user_ns['__name__'] = name_save
666
674
667 msg.user_exec.release_all()
675 msg.user_exec.release_all()
668 if IP_rc.messages:
676 if IP_rc.messages:
669 msg.summary += msg.user_exec.summary_all()
677 msg.summary += msg.user_exec.summary_all()
670
678
671 # since we can't specify a null string on the cmd line, 0 is the equivalent:
679 # since we can't specify a null string on the cmd line, 0 is the equivalent:
672 if IP_rc.nosep:
680 if IP_rc.nosep:
673 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
681 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
674 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
682 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
675 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
683 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
676 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
684 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
677 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
685 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
678 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
686 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
679 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
687 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
680
688
681 # Determine how many lines at the bottom of the screen are needed for
689 # Determine how many lines at the bottom of the screen are needed for
682 # showing prompts, so we can know wheter long strings are to be printed or
690 # showing prompts, so we can know wheter long strings are to be printed or
683 # paged:
691 # paged:
684 num_lines_bot = IP_rc.separate_in.count('\n')+1
692 num_lines_bot = IP_rc.separate_in.count('\n')+1
685 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
693 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
686
694
687 # configure startup banner
695 # configure startup banner
688 if IP_rc.c: # regular python doesn't print the banner with -c
696 if IP_rc.c: # regular python doesn't print the banner with -c
689 IP_rc.banner = 0
697 IP_rc.banner = 0
690 if IP_rc.banner:
698 if IP_rc.banner:
691 BANN_P = IP.BANNER_PARTS
699 BANN_P = IP.BANNER_PARTS
692 else:
700 else:
693 BANN_P = []
701 BANN_P = []
694
702
695 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
703 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
696
704
697 # add message log (possibly empty)
705 # add message log (possibly empty)
698 if msg.summary: BANN_P.append(msg.summary)
706 if msg.summary: BANN_P.append(msg.summary)
699 # Final banner is a string
707 # Final banner is a string
700 IP.BANNER = '\n'.join(BANN_P)
708 IP.BANNER = '\n'.join(BANN_P)
701
709
702 # Finalize the IPython instance. This assumes the rc structure is fully
710 # Finalize the IPython instance. This assumes the rc structure is fully
703 # in place.
711 # in place.
704 IP.post_config_initialization()
712 IP.post_config_initialization()
705
713
706 return IP
714 return IP
707 #************************ end of file <ipmaker.py> **************************
715 #************************ end of file <ipmaker.py> **************************
General Comments 0
You need to be logged in to leave comments. Login now