##// END OF EJS Templates
Made missing ipy_*_conf.py files less intrusive
vivainio -
Show More
@@ -1,273 +1,273 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Modified input prompt for executing files.
3 3
4 4 We define a special input line filter to allow typing lines which begin with
5 5 '~', '/' or '.'. If one of those strings is encountered, it is automatically
6 6 executed.
7 7
8 $Id: InterpreterExec.py 1039 2006-01-20 23:59:33Z vivainio $"""
8 $Id: InterpreterExec.py 1041 2006-01-21 09:29:14Z vivainio $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>
12 12 # Copyright (C) 2004-2006 Fernando Perez <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = 'W.J. van der Laan <gnufnork@hetdigitalegat.nl>, '\
20 20 '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 def prefilter_shell(self,line,continuation):
24 24 """Alternate prefilter, modified for shell-like functionality.
25 25
26 26 - Execute all lines beginning with '~', '/' or '.'
27 27 - $var=cmd <=> %sc var=cmd
28 28 - $$var=cmd <=> %sc -l var=cmd
29 29 """
30 30
31 31 if line:
32 32 l0 = line[0]
33 33 if l0 in '~/.':
34 34 return self._prefilter("!%s"%line,continuation)
35 35 elif l0=='$':
36 36 lrest = line[1:]
37 37 if lrest.startswith('$'):
38 38 # $$var=cmd <=> %sc -l var=cmd
39 39 return self._prefilter("%ssc -l %s" % (self.ESC_MAGIC,lrest[1:]),
40 40 continuation)
41 41 else:
42 42 # $var=cmd <=> %sc var=cmd
43 43 return self._prefilter("%ssc %s" % (self.ESC_MAGIC,lrest),
44 44 continuation)
45 45 else:
46 46 return self._prefilter(line,continuation)
47 47 else:
48 48 return self._prefilter(line,continuation)
49 49
50 50 # Rebind this to be the new IPython prefilter:
51 51 from IPython.iplib import InteractiveShell
52 52 InteractiveShell.prefilter = prefilter_shell
53 53 # Clean up the namespace.
54 54 del InteractiveShell,prefilter_shell
55 55
56 56 # Provide pysh and further shell-oriented services
57 57 import os,sys,shutil
58 58 from IPython.genutils import system,shell,getoutput,getoutputerror
59 59
60 60 # Short aliases for getting shell output as a string and a list
61 61 sout = getoutput
62 62 lout = lambda cmd: getoutput(cmd,split=1)
63 63
64 64 # Empty function, meant as a docstring holder so help(pysh) works.
65 65 def pysh():
66 66 """Pysh is a set of modules and extensions to IPython which make shell-like
67 67 usage with Python syntax more convenient. Keep in mind that pysh is NOT a
68 68 full-blown shell, so don't try to make it your /etc/passwd entry!
69 69
70 70 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
71 71 you'll suspend pysh itself, not the process you just started.
72 72
73 73 Since pysh is really nothing but a customized IPython, you should
74 74 familiarize yourself with IPython's features. This brief help mainly
75 75 documents areas in which pysh differs from the normal IPython.
76 76
77 77 ALIASES
78 78 -------
79 79 All of your $PATH has been loaded as IPython aliases, so you should be
80 80 able to type any normal system command and have it executed. See %alias?
81 81 and %unalias? for details on the alias facilities.
82 82
83 83 SPECIAL SYNTAX
84 84 --------------
85 85 Any lines which begin with '~', '/' and '.' will be executed as shell
86 86 commands instead of as Python code. The special escapes below are also
87 87 recognized. !cmd is valid in single or multi-line input, all others are
88 88 only valid in single-line input:
89 89
90 90 !cmd - pass 'cmd' directly to the shell
91 91 !!cmd - execute 'cmd' and return output as a list (split on '\\n')
92 92 $var=cmd - capture output of cmd into var, as a string
93 93 $$var=cmd - capture output of cmd into var, as a list (split on '\\n')
94 94
95 95 The $/$$ syntaxes make Python variables from system output, which you can
96 96 later use for further scripting. The converse is also possible: when
97 97 executing an alias or calling to the system via !/!!, you can expand any
98 98 python variable or expression by prepending it with $. Full details of
99 99 the allowed syntax can be found in Python's PEP 215.
100 100
101 101 A few brief examples will illustrate these:
102 102
103 103 fperez[~/test]|3> !ls *s.py
104 104 scopes.py strings.py
105 105
106 106 ls is an internal alias, so there's no need to use !:
107 107 fperez[~/test]|4> ls *s.py
108 108 scopes.py* strings.py
109 109
110 110 !!ls will return the output into a Python variable:
111 111 fperez[~/test]|5> !!ls *s.py
112 112 <5> ['scopes.py', 'strings.py']
113 113 fperez[~/test]|6> print _5
114 114 ['scopes.py', 'strings.py']
115 115
116 116 $ and $$ allow direct capture to named variables:
117 117 fperez[~/test]|7> $astr = ls *s.py
118 118 fperez[~/test]|8> astr
119 119 <8> 'scopes.py\\nstrings.py'
120 120
121 121 fperez[~/test]|9> $$alist = ls *s.py
122 122 fperez[~/test]|10> alist
123 123 <10> ['scopes.py', 'strings.py']
124 124
125 125 alist is now a normal python list you can loop over. Using $ will expand
126 126 back the python values when alias calls are made:
127 127 fperez[~/test]|11> for f in alist:
128 128 |..> print 'file',f,
129 129 |..> wc -l $f
130 130 |..>
131 131 file scopes.py 13 scopes.py
132 132 file strings.py 4 strings.py
133 133
134 134 Note that you may need to protect your variables with braces if you want
135 135 to append strings to their names. To copy all files in alist to .bak
136 136 extensions, you must use:
137 137 fperez[~/test]|12> for f in alist:
138 138 |..> cp $f ${f}.bak
139 139
140 140 If you try using $f.bak, you'll get an AttributeError exception saying
141 141 that your string object doesn't have a .bak attribute. This is because
142 142 the $ expansion mechanism allows you to expand full Python expressions:
143 143 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
144 144 sys.platform is: linux2
145 145
146 146 IPython's input history handling is still active, which allows you to
147 147 rerun a single block of multi-line input by simply using exec:
148 148 fperez[~/test]|14> $$alist = ls *.eps
149 149 fperez[~/test]|15> exec _i11
150 150 file image2.eps 921 image2.eps
151 151 file image.eps 921 image.eps
152 152
153 153 While these are new special-case syntaxes, they are designed to allow very
154 154 efficient use of the shell with minimal typing. At an interactive shell
155 155 prompt, conciseness of expression wins over readability.
156 156
157 157 USEFUL FUNCTIONS AND MODULES
158 158 ----------------------------
159 159 The os, sys and shutil modules from the Python standard library are
160 160 automatically loaded. Some additional functions, useful for shell usage,
161 161 are listed below. You can request more help about them with '?'.
162 162
163 163 shell - execute a command in the underlying system shell
164 164 system - like shell(), but return the exit status of the command
165 165 sout - capture the output of a command as a string
166 166 lout - capture the output of a command as a list (split on '\\n')
167 167 getoutputerror - capture (output,error) of a shell command
168 168
169 169 sout/lout are the functional equivalents of $/$$. They are provided to
170 170 allow you to capture system output in the middle of true python code,
171 171 function definitions, etc (where $ and $$ are invalid).
172 172
173 173 DIRECTORY MANAGEMENT
174 174 --------------------
175 175 Since each command passed by pysh to the underlying system is executed in
176 176 a subshell which exits immediately, you can NOT use !cd to navigate the
177 177 filesystem.
178 178
179 179 Pysh provides its own builtin '%cd' magic command to move in the
180 180 filesystem (the % is not required with automagic on). It also maintains a
181 181 list of visited directories (use %dhist to see it) and allows direct
182 182 switching to any of them. Type 'cd?' for more details.
183 183
184 184 %pushd, %popd and %dirs are provided for directory stack handling.
185 185
186 186 PROMPT CUSTOMIZATION
187 187 --------------------
188 188
189 189 The supplied ipythonrc-pysh profile comes with an example of a very
190 190 colored and detailed prompt, mainly to serve as an illustration. The
191 191 valid escape sequences, besides color names, are:
192 192
193 193 \\# - Prompt number.
194 194 \\D - Dots, as many as there are digits in \\# (so they align).
195 195 \\w - Current working directory (cwd).
196 196 \\W - Basename of current working directory.
197 197 \\XN - Where N=0..5. N terms of the cwd, with $HOME written as ~.
198 198 \\YN - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown.
199 199 \\u - Username.
200 200 \\H - Full hostname.
201 201 \\h - Hostname up to first '.'
202 202 \\$ - Root symbol ($ or #).
203 203 \\t - Current time, in H:M:S format.
204 204 \\v - IPython release version.
205 205 \\n - Newline.
206 206 \\r - Carriage return.
207 207 \\\\ - An explicitly escaped '\\'.
208 208
209 209 You can configure your prompt colors using any ANSI color escape. Each
210 210 color escape sets the color for any subsequent text, until another escape
211 211 comes in and changes things. The valid color escapes are:
212 212
213 213 \\C_Black
214 214 \\C_Blue
215 215 \\C_Brown
216 216 \\C_Cyan
217 217 \\C_DarkGray
218 218 \\C_Green
219 219 \\C_LightBlue
220 220 \\C_LightCyan
221 221 \\C_LightGray
222 222 \\C_LightGreen
223 223 \\C_LightPurple
224 224 \\C_LightRed
225 225 \\C_Purple
226 226 \\C_Red
227 227 \\C_White
228 228 \\C_Yellow
229 229 \\C_Normal - Stop coloring, defaults to your terminal settings.
230 230 """
231 231 pass
232 232
233 233 # Configure a few things. Much of this is fairly hackish, since IPython
234 234 # doesn't really expose a clean API for it. Be careful if you start making
235 235 # many modifications here.
236 236
237 237 print """\
238 238 Welcome to pysh, a set of extensions to IPython for shell usage.
239 239 help(pysh) -> help on the installed shell extensions and syntax.
240 240 """
241 241
242 242 # Set the 'cd' command to quiet mode, a more shell-like behavior
243 243 __IPYTHON__.default_option('cd','-q')
244 244
245 245 # This is redundant, ipy_user_conf.py will determine this
246 246 # Load all of $PATH as aliases
247 #if os.name == 'posix':
247 if os.name == 'posix':
248 248 # # %rehash is very fast, but it doesn't check for executability, it simply
249 249 # # dumps everything in $PATH as an alias. Use rehashx if you want more
250 250 # # checks.
251 # __IPYTHON__.magic_rehash()
252 #else:
251 __IPYTHON__.magic_rehash()
252 else:
253 253 # # Windows users: the list of extensions considered executable is read from
254 254 # # the environment variable 'pathext'. If this is undefined, IPython
255 255 # # defaults to EXE, COM and BAT.
256 256 # # %rehashx is the one which does extension analysis, at the cost of
257 257 # # being much slower than %rehash.
258 # __IPYTHON__.magic_rehashx()
258 __IPYTHON__.magic_rehashx()
259 259
260 260 # Remove %sc,%sx if present as aliases
261 261 __IPYTHON__.magic_unalias('sc')
262 262 __IPYTHON__.magic_unalias('sx')
263 263
264 264 # We need different criteria for line-splitting, so that aliases such as
265 265 # 'gnome-terminal' are interpreted as a single alias instead of variable
266 266 # 'gnome' minus variable 'terminal'.
267 267 import re
268 268 __IPYTHON__.line_split = re.compile(r'^([\s*,;/])'
269 269 r'([\?\w\.\-\+]+\w*\s*)'
270 270 r'(\(?.*$)')
271 271
272 272 # Namespace cleanup
273 273 del re
@@ -1,49 +1,50 b''
1 1 """ User configuration file for IPython
2 2
3 3 This is a more flexible and safe way to configure ipython than *rc files
4 4 (ipythonrc, ipythonrc-pysh etc.)
5 5
6 6 This file is always imported on ipython startup. You should import all the
7 7 ipython extensions you need here (see IPython/Extensions directory).
8 8
9 9 Feel free to edit this file to customize your ipython experience. If
10 10 you wish to only use the old config system, it's perfectly ok to make this file
11 11 empty.
12 12
13 13 """
14 14
15 15 # Most of your config files and extensions will probably start with this import
16 16
17 17 import IPython.ipapi as ip
18 18
19 19 import os
20 20
21 21 o = ip.options()
22 22 # autocall 1 ('smart') is default anyway, this is just an
23 23 # example on how to set an option
24 24 o.autocall = 1
25 25
26 26 if o.profile == 'pysh':
27 27 # Jason Orendorff's path class is handy to have in user namespace
28 28 # if you are doing shell-like stuff
29 29 ip.ex("from IPython.path import path" )
30 30
31 31 # Uncomment these lines to get pysh-like prompt for all profiles.
32 32
33 33 #o.prompt_in1= '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
34 34 #o.prompt_in2= '\C_Green|\C_LightGreen\D\C_Green> '
35 35 #o.prompt_out= '<\#> '
36 36
37 37 # make 'd' an alias for ls -F
38 38
39 39 ip.magic('alias d ls -F --color=auto')
40 40
41 41 # Make available all system commands through "rehashing" immediately.
42 42 # You can comment these lines out to speed up startup on very slow
43 # machines, and to conserve a bit of memory.
44
45 if os.name=='posix':
46 ip.magic('rehash')
47 else:
48 #slightly slower, but better results esp. with Windows
49 ip.magic('rehashx')
43 # machines, and to conserve a bit of memory. Note that pysh profile does this
44 # automatically
45
46 #if os.name=='posix':
47 # ip.magic('rehash')
48 #else:
49 # #slightly slower, but better results esp. with Windows
50 # ip.magic('rehashx')
@@ -1,715 +1,716 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 1037 2006-01-20 23:27:53Z vivainio $"""
9 $Id: ipmaker.py 1041 2006-01-21 09:29:14Z vivainio $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.ipstruct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.genutils import *
55 55
56 56 #-----------------------------------------------------------------------------
57 57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 58 rc_override=None,shell_class=InteractiveShell,
59 59 embedded=False,**kw):
60 60 """This is a dump of IPython into a single function.
61 61
62 62 Later it will have to be broken up in a sensible manner.
63 63
64 64 Arguments:
65 65
66 66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 67 script name, b/c DPyGetOpt strips the first argument only for the real
68 68 sys.argv.
69 69
70 70 - user_ns: a dict to be used as the user's namespace."""
71 71
72 72 #----------------------------------------------------------------------
73 73 # Defaults and initialization
74 74
75 75 # For developer debugging, deactivates crash handler and uses pdb.
76 76 DEVDEBUG = False
77 77
78 78 if argv is None:
79 79 argv = sys.argv
80 80
81 81 # __IP is the main global that lives throughout and represents the whole
82 82 # application. If the user redefines it, all bets are off as to what
83 83 # happens.
84 84
85 85 # __IP is the name of he global which the caller will have accessible as
86 86 # __IP.name. We set its name via the first parameter passed to
87 87 # InteractiveShell:
88 88
89 89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 90 embedded=embedded,**kw)
91 91
92 92 # Put 'help' in the user namespace
93 93 from site import _Helper
94 94 IP.user_ns['help'] = _Helper()
95 95
96 96
97 97 if DEVDEBUG:
98 98 # For developer debugging only (global flag)
99 99 from IPython import ultraTB
100 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101 101
102 102 IP.BANNER_PARTS = ['Python %s\n'
103 103 'Type "copyright", "credits" or "license" '
104 104 'for more information.\n'
105 105 % (sys.version.split('\n')[0],),
106 106 "IPython %s -- An enhanced Interactive Python."
107 107 % (__version__,),
108 108 """? -> Introduction to IPython's features.
109 109 %magic -> Information about IPython's 'magic' % functions.
110 110 help -> Python's own help system.
111 111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 112 """ ]
113 113
114 114 IP.usage = interactive_usage
115 115
116 116 # Platform-dependent suffix and directory names. We use _ipython instead
117 117 # of .ipython under win32 b/c there's software that breaks with .named
118 118 # directories on that platform.
119 119 if os.name == 'posix':
120 120 rc_suffix = ''
121 121 ipdir_def = '.ipython'
122 122 else:
123 123 rc_suffix = '.ini'
124 124 ipdir_def = '_ipython'
125 125
126 126 # default directory for configuration
127 127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 # we need the directory where IPython itself is installed
131 131 import IPython
132 132 IPython_dir = os.path.dirname(IPython.__file__)
133 133 del IPython
134 134
135 135 #-------------------------------------------------------------------------
136 136 # Command line handling
137 137
138 138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 139 # GetOpt::Long)
140 140
141 141 # Any key not listed here gets deleted even if in the file (like session
142 142 # or profile). That's deliberate, to maintain the rc namespace clean.
143 143
144 144 # Each set of options appears twice: under _conv only the names are
145 145 # listed, indicating which type they must be converted to when reading the
146 146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 147 # DPyGetOpt syntax (=s,=i,:f,etc).
148 148
149 149 # Make sure there's a space before each end of line (they get auto-joined!)
150 150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 154 'quick screen_length|sl=i prompts_pad_left=i '
155 155 'logfile|lf=s logplay|lp=s profile|p=s '
156 156 'readline! readline_merge_completions! '
157 157 'readline_omit__names! '
158 158 'rcfile=s separate_in|si=s separate_out|so=s '
159 159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 160 'magic_docstrings system_verbose! '
161 161 'multi_line_specials! '
162 162 'wxversion=s '
163 163 'autoedit_syntax!')
164 164
165 165 # Options that can *only* appear at the cmd line (not in rcfiles).
166 166
167 167 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
168 168 # the 'C-c !' command in emacs automatically appends a -i option at the end.
169 169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
170 170 'gthread! qthread! wthread! pylab! tk!')
171 171
172 172 # Build the actual name list to be used by DPyGetOpt
173 173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
174 174
175 175 # Set sensible command line defaults.
176 176 # This should have everything from cmdline_opts and cmdline_only
177 177 opts_def = Struct(autocall = 1,
178 178 autoedit_syntax = 1,
179 179 autoindent=0,
180 180 automagic = 1,
181 181 banner = 1,
182 182 cache_size = 1000,
183 183 c = '',
184 184 classic = 0,
185 185 colors = 'NoColor',
186 186 color_info = 0,
187 187 confirm_exit = 1,
188 188 debug = 0,
189 189 deep_reload = 0,
190 190 editor = '0',
191 191 help = 0,
192 192 ignore = 0,
193 193 ipythondir = ipythondir,
194 194 log = 0,
195 195 logfile = '',
196 196 logplay = '',
197 197 multi_line_specials = 1,
198 198 messages = 1,
199 199 nosep = 0,
200 200 pdb = 0,
201 201 pprint = 0,
202 202 profile = '',
203 203 prompt_in1 = 'In [\\#]: ',
204 204 prompt_in2 = ' .\\D.: ',
205 205 prompt_out = 'Out[\\#]: ',
206 206 prompts_pad_left = 1,
207 207 quick = 0,
208 208 readline = 1,
209 209 readline_merge_completions = 1,
210 210 readline_omit__names = 0,
211 211 rcfile = 'ipythonrc' + rc_suffix,
212 212 screen_length = 0,
213 213 separate_in = '\n',
214 214 separate_out = '\n',
215 215 separate_out2 = '',
216 216 system_verbose = 0,
217 217 gthread = 0,
218 218 qthread = 0,
219 219 wthread = 0,
220 220 pylab = 0,
221 221 tk = 0,
222 222 upgrade = 0,
223 223 Version = 0,
224 224 xmode = 'Verbose',
225 225 wildcards_case_sensitive = 1,
226 226 wxversion = '0',
227 227 magic_docstrings = 0, # undocumented, for doc generation
228 228 )
229 229
230 230 # Things that will *only* appear in rcfiles (not at the command line).
231 231 # Make sure there's a space before each end of line (they get auto-joined!)
232 232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
233 233 qw_lol: 'import_some ',
234 234 # for things with embedded whitespace:
235 235 list_strings:'execute alias readline_parse_and_bind ',
236 236 # Regular strings need no conversion:
237 237 None:'readline_remove_delims ',
238 238 }
239 239 # Default values for these
240 240 rc_def = Struct(include = [],
241 241 import_mod = [],
242 242 import_all = [],
243 243 import_some = [[]],
244 244 execute = [],
245 245 execfile = [],
246 246 alias = [],
247 247 readline_parse_and_bind = [],
248 248 readline_remove_delims = '',
249 249 )
250 250
251 251 # Build the type conversion dictionary from the above tables:
252 252 typeconv = rcfile_opts.copy()
253 253 typeconv.update(optstr2types(cmdline_opts))
254 254
255 255 # FIXME: the None key appears in both, put that back together by hand. Ugly!
256 256 typeconv[None] += ' ' + rcfile_opts[None]
257 257
258 258 # Remove quotes at ends of all strings (used to protect spaces)
259 259 typeconv[unquote_ends] = typeconv[None]
260 260 del typeconv[None]
261 261
262 262 # Build the list we'll use to make all config decisions with defaults:
263 263 opts_all = opts_def.copy()
264 264 opts_all.update(rc_def)
265 265
266 266 # Build conflict resolver for recursive loading of config files:
267 267 # - preserve means the outermost file maintains the value, it is not
268 268 # overwritten if an included file has the same key.
269 269 # - add_flip applies + to the two values, so it better make sense to add
270 270 # those types of keys. But it flips them first so that things loaded
271 271 # deeper in the inclusion chain have lower precedence.
272 272 conflict = {'preserve': ' '.join([ typeconv[int],
273 273 typeconv[unquote_ends] ]),
274 274 'add_flip': ' '.join([ typeconv[qwflat],
275 275 typeconv[qw_lol],
276 276 typeconv[list_strings] ])
277 277 }
278 278
279 279 # Now actually process the command line
280 280 getopt = DPyGetOpt.DPyGetOpt()
281 281 getopt.setIgnoreCase(0)
282 282
283 283 getopt.parseConfiguration(opts_names)
284 284
285 285 try:
286 286 getopt.processArguments(argv)
287 287 except:
288 288 print cmd_line_usage
289 289 warn('\nError in Arguments: ' + `sys.exc_value`)
290 290 sys.exit(1)
291 291
292 292 # convert the options dict to a struct for much lighter syntax later
293 293 opts = Struct(getopt.optionValues)
294 294 args = getopt.freeValues
295 295
296 296 # this is the struct (which has default values at this point) with which
297 297 # we make all decisions:
298 298 opts_all.update(opts)
299 299
300 300 # Options that force an immediate exit
301 301 if opts_all.help:
302 302 page(cmd_line_usage)
303 303 sys.exit()
304 304
305 305 if opts_all.Version:
306 306 print __version__
307 307 sys.exit()
308 308
309 309 if opts_all.magic_docstrings:
310 310 IP.magic_magic('-latex')
311 311 sys.exit()
312 312
313 313 # Create user config directory if it doesn't exist. This must be done
314 314 # *after* getting the cmd line options.
315 315 if not os.path.isdir(opts_all.ipythondir):
316 316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
317 317
318 318 # upgrade user config files while preserving a copy of the originals
319 319 if opts_all.upgrade:
320 320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
321 321
322 322 # check mutually exclusive options in the *original* command line
323 323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
324 324 qw('classic profile'),qw('classic rcfile')])
325 325
326 326 #---------------------------------------------------------------------------
327 327 # Log replay
328 328
329 329 # if -logplay, we need to 'become' the other session. That basically means
330 330 # replacing the current command line environment with that of the old
331 331 # session and moving on.
332 332
333 333 # this is needed so that later we know we're in session reload mode, as
334 334 # opts_all will get overwritten:
335 335 load_logplay = 0
336 336
337 337 if opts_all.logplay:
338 338 load_logplay = opts_all.logplay
339 339 opts_debug_save = opts_all.debug
340 340 try:
341 341 logplay = open(opts_all.logplay)
342 342 except IOError:
343 343 if opts_all.debug: IP.InteractiveTB()
344 344 warn('Could not open logplay file '+`opts_all.logplay`)
345 345 # restore state as if nothing had happened and move on, but make
346 346 # sure that later we don't try to actually load the session file
347 347 logplay = None
348 348 load_logplay = 0
349 349 del opts_all.logplay
350 350 else:
351 351 try:
352 352 logplay.readline()
353 353 logplay.readline();
354 354 # this reloads that session's command line
355 355 cmd = logplay.readline()[6:]
356 356 exec cmd
357 357 # restore the true debug flag given so that the process of
358 358 # session loading itself can be monitored.
359 359 opts.debug = opts_debug_save
360 360 # save the logplay flag so later we don't overwrite the log
361 361 opts.logplay = load_logplay
362 362 # now we must update our own structure with defaults
363 363 opts_all.update(opts)
364 364 # now load args
365 365 cmd = logplay.readline()[6:]
366 366 exec cmd
367 367 logplay.close()
368 368 except:
369 369 logplay.close()
370 370 if opts_all.debug: IP.InteractiveTB()
371 371 warn("Logplay file lacking full configuration information.\n"
372 372 "I'll try to read it, but some things may not work.")
373 373
374 374 #-------------------------------------------------------------------------
375 375 # set up output traps: catch all output from files, being run, modules
376 376 # loaded, etc. Then give it to the user in a clean form at the end.
377 377
378 378 msg_out = 'Output messages. '
379 379 msg_err = 'Error messages. '
380 380 msg_sep = '\n'
381 381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
382 382 msg_err,msg_sep,debug,
383 383 quiet_out=1),
384 384 user_exec = OutputTrap('User File Execution',msg_out,
385 385 msg_err,msg_sep,debug),
386 386 logplay = OutputTrap('Log Loader',msg_out,
387 387 msg_err,msg_sep,debug),
388 388 summary = ''
389 389 )
390 390
391 391 #-------------------------------------------------------------------------
392 392 # Process user ipythonrc-type configuration files
393 393
394 394 # turn on output trapping and log to msg.config
395 395 # remember that with debug on, trapping is actually disabled
396 396 msg.config.trap_all()
397 397
398 398 # look for rcfile in current or default directory
399 399 try:
400 400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
401 401 except IOError:
402 402 if opts_all.debug: IP.InteractiveTB()
403 403 warn('Configuration file %s not found. Ignoring request.'
404 404 % (opts_all.rcfile) )
405 405
406 406 # 'profiles' are a shorthand notation for config filenames
407 407 if opts_all.profile:
408 408 try:
409 409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
410 410 + rc_suffix,
411 411 opts_all.ipythondir)
412 412 except IOError:
413 413 if opts_all.debug: IP.InteractiveTB()
414 414 opts.profile = '' # remove profile from options if invalid
415 415 warn('Profile configuration file %s not found. Ignoring request.'
416 416 % (opts_all.profile) )
417 417
418 418
419 419 # load the config file
420 420 rcfiledata = None
421 421 if opts_all.quick:
422 422 print 'Launching IPython in quick mode. No config file read.'
423 423 elif opts_all.classic:
424 424 print 'Launching IPython in classic mode. No config file read.'
425 425 elif opts_all.rcfile:
426 426 try:
427 427 cfg_loader = ConfigLoader(conflict)
428 428 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
429 429 'include',opts_all.ipythondir,
430 430 purge = 1,
431 431 unique = conflict['preserve'])
432 432 except:
433 433 IP.InteractiveTB()
434 434 warn('Problems loading configuration file '+
435 435 `opts_all.rcfile`+
436 436 '\nStarting with default -bare bones- configuration.')
437 437 else:
438 438 warn('No valid configuration file found in either currrent directory\n'+
439 439 'or in the IPython config. directory: '+`opts_all.ipythondir`+
440 440 '\nProceeding with internal defaults.')
441 441
442 442 #------------------------------------------------------------------------
443 443 # Set exception handlers in mode requested by user.
444 444 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
445 445 IP.magic_xmode(opts_all.xmode)
446 446 otrap.release_out()
447 447
448 448 #------------------------------------------------------------------------
449 449 # Execute user config
450 450
451 451 # Create a valid config structure with the right precedence order:
452 452 # defaults < rcfile < command line. This needs to be in the instance, so
453 453 # that method calls below that rely on it find it.
454 454 IP.rc = rc_def.copy()
455 455
456 456 # Work with a local alias inside this routine to avoid unnecessary
457 457 # attribute lookups.
458 458 IP_rc = IP.rc
459 459
460 460 IP_rc.update(opts_def)
461 461 if rcfiledata:
462 462 # now we can update
463 463 IP_rc.update(rcfiledata)
464 464 IP_rc.update(opts)
465 465 IP_rc.update(rc_override)
466 466
467 467 # Store the original cmd line for reference:
468 468 IP_rc.opts = opts
469 469 IP_rc.args = args
470 470
471 471 # create a *runtime* Struct like rc for holding parameters which may be
472 472 # created and/or modified by runtime user extensions.
473 473 IP.runtime_rc = Struct()
474 474
475 475 # from this point on, all config should be handled through IP_rc,
476 476 # opts* shouldn't be used anymore.
477 477
478 478 # add personal .ipython dir to sys.path so that users can put things in
479 479 # there for customization
480 480 sys.path.append(IP_rc.ipythondir)
481 481
482 482 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
483 483
484 484 # update IP_rc with some special things that need manual
485 485 # tweaks. Basically options which affect other options. I guess this
486 486 # should just be written so that options are fully orthogonal and we
487 487 # wouldn't worry about this stuff!
488 488
489 489 if IP_rc.classic:
490 490 IP_rc.quick = 1
491 491 IP_rc.cache_size = 0
492 492 IP_rc.pprint = 0
493 493 IP_rc.prompt_in1 = '>>> '
494 494 IP_rc.prompt_in2 = '... '
495 495 IP_rc.prompt_out = ''
496 496 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
497 497 IP_rc.colors = 'NoColor'
498 498 IP_rc.xmode = 'Plain'
499 499
500 500 # configure readline
501 501 # Define the history file for saving commands in between sessions
502 502 if IP_rc.profile:
503 503 histfname = 'history-%s' % IP_rc.profile
504 504 else:
505 505 histfname = 'history'
506 506 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
507 507
508 508 # update exception handlers with rc file status
509 509 otrap.trap_out() # I don't want these messages ever.
510 510 IP.magic_xmode(IP_rc.xmode)
511 511 otrap.release_out()
512 512
513 513 # activate logging if requested and not reloading a log
514 514 if IP_rc.logplay:
515 515 IP.magic_logstart(IP_rc.logplay + ' append')
516 516 elif IP_rc.logfile:
517 517 IP.magic_logstart(IP_rc.logfile)
518 518 elif IP_rc.log:
519 519 IP.magic_logstart()
520 520
521 521 # find user editor so that it we don't have to look it up constantly
522 522 if IP_rc.editor.strip()=='0':
523 523 try:
524 524 ed = os.environ['EDITOR']
525 525 except KeyError:
526 526 if os.name == 'posix':
527 527 ed = 'vi' # the only one guaranteed to be there!
528 528 else:
529 529 ed = 'notepad' # same in Windows!
530 530 IP_rc.editor = ed
531 531
532 532 # Keep track of whether this is an embedded instance or not (useful for
533 533 # post-mortems).
534 534 IP_rc.embedded = IP.embedded
535 535
536 536 # Recursive reload
537 537 try:
538 538 from IPython import deep_reload
539 539 if IP_rc.deep_reload:
540 540 __builtin__.reload = deep_reload.reload
541 541 else:
542 542 __builtin__.dreload = deep_reload.reload
543 543 del deep_reload
544 544 except ImportError:
545 545 pass
546 546
547 547 # Save the current state of our namespace so that the interactive shell
548 548 # can later know which variables have been created by us from config files
549 549 # and loading. This way, loading a file (in any way) is treated just like
550 550 # defining things on the command line, and %who works as expected.
551 551
552 552 # DON'T do anything that affects the namespace beyond this point!
553 553 IP.internal_ns.update(__main__.__dict__)
554 554
555 555 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
556 556
557 557 # Now run through the different sections of the users's config
558 558 if IP_rc.debug:
559 559 print 'Trying to execute the following configuration structure:'
560 560 print '(Things listed first are deeper in the inclusion tree and get'
561 561 print 'loaded first).\n'
562 562 pprint(IP_rc.__dict__)
563 563
564 564 # Make it easy to import extensions
565 565 sys.path.append(os.path.join(IPython_dir,"Extensions"))
566 566 for mod in IP_rc.import_mod:
567 567 try:
568 568 exec 'import '+mod in IP.user_ns
569 569 except :
570 570 IP.InteractiveTB()
571 571 import_fail_info(mod)
572 572
573 573 for mod_fn in IP_rc.import_some:
574 574 if mod_fn == []: break
575 575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
576 576 try:
577 577 exec 'from '+mod+' import '+fn in IP.user_ns
578 578 except :
579 579 IP.InteractiveTB()
580 580 import_fail_info(mod,fn)
581 581
582 582 for mod in IP_rc.import_all:
583 583 try:
584 584 exec 'from '+mod+' import *' in IP.user_ns
585 585 except :
586 586 IP.InteractiveTB()
587 587 import_fail_info(mod)
588 588
589 589 for code in IP_rc.execute:
590 590 try:
591 591 exec code in IP.user_ns
592 592 except:
593 593 IP.InteractiveTB()
594 594 warn('Failure executing code: ' + `code`)
595 595
596 596 # Execute the files the user wants in ipythonrc
597 597 for file in IP_rc.execfile:
598 598 try:
599 599 file = filefind(file,sys.path+[IPython_dir])
600 600 except IOError:
601 601 warn(itpl('File $file not found. Skipping it.'))
602 602 else:
603 603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
604 604
605 605 # finally, try importing ipy_*_conf for final configuration
606 606 try:
607 607 import ipy_system_conf
608 608 import ipy_user_conf
609 609
610 610 except ImportError:
611 IP.InteractiveTB()
611 pass
612 #IP.InteractiveTB() XXX uncomment in a later release
612 613
613 614 # release stdout and stderr and save config log into a global summary
614 615 msg.config.release_all()
615 616 if IP_rc.messages:
616 617 msg.summary += msg.config.summary_all()
617 618
618 619 #------------------------------------------------------------------------
619 620 # Setup interactive session
620 621
621 622 # Now we should be fully configured. We can then execute files or load
622 623 # things only needed for interactive use. Then we'll open the shell.
623 624
624 625 # Take a snapshot of the user namespace before opening the shell. That way
625 626 # we'll be able to identify which things were interactively defined and
626 627 # which were defined through config files.
627 628 IP.user_config_ns = IP.user_ns.copy()
628 629
629 630 # Force reading a file as if it were a session log. Slower but safer.
630 631 if load_logplay:
631 632 print 'Replaying log...'
632 633 try:
633 634 if IP_rc.debug:
634 635 logplay_quiet = 0
635 636 else:
636 637 logplay_quiet = 1
637 638
638 639 msg.logplay.trap_all()
639 640 IP.safe_execfile(load_logplay,IP.user_ns,
640 641 islog = 1, quiet = logplay_quiet)
641 642 msg.logplay.release_all()
642 643 if IP_rc.messages:
643 644 msg.summary += msg.logplay.summary_all()
644 645 except:
645 646 warn('Problems replaying logfile %s.' % load_logplay)
646 647 IP.InteractiveTB()
647 648
648 649 # Load remaining files in command line
649 650 msg.user_exec.trap_all()
650 651
651 652 # Do NOT execute files named in the command line as scripts to be loaded
652 653 # by embedded instances. Doing so has the potential for an infinite
653 654 # recursion if there are exceptions thrown in the process.
654 655
655 656 # XXX FIXME: the execution of user files should be moved out to after
656 657 # ipython is fully initialized, just as if they were run via %run at the
657 658 # ipython prompt. This would also give them the benefit of ipython's
658 659 # nice tracebacks.
659 660
660 661 if not embedded and IP_rc.args:
661 662 name_save = IP.user_ns['__name__']
662 663 IP.user_ns['__name__'] = '__main__'
663 664 try:
664 665 # Set our own excepthook in case the user code tries to call it
665 666 # directly. This prevents triggering the IPython crash handler.
666 667 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
667 668 for run in args:
668 669 IP.safe_execfile(run,IP.user_ns)
669 670 finally:
670 671 # Reset our crash handler in place
671 672 sys.excepthook = old_excepthook
672 673
673 674 IP.user_ns['__name__'] = name_save
674 675
675 676 msg.user_exec.release_all()
676 677 if IP_rc.messages:
677 678 msg.summary += msg.user_exec.summary_all()
678 679
679 680 # since we can't specify a null string on the cmd line, 0 is the equivalent:
680 681 if IP_rc.nosep:
681 682 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
682 683 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
683 684 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
684 685 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
685 686 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
686 687 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
687 688 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
688 689
689 690 # Determine how many lines at the bottom of the screen are needed for
690 691 # showing prompts, so we can know wheter long strings are to be printed or
691 692 # paged:
692 693 num_lines_bot = IP_rc.separate_in.count('\n')+1
693 694 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
694 695
695 696 # configure startup banner
696 697 if IP_rc.c: # regular python doesn't print the banner with -c
697 698 IP_rc.banner = 0
698 699 if IP_rc.banner:
699 700 BANN_P = IP.BANNER_PARTS
700 701 else:
701 702 BANN_P = []
702 703
703 704 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
704 705
705 706 # add message log (possibly empty)
706 707 if msg.summary: BANN_P.append(msg.summary)
707 708 # Final banner is a string
708 709 IP.BANNER = '\n'.join(BANN_P)
709 710
710 711 # Finalize the IPython instance. This assumes the rc structure is fully
711 712 # in place.
712 713 IP.post_config_initialization()
713 714
714 715 return IP
715 716 #************************ end of file <ipmaker.py> **************************
General Comments 0
You need to be logged in to leave comments. Login now