##// END OF EJS Templates
Arnd's wxversion support.
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,917 +1,933 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 994 2006-01-08 08:29:44Z fperez $"""
7 $Id: Shell.py 998 2006-01-09 06:57:40Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
21 import __main__
22 import __builtin__
22 import __builtin__
23 import os
23 import os
24 import sys
24 import sys
25 import signal
25 import signal
26 import threading
26 import threading
27
27
28 import IPython
28 import IPython
29 from IPython import ultraTB
29 from IPython import ultraTB
30 from IPython.genutils import Term,warn,error,flag_calls
30 from IPython.genutils import Term,warn,error,flag_calls
31 from IPython.iplib import InteractiveShell
31 from IPython.iplib import InteractiveShell
32 from IPython.ipmaker import make_IPython
32 from IPython.ipmaker import make_IPython
33 from IPython.Magic import Magic
33 from IPython.Magic import Magic
34 from IPython.Struct import Struct
34 from IPython.Struct import Struct
35
35
36 # global flag to pass around information about Ctrl-C without exceptions
36 # global flag to pass around information about Ctrl-C without exceptions
37 KBINT = False
37 KBINT = False
38
38
39 # global flag to turn on/off Tk support.
39 # global flag to turn on/off Tk support.
40 USE_TK = False
40 USE_TK = False
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # This class is trivial now, but I want to have it in to publish a clean
43 # This class is trivial now, but I want to have it in to publish a clean
44 # interface. Later when the internals are reorganized, code that uses this
44 # interface. Later when the internals are reorganized, code that uses this
45 # shouldn't have to change.
45 # shouldn't have to change.
46
46
47 class IPShell:
47 class IPShell:
48 """Create an IPython instance."""
48 """Create an IPython instance."""
49
49
50 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
50 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
51 debug=1,shell_class=InteractiveShell):
51 debug=1,shell_class=InteractiveShell):
52 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
52 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
53 debug=debug,shell_class=shell_class)
53 debug=debug,shell_class=shell_class)
54
54
55 def mainloop(self,sys_exit=0,banner=None):
55 def mainloop(self,sys_exit=0,banner=None):
56 self.IP.mainloop(banner)
56 self.IP.mainloop(banner)
57 if sys_exit:
57 if sys_exit:
58 sys.exit()
58 sys.exit()
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 class IPShellEmbed:
61 class IPShellEmbed:
62 """Allow embedding an IPython shell into a running program.
62 """Allow embedding an IPython shell into a running program.
63
63
64 Instances of this class are callable, with the __call__ method being an
64 Instances of this class are callable, with the __call__ method being an
65 alias to the embed() method of an InteractiveShell instance.
65 alias to the embed() method of an InteractiveShell instance.
66
66
67 Usage (see also the example-embed.py file for a running example):
67 Usage (see also the example-embed.py file for a running example):
68
68
69 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
69 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70
70
71 - argv: list containing valid command-line options for IPython, as they
71 - argv: list containing valid command-line options for IPython, as they
72 would appear in sys.argv[1:].
72 would appear in sys.argv[1:].
73
73
74 For example, the following command-line options:
74 For example, the following command-line options:
75
75
76 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
76 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77
77
78 would be passed in the argv list as:
78 would be passed in the argv list as:
79
79
80 ['-prompt_in1','Input <\\#>','-colors','LightBG']
80 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81
81
82 - banner: string which gets printed every time the interpreter starts.
82 - banner: string which gets printed every time the interpreter starts.
83
83
84 - exit_msg: string which gets printed every time the interpreter exits.
84 - exit_msg: string which gets printed every time the interpreter exits.
85
85
86 - rc_override: a dict or Struct of configuration options such as those
86 - rc_override: a dict or Struct of configuration options such as those
87 used by IPython. These options are read from your ~/.ipython/ipythonrc
87 used by IPython. These options are read from your ~/.ipython/ipythonrc
88 file when the Shell object is created. Passing an explicit rc_override
88 file when the Shell object is created. Passing an explicit rc_override
89 dict with any options you want allows you to override those values at
89 dict with any options you want allows you to override those values at
90 creation time without having to modify the file. This way you can create
90 creation time without having to modify the file. This way you can create
91 embeddable instances configured in any way you want without editing any
91 embeddable instances configured in any way you want without editing any
92 global files (thus keeping your interactive IPython configuration
92 global files (thus keeping your interactive IPython configuration
93 unchanged).
93 unchanged).
94
94
95 Then the ipshell instance can be called anywhere inside your code:
95 Then the ipshell instance can be called anywhere inside your code:
96
96
97 ipshell(header='') -> Opens up an IPython shell.
97 ipshell(header='') -> Opens up an IPython shell.
98
98
99 - header: string printed by the IPython shell upon startup. This can let
99 - header: string printed by the IPython shell upon startup. This can let
100 you know where in your code you are when dropping into the shell. Note
100 you know where in your code you are when dropping into the shell. Note
101 that 'banner' gets prepended to all calls, so header is used for
101 that 'banner' gets prepended to all calls, so header is used for
102 location-specific information.
102 location-specific information.
103
103
104 For more details, see the __call__ method below.
104 For more details, see the __call__ method below.
105
105
106 When the IPython shell is exited with Ctrl-D, normal program execution
106 When the IPython shell is exited with Ctrl-D, normal program execution
107 resumes.
107 resumes.
108
108
109 This functionality was inspired by a posting on comp.lang.python by cmkl
109 This functionality was inspired by a posting on comp.lang.python by cmkl
110 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
110 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
111 by the IDL stop/continue commands."""
111 by the IDL stop/continue commands."""
112
112
113 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
113 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 """Note that argv here is a string, NOT a list."""
114 """Note that argv here is a string, NOT a list."""
115 self.set_banner(banner)
115 self.set_banner(banner)
116 self.set_exit_msg(exit_msg)
116 self.set_exit_msg(exit_msg)
117 self.set_dummy_mode(0)
117 self.set_dummy_mode(0)
118
118
119 # sys.displayhook is a global, we need to save the user's original
119 # sys.displayhook is a global, we need to save the user's original
120 # Don't rely on __displayhook__, as the user may have changed that.
120 # Don't rely on __displayhook__, as the user may have changed that.
121 self.sys_displayhook_ori = sys.displayhook
121 self.sys_displayhook_ori = sys.displayhook
122
122
123 # save readline completer status
123 # save readline completer status
124 try:
124 try:
125 #print 'Save completer',sys.ipcompleter # dbg
125 #print 'Save completer',sys.ipcompleter # dbg
126 self.sys_ipcompleter_ori = sys.ipcompleter
126 self.sys_ipcompleter_ori = sys.ipcompleter
127 except:
127 except:
128 pass # not nested with IPython
128 pass # not nested with IPython
129
129
130 # FIXME. Passing user_ns breaks namespace handling.
130 # FIXME. Passing user_ns breaks namespace handling.
131 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
131 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
132 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133
133
134 # copy our own displayhook also
134 # copy our own displayhook also
135 self.sys_displayhook_embed = sys.displayhook
135 self.sys_displayhook_embed = sys.displayhook
136 # and leave the system's display hook clean
136 # and leave the system's display hook clean
137 sys.displayhook = self.sys_displayhook_ori
137 sys.displayhook = self.sys_displayhook_ori
138 # don't use the ipython crash handler so that user exceptions aren't
138 # don't use the ipython crash handler so that user exceptions aren't
139 # trapped
139 # trapped
140 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
140 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
141 mode = self.IP.rc.xmode,
141 mode = self.IP.rc.xmode,
142 call_pdb = self.IP.rc.pdb)
142 call_pdb = self.IP.rc.pdb)
143 self.restore_system_completer()
143 self.restore_system_completer()
144
144
145 def restore_system_completer(self):
145 def restore_system_completer(self):
146 """Restores the readline completer which was in place.
146 """Restores the readline completer which was in place.
147
147
148 This allows embedded IPython within IPython not to disrupt the
148 This allows embedded IPython within IPython not to disrupt the
149 parent's completion.
149 parent's completion.
150 """
150 """
151
151
152 try:
152 try:
153 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
153 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
154 sys.ipcompleter = self.sys_ipcompleter_ori
154 sys.ipcompleter = self.sys_ipcompleter_ori
155 except:
155 except:
156 pass
156 pass
157
157
158 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
158 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
159 """Activate the interactive interpreter.
159 """Activate the interactive interpreter.
160
160
161 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
161 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
162 the interpreter shell with the given local and global namespaces, and
162 the interpreter shell with the given local and global namespaces, and
163 optionally print a header string at startup.
163 optionally print a header string at startup.
164
164
165 The shell can be globally activated/deactivated using the
165 The shell can be globally activated/deactivated using the
166 set/get_dummy_mode methods. This allows you to turn off a shell used
166 set/get_dummy_mode methods. This allows you to turn off a shell used
167 for debugging globally.
167 for debugging globally.
168
168
169 However, *each* time you call the shell you can override the current
169 However, *each* time you call the shell you can override the current
170 state of dummy_mode with the optional keyword parameter 'dummy'. For
170 state of dummy_mode with the optional keyword parameter 'dummy'. For
171 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
171 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
172 can still have a specific call work by making it as IPShell(dummy=0).
172 can still have a specific call work by making it as IPShell(dummy=0).
173
173
174 The optional keyword parameter dummy controls whether the call
174 The optional keyword parameter dummy controls whether the call
175 actually does anything. """
175 actually does anything. """
176
176
177 # Allow the dummy parameter to override the global __dummy_mode
177 # Allow the dummy parameter to override the global __dummy_mode
178 if dummy or (dummy != 0 and self.__dummy_mode):
178 if dummy or (dummy != 0 and self.__dummy_mode):
179 return
179 return
180
180
181 # Set global subsystems (display,completions) to our values
181 # Set global subsystems (display,completions) to our values
182 sys.displayhook = self.sys_displayhook_embed
182 sys.displayhook = self.sys_displayhook_embed
183 if self.IP.has_readline:
183 if self.IP.has_readline:
184 self.IP.readline.set_completer(self.IP.Completer.complete)
184 self.IP.readline.set_completer(self.IP.Completer.complete)
185
185
186 if self.banner and header:
186 if self.banner and header:
187 format = '%s\n%s\n'
187 format = '%s\n%s\n'
188 else:
188 else:
189 format = '%s%s\n'
189 format = '%s%s\n'
190 banner = format % (self.banner,header)
190 banner = format % (self.banner,header)
191
191
192 # Call the embedding code with a stack depth of 1 so it can skip over
192 # Call the embedding code with a stack depth of 1 so it can skip over
193 # our call and get the original caller's namespaces.
193 # our call and get the original caller's namespaces.
194 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
194 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
195
195
196 if self.exit_msg:
196 if self.exit_msg:
197 print self.exit_msg
197 print self.exit_msg
198
198
199 # Restore global systems (display, completion)
199 # Restore global systems (display, completion)
200 sys.displayhook = self.sys_displayhook_ori
200 sys.displayhook = self.sys_displayhook_ori
201 self.restore_system_completer()
201 self.restore_system_completer()
202
202
203 def set_dummy_mode(self,dummy):
203 def set_dummy_mode(self,dummy):
204 """Sets the embeddable shell's dummy mode parameter.
204 """Sets the embeddable shell's dummy mode parameter.
205
205
206 set_dummy_mode(dummy): dummy = 0 or 1.
206 set_dummy_mode(dummy): dummy = 0 or 1.
207
207
208 This parameter is persistent and makes calls to the embeddable shell
208 This parameter is persistent and makes calls to the embeddable shell
209 silently return without performing any action. This allows you to
209 silently return without performing any action. This allows you to
210 globally activate or deactivate a shell you're using with a single call.
210 globally activate or deactivate a shell you're using with a single call.
211
211
212 If you need to manually"""
212 If you need to manually"""
213
213
214 if dummy not in [0,1,False,True]:
214 if dummy not in [0,1,False,True]:
215 raise ValueError,'dummy parameter must be boolean'
215 raise ValueError,'dummy parameter must be boolean'
216 self.__dummy_mode = dummy
216 self.__dummy_mode = dummy
217
217
218 def get_dummy_mode(self):
218 def get_dummy_mode(self):
219 """Return the current value of the dummy mode parameter.
219 """Return the current value of the dummy mode parameter.
220 """
220 """
221 return self.__dummy_mode
221 return self.__dummy_mode
222
222
223 def set_banner(self,banner):
223 def set_banner(self,banner):
224 """Sets the global banner.
224 """Sets the global banner.
225
225
226 This banner gets prepended to every header printed when the shell
226 This banner gets prepended to every header printed when the shell
227 instance is called."""
227 instance is called."""
228
228
229 self.banner = banner
229 self.banner = banner
230
230
231 def set_exit_msg(self,exit_msg):
231 def set_exit_msg(self,exit_msg):
232 """Sets the global exit_msg.
232 """Sets the global exit_msg.
233
233
234 This exit message gets printed upon exiting every time the embedded
234 This exit message gets printed upon exiting every time the embedded
235 shell is called. It is None by default. """
235 shell is called. It is None by default. """
236
236
237 self.exit_msg = exit_msg
237 self.exit_msg = exit_msg
238
238
239 #-----------------------------------------------------------------------------
239 #-----------------------------------------------------------------------------
240 def sigint_handler (signum,stack_frame):
240 def sigint_handler (signum,stack_frame):
241 """Sigint handler for threaded apps.
241 """Sigint handler for threaded apps.
242
242
243 This is a horrible hack to pass information about SIGINT _without_ using
243 This is a horrible hack to pass information about SIGINT _without_ using
244 exceptions, since I haven't been able to properly manage cross-thread
244 exceptions, since I haven't been able to properly manage cross-thread
245 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
245 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
246 that's my understanding from a c.l.py thread where this was discussed)."""
246 that's my understanding from a c.l.py thread where this was discussed)."""
247
247
248 global KBINT
248 global KBINT
249
249
250 print '\nKeyboardInterrupt - Press <Enter> to continue.',
250 print '\nKeyboardInterrupt - Press <Enter> to continue.',
251 Term.cout.flush()
251 Term.cout.flush()
252 # Set global flag so that runsource can know that Ctrl-C was hit
252 # Set global flag so that runsource can know that Ctrl-C was hit
253 KBINT = True
253 KBINT = True
254
254
255 class MTInteractiveShell(InteractiveShell):
255 class MTInteractiveShell(InteractiveShell):
256 """Simple multi-threaded shell."""
256 """Simple multi-threaded shell."""
257
257
258 # Threading strategy taken from:
258 # Threading strategy taken from:
259 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
259 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
260 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
260 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
261 # from the pygtk mailing list, to avoid lockups with system calls.
261 # from the pygtk mailing list, to avoid lockups with system calls.
262
262
263 # class attribute to indicate whether the class supports threads or not.
263 # class attribute to indicate whether the class supports threads or not.
264 # Subclasses with thread support should override this as needed.
264 # Subclasses with thread support should override this as needed.
265 isthreaded = True
265 isthreaded = True
266
266
267 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
267 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 user_ns=None,user_global_ns=None,banner2='',**kw):
268 user_ns=None,user_global_ns=None,banner2='',**kw):
269 """Similar to the normal InteractiveShell, but with threading control"""
269 """Similar to the normal InteractiveShell, but with threading control"""
270
270
271 InteractiveShell.__init__(self,name,usage,rc,user_ns,
271 InteractiveShell.__init__(self,name,usage,rc,user_ns,
272 user_global_ns,banner2)
272 user_global_ns,banner2)
273
273
274 # Locking control variable
274 # Locking control variable
275 self.thread_ready = threading.Condition()
275 self.thread_ready = threading.Condition()
276
276
277 # Stuff to do at closing time
277 # Stuff to do at closing time
278 self._kill = False
278 self._kill = False
279 on_kill = kw.get('on_kill')
279 on_kill = kw.get('on_kill')
280 if on_kill is None:
280 if on_kill is None:
281 on_kill = []
281 on_kill = []
282 # Check that all things to kill are callable:
282 # Check that all things to kill are callable:
283 for t in on_kill:
283 for t in on_kill:
284 if not callable(t):
284 if not callable(t):
285 raise TypeError,'on_kill must be a list of callables'
285 raise TypeError,'on_kill must be a list of callables'
286 self.on_kill = on_kill
286 self.on_kill = on_kill
287
287
288 def runsource(self, source, filename="<input>", symbol="single"):
288 def runsource(self, source, filename="<input>", symbol="single"):
289 """Compile and run some source in the interpreter.
289 """Compile and run some source in the interpreter.
290
290
291 Modified version of code.py's runsource(), to handle threading issues.
291 Modified version of code.py's runsource(), to handle threading issues.
292 See the original for full docstring details."""
292 See the original for full docstring details."""
293
293
294 global KBINT
294 global KBINT
295
295
296 # If Ctrl-C was typed, we reset the flag and return right away
296 # If Ctrl-C was typed, we reset the flag and return right away
297 if KBINT:
297 if KBINT:
298 KBINT = False
298 KBINT = False
299 return False
299 return False
300
300
301 try:
301 try:
302 code = self.compile(source, filename, symbol)
302 code = self.compile(source, filename, symbol)
303 except (OverflowError, SyntaxError, ValueError):
303 except (OverflowError, SyntaxError, ValueError):
304 # Case 1
304 # Case 1
305 self.showsyntaxerror(filename)
305 self.showsyntaxerror(filename)
306 return False
306 return False
307
307
308 if code is None:
308 if code is None:
309 # Case 2
309 # Case 2
310 return True
310 return True
311
311
312 # Case 3
312 # Case 3
313 # Store code in self, so the execution thread can handle it
313 # Store code in self, so the execution thread can handle it
314 self.thread_ready.acquire()
314 self.thread_ready.acquire()
315 self.code_to_run = code
315 self.code_to_run = code
316 self.thread_ready.wait() # Wait until processed in timeout interval
316 self.thread_ready.wait() # Wait until processed in timeout interval
317 self.thread_ready.release()
317 self.thread_ready.release()
318
318
319 return False
319 return False
320
320
321 def runcode(self):
321 def runcode(self):
322 """Execute a code object.
322 """Execute a code object.
323
323
324 Multithreaded wrapper around IPython's runcode()."""
324 Multithreaded wrapper around IPython's runcode()."""
325
325
326 # lock thread-protected stuff
326 # lock thread-protected stuff
327 self.thread_ready.acquire()
327 self.thread_ready.acquire()
328
328
329 # Install sigint handler
329 # Install sigint handler
330 try:
330 try:
331 signal.signal(signal.SIGINT, sigint_handler)
331 signal.signal(signal.SIGINT, sigint_handler)
332 except SystemError:
332 except SystemError:
333 # This happens under Windows, which seems to have all sorts
333 # This happens under Windows, which seems to have all sorts
334 # of problems with signal handling. Oh well...
334 # of problems with signal handling. Oh well...
335 pass
335 pass
336
336
337 if self._kill:
337 if self._kill:
338 print >>Term.cout, 'Closing threads...',
338 print >>Term.cout, 'Closing threads...',
339 Term.cout.flush()
339 Term.cout.flush()
340 for tokill in self.on_kill:
340 for tokill in self.on_kill:
341 tokill()
341 tokill()
342 print >>Term.cout, 'Done.'
342 print >>Term.cout, 'Done.'
343
343
344 # Run pending code by calling parent class
344 # Run pending code by calling parent class
345 if self.code_to_run is not None:
345 if self.code_to_run is not None:
346 self.thread_ready.notify()
346 self.thread_ready.notify()
347 InteractiveShell.runcode(self,self.code_to_run)
347 InteractiveShell.runcode(self,self.code_to_run)
348
348
349 # We're done with thread-protected variables
349 # We're done with thread-protected variables
350 self.thread_ready.release()
350 self.thread_ready.release()
351 # This MUST return true for gtk threading to work
351 # This MUST return true for gtk threading to work
352 return True
352 return True
353
353
354 def kill (self):
354 def kill (self):
355 """Kill the thread, returning when it has been shut down."""
355 """Kill the thread, returning when it has been shut down."""
356 self.thread_ready.acquire()
356 self.thread_ready.acquire()
357 self._kill = True
357 self._kill = True
358 self.thread_ready.release()
358 self.thread_ready.release()
359
359
360 class MatplotlibShellBase:
360 class MatplotlibShellBase:
361 """Mixin class to provide the necessary modifications to regular IPython
361 """Mixin class to provide the necessary modifications to regular IPython
362 shell classes for matplotlib support.
362 shell classes for matplotlib support.
363
363
364 Given Python's MRO, this should be used as the FIRST class in the
364 Given Python's MRO, this should be used as the FIRST class in the
365 inheritance hierarchy, so that it overrides the relevant methods."""
365 inheritance hierarchy, so that it overrides the relevant methods."""
366
366
367 def _matplotlib_config(self,name):
367 def _matplotlib_config(self,name):
368 """Return various items needed to setup the user's shell with matplotlib"""
368 """Return various items needed to setup the user's shell with matplotlib"""
369
369
370 # Initialize matplotlib to interactive mode always
370 # Initialize matplotlib to interactive mode always
371 import matplotlib
371 import matplotlib
372 from matplotlib import backends
372 from matplotlib import backends
373 matplotlib.interactive(True)
373 matplotlib.interactive(True)
374
374
375 def use(arg):
375 def use(arg):
376 """IPython wrapper for matplotlib's backend switcher.
376 """IPython wrapper for matplotlib's backend switcher.
377
377
378 In interactive use, we can not allow switching to a different
378 In interactive use, we can not allow switching to a different
379 interactive backend, since thread conflicts will most likely crash
379 interactive backend, since thread conflicts will most likely crash
380 the python interpreter. This routine does a safety check first,
380 the python interpreter. This routine does a safety check first,
381 and refuses to perform a dangerous switch. It still allows
381 and refuses to perform a dangerous switch. It still allows
382 switching to non-interactive backends."""
382 switching to non-interactive backends."""
383
383
384 if arg in backends.interactive_bk and arg != self.mpl_backend:
384 if arg in backends.interactive_bk and arg != self.mpl_backend:
385 m=('invalid matplotlib backend switch.\n'
385 m=('invalid matplotlib backend switch.\n'
386 'This script attempted to switch to the interactive '
386 'This script attempted to switch to the interactive '
387 'backend: `%s`\n'
387 'backend: `%s`\n'
388 'Your current choice of interactive backend is: `%s`\n\n'
388 'Your current choice of interactive backend is: `%s`\n\n'
389 'Switching interactive matplotlib backends at runtime\n'
389 'Switching interactive matplotlib backends at runtime\n'
390 'would crash the python interpreter, '
390 'would crash the python interpreter, '
391 'and IPython has blocked it.\n\n'
391 'and IPython has blocked it.\n\n'
392 'You need to either change your choice of matplotlib backend\n'
392 'You need to either change your choice of matplotlib backend\n'
393 'by editing your .matplotlibrc file, or run this script as a \n'
393 'by editing your .matplotlibrc file, or run this script as a \n'
394 'standalone file from the command line, not using IPython.\n' %
394 'standalone file from the command line, not using IPython.\n' %
395 (arg,self.mpl_backend) )
395 (arg,self.mpl_backend) )
396 raise RuntimeError, m
396 raise RuntimeError, m
397 else:
397 else:
398 self.mpl_use(arg)
398 self.mpl_use(arg)
399 self.mpl_use._called = True
399 self.mpl_use._called = True
400
400
401 self.matplotlib = matplotlib
401 self.matplotlib = matplotlib
402 self.mpl_backend = matplotlib.rcParams['backend']
402 self.mpl_backend = matplotlib.rcParams['backend']
403
403
404 # we also need to block switching of interactive backends by use()
404 # we also need to block switching of interactive backends by use()
405 self.mpl_use = matplotlib.use
405 self.mpl_use = matplotlib.use
406 self.mpl_use._called = False
406 self.mpl_use._called = False
407 # overwrite the original matplotlib.use with our wrapper
407 # overwrite the original matplotlib.use with our wrapper
408 matplotlib.use = use
408 matplotlib.use = use
409
409
410
410
411 # This must be imported last in the matplotlib series, after
411 # This must be imported last in the matplotlib series, after
412 # backend/interactivity choices have been made
412 # backend/interactivity choices have been made
413 try:
413 try:
414 import matplotlib.pylab as pylab
414 import matplotlib.pylab as pylab
415 self.pylab = pylab
415 self.pylab = pylab
416 self.pylab_name = 'pylab'
416 self.pylab_name = 'pylab'
417 except ImportError:
417 except ImportError:
418 import matplotlib.matlab as matlab
418 import matplotlib.matlab as matlab
419 self.pylab = matlab
419 self.pylab = matlab
420 self.pylab_name = 'matlab'
420 self.pylab_name = 'matlab'
421
421
422 self.pylab.show._needmain = False
422 self.pylab.show._needmain = False
423 # We need to detect at runtime whether show() is called by the user.
423 # We need to detect at runtime whether show() is called by the user.
424 # For this, we wrap it into a decorator which adds a 'called' flag.
424 # For this, we wrap it into a decorator which adds a 'called' flag.
425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
426
426
427 # Build a user namespace initialized with matplotlib/matlab features.
427 # Build a user namespace initialized with matplotlib/matlab features.
428 user_ns = {'__name__':'__main__',
428 user_ns = {'__name__':'__main__',
429 '__builtins__' : __builtin__ }
429 '__builtins__' : __builtin__ }
430
430
431 # Be careful not to remove the final \n in the code string below, or
431 # Be careful not to remove the final \n in the code string below, or
432 # things will break badly with py22 (I think it's a python bug, 2.3 is
432 # things will break badly with py22 (I think it's a python bug, 2.3 is
433 # OK).
433 # OK).
434 pname = self.pylab_name # Python can't interpolate dotted var names
434 pname = self.pylab_name # Python can't interpolate dotted var names
435 exec ("import matplotlib\n"
435 exec ("import matplotlib\n"
436 "import matplotlib.%(pname)s as %(pname)s\n"
436 "import matplotlib.%(pname)s as %(pname)s\n"
437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
438
438
439 # Build matplotlib info banner
439 # Build matplotlib info banner
440 b="""
440 b="""
441 Welcome to pylab, a matplotlib-based Python environment.
441 Welcome to pylab, a matplotlib-based Python environment.
442 For more information, type 'help(pylab)'.
442 For more information, type 'help(pylab)'.
443 """
443 """
444 return user_ns,b
444 return user_ns,b
445
445
446 def mplot_exec(self,fname,*where,**kw):
446 def mplot_exec(self,fname,*where,**kw):
447 """Execute a matplotlib script.
447 """Execute a matplotlib script.
448
448
449 This is a call to execfile(), but wrapped in safeties to properly
449 This is a call to execfile(), but wrapped in safeties to properly
450 handle interactive rendering and backend switching."""
450 handle interactive rendering and backend switching."""
451
451
452 #print '*** Matplotlib runner ***' # dbg
452 #print '*** Matplotlib runner ***' # dbg
453 # turn off rendering until end of script
453 # turn off rendering until end of script
454 isInteractive = self.matplotlib.rcParams['interactive']
454 isInteractive = self.matplotlib.rcParams['interactive']
455 self.matplotlib.interactive(False)
455 self.matplotlib.interactive(False)
456 self.safe_execfile(fname,*where,**kw)
456 self.safe_execfile(fname,*where,**kw)
457 self.matplotlib.interactive(isInteractive)
457 self.matplotlib.interactive(isInteractive)
458 # make rendering call now, if the user tried to do it
458 # make rendering call now, if the user tried to do it
459 if self.pylab.draw_if_interactive.called:
459 if self.pylab.draw_if_interactive.called:
460 self.pylab.draw()
460 self.pylab.draw()
461 self.pylab.draw_if_interactive.called = False
461 self.pylab.draw_if_interactive.called = False
462
462
463 # if a backend switch was performed, reverse it now
463 # if a backend switch was performed, reverse it now
464 if self.mpl_use._called:
464 if self.mpl_use._called:
465 self.matplotlib.rcParams['backend'] = self.mpl_backend
465 self.matplotlib.rcParams['backend'] = self.mpl_backend
466
466
467 def magic_run(self,parameter_s=''):
467 def magic_run(self,parameter_s=''):
468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
469
469
470 # Fix the docstring so users see the original as well
470 # Fix the docstring so users see the original as well
471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
472 "\n *** Modified %run for Matplotlib,"
472 "\n *** Modified %run for Matplotlib,"
473 " with proper interactive handling ***")
473 " with proper interactive handling ***")
474
474
475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
476 # and multithreaded. Note that these are meant for internal use, the IPShell*
476 # and multithreaded. Note that these are meant for internal use, the IPShell*
477 # classes below are the ones meant for public consumption.
477 # classes below are the ones meant for public consumption.
478
478
479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
480 """Single-threaded shell with matplotlib support."""
480 """Single-threaded shell with matplotlib support."""
481
481
482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
483 user_ns=None,user_global_ns=None,**kw):
483 user_ns=None,user_global_ns=None,**kw):
484 user_ns,b2 = self._matplotlib_config(name)
484 user_ns,b2 = self._matplotlib_config(name)
485 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
485 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
486 banner2=b2,**kw)
486 banner2=b2,**kw)
487
487
488 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
488 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
489 """Multi-threaded shell with matplotlib support."""
489 """Multi-threaded shell with matplotlib support."""
490
490
491 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
491 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
492 user_ns=None,user_global_ns=None, **kw):
492 user_ns=None,user_global_ns=None, **kw):
493 user_ns,b2 = self._matplotlib_config(name)
493 user_ns,b2 = self._matplotlib_config(name)
494 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
494 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
495 banner2=b2,**kw)
495 banner2=b2,**kw)
496
496
497 #-----------------------------------------------------------------------------
497 #-----------------------------------------------------------------------------
498 # Utility functions for the different GUI enabled IPShell* classes.
498 # Utility functions for the different GUI enabled IPShell* classes.
499
499
500 def get_tk():
500 def get_tk():
501 """Tries to import Tkinter and returns a withdrawn Tkinter root
501 """Tries to import Tkinter and returns a withdrawn Tkinter root
502 window. If Tkinter is already imported or not available, this
502 window. If Tkinter is already imported or not available, this
503 returns None. This function calls `hijack_tk` underneath.
503 returns None. This function calls `hijack_tk` underneath.
504 """
504 """
505 if not USE_TK or sys.modules.has_key('Tkinter'):
505 if not USE_TK or sys.modules.has_key('Tkinter'):
506 return None
506 return None
507 else:
507 else:
508 try:
508 try:
509 import Tkinter
509 import Tkinter
510 except ImportError:
510 except ImportError:
511 return None
511 return None
512 else:
512 else:
513 hijack_tk()
513 hijack_tk()
514 r = Tkinter.Tk()
514 r = Tkinter.Tk()
515 r.withdraw()
515 r.withdraw()
516 return r
516 return r
517
517
518 def hijack_tk():
518 def hijack_tk():
519 """Modifies Tkinter's mainloop with a dummy so when a module calls
519 """Modifies Tkinter's mainloop with a dummy so when a module calls
520 mainloop, it does not block.
520 mainloop, it does not block.
521
521
522 """
522 """
523 def misc_mainloop(self, n=0):
523 def misc_mainloop(self, n=0):
524 pass
524 pass
525 def tkinter_mainloop(n=0):
525 def tkinter_mainloop(n=0):
526 pass
526 pass
527
527
528 import Tkinter
528 import Tkinter
529 Tkinter.Misc.mainloop = misc_mainloop
529 Tkinter.Misc.mainloop = misc_mainloop
530 Tkinter.mainloop = tkinter_mainloop
530 Tkinter.mainloop = tkinter_mainloop
531
531
532 def update_tk(tk):
532 def update_tk(tk):
533 """Updates the Tkinter event loop. This is typically called from
533 """Updates the Tkinter event loop. This is typically called from
534 the respective WX or GTK mainloops.
534 the respective WX or GTK mainloops.
535 """
535 """
536 if tk:
536 if tk:
537 tk.update()
537 tk.update()
538
538
539 def hijack_wx():
539 def hijack_wx():
540 """Modifies wxPython's MainLoop with a dummy so user code does not
540 """Modifies wxPython's MainLoop with a dummy so user code does not
541 block IPython. The hijacked mainloop function is returned.
541 block IPython. The hijacked mainloop function is returned.
542 """
542 """
543 def dummy_mainloop(*args, **kw):
543 def dummy_mainloop(*args, **kw):
544 pass
544 pass
545 import wxPython
545 import wxPython
546 ver = wxPython.__version__
546 ver = wxPython.__version__
547 orig_mainloop = None
547 orig_mainloop = None
548 if ver[:3] >= '2.5':
548 if ver[:3] >= '2.5':
549 import wx
549 import wx
550 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
550 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
551 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
551 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
552 else: raise AttributeError('Could not find wx core module')
552 else: raise AttributeError('Could not find wx core module')
553 orig_mainloop = core.PyApp_MainLoop
553 orig_mainloop = core.PyApp_MainLoop
554 core.PyApp_MainLoop = dummy_mainloop
554 core.PyApp_MainLoop = dummy_mainloop
555 elif ver[:3] == '2.4':
555 elif ver[:3] == '2.4':
556 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
556 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
557 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
557 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
558 else:
558 else:
559 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
559 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
560 return orig_mainloop
560 return orig_mainloop
561
561
562 def hijack_gtk():
562 def hijack_gtk():
563 """Modifies pyGTK's mainloop with a dummy so user code does not
563 """Modifies pyGTK's mainloop with a dummy so user code does not
564 block IPython. This function returns the original `gtk.mainloop`
564 block IPython. This function returns the original `gtk.mainloop`
565 function that has been hijacked.
565 function that has been hijacked.
566 """
566 """
567 def dummy_mainloop(*args, **kw):
567 def dummy_mainloop(*args, **kw):
568 pass
568 pass
569 import gtk
569 import gtk
570 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
570 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
571 else: orig_mainloop = gtk.mainloop
571 else: orig_mainloop = gtk.mainloop
572 gtk.mainloop = dummy_mainloop
572 gtk.mainloop = dummy_mainloop
573 gtk.main = dummy_mainloop
573 gtk.main = dummy_mainloop
574 return orig_mainloop
574 return orig_mainloop
575
575
576 #-----------------------------------------------------------------------------
576 #-----------------------------------------------------------------------------
577 # The IPShell* classes below are the ones meant to be run by external code as
577 # The IPShell* classes below are the ones meant to be run by external code as
578 # IPython instances. Note that unless a specific threading strategy is
578 # IPython instances. Note that unless a specific threading strategy is
579 # desired, the factory function start() below should be used instead (it
579 # desired, the factory function start() below should be used instead (it
580 # selects the proper threaded class).
580 # selects the proper threaded class).
581
581
582 class IPShellGTK(threading.Thread):
582 class IPShellGTK(threading.Thread):
583 """Run a gtk mainloop() in a separate thread.
583 """Run a gtk mainloop() in a separate thread.
584
584
585 Python commands can be passed to the thread where they will be executed.
585 Python commands can be passed to the thread where they will be executed.
586 This is implemented by periodically checking for passed code using a
586 This is implemented by periodically checking for passed code using a
587 GTK timeout callback."""
587 GTK timeout callback."""
588
588
589 TIMEOUT = 100 # Millisecond interval between timeouts.
589 TIMEOUT = 100 # Millisecond interval between timeouts.
590
590
591 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
591 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
592 debug=1,shell_class=MTInteractiveShell):
592 debug=1,shell_class=MTInteractiveShell):
593
593
594 import gtk
594 import gtk
595
595
596 self.gtk = gtk
596 self.gtk = gtk
597 self.gtk_mainloop = hijack_gtk()
597 self.gtk_mainloop = hijack_gtk()
598
598
599 # Allows us to use both Tk and GTK.
599 # Allows us to use both Tk and GTK.
600 self.tk = get_tk()
600 self.tk = get_tk()
601
601
602 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
602 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
603 else: mainquit = self.gtk.mainquit
603 else: mainquit = self.gtk.mainquit
604
604
605 self.IP = make_IPython(argv,user_ns=user_ns,
605 self.IP = make_IPython(argv,user_ns=user_ns,
606 user_global_ns=user_global_ns,
606 user_global_ns=user_global_ns,
607 debug=debug,
607 debug=debug,
608 shell_class=shell_class,
608 shell_class=shell_class,
609 on_kill=[mainquit])
609 on_kill=[mainquit])
610
610
611 # HACK: slot for banner in self; it will be passed to the mainloop
611 # HACK: slot for banner in self; it will be passed to the mainloop
612 # method only and .run() needs it. The actual value will be set by
612 # method only and .run() needs it. The actual value will be set by
613 # .mainloop().
613 # .mainloop().
614 self._banner = None
614 self._banner = None
615
615
616 threading.Thread.__init__(self)
616 threading.Thread.__init__(self)
617
617
618 def run(self):
618 def run(self):
619 self.IP.mainloop(self._banner)
619 self.IP.mainloop(self._banner)
620 self.IP.kill()
620 self.IP.kill()
621
621
622 def mainloop(self,sys_exit=0,banner=None):
622 def mainloop(self,sys_exit=0,banner=None):
623
623
624 self._banner = banner
624 self._banner = banner
625
625
626 if self.gtk.pygtk_version >= (2,4,0):
626 if self.gtk.pygtk_version >= (2,4,0):
627 import gobject
627 import gobject
628 gobject.timeout_add(self.TIMEOUT, self.on_timer)
628 gobject.timeout_add(self.TIMEOUT, self.on_timer)
629 else:
629 else:
630 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
630 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
631
631
632 if sys.platform != 'win32':
632 if sys.platform != 'win32':
633 try:
633 try:
634 if self.gtk.gtk_version[0] >= 2:
634 if self.gtk.gtk_version[0] >= 2:
635 self.gtk.threads_init()
635 self.gtk.threads_init()
636 except AttributeError:
636 except AttributeError:
637 pass
637 pass
638 except RuntimeError:
638 except RuntimeError:
639 error('Your pyGTK likely has not been compiled with '
639 error('Your pyGTK likely has not been compiled with '
640 'threading support.\n'
640 'threading support.\n'
641 'The exception printout is below.\n'
641 'The exception printout is below.\n'
642 'You can either rebuild pyGTK with threads, or '
642 'You can either rebuild pyGTK with threads, or '
643 'try using \n'
643 'try using \n'
644 'matplotlib with a different backend (like Tk or WX).\n'
644 'matplotlib with a different backend (like Tk or WX).\n'
645 'Note that matplotlib will most likely not work in its '
645 'Note that matplotlib will most likely not work in its '
646 'current state!')
646 'current state!')
647 self.IP.InteractiveTB()
647 self.IP.InteractiveTB()
648 self.start()
648 self.start()
649 self.gtk.threads_enter()
649 self.gtk.threads_enter()
650 self.gtk_mainloop()
650 self.gtk_mainloop()
651 self.gtk.threads_leave()
651 self.gtk.threads_leave()
652 self.join()
652 self.join()
653
653
654 def on_timer(self):
654 def on_timer(self):
655 update_tk(self.tk)
655 update_tk(self.tk)
656 return self.IP.runcode()
656 return self.IP.runcode()
657
657
658
658
659 class IPShellWX(threading.Thread):
659 class IPShellWX(threading.Thread):
660 """Run a wx mainloop() in a separate thread.
660 """Run a wx mainloop() in a separate thread.
661
661
662 Python commands can be passed to the thread where they will be executed.
662 Python commands can be passed to the thread where they will be executed.
663 This is implemented by periodically checking for passed code using a
663 This is implemented by periodically checking for passed code using a
664 GTK timeout callback."""
664 GTK timeout callback."""
665
665
666 TIMEOUT = 100 # Millisecond interval between timeouts.
666 TIMEOUT = 100 # Millisecond interval between timeouts.
667
667
668 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
668 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
669 debug=1,shell_class=MTInteractiveShell):
669 debug=1,shell_class=MTInteractiveShell):
670
670
671 self.IP = make_IPython(argv,user_ns=user_ns,
672 user_global_ns=user_global_ns,
673 debug=debug,
674 shell_class=shell_class,
675 on_kill=[self.wxexit])
676
677 wantedwxversion=self.IP.rc.wxversion
678 if wantedwxversion!="0":
679 try:
680 import wxversion
681 except ImportError:
682 error('The wxversion module is needed for WX version selection')
683 else:
684 try:
685 wxversion.select(wantedwxversion)
686 except:
687 self.IP.InteractiveTB()
688 error('Requested wxPython version %s could not be loaded' %
689 wantedwxversion)
690
671 import wxPython.wx as wx
691 import wxPython.wx as wx
672
692
673 threading.Thread.__init__(self)
693 threading.Thread.__init__(self)
674 self.wx = wx
694 self.wx = wx
675 self.wx_mainloop = hijack_wx()
695 self.wx_mainloop = hijack_wx()
676
696
677 # Allows us to use both Tk and GTK.
697 # Allows us to use both Tk and GTK.
678 self.tk = get_tk()
698 self.tk = get_tk()
679
699
680 self.IP = make_IPython(argv,user_ns=user_ns,
700
681 user_global_ns=user_global_ns,
682 debug=debug,
683 shell_class=shell_class,
684 on_kill=[self.wxexit])
685 # HACK: slot for banner in self; it will be passed to the mainloop
701 # HACK: slot for banner in self; it will be passed to the mainloop
686 # method only and .run() needs it. The actual value will be set by
702 # method only and .run() needs it. The actual value will be set by
687 # .mainloop().
703 # .mainloop().
688 self._banner = None
704 self._banner = None
689
705
690 self.app = None
706 self.app = None
691
707
692 def wxexit(self, *args):
708 def wxexit(self, *args):
693 if self.app is not None:
709 if self.app is not None:
694 self.app.agent.timer.Stop()
710 self.app.agent.timer.Stop()
695 self.app.ExitMainLoop()
711 self.app.ExitMainLoop()
696
712
697 def run(self):
713 def run(self):
698 self.IP.mainloop(self._banner)
714 self.IP.mainloop(self._banner)
699 self.IP.kill()
715 self.IP.kill()
700
716
701 def mainloop(self,sys_exit=0,banner=None):
717 def mainloop(self,sys_exit=0,banner=None):
702
718
703 self._banner = banner
719 self._banner = banner
704
720
705 self.start()
721 self.start()
706
722
707 class TimerAgent(self.wx.wxMiniFrame):
723 class TimerAgent(self.wx.wxMiniFrame):
708 wx = self.wx
724 wx = self.wx
709 IP = self.IP
725 IP = self.IP
710 tk = self.tk
726 tk = self.tk
711 def __init__(self, parent, interval):
727 def __init__(self, parent, interval):
712 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
728 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
713 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
729 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
714 size=(100, 100),style=style)
730 size=(100, 100),style=style)
715 self.Show(False)
731 self.Show(False)
716 self.interval = interval
732 self.interval = interval
717 self.timerId = self.wx.wxNewId()
733 self.timerId = self.wx.wxNewId()
718
734
719 def StartWork(self):
735 def StartWork(self):
720 self.timer = self.wx.wxTimer(self, self.timerId)
736 self.timer = self.wx.wxTimer(self, self.timerId)
721 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
737 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
722 self.timer.Start(self.interval)
738 self.timer.Start(self.interval)
723
739
724 def OnTimer(self, event):
740 def OnTimer(self, event):
725 update_tk(self.tk)
741 update_tk(self.tk)
726 self.IP.runcode()
742 self.IP.runcode()
727
743
728 class App(self.wx.wxApp):
744 class App(self.wx.wxApp):
729 wx = self.wx
745 wx = self.wx
730 TIMEOUT = self.TIMEOUT
746 TIMEOUT = self.TIMEOUT
731 def OnInit(self):
747 def OnInit(self):
732 'Create the main window and insert the custom frame'
748 'Create the main window and insert the custom frame'
733 self.agent = TimerAgent(None, self.TIMEOUT)
749 self.agent = TimerAgent(None, self.TIMEOUT)
734 self.agent.Show(self.wx.false)
750 self.agent.Show(self.wx.false)
735 self.agent.StartWork()
751 self.agent.StartWork()
736 return self.wx.true
752 return self.wx.true
737
753
738 self.app = App(redirect=False)
754 self.app = App(redirect=False)
739 self.wx_mainloop(self.app)
755 self.wx_mainloop(self.app)
740 self.join()
756 self.join()
741
757
742
758
743 class IPShellQt(threading.Thread):
759 class IPShellQt(threading.Thread):
744 """Run a Qt event loop in a separate thread.
760 """Run a Qt event loop in a separate thread.
745
761
746 Python commands can be passed to the thread where they will be executed.
762 Python commands can be passed to the thread where they will be executed.
747 This is implemented by periodically checking for passed code using a
763 This is implemented by periodically checking for passed code using a
748 Qt timer / slot."""
764 Qt timer / slot."""
749
765
750 TIMEOUT = 100 # Millisecond interval between timeouts.
766 TIMEOUT = 100 # Millisecond interval between timeouts.
751
767
752 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
768 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
753 debug=0,shell_class=MTInteractiveShell):
769 debug=0,shell_class=MTInteractiveShell):
754
770
755 import qt
771 import qt
756
772
757 class newQApplication:
773 class newQApplication:
758 def __init__( self ):
774 def __init__( self ):
759 self.QApplication = qt.QApplication
775 self.QApplication = qt.QApplication
760
776
761 def __call__( *args, **kwargs ):
777 def __call__( *args, **kwargs ):
762 return qt.qApp
778 return qt.qApp
763
779
764 def exec_loop( *args, **kwargs ):
780 def exec_loop( *args, **kwargs ):
765 pass
781 pass
766
782
767 def __getattr__( self, name ):
783 def __getattr__( self, name ):
768 return getattr( self.QApplication, name )
784 return getattr( self.QApplication, name )
769
785
770 qt.QApplication = newQApplication()
786 qt.QApplication = newQApplication()
771
787
772 # Allows us to use both Tk and QT.
788 # Allows us to use both Tk and QT.
773 self.tk = get_tk()
789 self.tk = get_tk()
774
790
775 self.IP = make_IPython(argv,user_ns=user_ns,
791 self.IP = make_IPython(argv,user_ns=user_ns,
776 user_global_ns=user_global_ns,
792 user_global_ns=user_global_ns,
777 debug=debug,
793 debug=debug,
778 shell_class=shell_class,
794 shell_class=shell_class,
779 on_kill=[qt.qApp.exit])
795 on_kill=[qt.qApp.exit])
780
796
781 # HACK: slot for banner in self; it will be passed to the mainloop
797 # HACK: slot for banner in self; it will be passed to the mainloop
782 # method only and .run() needs it. The actual value will be set by
798 # method only and .run() needs it. The actual value will be set by
783 # .mainloop().
799 # .mainloop().
784 self._banner = None
800 self._banner = None
785
801
786 threading.Thread.__init__(self)
802 threading.Thread.__init__(self)
787
803
788 def run(self):
804 def run(self):
789 self.IP.mainloop(self._banner)
805 self.IP.mainloop(self._banner)
790 self.IP.kill()
806 self.IP.kill()
791
807
792 def mainloop(self,sys_exit=0,banner=None):
808 def mainloop(self,sys_exit=0,banner=None):
793
809
794 import qt
810 import qt
795
811
796 self._banner = banner
812 self._banner = banner
797
813
798 if qt.QApplication.startingUp():
814 if qt.QApplication.startingUp():
799 a = qt.QApplication.QApplication(sys.argv)
815 a = qt.QApplication.QApplication(sys.argv)
800 self.timer = qt.QTimer()
816 self.timer = qt.QTimer()
801 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
817 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
802
818
803 self.start()
819 self.start()
804 self.timer.start( self.TIMEOUT, True )
820 self.timer.start( self.TIMEOUT, True )
805 while True:
821 while True:
806 if self.IP._kill: break
822 if self.IP._kill: break
807 qt.qApp.exec_loop()
823 qt.qApp.exec_loop()
808 self.join()
824 self.join()
809
825
810 def on_timer(self):
826 def on_timer(self):
811 update_tk(self.tk)
827 update_tk(self.tk)
812 result = self.IP.runcode()
828 result = self.IP.runcode()
813 self.timer.start( self.TIMEOUT, True )
829 self.timer.start( self.TIMEOUT, True )
814 return result
830 return result
815
831
816 # A set of matplotlib public IPython shell classes, for single-threaded
832 # A set of matplotlib public IPython shell classes, for single-threaded
817 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
833 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
818 class IPShellMatplotlib(IPShell):
834 class IPShellMatplotlib(IPShell):
819 """Subclass IPShell with MatplotlibShell as the internal shell.
835 """Subclass IPShell with MatplotlibShell as the internal shell.
820
836
821 Single-threaded class, meant for the Tk* and FLTK* backends.
837 Single-threaded class, meant for the Tk* and FLTK* backends.
822
838
823 Having this on a separate class simplifies the external driver code."""
839 Having this on a separate class simplifies the external driver code."""
824
840
825 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
841 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
826 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
842 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
827 shell_class=MatplotlibShell)
843 shell_class=MatplotlibShell)
828
844
829 class IPShellMatplotlibGTK(IPShellGTK):
845 class IPShellMatplotlibGTK(IPShellGTK):
830 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
846 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
831
847
832 Multi-threaded class, meant for the GTK* backends."""
848 Multi-threaded class, meant for the GTK* backends."""
833
849
834 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
850 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
835 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
851 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
836 shell_class=MatplotlibMTShell)
852 shell_class=MatplotlibMTShell)
837
853
838 class IPShellMatplotlibWX(IPShellWX):
854 class IPShellMatplotlibWX(IPShellWX):
839 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
855 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
840
856
841 Multi-threaded class, meant for the WX* backends."""
857 Multi-threaded class, meant for the WX* backends."""
842
858
843 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
859 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
844 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
860 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
845 shell_class=MatplotlibMTShell)
861 shell_class=MatplotlibMTShell)
846
862
847 class IPShellMatplotlibQt(IPShellQt):
863 class IPShellMatplotlibQt(IPShellQt):
848 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
864 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
849
865
850 Multi-threaded class, meant for the Qt* backends."""
866 Multi-threaded class, meant for the Qt* backends."""
851
867
852 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
868 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
853 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
869 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
854 shell_class=MatplotlibMTShell)
870 shell_class=MatplotlibMTShell)
855
871
856 #-----------------------------------------------------------------------------
872 #-----------------------------------------------------------------------------
857 # Factory functions to actually start the proper thread-aware shell
873 # Factory functions to actually start the proper thread-aware shell
858
874
859 def _matplotlib_shell_class():
875 def _matplotlib_shell_class():
860 """Factory function to handle shell class selection for matplotlib.
876 """Factory function to handle shell class selection for matplotlib.
861
877
862 The proper shell class to use depends on the matplotlib backend, since
878 The proper shell class to use depends on the matplotlib backend, since
863 each backend requires a different threading strategy."""
879 each backend requires a different threading strategy."""
864
880
865 try:
881 try:
866 import matplotlib
882 import matplotlib
867 except ImportError:
883 except ImportError:
868 error('matplotlib could NOT be imported! Starting normal IPython.')
884 error('matplotlib could NOT be imported! Starting normal IPython.')
869 sh_class = IPShell
885 sh_class = IPShell
870 else:
886 else:
871 backend = matplotlib.rcParams['backend']
887 backend = matplotlib.rcParams['backend']
872 if backend.startswith('GTK'):
888 if backend.startswith('GTK'):
873 sh_class = IPShellMatplotlibGTK
889 sh_class = IPShellMatplotlibGTK
874 elif backend.startswith('WX'):
890 elif backend.startswith('WX'):
875 sh_class = IPShellMatplotlibWX
891 sh_class = IPShellMatplotlibWX
876 elif backend.startswith('Qt'):
892 elif backend.startswith('Qt'):
877 sh_class = IPShellMatplotlibQt
893 sh_class = IPShellMatplotlibQt
878 else:
894 else:
879 sh_class = IPShellMatplotlib
895 sh_class = IPShellMatplotlib
880 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
896 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
881 return sh_class
897 return sh_class
882
898
883 # This is the one which should be called by external code.
899 # This is the one which should be called by external code.
884 def start():
900 def start():
885 """Return a running shell instance, dealing with threading options.
901 """Return a running shell instance, dealing with threading options.
886
902
887 This is a factory function which will instantiate the proper IPython shell
903 This is a factory function which will instantiate the proper IPython shell
888 based on the user's threading choice. Such a selector is needed because
904 based on the user's threading choice. Such a selector is needed because
889 different GUI toolkits require different thread handling details."""
905 different GUI toolkits require different thread handling details."""
890
906
891 global USE_TK
907 global USE_TK
892 # Crude sys.argv hack to extract the threading options.
908 # Crude sys.argv hack to extract the threading options.
893 argv = sys.argv
909 argv = sys.argv
894 if len(argv) > 1:
910 if len(argv) > 1:
895 if len(argv) > 2:
911 if len(argv) > 2:
896 arg2 = argv[2]
912 arg2 = argv[2]
897 if arg2.endswith('-tk'):
913 if arg2.endswith('-tk'):
898 USE_TK = True
914 USE_TK = True
899 arg1 = argv[1]
915 arg1 = argv[1]
900 if arg1.endswith('-gthread'):
916 if arg1.endswith('-gthread'):
901 shell = IPShellGTK
917 shell = IPShellGTK
902 elif arg1.endswith( '-qthread' ):
918 elif arg1.endswith( '-qthread' ):
903 shell = IPShellQt
919 shell = IPShellQt
904 elif arg1.endswith('-wthread'):
920 elif arg1.endswith('-wthread'):
905 shell = IPShellWX
921 shell = IPShellWX
906 elif arg1.endswith('-pylab'):
922 elif arg1.endswith('-pylab'):
907 shell = _matplotlib_shell_class()
923 shell = _matplotlib_shell_class()
908 else:
924 else:
909 shell = IPShell
925 shell = IPShell
910 else:
926 else:
911 shell = IPShell
927 shell = IPShell
912 return shell()
928 return shell()
913
929
914 # Some aliases for backwards compatibility
930 # Some aliases for backwards compatibility
915 IPythonShell = IPShell
931 IPythonShell = IPShell
916 IPythonShellEmbed = IPShellEmbed
932 IPythonShellEmbed = IPShellEmbed
917 #************************ End of file <Shell.py> ***************************
933 #************************ End of file <Shell.py> ***************************
@@ -1,587 +1,597 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 990 2006-01-04 06:59:02Z fperez $
2 # $Id: ipythonrc 998 2006-01-09 06:57:40Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40
40
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 # are automatically called when invoked at the command line, even if you don't
43 # type parentheses. IPython adds the parentheses for you. For example:
43 # type parentheses. IPython adds the parentheses for you. For example:
44
44
45 #In [1]: str 45
45 #In [1]: str 45
46 #------> str(45)
46 #------> str(45)
47 #Out[1]: '45'
47 #Out[1]: '45'
48
48
49 # IPython reprints your line with '---->' indicating that it added
49 # IPython reprints your line with '---->' indicating that it added
50 # parentheses. While this option is very convenient for interactive use, it
50 # parentheses. While this option is very convenient for interactive use, it
51 # may occasionally cause problems with objects which have side-effects if
51 # may occasionally cause problems with objects which have side-effects if
52 # called unexpectedly.
52 # called unexpectedly.
53
53
54 # The valid values for autocall are:
54 # The valid values for autocall are:
55
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
59
60 # In this mode, you get:
60 # In this mode, you get:
61
61
62 #In [1]: callable
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
63 #Out[1]: <built-in function callable>
64
64
65 #In [2]: callable 'hello'
65 #In [2]: callable 'hello'
66 #------> callable('hello')
66 #------> callable('hello')
67 #Out[2]: False
67 #Out[2]: False
68
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
70 # is called:
71
71
72 #In [4]: callable
72 #In [4]: callable
73 #------> callable()
73 #------> callable()
74
74
75 # Note that even with autocall off, you can still use '/' at the start of a
75 # Note that even with autocall off, you can still use '/' at the start of a
76 # line to treat the first argument on the command line as a function and add
76 # line to treat the first argument on the command line as a function and add
77 # parentheses to it:
77 # parentheses to it:
78
78
79 #In [8]: /str 43
79 #In [8]: /str 43
80 #------> str(43)
80 #------> str(43)
81 #Out[8]: '43'
81 #Out[8]: '43'
82
82
83 autocall 1
83 autocall 1
84
84
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
86 # source code (see the 'editor' variable below), it is possible that you save
86 # source code (see the 'editor' variable below), it is possible that you save
87 # a file with syntax errors in it. If this variable is true, IPython will ask
87 # a file with syntax errors in it. If this variable is true, IPython will ask
88 # you whether to re-open the editor immediately to correct such an error.
88 # you whether to re-open the editor immediately to correct such an error.
89
89
90 autoedit_syntax 1
90 autoedit_syntax 1
91
91
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
93 # line, while also un-indenting automatically after 'raise' or 'return'.
93 # line, while also un-indenting automatically after 'raise' or 'return'.
94
94
95 # This feature uses the readline library, so it will honor your ~/.inputrc
95 # This feature uses the readline library, so it will honor your ~/.inputrc
96 # configuration (or whatever file your INPUTRC variable points to). Adding
96 # configuration (or whatever file your INPUTRC variable points to). Adding
97 # the following lines to your .inputrc file can make indent/unindenting more
97 # the following lines to your .inputrc file can make indent/unindenting more
98 # convenient (M-i indents, M-u unindents):
98 # convenient (M-i indents, M-u unindents):
99
99
100 # $if Python
100 # $if Python
101 # "\M-i": " "
101 # "\M-i": " "
102 # "\M-u": "\d\d\d\d"
102 # "\M-u": "\d\d\d\d"
103 # $endif
103 # $endif
104
104
105 # The feature is potentially a bit dangerous, because it can cause problems
105 # The feature is potentially a bit dangerous, because it can cause problems
106 # with pasting of indented code (the pasted code gets re-indented on each
106 # with pasting of indented code (the pasted code gets re-indented on each
107 # line). But it's a huge time-saver when working interactively. The magic
107 # line). But it's a huge time-saver when working interactively. The magic
108 # function @autoindent allows you to toggle it on/off at runtime.
108 # function @autoindent allows you to toggle it on/off at runtime.
109
109
110 autoindent 1
110 autoindent 1
111
111
112 # Auto-magic. This gives you access to all the magic functions without having
112 # Auto-magic. This gives you access to all the magic functions without having
113 # to prepend them with an @ sign. If you define a variable with the same name
113 # to prepend them with an @ sign. If you define a variable with the same name
114 # as a magic function (say who=1), you will need to access the magic function
114 # as a magic function (say who=1), you will need to access the magic function
115 # with @ (@who in this example). However, if later you delete your variable
115 # with @ (@who in this example). However, if later you delete your variable
116 # (del who), you'll recover the automagic calling form.
116 # (del who), you'll recover the automagic calling form.
117
117
118 # Considering that many magic functions provide a lot of shell-like
118 # Considering that many magic functions provide a lot of shell-like
119 # functionality, automagic gives you something close to a full Python+system
119 # functionality, automagic gives you something close to a full Python+system
120 # shell environment (and you can extend it further if you want).
120 # shell environment (and you can extend it further if you want).
121
121
122 automagic 1
122 automagic 1
123
123
124 # Size of the output cache. After this many entries are stored, the cache will
124 # Size of the output cache. After this many entries are stored, the cache will
125 # get flushed. Depending on the size of your intermediate calculations, you
125 # get flushed. Depending on the size of your intermediate calculations, you
126 # may have memory problems if you make it too big, since keeping things in the
126 # may have memory problems if you make it too big, since keeping things in the
127 # cache prevents Python from reclaiming the memory for old results. Experiment
127 # cache prevents Python from reclaiming the memory for old results. Experiment
128 # with a value that works well for you.
128 # with a value that works well for you.
129
129
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
133 # you are running on a slow machine or with very limited memory, this may
133 # you are running on a slow machine or with very limited memory, this may
134 # help.
134 # help.
135
135
136 cache_size 1000
136 cache_size 1000
137
137
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
139 # but that's your choice! Classic 1 -> same as IPython -classic.
139 # but that's your choice! Classic 1 -> same as IPython -classic.
140 # Note that this is _not_ the normal python interpreter, it's simply
140 # Note that this is _not_ the normal python interpreter, it's simply
141 # IPython emulating most of the classic interpreter's behavior.
141 # IPython emulating most of the classic interpreter's behavior.
142 classic 0
142 classic 0
143
143
144 # colors - Coloring option for prompts and traceback printouts.
144 # colors - Coloring option for prompts and traceback printouts.
145
145
146 # Currently available schemes: NoColor, Linux, LightBG.
146 # Currently available schemes: NoColor, Linux, LightBG.
147
147
148 # This option allows coloring the prompts and traceback printouts. This
148 # This option allows coloring the prompts and traceback printouts. This
149 # requires a terminal which can properly handle color escape sequences. If you
149 # requires a terminal which can properly handle color escape sequences. If you
150 # are having problems with this, use the NoColor scheme (uses no color escapes
150 # are having problems with this, use the NoColor scheme (uses no color escapes
151 # at all).
151 # at all).
152
152
153 # The Linux option works well in linux console type environments: dark
153 # The Linux option works well in linux console type environments: dark
154 # background with light fonts.
154 # background with light fonts.
155
155
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
157 # in light background terminals.
157 # in light background terminals.
158
158
159 # keep uncommented only the one you want:
159 # keep uncommented only the one you want:
160 colors Linux
160 colors Linux
161 #colors LightBG
161 #colors LightBG
162 #colors NoColor
162 #colors NoColor
163
163
164 ########################
164 ########################
165 # Note to Windows users
165 # Note to Windows users
166 #
166 #
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
168 # readline library. You can find Gary's tools at
168 # readline library. You can find Gary's tools at
169 # http://sourceforge.net/projects/uncpythontools.
169 # http://sourceforge.net/projects/uncpythontools.
170 # Note that his readline module requires in turn the ctypes library, available
170 # Note that his readline module requires in turn the ctypes library, available
171 # at http://starship.python.net/crew/theller/ctypes.
171 # at http://starship.python.net/crew/theller/ctypes.
172 ########################
172 ########################
173
173
174 # color_info: IPython can display information about objects via a set of
174 # color_info: IPython can display information about objects via a set of
175 # functions, and optionally can use colors for this, syntax highlighting
175 # functions, and optionally can use colors for this, syntax highlighting
176 # source code and various other elements. This information is passed through a
176 # source code and various other elements. This information is passed through a
177 # pager (it defaults to 'less' if $PAGER is not set).
177 # pager (it defaults to 'less' if $PAGER is not set).
178
178
179 # If your pager has problems, try to setting it to properly handle escapes
179 # If your pager has problems, try to setting it to properly handle escapes
180 # (see the less manpage for detail), or disable this option. The magic
180 # (see the less manpage for detail), or disable this option. The magic
181 # function @color_info allows you to toggle this interactively for testing.
181 # function @color_info allows you to toggle this interactively for testing.
182
182
183 color_info 1
183 color_info 1
184
184
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
187 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
187 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
188 # any confirmation.
188 # any confirmation.
189
189
190 confirm_exit 1
190 confirm_exit 1
191
191
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
193 # still available as dreload() and appears as a builtin.
193 # still available as dreload() and appears as a builtin.
194
194
195 deep_reload 0
195 deep_reload 0
196
196
197 # Which editor to use with the @edit command. If you leave this at 0, IPython
197 # Which editor to use with the @edit command. If you leave this at 0, IPython
198 # will honor your EDITOR environment variable. Since this editor is invoked on
198 # will honor your EDITOR environment variable. Since this editor is invoked on
199 # the fly by ipython and is meant for editing small code snippets, you may
199 # the fly by ipython and is meant for editing small code snippets, you may
200 # want to use a small, lightweight editor here.
200 # want to use a small, lightweight editor here.
201
201
202 # For Emacs users, setting up your Emacs server properly as described in the
202 # For Emacs users, setting up your Emacs server properly as described in the
203 # manual is a good idea. An alternative is to use jed, a very light editor
203 # manual is a good idea. An alternative is to use jed, a very light editor
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
205
205
206 editor 0
206 editor 0
207
207
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
209 log 0
209 log 0
210
210
211 # Same as ipython -Logfile YourLogfileName.
211 # Same as ipython -Logfile YourLogfileName.
212 # Don't use with log 1 (use one or the other)
212 # Don't use with log 1 (use one or the other)
213 logfile ''
213 logfile ''
214
214
215 # banner 0 -> same as ipython -nobanner
215 # banner 0 -> same as ipython -nobanner
216 banner 1
216 banner 1
217
217
218 # messages 0 -> same as ipython -nomessages
218 # messages 0 -> same as ipython -nomessages
219 messages 1
219 messages 1
220
220
221 # Automatically call the pdb debugger after every uncaught exception. If you
221 # Automatically call the pdb debugger after every uncaught exception. If you
222 # are used to debugging using pdb, this puts you automatically inside of it
222 # are used to debugging using pdb, this puts you automatically inside of it
223 # after any call (either in IPython or in code called by it) which triggers an
223 # after any call (either in IPython or in code called by it) which triggers an
224 # exception which goes uncaught.
224 # exception which goes uncaught.
225 pdb 0
225 pdb 0
226
226
227 # Enable the pprint module for printing. pprint tends to give a more readable
227 # Enable the pprint module for printing. pprint tends to give a more readable
228 # display (than print) for complex nested data structures.
228 # display (than print) for complex nested data structures.
229 pprint 1
229 pprint 1
230
230
231 # Prompt strings
231 # Prompt strings
232
232
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
234 # a few additional ones which are IPython-specific. All valid prompt escapes
234 # a few additional ones which are IPython-specific. All valid prompt escapes
235 # are described in detail in the Customization section of the IPython HTML/PDF
235 # are described in detail in the Customization section of the IPython HTML/PDF
236 # manual.
236 # manual.
237
237
238 # Use \# to represent the current prompt number, and quote them to protect
238 # Use \# to represent the current prompt number, and quote them to protect
239 # spaces.
239 # spaces.
240 prompt_in1 'In [\#]: '
240 prompt_in1 'In [\#]: '
241
241
242 # \D is replaced by as many dots as there are digits in the
242 # \D is replaced by as many dots as there are digits in the
243 # current value of \#.
243 # current value of \#.
244 prompt_in2 ' .\D.: '
244 prompt_in2 ' .\D.: '
245
245
246 prompt_out 'Out[\#]: '
246 prompt_out 'Out[\#]: '
247
247
248 # Select whether to left-pad the output prompts to match the length of the
248 # Select whether to left-pad the output prompts to match the length of the
249 # input ones. This allows you for example to use a simple '>' as an output
249 # input ones. This allows you for example to use a simple '>' as an output
250 # prompt, and yet have the output line up with the input. If set to false,
250 # prompt, and yet have the output line up with the input. If set to false,
251 # the output prompts will be unpadded (flush left).
251 # the output prompts will be unpadded (flush left).
252 prompts_pad_left 1
252 prompts_pad_left 1
253
253
254 # quick 1 -> same as ipython -quick
254 # quick 1 -> same as ipython -quick
255 quick 0
255 quick 0
256
256
257 # Use the readline library (1) or not (0). Most users will want this on, but
257 # Use the readline library (1) or not (0). Most users will want this on, but
258 # if you experience strange problems with line management (mainly when using
258 # if you experience strange problems with line management (mainly when using
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
260 # prevents you from getting command history with the arrow keys, searching and
260 # prevents you from getting command history with the arrow keys, searching and
261 # name completion using TAB.
261 # name completion using TAB.
262
262
263 readline 1
263 readline 1
264
264
265 # Screen Length: number of lines of your screen. This is used to control
265 # Screen Length: number of lines of your screen. This is used to control
266 # printing of very long strings. Strings longer than this number of lines will
266 # printing of very long strings. Strings longer than this number of lines will
267 # be paged with the less command instead of directly printed.
267 # be paged with the less command instead of directly printed.
268
268
269 # The default value for this is 0, which means IPython will auto-detect your
269 # The default value for this is 0, which means IPython will auto-detect your
270 # screen size every time it needs to print. If for some reason this isn't
270 # screen size every time it needs to print. If for some reason this isn't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
272 # change the default.
272 # change the default.
273
273
274 screen_length 0
274 screen_length 0
275
275
276 # Prompt separators for input and output.
276 # Prompt separators for input and output.
277 # Use \n for newline explicitly, without quotes.
277 # Use \n for newline explicitly, without quotes.
278 # Use 0 (like at the cmd line) to turn off a given separator.
278 # Use 0 (like at the cmd line) to turn off a given separator.
279
279
280 # The structure of prompt printing is:
280 # The structure of prompt printing is:
281 # (SeparateIn)Input....
281 # (SeparateIn)Input....
282 # (SeparateOut)Output...
282 # (SeparateOut)Output...
283 # (SeparateOut2), # that is, no newline is printed after Out2
283 # (SeparateOut2), # that is, no newline is printed after Out2
284 # By choosing these you can organize your output any way you want.
284 # By choosing these you can organize your output any way you want.
285
285
286 separate_in \n
286 separate_in \n
287 separate_out 0
287 separate_out 0
288 separate_out2 0
288 separate_out2 0
289
289
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
291 # Simply removes all input/output separators, overriding the choices above.
291 # Simply removes all input/output separators, overriding the choices above.
292 nosep 0
292 nosep 0
293
293
294 # Wildcard searches - IPython has a system for searching names using
294 # Wildcard searches - IPython has a system for searching names using
295 # shell-like wildcards; type %psearch? for details. This variables sets
295 # shell-like wildcards; type %psearch? for details. This variables sets
296 # whether by default such searches should be case sensitive or not. You can
296 # whether by default such searches should be case sensitive or not. You can
297 # always override the default at the system command line or the IPython
297 # always override the default at the system command line or the IPython
298 # prompt.
298 # prompt.
299
299
300 wildcards_case_sensitive 1
300 wildcards_case_sensitive 1
301
301
302 # xmode - Exception reporting mode.
302 # xmode - Exception reporting mode.
303
303
304 # Valid modes: Plain, Context and Verbose.
304 # Valid modes: Plain, Context and Verbose.
305
305
306 # Plain: similar to python's normal traceback printing.
306 # Plain: similar to python's normal traceback printing.
307
307
308 # Context: prints 5 lines of context source code around each line in the
308 # Context: prints 5 lines of context source code around each line in the
309 # traceback.
309 # traceback.
310
310
311 # Verbose: similar to Context, but additionally prints the variables currently
311 # Verbose: similar to Context, but additionally prints the variables currently
312 # visible where the exception happened (shortening their strings if too
312 # visible where the exception happened (shortening their strings if too
313 # long). This can potentially be very slow, if you happen to have a huge data
313 # long). This can potentially be very slow, if you happen to have a huge data
314 # structure whose string representation is complex to compute. Your computer
314 # structure whose string representation is complex to compute. Your computer
315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
317
317
318 #xmode Plain
318 #xmode Plain
319 xmode Context
319 xmode Context
320 #xmode Verbose
320 #xmode Verbose
321
321
322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
323 # !cmd) to be used in multi-line input (like for loops). For example, if you
323 # !cmd) to be used in multi-line input (like for loops). For example, if you
324 # have this active, the following is valid in IPython:
324 # have this active, the following is valid in IPython:
325 #
325 #
326 #In [17]: for i in range(3):
326 #In [17]: for i in range(3):
327 # ....: mkdir $i
327 # ....: mkdir $i
328 # ....: !touch $i/hello
328 # ....: !touch $i/hello
329 # ....: ls -l $i
329 # ....: ls -l $i
330
330
331 multi_line_specials 1
331 multi_line_specials 1
332
332
333 # wxversion: request a specific wxPython version (used for -wthread)
334
335 # Set this to the value of wxPython you want to use, but note that this
336 # feature requires you to have the wxversion Python module to work. If you
337 # don't have the wxversion module (try 'import wxversion' at the prompt to
338 # check) or simply want to leave the system to pick up the default, leave this
339 # variable at 0.
340
341 wxversion 0
342
333 #---------------------------------------------------------------------------
343 #---------------------------------------------------------------------------
334 # Section: Readline configuration (readline is not available for MS-Windows)
344 # Section: Readline configuration (readline is not available for MS-Windows)
335
345
336 # This is done via the following options:
346 # This is done via the following options:
337
347
338 # (i) readline_parse_and_bind: this option can appear as many times as you
348 # (i) readline_parse_and_bind: this option can appear as many times as you
339 # want, each time defining a string to be executed via a
349 # want, each time defining a string to be executed via a
340 # readline.parse_and_bind() command. The syntax for valid commands of this
350 # readline.parse_and_bind() command. The syntax for valid commands of this
341 # kind can be found by reading the documentation for the GNU readline library,
351 # kind can be found by reading the documentation for the GNU readline library,
342 # as these commands are of the kind which readline accepts in its
352 # as these commands are of the kind which readline accepts in its
343 # configuration file.
353 # configuration file.
344
354
345 # The TAB key can be used to complete names at the command line in one of two
355 # The TAB key can be used to complete names at the command line in one of two
346 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
356 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
347 # completes as much as possible while 'menu-complete' cycles through all
357 # completes as much as possible while 'menu-complete' cycles through all
348 # possible completions. Leave the one you prefer uncommented.
358 # possible completions. Leave the one you prefer uncommented.
349
359
350 readline_parse_and_bind tab: complete
360 readline_parse_and_bind tab: complete
351 #readline_parse_and_bind tab: menu-complete
361 #readline_parse_and_bind tab: menu-complete
352
362
353 # This binds Control-l to printing the list of all possible completions when
363 # This binds Control-l to printing the list of all possible completions when
354 # there is more than one (what 'complete' does when hitting TAB twice, or at
364 # there is more than one (what 'complete' does when hitting TAB twice, or at
355 # the first TAB if show-all-if-ambiguous is on)
365 # the first TAB if show-all-if-ambiguous is on)
356 readline_parse_and_bind "\C-l": possible-completions
366 readline_parse_and_bind "\C-l": possible-completions
357
367
358 # This forces readline to automatically print the above list when tab
368 # This forces readline to automatically print the above list when tab
359 # completion is set to 'complete'. You can still get this list manually by
369 # completion is set to 'complete'. You can still get this list manually by
360 # using the key bound to 'possible-completions' (Control-l by default) or by
370 # using the key bound to 'possible-completions' (Control-l by default) or by
361 # hitting TAB twice. Turning this on makes the printing happen at the first
371 # hitting TAB twice. Turning this on makes the printing happen at the first
362 # TAB.
372 # TAB.
363 readline_parse_and_bind set show-all-if-ambiguous on
373 readline_parse_and_bind set show-all-if-ambiguous on
364
374
365 # If you have TAB set to complete names, you can rebind any key (Control-o by
375 # If you have TAB set to complete names, you can rebind any key (Control-o by
366 # default) to insert a true TAB character.
376 # default) to insert a true TAB character.
367 readline_parse_and_bind "\C-o": tab-insert
377 readline_parse_and_bind "\C-o": tab-insert
368
378
369 # These commands allow you to indent/unindent easily, with the 4-space
379 # These commands allow you to indent/unindent easily, with the 4-space
370 # convention of the Python coding standards. Since IPython's internal
380 # convention of the Python coding standards. Since IPython's internal
371 # auto-indent system also uses 4 spaces, you should not change the number of
381 # auto-indent system also uses 4 spaces, you should not change the number of
372 # spaces in the code below.
382 # spaces in the code below.
373 readline_parse_and_bind "\M-i": " "
383 readline_parse_and_bind "\M-i": " "
374 readline_parse_and_bind "\M-o": "\d\d\d\d"
384 readline_parse_and_bind "\M-o": "\d\d\d\d"
375 readline_parse_and_bind "\M-I": "\d\d\d\d"
385 readline_parse_and_bind "\M-I": "\d\d\d\d"
376
386
377 # Bindings for incremental searches in the history. These searches use the
387 # Bindings for incremental searches in the history. These searches use the
378 # string typed so far on the command line and search anything in the previous
388 # string typed so far on the command line and search anything in the previous
379 # input history containing them.
389 # input history containing them.
380 readline_parse_and_bind "\C-r": reverse-search-history
390 readline_parse_and_bind "\C-r": reverse-search-history
381 readline_parse_and_bind "\C-s": forward-search-history
391 readline_parse_and_bind "\C-s": forward-search-history
382
392
383 # Bindings for completing the current line in the history of previous
393 # Bindings for completing the current line in the history of previous
384 # commands. This allows you to recall any previous command by typing its first
394 # commands. This allows you to recall any previous command by typing its first
385 # few letters and hitting Control-p, bypassing all intermediate commands which
395 # few letters and hitting Control-p, bypassing all intermediate commands which
386 # may be in the history (much faster than hitting up-arrow 50 times!)
396 # may be in the history (much faster than hitting up-arrow 50 times!)
387 readline_parse_and_bind "\C-p": history-search-backward
397 readline_parse_and_bind "\C-p": history-search-backward
388 readline_parse_and_bind "\C-n": history-search-forward
398 readline_parse_and_bind "\C-n": history-search-forward
389
399
390 # I also like to have the same functionality on the plain arrow keys. If you'd
400 # I also like to have the same functionality on the plain arrow keys. If you'd
391 # rather have the arrows use all the history (and not just match what you've
401 # rather have the arrows use all the history (and not just match what you've
392 # typed so far), comment out or delete the next two lines.
402 # typed so far), comment out or delete the next two lines.
393 readline_parse_and_bind "\e[A": history-search-backward
403 readline_parse_and_bind "\e[A": history-search-backward
394 readline_parse_and_bind "\e[B": history-search-forward
404 readline_parse_and_bind "\e[B": history-search-forward
395
405
396 # These are typically on by default under *nix, but not win32.
406 # These are typically on by default under *nix, but not win32.
397 readline_parse_and_bind "\C-k": kill-line
407 readline_parse_and_bind "\C-k": kill-line
398 readline_parse_and_bind "\C-u": unix-line-discard
408 readline_parse_and_bind "\C-u": unix-line-discard
399
409
400 # (ii) readline_remove_delims: a string of characters to be removed from the
410 # (ii) readline_remove_delims: a string of characters to be removed from the
401 # default word-delimiters list used by readline, so that completions may be
411 # default word-delimiters list used by readline, so that completions may be
402 # performed on strings which contain them.
412 # performed on strings which contain them.
403
413
404 readline_remove_delims -/~
414 readline_remove_delims -/~
405
415
406 # (iii) readline_merge_completions: whether to merge the result of all
416 # (iii) readline_merge_completions: whether to merge the result of all
407 # possible completions or not. If true, IPython will complete filenames,
417 # possible completions or not. If true, IPython will complete filenames,
408 # python names and aliases and return all possible completions. If you set it
418 # python names and aliases and return all possible completions. If you set it
409 # to false, each completer is used at a time, and only if it doesn't return
419 # to false, each completer is used at a time, and only if it doesn't return
410 # any completions is the next one used.
420 # any completions is the next one used.
411
421
412 # The default order is: [python_matches, file_matches, alias_matches]
422 # The default order is: [python_matches, file_matches, alias_matches]
413
423
414 readline_merge_completions 1
424 readline_merge_completions 1
415
425
416 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
426 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
417 # will complete all attributes of an object, including all the special methods
427 # will complete all attributes of an object, including all the special methods
418 # whose names start with single or double underscores (like __getitem__ or
428 # whose names start with single or double underscores (like __getitem__ or
419 # __class__).
429 # __class__).
420
430
421 # This variable allows you to control this completion behavior:
431 # This variable allows you to control this completion behavior:
422
432
423 # readline_omit__names 1 -> completion will omit showing any names starting
433 # readline_omit__names 1 -> completion will omit showing any names starting
424 # with two __, but it will still show names starting with one _.
434 # with two __, but it will still show names starting with one _.
425
435
426 # readline_omit__names 2 -> completion will omit all names beginning with one
436 # readline_omit__names 2 -> completion will omit all names beginning with one
427 # _ (which obviously means filtering out the double __ ones).
437 # _ (which obviously means filtering out the double __ ones).
428
438
429 # Even when this option is set, you can still see those names by explicitly
439 # Even when this option is set, you can still see those names by explicitly
430 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
440 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
431 # complete attribute names starting with '_'.
441 # complete attribute names starting with '_'.
432
442
433 # This option is off by default so that new users see all attributes of any
443 # This option is off by default so that new users see all attributes of any
434 # objects they are dealing with.
444 # objects they are dealing with.
435
445
436 readline_omit__names 0
446 readline_omit__names 0
437
447
438 #---------------------------------------------------------------------------
448 #---------------------------------------------------------------------------
439 # Section: modules to be loaded with 'import ...'
449 # Section: modules to be loaded with 'import ...'
440
450
441 # List, separated by spaces, the names of the modules you want to import
451 # List, separated by spaces, the names of the modules you want to import
442
452
443 # Example:
453 # Example:
444 # import_mod sys os
454 # import_mod sys os
445 # will produce internally the statements
455 # will produce internally the statements
446 # import sys
456 # import sys
447 # import os
457 # import os
448
458
449 # Each import is executed in its own try/except block, so if one module
459 # Each import is executed in its own try/except block, so if one module
450 # fails to load the others will still be ok.
460 # fails to load the others will still be ok.
451
461
452 import_mod
462 import_mod
453
463
454 #---------------------------------------------------------------------------
464 #---------------------------------------------------------------------------
455 # Section: modules to import some functions from: 'from ... import ...'
465 # Section: modules to import some functions from: 'from ... import ...'
456
466
457 # List, one per line, the modules for which you want only to import some
467 # List, one per line, the modules for which you want only to import some
458 # functions. Give the module name first and then the name of functions to be
468 # functions. Give the module name first and then the name of functions to be
459 # imported from that module.
469 # imported from that module.
460
470
461 # Example:
471 # Example:
462
472
463 # import_some IPython.genutils timing timings
473 # import_some IPython.genutils timing timings
464 # will produce internally the statement
474 # will produce internally the statement
465 # from IPython.genutils import timing, timings
475 # from IPython.genutils import timing, timings
466
476
467 # timing() and timings() are two IPython utilities for timing the execution of
477 # timing() and timings() are two IPython utilities for timing the execution of
468 # your own functions, which you may find useful. Just commment out the above
478 # your own functions, which you may find useful. Just commment out the above
469 # line if you want to test them.
479 # line if you want to test them.
470
480
471 # If you have more than one modules_some line, each gets its own try/except
481 # If you have more than one modules_some line, each gets its own try/except
472 # block (like modules, see above).
482 # block (like modules, see above).
473
483
474 import_some
484 import_some
475
485
476 #---------------------------------------------------------------------------
486 #---------------------------------------------------------------------------
477 # Section: modules to import all from : 'from ... import *'
487 # Section: modules to import all from : 'from ... import *'
478
488
479 # List (same syntax as import_mod above) those modules for which you want to
489 # List (same syntax as import_mod above) those modules for which you want to
480 # import all functions. Remember, this is a potentially dangerous thing to do,
490 # import all functions. Remember, this is a potentially dangerous thing to do,
481 # since it is very easy to overwrite names of things you need. Use with
491 # since it is very easy to overwrite names of things you need. Use with
482 # caution.
492 # caution.
483
493
484 # Example:
494 # Example:
485 # import_all sys os
495 # import_all sys os
486 # will produce internally the statements
496 # will produce internally the statements
487 # from sys import *
497 # from sys import *
488 # from os import *
498 # from os import *
489
499
490 # As before, each will be called in a separate try/except block.
500 # As before, each will be called in a separate try/except block.
491
501
492 import_all
502 import_all
493
503
494 #---------------------------------------------------------------------------
504 #---------------------------------------------------------------------------
495 # Section: Python code to execute.
505 # Section: Python code to execute.
496
506
497 # Put here code to be explicitly executed (keep it simple!)
507 # Put here code to be explicitly executed (keep it simple!)
498 # Put one line of python code per line. All whitespace is removed (this is a
508 # Put one line of python code per line. All whitespace is removed (this is a
499 # feature, not a bug), so don't get fancy building loops here.
509 # feature, not a bug), so don't get fancy building loops here.
500 # This is just for quick convenient creation of things you want available.
510 # This is just for quick convenient creation of things you want available.
501
511
502 # Example:
512 # Example:
503 # execute x = 1
513 # execute x = 1
504 # execute print 'hello world'; y = z = 'a'
514 # execute print 'hello world'; y = z = 'a'
505 # will produce internally
515 # will produce internally
506 # x = 1
516 # x = 1
507 # print 'hello world'; y = z = 'a'
517 # print 'hello world'; y = z = 'a'
508 # and each *line* (not each statement, we don't do python syntax parsing) is
518 # and each *line* (not each statement, we don't do python syntax parsing) is
509 # executed in its own try/except block.
519 # executed in its own try/except block.
510
520
511 execute
521 execute
512
522
513 # Note for the adventurous: you can use this to define your own names for the
523 # Note for the adventurous: you can use this to define your own names for the
514 # magic functions, by playing some namespace tricks:
524 # magic functions, by playing some namespace tricks:
515
525
516 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
526 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
517
527
518 # defines @pf as a new name for @profile.
528 # defines @pf as a new name for @profile.
519
529
520 #---------------------------------------------------------------------------
530 #---------------------------------------------------------------------------
521 # Section: Pyhton files to load and execute.
531 # Section: Pyhton files to load and execute.
522
532
523 # Put here the full names of files you want executed with execfile(file). If
533 # Put here the full names of files you want executed with execfile(file). If
524 # you want complicated initialization, just write whatever you want in a
534 # you want complicated initialization, just write whatever you want in a
525 # regular python file and load it from here.
535 # regular python file and load it from here.
526
536
527 # Filenames defined here (which *must* include the extension) are searched for
537 # Filenames defined here (which *must* include the extension) are searched for
528 # through all of sys.path. Since IPython adds your .ipython directory to
538 # through all of sys.path. Since IPython adds your .ipython directory to
529 # sys.path, they can also be placed in your .ipython dir and will be
539 # sys.path, they can also be placed in your .ipython dir and will be
530 # found. Otherwise (if you want to execute things not in .ipyton nor in
540 # found. Otherwise (if you want to execute things not in .ipyton nor in
531 # sys.path) give a full path (you can use ~, it gets expanded)
541 # sys.path) give a full path (you can use ~, it gets expanded)
532
542
533 # Example:
543 # Example:
534 # execfile file1.py ~/file2.py
544 # execfile file1.py ~/file2.py
535 # will generate
545 # will generate
536 # execfile('file1.py')
546 # execfile('file1.py')
537 # execfile('_path_to_your_home/file2.py')
547 # execfile('_path_to_your_home/file2.py')
538
548
539 # As before, each file gets its own try/except block.
549 # As before, each file gets its own try/except block.
540
550
541 execfile
551 execfile
542
552
543 # If you are feeling adventurous, you can even add functionality to IPython
553 # If you are feeling adventurous, you can even add functionality to IPython
544 # through here. IPython works through a global variable called __ip which
554 # through here. IPython works through a global variable called __ip which
545 # exists at the time when these files are read. If you know what you are doing
555 # exists at the time when these files are read. If you know what you are doing
546 # (read the source) you can add functions to __ip in files loaded here.
556 # (read the source) you can add functions to __ip in files loaded here.
547
557
548 # The file example-magic.py contains a simple but correct example. Try it:
558 # The file example-magic.py contains a simple but correct example. Try it:
549
559
550 # execfile example-magic.py
560 # execfile example-magic.py
551
561
552 # Look at the examples in IPython/iplib.py for more details on how these magic
562 # Look at the examples in IPython/iplib.py for more details on how these magic
553 # functions need to process their arguments.
563 # functions need to process their arguments.
554
564
555 #---------------------------------------------------------------------------
565 #---------------------------------------------------------------------------
556 # Section: aliases for system shell commands
566 # Section: aliases for system shell commands
557
567
558 # Here you can define your own names for system commands. The syntax is
568 # Here you can define your own names for system commands. The syntax is
559 # similar to that of the builtin @alias function:
569 # similar to that of the builtin @alias function:
560
570
561 # alias alias_name command_string
571 # alias alias_name command_string
562
572
563 # The resulting aliases are auto-generated magic functions (hence usable as
573 # The resulting aliases are auto-generated magic functions (hence usable as
564 # @alias_name)
574 # @alias_name)
565
575
566 # For example:
576 # For example:
567
577
568 # alias myls ls -la
578 # alias myls ls -la
569
579
570 # will define 'myls' as an alias for executing the system command 'ls -la'.
580 # will define 'myls' as an alias for executing the system command 'ls -la'.
571 # This allows you to customize IPython's environment to have the same aliases
581 # This allows you to customize IPython's environment to have the same aliases
572 # you are accustomed to from your own shell.
582 # you are accustomed to from your own shell.
573
583
574 # You can also define aliases with parameters using %s specifiers (one per
584 # You can also define aliases with parameters using %s specifiers (one per
575 # parameter):
585 # parameter):
576
586
577 # alias parts echo first %s second %s
587 # alias parts echo first %s second %s
578
588
579 # will give you in IPython:
589 # will give you in IPython:
580 # >>> @parts A B
590 # >>> @parts A B
581 # first A second B
591 # first A second B
582
592
583 # Use one 'alias' statement per alias you wish to define.
593 # Use one 'alias' statement per alias you wish to define.
584
594
585 # alias
595 # alias
586
596
587 #************************* end of file <ipythonrc> ************************
597 #************************* end of file <ipythonrc> ************************
@@ -1,64 +1,64 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 One of Python's nicest features is its interactive interpreter. This allows
5 One of Python's nicest features is its interactive interpreter. This allows
6 very fast testing of ideas without the overhead of creating test files as is
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
9 much better).
10
10
11 IPython tries to:
11 IPython tries to:
12
12
13 i - provide an efficient environment for interactive work in Python
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
16 efficient.
17
17
18 ii - offer a flexible framework so that it can be used as the base
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
24 entire systems could be built leveraging Python's power.
25
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
27
28 IPython requires Python 2.2 or newer.
28 IPython requires Python 2.2 or newer.
29
29
30 $Id: __init__.py 775 2005-09-01 20:24:59Z fperez $"""
30 $Id: __init__.py 998 2006-01-09 06:57:40Z fperez $"""
31
31
32 #*****************************************************************************
32 #*****************************************************************************
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
34 #
34 #
35 # Distributed under the terms of the BSD License. The full license is in
35 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
36 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
37 #*****************************************************************************
38
38
39 # Enforce proper version requirements
39 # Enforce proper version requirements
40 import sys
40 import sys
41 if sys.version[0:3] < '2.2':
41 if sys.version[0:3] < '2.3':
42 raise ImportError, 'Python Version 2.2 or above is required.'
42 raise ImportError, 'Python Version 2.3 or above is required.'
43
43
44 # Define what gets imported with a 'from IPython import *'
44 # Define what gets imported with a 'from IPython import *'
45 __all__ = ['deep_reload','genutils','ultraTB','DPyGetOpt','Itpl','hooks',
45 __all__ = ['deep_reload','genutils','ultraTB','DPyGetOpt','Itpl','hooks',
46 'ConfigLoader','OutputTrap','Release','Struct','Shell']
46 'ConfigLoader','OutputTrap','Release','Struct','Shell']
47
47
48 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
48 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
49 # access to them via IPython.<name>
49 # access to them via IPython.<name>
50 glob,loc = globals(),locals()
50 glob,loc = globals(),locals()
51 for name in __all__:
51 for name in __all__:
52 __import__(name,glob,loc,[])
52 __import__(name,glob,loc,[])
53
53
54 # Release data
54 # Release data
55 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
55 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
56 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
56 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
57 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
57 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
58 Release.authors['Nathan'] )
58 Release.authors['Nathan'] )
59 __license__ = Release.license
59 __license__ = Release.license
60 __version__ = Release.version
60 __version__ = Release.version
61 __revision__ = Release.revision
61 __revision__ = Release.revision
62
62
63 # Namespace cleanup
63 # Namespace cleanup
64 del name,glob,loc
64 del name,glob,loc
@@ -1,701 +1,703 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 994 2006-01-08 08:29:44Z fperez $"""
9 $Id: ipmaker.py 998 2006-01-09 06:57:40Z fperez $"""
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.Struct import Struct
49 from IPython.Struct 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 'autoedit_syntax!')
163 'autoedit_syntax!')
163
164
164 # 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).
165
166
166 # 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
167 # 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.
168 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 'gthread! qthread! wthread! pylab! tk!')
170 'gthread! qthread! wthread! pylab! tk!')
170
171
171 # Build the actual name list to be used by DPyGetOpt
172 # Build the actual name list to be used by DPyGetOpt
172 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173
174
174 # Set sensible command line defaults.
175 # Set sensible command line defaults.
175 # This should have everything from cmdline_opts and cmdline_only
176 # This should have everything from cmdline_opts and cmdline_only
176 opts_def = Struct(autocall = 1,
177 opts_def = Struct(autocall = 1,
177 autoedit_syntax = 1,
178 autoedit_syntax = 1,
178 autoindent=0,
179 autoindent=0,
179 automagic = 1,
180 automagic = 1,
180 banner = 1,
181 banner = 1,
181 cache_size = 1000,
182 cache_size = 1000,
182 c = '',
183 c = '',
183 classic = 0,
184 classic = 0,
184 colors = 'NoColor',
185 colors = 'NoColor',
185 color_info = 0,
186 color_info = 0,
186 confirm_exit = 1,
187 confirm_exit = 1,
187 debug = 0,
188 debug = 0,
188 deep_reload = 0,
189 deep_reload = 0,
189 editor = '0',
190 editor = '0',
190 help = 0,
191 help = 0,
191 ignore = 0,
192 ignore = 0,
192 ipythondir = ipythondir,
193 ipythondir = ipythondir,
193 log = 0,
194 log = 0,
194 logfile = '',
195 logfile = '',
195 logplay = '',
196 logplay = '',
196 multi_line_specials = 1,
197 multi_line_specials = 1,
197 messages = 1,
198 messages = 1,
198 nosep = 0,
199 nosep = 0,
199 pdb = 0,
200 pdb = 0,
200 pprint = 0,
201 pprint = 0,
201 profile = '',
202 profile = '',
202 prompt_in1 = 'In [\\#]: ',
203 prompt_in1 = 'In [\\#]: ',
203 prompt_in2 = ' .\\D.: ',
204 prompt_in2 = ' .\\D.: ',
204 prompt_out = 'Out[\\#]: ',
205 prompt_out = 'Out[\\#]: ',
205 prompts_pad_left = 1,
206 prompts_pad_left = 1,
206 quick = 0,
207 quick = 0,
207 readline = 1,
208 readline = 1,
208 readline_merge_completions = 1,
209 readline_merge_completions = 1,
209 readline_omit__names = 0,
210 readline_omit__names = 0,
210 rcfile = 'ipythonrc' + rc_suffix,
211 rcfile = 'ipythonrc' + rc_suffix,
211 screen_length = 0,
212 screen_length = 0,
212 separate_in = '\n',
213 separate_in = '\n',
213 separate_out = '\n',
214 separate_out = '\n',
214 separate_out2 = '',
215 separate_out2 = '',
215 system_verbose = 0,
216 system_verbose = 0,
216 gthread = 0,
217 gthread = 0,
217 qthread = 0,
218 qthread = 0,
218 wthread = 0,
219 wthread = 0,
219 pylab = 0,
220 pylab = 0,
220 tk = 0,
221 tk = 0,
221 upgrade = 0,
222 upgrade = 0,
222 Version = 0,
223 Version = 0,
223 xmode = 'Verbose',
224 xmode = 'Verbose',
224 wildcards_case_sensitive = 1,
225 wildcards_case_sensitive = 1,
226 wxversion = '0',
225 magic_docstrings = 0, # undocumented, for doc generation
227 magic_docstrings = 0, # undocumented, for doc generation
226 )
228 )
227
229
228 # 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).
229 # 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!)
230 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
231 qw_lol: 'import_some ',
233 qw_lol: 'import_some ',
232 # for things with embedded whitespace:
234 # for things with embedded whitespace:
233 list_strings:'execute alias readline_parse_and_bind ',
235 list_strings:'execute alias readline_parse_and_bind ',
234 # Regular strings need no conversion:
236 # Regular strings need no conversion:
235 None:'readline_remove_delims ',
237 None:'readline_remove_delims ',
236 }
238 }
237 # Default values for these
239 # Default values for these
238 rc_def = Struct(include = [],
240 rc_def = Struct(include = [],
239 import_mod = [],
241 import_mod = [],
240 import_all = [],
242 import_all = [],
241 import_some = [[]],
243 import_some = [[]],
242 execute = [],
244 execute = [],
243 execfile = [],
245 execfile = [],
244 alias = [],
246 alias = [],
245 readline_parse_and_bind = [],
247 readline_parse_and_bind = [],
246 readline_remove_delims = '',
248 readline_remove_delims = '',
247 )
249 )
248
250
249 # Build the type conversion dictionary from the above tables:
251 # Build the type conversion dictionary from the above tables:
250 typeconv = rcfile_opts.copy()
252 typeconv = rcfile_opts.copy()
251 typeconv.update(optstr2types(cmdline_opts))
253 typeconv.update(optstr2types(cmdline_opts))
252
254
253 # 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!
254 typeconv[None] += ' ' + rcfile_opts[None]
256 typeconv[None] += ' ' + rcfile_opts[None]
255
257
256 # Remove quotes at ends of all strings (used to protect spaces)
258 # Remove quotes at ends of all strings (used to protect spaces)
257 typeconv[unquote_ends] = typeconv[None]
259 typeconv[unquote_ends] = typeconv[None]
258 del typeconv[None]
260 del typeconv[None]
259
261
260 # 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:
261 opts_all = opts_def.copy()
263 opts_all = opts_def.copy()
262 opts_all.update(rc_def)
264 opts_all.update(rc_def)
263
265
264 # Build conflict resolver for recursive loading of config files:
266 # Build conflict resolver for recursive loading of config files:
265 # - preserve means the outermost file maintains the value, it is not
267 # - preserve means the outermost file maintains the value, it is not
266 # overwritten if an included file has the same key.
268 # overwritten if an included file has the same key.
267 # - 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
268 # 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
269 # deeper in the inclusion chain have lower precedence.
271 # deeper in the inclusion chain have lower precedence.
270 conflict = {'preserve': ' '.join([ typeconv[int],
272 conflict = {'preserve': ' '.join([ typeconv[int],
271 typeconv[unquote_ends] ]),
273 typeconv[unquote_ends] ]),
272 'add_flip': ' '.join([ typeconv[qwflat],
274 'add_flip': ' '.join([ typeconv[qwflat],
273 typeconv[qw_lol],
275 typeconv[qw_lol],
274 typeconv[list_strings] ])
276 typeconv[list_strings] ])
275 }
277 }
276
278
277 # Now actually process the command line
279 # Now actually process the command line
278 getopt = DPyGetOpt.DPyGetOpt()
280 getopt = DPyGetOpt.DPyGetOpt()
279 getopt.setIgnoreCase(0)
281 getopt.setIgnoreCase(0)
280
282
281 getopt.parseConfiguration(opts_names)
283 getopt.parseConfiguration(opts_names)
282
284
283 try:
285 try:
284 getopt.processArguments(argv)
286 getopt.processArguments(argv)
285 except:
287 except:
286 print cmd_line_usage
288 print cmd_line_usage
287 warn('\nError in Arguments: ' + `sys.exc_value`)
289 warn('\nError in Arguments: ' + `sys.exc_value`)
288 sys.exit(1)
290 sys.exit(1)
289
291
290 # 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
291 opts = Struct(getopt.optionValues)
293 opts = Struct(getopt.optionValues)
292 args = getopt.freeValues
294 args = getopt.freeValues
293
295
294 # 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
295 # we make all decisions:
297 # we make all decisions:
296 opts_all.update(opts)
298 opts_all.update(opts)
297
299
298 # Options that force an immediate exit
300 # Options that force an immediate exit
299 if opts_all.help:
301 if opts_all.help:
300 page(cmd_line_usage)
302 page(cmd_line_usage)
301 sys.exit()
303 sys.exit()
302
304
303 if opts_all.Version:
305 if opts_all.Version:
304 print __version__
306 print __version__
305 sys.exit()
307 sys.exit()
306
308
307 if opts_all.magic_docstrings:
309 if opts_all.magic_docstrings:
308 IP.magic_magic('-latex')
310 IP.magic_magic('-latex')
309 sys.exit()
311 sys.exit()
310
312
311 # 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
312 # *after* getting the cmd line options.
314 # *after* getting the cmd line options.
313 if not os.path.isdir(opts_all.ipythondir):
315 if not os.path.isdir(opts_all.ipythondir):
314 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
315
317
316 # upgrade user config files while preserving a copy of the originals
318 # upgrade user config files while preserving a copy of the originals
317 if opts_all.upgrade:
319 if opts_all.upgrade:
318 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
319
321
320 # check mutually exclusive options in the *original* command line
322 # check mutually exclusive options in the *original* command line
321 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
322 qw('classic profile'),qw('classic rcfile')])
324 qw('classic profile'),qw('classic rcfile')])
323
325
324 #---------------------------------------------------------------------------
326 #---------------------------------------------------------------------------
325 # Log replay
327 # Log replay
326
328
327 # 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
328 # replacing the current command line environment with that of the old
330 # replacing the current command line environment with that of the old
329 # session and moving on.
331 # session and moving on.
330
332
331 # 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
332 # opts_all will get overwritten:
334 # opts_all will get overwritten:
333 load_logplay = 0
335 load_logplay = 0
334
336
335 if opts_all.logplay:
337 if opts_all.logplay:
336 load_logplay = opts_all.logplay
338 load_logplay = opts_all.logplay
337 opts_debug_save = opts_all.debug
339 opts_debug_save = opts_all.debug
338 try:
340 try:
339 logplay = open(opts_all.logplay)
341 logplay = open(opts_all.logplay)
340 except IOError:
342 except IOError:
341 if opts_all.debug: IP.InteractiveTB()
343 if opts_all.debug: IP.InteractiveTB()
342 warn('Could not open logplay file '+`opts_all.logplay`)
344 warn('Could not open logplay file '+`opts_all.logplay`)
343 # 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
344 # 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
345 logplay = None
347 logplay = None
346 load_logplay = 0
348 load_logplay = 0
347 del opts_all.logplay
349 del opts_all.logplay
348 else:
350 else:
349 try:
351 try:
350 logplay.readline()
352 logplay.readline()
351 logplay.readline();
353 logplay.readline();
352 # this reloads that session's command line
354 # this reloads that session's command line
353 cmd = logplay.readline()[6:]
355 cmd = logplay.readline()[6:]
354 exec cmd
356 exec cmd
355 # restore the true debug flag given so that the process of
357 # restore the true debug flag given so that the process of
356 # session loading itself can be monitored.
358 # session loading itself can be monitored.
357 opts.debug = opts_debug_save
359 opts.debug = opts_debug_save
358 # 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
359 opts.logplay = load_logplay
361 opts.logplay = load_logplay
360 # now we must update our own structure with defaults
362 # now we must update our own structure with defaults
361 opts_all.update(opts)
363 opts_all.update(opts)
362 # now load args
364 # now load args
363 cmd = logplay.readline()[6:]
365 cmd = logplay.readline()[6:]
364 exec cmd
366 exec cmd
365 logplay.close()
367 logplay.close()
366 except:
368 except:
367 logplay.close()
369 logplay.close()
368 if opts_all.debug: IP.InteractiveTB()
370 if opts_all.debug: IP.InteractiveTB()
369 warn("Logplay file lacking full configuration information.\n"
371 warn("Logplay file lacking full configuration information.\n"
370 "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.")
371
373
372 #-------------------------------------------------------------------------
374 #-------------------------------------------------------------------------
373 # 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
374 # 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.
375
377
376 msg_out = 'Output messages. '
378 msg_out = 'Output messages. '
377 msg_err = 'Error messages. '
379 msg_err = 'Error messages. '
378 msg_sep = '\n'
380 msg_sep = '\n'
379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
380 msg_err,msg_sep,debug,
382 msg_err,msg_sep,debug,
381 quiet_out=1),
383 quiet_out=1),
382 user_exec = OutputTrap('User File Execution',msg_out,
384 user_exec = OutputTrap('User File Execution',msg_out,
383 msg_err,msg_sep,debug),
385 msg_err,msg_sep,debug),
384 logplay = OutputTrap('Log Loader',msg_out,
386 logplay = OutputTrap('Log Loader',msg_out,
385 msg_err,msg_sep,debug),
387 msg_err,msg_sep,debug),
386 summary = ''
388 summary = ''
387 )
389 )
388
390
389 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
390 # Process user ipythonrc-type configuration files
392 # Process user ipythonrc-type configuration files
391
393
392 # turn on output trapping and log to msg.config
394 # turn on output trapping and log to msg.config
393 # remember that with debug on, trapping is actually disabled
395 # remember that with debug on, trapping is actually disabled
394 msg.config.trap_all()
396 msg.config.trap_all()
395
397
396 # look for rcfile in current or default directory
398 # look for rcfile in current or default directory
397 try:
399 try:
398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
399 except IOError:
401 except IOError:
400 if opts_all.debug: IP.InteractiveTB()
402 if opts_all.debug: IP.InteractiveTB()
401 warn('Configuration file %s not found. Ignoring request.'
403 warn('Configuration file %s not found. Ignoring request.'
402 % (opts_all.rcfile) )
404 % (opts_all.rcfile) )
403
405
404 # 'profiles' are a shorthand notation for config filenames
406 # 'profiles' are a shorthand notation for config filenames
405 if opts_all.profile:
407 if opts_all.profile:
406 try:
408 try:
407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
408 + rc_suffix,
410 + rc_suffix,
409 opts_all.ipythondir)
411 opts_all.ipythondir)
410 except IOError:
412 except IOError:
411 if opts_all.debug: IP.InteractiveTB()
413 if opts_all.debug: IP.InteractiveTB()
412 opts.profile = '' # remove profile from options if invalid
414 opts.profile = '' # remove profile from options if invalid
413 warn('Profile configuration file %s not found. Ignoring request.'
415 warn('Profile configuration file %s not found. Ignoring request.'
414 % (opts_all.profile) )
416 % (opts_all.profile) )
415
417
416 # load the config file
418 # load the config file
417 rcfiledata = None
419 rcfiledata = None
418 if opts_all.quick:
420 if opts_all.quick:
419 print 'Launching IPython in quick mode. No config file read.'
421 print 'Launching IPython in quick mode. No config file read.'
420 elif opts_all.classic:
422 elif opts_all.classic:
421 print 'Launching IPython in classic mode. No config file read.'
423 print 'Launching IPython in classic mode. No config file read.'
422 elif opts_all.rcfile:
424 elif opts_all.rcfile:
423 try:
425 try:
424 cfg_loader = ConfigLoader(conflict)
426 cfg_loader = ConfigLoader(conflict)
425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
427 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
426 'include',opts_all.ipythondir,
428 'include',opts_all.ipythondir,
427 purge = 1,
429 purge = 1,
428 unique = conflict['preserve'])
430 unique = conflict['preserve'])
429 except:
431 except:
430 IP.InteractiveTB()
432 IP.InteractiveTB()
431 warn('Problems loading configuration file '+
433 warn('Problems loading configuration file '+
432 `opts_all.rcfile`+
434 `opts_all.rcfile`+
433 '\nStarting with default -bare bones- configuration.')
435 '\nStarting with default -bare bones- configuration.')
434 else:
436 else:
435 warn('No valid configuration file found in either currrent directory\n'+
437 warn('No valid configuration file found in either currrent directory\n'+
436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
438 'or in the IPython config. directory: '+`opts_all.ipythondir`+
437 '\nProceeding with internal defaults.')
439 '\nProceeding with internal defaults.')
438
440
439 #------------------------------------------------------------------------
441 #------------------------------------------------------------------------
440 # Set exception handlers in mode requested by user.
442 # Set exception handlers in mode requested by user.
441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
443 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
442 IP.magic_xmode(opts_all.xmode)
444 IP.magic_xmode(opts_all.xmode)
443 otrap.release_out()
445 otrap.release_out()
444
446
445 #------------------------------------------------------------------------
447 #------------------------------------------------------------------------
446 # Execute user config
448 # Execute user config
447
449
448 # Create a valid config structure with the right precedence order:
450 # Create a valid config structure with the right precedence order:
449 # defaults < rcfile < command line. This needs to be in the instance, so
451 # defaults < rcfile < command line. This needs to be in the instance, so
450 # that method calls below that rely on it find it.
452 # that method calls below that rely on it find it.
451 IP.rc = rc_def.copy()
453 IP.rc = rc_def.copy()
452
454
453 # Work with a local alias inside this routine to avoid unnecessary
455 # Work with a local alias inside this routine to avoid unnecessary
454 # attribute lookups.
456 # attribute lookups.
455 IP_rc = IP.rc
457 IP_rc = IP.rc
456
458
457 IP_rc.update(opts_def)
459 IP_rc.update(opts_def)
458 if rcfiledata:
460 if rcfiledata:
459 # now we can update
461 # now we can update
460 IP_rc.update(rcfiledata)
462 IP_rc.update(rcfiledata)
461 IP_rc.update(opts)
463 IP_rc.update(opts)
462 IP_rc.update(rc_override)
464 IP_rc.update(rc_override)
463
465
464 # Store the original cmd line for reference:
466 # Store the original cmd line for reference:
465 IP_rc.opts = opts
467 IP_rc.opts = opts
466 IP_rc.args = args
468 IP_rc.args = args
467
469
468 # create a *runtime* Struct like rc for holding parameters which may be
470 # create a *runtime* Struct like rc for holding parameters which may be
469 # created and/or modified by runtime user extensions.
471 # created and/or modified by runtime user extensions.
470 IP.runtime_rc = Struct()
472 IP.runtime_rc = Struct()
471
473
472 # from this point on, all config should be handled through IP_rc,
474 # from this point on, all config should be handled through IP_rc,
473 # opts* shouldn't be used anymore.
475 # opts* shouldn't be used anymore.
474
476
475 # add personal .ipython dir to sys.path so that users can put things in
477 # add personal .ipython dir to sys.path so that users can put things in
476 # there for customization
478 # there for customization
477 sys.path.append(IP_rc.ipythondir)
479 sys.path.append(IP_rc.ipythondir)
478 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
480 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
479
481
480 # update IP_rc with some special things that need manual
482 # update IP_rc with some special things that need manual
481 # tweaks. Basically options which affect other options. I guess this
483 # tweaks. Basically options which affect other options. I guess this
482 # should just be written so that options are fully orthogonal and we
484 # should just be written so that options are fully orthogonal and we
483 # wouldn't worry about this stuff!
485 # wouldn't worry about this stuff!
484
486
485 if IP_rc.classic:
487 if IP_rc.classic:
486 IP_rc.quick = 1
488 IP_rc.quick = 1
487 IP_rc.cache_size = 0
489 IP_rc.cache_size = 0
488 IP_rc.pprint = 0
490 IP_rc.pprint = 0
489 IP_rc.prompt_in1 = '>>> '
491 IP_rc.prompt_in1 = '>>> '
490 IP_rc.prompt_in2 = '... '
492 IP_rc.prompt_in2 = '... '
491 IP_rc.prompt_out = ''
493 IP_rc.prompt_out = ''
492 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
494 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
493 IP_rc.colors = 'NoColor'
495 IP_rc.colors = 'NoColor'
494 IP_rc.xmode = 'Plain'
496 IP_rc.xmode = 'Plain'
495
497
496 # configure readline
498 # configure readline
497 # Define the history file for saving commands in between sessions
499 # Define the history file for saving commands in between sessions
498 if IP_rc.profile:
500 if IP_rc.profile:
499 histfname = 'history-%s' % IP_rc.profile
501 histfname = 'history-%s' % IP_rc.profile
500 else:
502 else:
501 histfname = 'history'
503 histfname = 'history'
502 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
504 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
503
505
504 # update exception handlers with rc file status
506 # update exception handlers with rc file status
505 otrap.trap_out() # I don't want these messages ever.
507 otrap.trap_out() # I don't want these messages ever.
506 IP.magic_xmode(IP_rc.xmode)
508 IP.magic_xmode(IP_rc.xmode)
507 otrap.release_out()
509 otrap.release_out()
508
510
509 # activate logging if requested and not reloading a log
511 # activate logging if requested and not reloading a log
510 if IP_rc.logplay:
512 if IP_rc.logplay:
511 IP.magic_logstart(IP_rc.logplay + ' append')
513 IP.magic_logstart(IP_rc.logplay + ' append')
512 elif IP_rc.logfile:
514 elif IP_rc.logfile:
513 IP.magic_logstart(IP_rc.logfile)
515 IP.magic_logstart(IP_rc.logfile)
514 elif IP_rc.log:
516 elif IP_rc.log:
515 IP.magic_logstart()
517 IP.magic_logstart()
516
518
517 # find user editor so that it we don't have to look it up constantly
519 # find user editor so that it we don't have to look it up constantly
518 if IP_rc.editor.strip()=='0':
520 if IP_rc.editor.strip()=='0':
519 try:
521 try:
520 ed = os.environ['EDITOR']
522 ed = os.environ['EDITOR']
521 except KeyError:
523 except KeyError:
522 if os.name == 'posix':
524 if os.name == 'posix':
523 ed = 'vi' # the only one guaranteed to be there!
525 ed = 'vi' # the only one guaranteed to be there!
524 else:
526 else:
525 ed = 'notepad' # same in Windows!
527 ed = 'notepad' # same in Windows!
526 IP_rc.editor = ed
528 IP_rc.editor = ed
527
529
528 # Keep track of whether this is an embedded instance or not (useful for
530 # Keep track of whether this is an embedded instance or not (useful for
529 # post-mortems).
531 # post-mortems).
530 IP_rc.embedded = IP.embedded
532 IP_rc.embedded = IP.embedded
531
533
532 # Recursive reload
534 # Recursive reload
533 try:
535 try:
534 from IPython import deep_reload
536 from IPython import deep_reload
535 if IP_rc.deep_reload:
537 if IP_rc.deep_reload:
536 __builtin__.reload = deep_reload.reload
538 __builtin__.reload = deep_reload.reload
537 else:
539 else:
538 __builtin__.dreload = deep_reload.reload
540 __builtin__.dreload = deep_reload.reload
539 del deep_reload
541 del deep_reload
540 except ImportError:
542 except ImportError:
541 pass
543 pass
542
544
543 # Save the current state of our namespace so that the interactive shell
545 # Save the current state of our namespace so that the interactive shell
544 # can later know which variables have been created by us from config files
546 # can later know which variables have been created by us from config files
545 # and loading. This way, loading a file (in any way) is treated just like
547 # and loading. This way, loading a file (in any way) is treated just like
546 # defining things on the command line, and %who works as expected.
548 # defining things on the command line, and %who works as expected.
547
549
548 # DON'T do anything that affects the namespace beyond this point!
550 # DON'T do anything that affects the namespace beyond this point!
549 IP.internal_ns.update(__main__.__dict__)
551 IP.internal_ns.update(__main__.__dict__)
550
552
551 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
553 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
552
554
553 # Now run through the different sections of the users's config
555 # Now run through the different sections of the users's config
554 if IP_rc.debug:
556 if IP_rc.debug:
555 print 'Trying to execute the following configuration structure:'
557 print 'Trying to execute the following configuration structure:'
556 print '(Things listed first are deeper in the inclusion tree and get'
558 print '(Things listed first are deeper in the inclusion tree and get'
557 print 'loaded first).\n'
559 print 'loaded first).\n'
558 pprint(IP_rc.__dict__)
560 pprint(IP_rc.__dict__)
559
561
560 for mod in IP_rc.import_mod:
562 for mod in IP_rc.import_mod:
561 try:
563 try:
562 exec 'import '+mod in IP.user_ns
564 exec 'import '+mod in IP.user_ns
563 except :
565 except :
564 IP.InteractiveTB()
566 IP.InteractiveTB()
565 import_fail_info(mod)
567 import_fail_info(mod)
566
568
567 for mod_fn in IP_rc.import_some:
569 for mod_fn in IP_rc.import_some:
568 if mod_fn == []: break
570 if mod_fn == []: break
569 mod,fn = mod_fn[0],','.join(mod_fn[1:])
571 mod,fn = mod_fn[0],','.join(mod_fn[1:])
570 try:
572 try:
571 exec 'from '+mod+' import '+fn in IP.user_ns
573 exec 'from '+mod+' import '+fn in IP.user_ns
572 except :
574 except :
573 IP.InteractiveTB()
575 IP.InteractiveTB()
574 import_fail_info(mod,fn)
576 import_fail_info(mod,fn)
575
577
576 for mod in IP_rc.import_all:
578 for mod in IP_rc.import_all:
577 try:
579 try:
578 exec 'from '+mod+' import *' in IP.user_ns
580 exec 'from '+mod+' import *' in IP.user_ns
579 except :
581 except :
580 IP.InteractiveTB()
582 IP.InteractiveTB()
581 import_fail_info(mod)
583 import_fail_info(mod)
582
584
583 for code in IP_rc.execute:
585 for code in IP_rc.execute:
584 try:
586 try:
585 exec code in IP.user_ns
587 exec code in IP.user_ns
586 except:
588 except:
587 IP.InteractiveTB()
589 IP.InteractiveTB()
588 warn('Failure executing code: ' + `code`)
590 warn('Failure executing code: ' + `code`)
589
591
590 # Execute the files the user wants in ipythonrc
592 # Execute the files the user wants in ipythonrc
591 for file in IP_rc.execfile:
593 for file in IP_rc.execfile:
592 try:
594 try:
593 file = filefind(file,sys.path+[IPython_dir])
595 file = filefind(file,sys.path+[IPython_dir])
594 except IOError:
596 except IOError:
595 warn(itpl('File $file not found. Skipping it.'))
597 warn(itpl('File $file not found. Skipping it.'))
596 else:
598 else:
597 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
599 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
598
600
599 # release stdout and stderr and save config log into a global summary
601 # release stdout and stderr and save config log into a global summary
600 msg.config.release_all()
602 msg.config.release_all()
601 if IP_rc.messages:
603 if IP_rc.messages:
602 msg.summary += msg.config.summary_all()
604 msg.summary += msg.config.summary_all()
603
605
604 #------------------------------------------------------------------------
606 #------------------------------------------------------------------------
605 # Setup interactive session
607 # Setup interactive session
606
608
607 # Now we should be fully configured. We can then execute files or load
609 # Now we should be fully configured. We can then execute files or load
608 # things only needed for interactive use. Then we'll open the shell.
610 # things only needed for interactive use. Then we'll open the shell.
609
611
610 # Take a snapshot of the user namespace before opening the shell. That way
612 # Take a snapshot of the user namespace before opening the shell. That way
611 # we'll be able to identify which things were interactively defined and
613 # we'll be able to identify which things were interactively defined and
612 # which were defined through config files.
614 # which were defined through config files.
613 IP.user_config_ns = IP.user_ns.copy()
615 IP.user_config_ns = IP.user_ns.copy()
614
616
615 # Force reading a file as if it were a session log. Slower but safer.
617 # Force reading a file as if it were a session log. Slower but safer.
616 if load_logplay:
618 if load_logplay:
617 print 'Replaying log...'
619 print 'Replaying log...'
618 try:
620 try:
619 if IP_rc.debug:
621 if IP_rc.debug:
620 logplay_quiet = 0
622 logplay_quiet = 0
621 else:
623 else:
622 logplay_quiet = 1
624 logplay_quiet = 1
623
625
624 msg.logplay.trap_all()
626 msg.logplay.trap_all()
625 IP.safe_execfile(load_logplay,IP.user_ns,
627 IP.safe_execfile(load_logplay,IP.user_ns,
626 islog = 1, quiet = logplay_quiet)
628 islog = 1, quiet = logplay_quiet)
627 msg.logplay.release_all()
629 msg.logplay.release_all()
628 if IP_rc.messages:
630 if IP_rc.messages:
629 msg.summary += msg.logplay.summary_all()
631 msg.summary += msg.logplay.summary_all()
630 except:
632 except:
631 warn('Problems replaying logfile %s.' % load_logplay)
633 warn('Problems replaying logfile %s.' % load_logplay)
632 IP.InteractiveTB()
634 IP.InteractiveTB()
633
635
634 # Load remaining files in command line
636 # Load remaining files in command line
635 msg.user_exec.trap_all()
637 msg.user_exec.trap_all()
636
638
637 # Do NOT execute files named in the command line as scripts to be loaded
639 # Do NOT execute files named in the command line as scripts to be loaded
638 # by embedded instances. Doing so has the potential for an infinite
640 # by embedded instances. Doing so has the potential for an infinite
639 # recursion if there are exceptions thrown in the process.
641 # recursion if there are exceptions thrown in the process.
640
642
641 # XXX FIXME: the execution of user files should be moved out to after
643 # XXX FIXME: the execution of user files should be moved out to after
642 # ipython is fully initialized, just as if they were run via %run at the
644 # ipython is fully initialized, just as if they were run via %run at the
643 # ipython prompt. This would also give them the benefit of ipython's
645 # ipython prompt. This would also give them the benefit of ipython's
644 # nice tracebacks.
646 # nice tracebacks.
645
647
646 if not embedded and IP_rc.args:
648 if not embedded and IP_rc.args:
647 name_save = IP.user_ns['__name__']
649 name_save = IP.user_ns['__name__']
648 IP.user_ns['__name__'] = '__main__'
650 IP.user_ns['__name__'] = '__main__'
649 try:
651 try:
650 # Set our own excepthook in case the user code tries to call it
652 # Set our own excepthook in case the user code tries to call it
651 # directly. This prevents triggering the IPython crash handler.
653 # directly. This prevents triggering the IPython crash handler.
652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
654 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
653 for run in args:
655 for run in args:
654 IP.safe_execfile(run,IP.user_ns)
656 IP.safe_execfile(run,IP.user_ns)
655 finally:
657 finally:
656 # Reset our crash handler in place
658 # Reset our crash handler in place
657 sys.excepthook = old_excepthook
659 sys.excepthook = old_excepthook
658
660
659 IP.user_ns['__name__'] = name_save
661 IP.user_ns['__name__'] = name_save
660
662
661 msg.user_exec.release_all()
663 msg.user_exec.release_all()
662 if IP_rc.messages:
664 if IP_rc.messages:
663 msg.summary += msg.user_exec.summary_all()
665 msg.summary += msg.user_exec.summary_all()
664
666
665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
667 # since we can't specify a null string on the cmd line, 0 is the equivalent:
666 if IP_rc.nosep:
668 if IP_rc.nosep:
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
669 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
670 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
671 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
672 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
673 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
674 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
675 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
674
676
675 # Determine how many lines at the bottom of the screen are needed for
677 # Determine how many lines at the bottom of the screen are needed for
676 # showing prompts, so we can know wheter long strings are to be printed or
678 # showing prompts, so we can know wheter long strings are to be printed or
677 # paged:
679 # paged:
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
680 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
681 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
680
682
681 # configure startup banner
683 # configure startup banner
682 if IP_rc.c: # regular python doesn't print the banner with -c
684 if IP_rc.c: # regular python doesn't print the banner with -c
683 IP_rc.banner = 0
685 IP_rc.banner = 0
684 if IP_rc.banner:
686 if IP_rc.banner:
685 BANN_P = IP.BANNER_PARTS
687 BANN_P = IP.BANNER_PARTS
686 else:
688 else:
687 BANN_P = []
689 BANN_P = []
688
690
689 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
691 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
690
692
691 # add message log (possibly empty)
693 # add message log (possibly empty)
692 if msg.summary: BANN_P.append(msg.summary)
694 if msg.summary: BANN_P.append(msg.summary)
693 # Final banner is a string
695 # Final banner is a string
694 IP.BANNER = '\n'.join(BANN_P)
696 IP.BANNER = '\n'.join(BANN_P)
695
697
696 # Finalize the IPython instance. This assumes the rc structure is fully
698 # Finalize the IPython instance. This assumes the rc structure is fully
697 # in place.
699 # in place.
698 IP.post_config_initialization()
700 IP.post_config_initialization()
699
701
700 return IP
702 return IP
701 #************************ end of file <ipmaker.py> **************************
703 #************************ end of file <ipmaker.py> **************************
@@ -1,589 +1,599 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 # $Id: usage.py 990 2006-01-04 06:59:02Z fperez $
9 # $Id: usage.py 998 2006-01-09 06:57:40Z fperez $
10
10
11 from IPython import Release
11 from IPython import Release
12 __author__ = '%s <%s>' % Release.authors['Fernando']
12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 __license__ = Release.license
13 __license__ = Release.license
14 __version__ = Release.version
14 __version__ = Release.version
15
15
16 __doc__ = """
16 __doc__ = """
17 IPython -- An enhanced Interactive Python
17 IPython -- An enhanced Interactive Python
18 =========================================
18 =========================================
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the system
21 introspection, easier configuration, command completion, access to the system
22 shell and more.
22 shell and more.
23
23
24 IPython can also be embedded in running programs. See EMBEDDING below.
24 IPython can also be embedded in running programs. See EMBEDDING below.
25
25
26
26
27 USAGE
27 USAGE
28 ipython [options] files
28 ipython [options] files
29
29
30 If invoked with no options, it executes all the files listed in
30 If invoked with no options, it executes all the files listed in
31 sequence and drops you into the interpreter while still acknowledging
31 sequence and drops you into the interpreter while still acknowledging
32 any options you may have set in your ipythonrc file. This behavior is
32 any options you may have set in your ipythonrc file. This behavior is
33 different from standard Python, which when called as python -i will
33 different from standard Python, which when called as python -i will
34 only execute one file and will ignore your configuration setup.
34 only execute one file and will ignore your configuration setup.
35
35
36 Please note that some of the configuration options are not available at
36 Please note that some of the configuration options are not available at
37 the command line, simply because they are not practical here. Look into
37 the command line, simply because they are not practical here. Look into
38 your ipythonrc configuration file for details on those. This file
38 your ipythonrc configuration file for details on those. This file
39 typically installed in the $HOME/.ipython directory.
39 typically installed in the $HOME/.ipython directory.
40
40
41 For Windows users, $HOME resolves to C:\\Documents and
41 For Windows users, $HOME resolves to C:\\Documents and
42 Settings\\YourUserName in most instances, and _ipython is used instead
42 Settings\\YourUserName in most instances, and _ipython is used instead
43 of .ipython, since some Win32 programs have problems with dotted names
43 of .ipython, since some Win32 programs have problems with dotted names
44 in directories.
44 in directories.
45
45
46 In the rest of this text, we will refer to this directory as
46 In the rest of this text, we will refer to this directory as
47 IPYTHONDIR.
47 IPYTHONDIR.
48
48
49
49
50 SPECIAL THREADING OPTIONS
50 SPECIAL THREADING OPTIONS
51 The following special options are ONLY valid at the beginning of the
51 The following special options are ONLY valid at the beginning of the
52 command line, and not later. This is because they control the initial-
52 command line, and not later. This is because they control the initial-
53 ization of ipython itself, before the normal option-handling mechanism
53 ization of ipython itself, before the normal option-handling mechanism
54 is active.
54 is active.
55
55
56 -gthread, -qthread, -wthread, -pylab
56 -gthread, -qthread, -wthread, -pylab
57
57
58 Only ONE of these can be given, and it can only be given as the
58 Only ONE of these can be given, and it can only be given as the
59 first option passed to IPython (it will have no effect in any
59 first option passed to IPython (it will have no effect in any
60 other position). They provide threading support for the GTK, QT
60 other position). They provide threading support for the GTK, QT
61 and WXWidgets toolkits, and for the matplotlib library.
61 and WXWidgets toolkits, and for the matplotlib library.
62
62
63 With any of the first three options, IPython starts running a
63 With any of the first three options, IPython starts running a
64 separate thread for the graphical toolkit's operation, so that
64 separate thread for the graphical toolkit's operation, so that
65 you can open and control graphical elements from within an
65 you can open and control graphical elements from within an
66 IPython command line, without blocking. All three provide
66 IPython command line, without blocking. All three provide
67 essentially the same functionality, respectively for GTK, QT and
67 essentially the same functionality, respectively for GTK, QT and
68 WXWidgets (via their Python interfaces).
68 WXWidgets (via their Python interfaces).
69
69
70 Note that with -wthread, you can additionally use the -wxversion
71 option to request a specific version of wx to be used. This
72 requires that you have the 'wxversion' Python module installed,
73 which is part of recent wxPython distributions.
74
70 If -pylab is given, IPython loads special support for the mat-
75 If -pylab is given, IPython loads special support for the mat-
71 plotlib library (http://matplotlib.sourceforge.net), allowing
76 plotlib library (http://matplotlib.sourceforge.net), allowing
72 interactive usage of any of its backends as defined in the
77 interactive usage of any of its backends as defined in the
73 user's .matplotlibrc file. It automatically activates GTK, QT
78 user's .matplotlibrc file. It automatically activates GTK, QT
74 or WX threading for IPyhton if the choice of matplotlib backend
79 or WX threading for IPyhton if the choice of matplotlib backend
75 requires it. It also modifies the %run command to correctly
80 requires it. It also modifies the %run command to correctly
76 execute (without blocking) any matplotlib-based script which
81 execute (without blocking) any matplotlib-based script which
77 calls show() at the end.
82 calls show() at the end.
78
83
79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
84 -tk The -g/q/wthread options, and -pylab (if matplotlib is
80 configured to use GTK, QT or WX), will normally block Tk
85 configured to use GTK, QT or WX), will normally block Tk
81 graphical interfaces. This means that when GTK, QT or WX
86 graphical interfaces. This means that when GTK, QT or WX
82 threading is active, any attempt to open a Tk GUI will result in
87 threading is active, any attempt to open a Tk GUI will result in
83 a dead window, and possibly cause the Python interpreter to
88 a dead window, and possibly cause the Python interpreter to
84 crash. An extra option, -tk, is available to address this
89 crash. An extra option, -tk, is available to address this
85 issue. It can ONLY be given as a SECOND option after any of the
90 issue. It can ONLY be given as a SECOND option after any of the
86 above (-gthread, -qthread, -wthread or -pylab).
91 above (-gthread, -qthread, -wthread or -pylab).
87
92
88 If -tk is given, IPython will try to coordinate Tk threading
93 If -tk is given, IPython will try to coordinate Tk threading
89 with GTK, QT or WX. This is however potentially unreliable, and
94 with GTK, QT or WX. This is however potentially unreliable, and
90 you will have to test on your platform and Python configuration
95 you will have to test on your platform and Python configuration
91 to determine whether it works for you. Debian users have
96 to determine whether it works for you. Debian users have
92 reported success, apparently due to the fact that Debian builds
97 reported success, apparently due to the fact that Debian builds
93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
98 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
94 other Linux environments (such as Fedora Core 2/3), this option
99 other Linux environments (such as Fedora Core 2/3), this option
95 has caused random crashes and lockups of the Python interpreter.
100 has caused random crashes and lockups of the Python interpreter.
96 Under other operating systems (Mac OSX and Windows), you'll need
101 Under other operating systems (Mac OSX and Windows), you'll need
97 to try it to find out, since currently no user reports are
102 to try it to find out, since currently no user reports are
98 available.
103 available.
99
104
100 There is unfortunately no way for IPython to determine at run-
105 There is unfortunately no way for IPython to determine at run-
101 time whether -tk will work reliably or not, so you will need to
106 time whether -tk will work reliably or not, so you will need to
102 do some experiments before relying on it for regular work.
107 do some experiments before relying on it for regular work.
103
108
104 A WARNING ABOUT SIGNALS AND THREADS
109 A WARNING ABOUT SIGNALS AND THREADS
105
110
106 When any of the thread systems (GTK, QT or WX) are active, either
111 When any of the thread systems (GTK, QT or WX) are active, either
107 directly or via -pylab with a threaded backend, it is impossible to
112 directly or via -pylab with a threaded backend, it is impossible to
108 interrupt long-running Python code via Ctrl-C. IPython can not pass
113 interrupt long-running Python code via Ctrl-C. IPython can not pass
109 the KeyboardInterrupt exception (or the underlying SIGINT) across
114 the KeyboardInterrupt exception (or the underlying SIGINT) across
110 threads, so any long-running process started from IPython will run to
115 threads, so any long-running process started from IPython will run to
111 completion, or will have to be killed via an external (OS-based)
116 completion, or will have to be killed via an external (OS-based)
112 mechanism.
117 mechanism.
113
118
114 To the best of my knowledge, this limitation is imposed by the Python
119 To the best of my knowledge, this limitation is imposed by the Python
115 interpreter itself, and it comes from the difficulty of writing
120 interpreter itself, and it comes from the difficulty of writing
116 portable signal/threaded code. If any user is an expert on this topic
121 portable signal/threaded code. If any user is an expert on this topic
117 and can suggest a better solution, I would love to hear about it. In
122 and can suggest a better solution, I would love to hear about it. In
118 the IPython sources, look at the Shell.py module, and in particular at
123 the IPython sources, look at the Shell.py module, and in particular at
119 the runcode() method.
124 the runcode() method.
120
125
121 REGULAR OPTIONS
126 REGULAR OPTIONS
122 After the above threading options have been given, regular options can
127 After the above threading options have been given, regular options can
123 follow in any order. All options can be abbreviated to their shortest
128 follow in any order. All options can be abbreviated to their shortest
124 non-ambiguous form and are case-sensitive. One or two dashes can be
129 non-ambiguous form and are case-sensitive. One or two dashes can be
125 used. Some options have an alternate short form, indicated after a |.
130 used. Some options have an alternate short form, indicated after a |.
126
131
127 Most options can also be set from your ipythonrc configuration file.
132 Most options can also be set from your ipythonrc configuration file.
128 See the provided examples for assistance. Options given on the comman-
133 See the provided examples for assistance. Options given on the comman-
129 dline override the values set in the ipythonrc file.
134 dline override the values set in the ipythonrc file.
130
135
131 All options with a [no] prepended can be specified in negated form
136 All options with a [no] prepended can be specified in negated form
132 (using -nooption instead of -option) to turn the feature off.
137 (using -nooption instead of -option) to turn the feature off.
133
138
134 -h, --help
139 -h, --help
135 Show summary of options.
140 Show summary of options.
136
141
137 -pylab This can only be given as the first option passed to IPython (it
142 -pylab This can only be given as the first option passed to IPython (it
138 will have no effect in any other position). It adds special sup-
143 will have no effect in any other position). It adds special sup-
139 port for the matplotlib library (http://matplotlib.source-
144 port for the matplotlib library (http://matplotlib.source-
140 forge.net), allowing interactive usage of any of its backends as
145 forge.net), allowing interactive usage of any of its backends as
141 defined in the user’s .matplotlibrc file. It automatically
146 defined in the user’s .matplotlibrc file. It automatically
142 activates GTK or WX threading for IPyhton if the choice of mat-
147 activates GTK or WX threading for IPyhton if the choice of mat-
143 plotlib backend requires it. It also modifies the @run command
148 plotlib backend requires it. It also modifies the @run command
144 to correctly execute (without blocking) any matplotlib-based
149 to correctly execute (without blocking) any matplotlib-based
145 script which calls show() at the end.
150 script which calls show() at the end.
146
151
147 -autocall <val>
152 -autocall <val>
148 Make IPython automatically call any callable object even if you
153 Make IPython automatically call any callable object even if you
149 didn't type explicit parentheses. For example, 'str 43' becomes
154 didn't type explicit parentheses. For example, 'str 43' becomes
150 'str(43)' automatically. The value can be '0' to disable the
155 'str(43)' automatically. The value can be '0' to disable the
151 feature, '1' for 'smart' autocall, where it is not applied if
156 feature, '1' for 'smart' autocall, where it is not applied if
152 there are no more arguments on the line, and '2' for 'full'
157 there are no more arguments on the line, and '2' for 'full'
153 autocall, where all callable objects are automatically called
158 autocall, where all callable objects are automatically called
154 (even if no arguments are present). The default is '1'.
159 (even if no arguments are present). The default is '1'.
155
160
156 -[no]autoindent
161 -[no]autoindent
157 Turn automatic indentation on/off.
162 Turn automatic indentation on/off.
158
163
159 -[no]automagic
164 -[no]automagic
160 Make magic commands automatic (without needing their first char-
165 Make magic commands automatic (without needing their first char-
161 acter to be %). Type %magic at the IPython prompt for more
166 acter to be %). Type %magic at the IPython prompt for more
162 information.
167 information.
163
168
164 -[no]autoedit_syntax
169 -[no]autoedit_syntax
165 When a syntax error occurs after editing a file, automatically
170 When a syntax error occurs after editing a file, automatically
166 open the file to the trouble causing line for convenient fixing.
171 open the file to the trouble causing line for convenient fixing.
167
172
168 -[no]banner
173 -[no]banner
169 Print the intial information banner (default on).
174 Print the intial information banner (default on).
170
175
171 -c <command>
176 -c <command>
172 Execute the given command string, and set sys.argv to [’c’].
177 Execute the given command string, and set sys.argv to [’c’].
173 This is similar to the -c option in the normal Python inter-
178 This is similar to the -c option in the normal Python inter-
174 preter.
179 preter.
175
180
176 -cache_size|cs <n>
181 -cache_size|cs <n>
177 Size of the output cache (maximum number of entries to hold in
182 Size of the output cache (maximum number of entries to hold in
178 memory). The default is 1000, you can change it permanently in
183 memory). The default is 1000, you can change it permanently in
179 your config file. Setting it to 0 completely disables the
184 your config file. Setting it to 0 completely disables the
180 caching system, and the minimum value accepted is 20 (if you
185 caching system, and the minimum value accepted is 20 (if you
181 provide a value less than 20, it is reset to 0 and a warning is
186 provide a value less than 20, it is reset to 0 and a warning is
182 issued). This limit is defined because otherwise you’ll spend
187 issued). This limit is defined because otherwise you’ll spend
183 more time re-flushing a too small cache than working.
188 more time re-flushing a too small cache than working.
184
189
185 -classic|cl
190 -classic|cl
186 Gives IPython a similar feel to the classic Python prompt.
191 Gives IPython a similar feel to the classic Python prompt.
187
192
188 -colors <scheme>
193 -colors <scheme>
189 Color scheme for prompts and exception reporting. Currently
194 Color scheme for prompts and exception reporting. Currently
190 implemented: NoColor, Linux, and LightBG.
195 implemented: NoColor, Linux, and LightBG.
191
196
192 -[no]color_info
197 -[no]color_info
193 IPython can display information about objects via a set of func-
198 IPython can display information about objects via a set of func-
194 tions, and optionally can use colors for this, syntax highlight-
199 tions, and optionally can use colors for this, syntax highlight-
195 ing source code and various other elements. However, because
200 ing source code and various other elements. However, because
196 this information is passed through a pager (like ’less’) and
201 this information is passed through a pager (like ’less’) and
197 many pagers get confused with color codes, this option is off by
202 many pagers get confused with color codes, this option is off by
198 default. You can test it and turn it on permanently in your
203 default. You can test it and turn it on permanently in your
199 ipythonrc file if it works for you. As a reference, the ’less’
204 ipythonrc file if it works for you. As a reference, the ’less’
200 pager supplied with Mandrake 8.2 works ok, but that in RedHat
205 pager supplied with Mandrake 8.2 works ok, but that in RedHat
201 7.2 doesn’t.
206 7.2 doesn’t.
202
207
203 Test it and turn it on permanently if it works with your system.
208 Test it and turn it on permanently if it works with your system.
204 The magic function @color_info allows you to toggle this inter-
209 The magic function @color_info allows you to toggle this inter-
205 actively for testing.
210 actively for testing.
206
211
207 -[no]confirm_exit
212 -[no]confirm_exit
208 Set to confirm when you try to exit IPython with an EOF (Con-
213 Set to confirm when you try to exit IPython with an EOF (Con-
209 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
214 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
210 magic functions @Exit or @Quit you can force a direct exit,
215 magic functions @Exit or @Quit you can force a direct exit,
211 bypassing any confirmation.
216 bypassing any confirmation.
212
217
213 -[no]debug
218 -[no]debug
214 Show information about the loading process. Very useful to pin
219 Show information about the loading process. Very useful to pin
215 down problems with your configuration files or to get details
220 down problems with your configuration files or to get details
216 about session restores.
221 about session restores.
217
222
218 -[no]deep_reload
223 -[no]deep_reload
219 IPython can use the deep_reload module which reloads changes in
224 IPython can use the deep_reload module which reloads changes in
220 modules recursively (it replaces the reload() function, so you
225 modules recursively (it replaces the reload() function, so you
221 don’t need to change anything to use it). deep_reload() forces a
226 don’t need to change anything to use it). deep_reload() forces a
222 full reload of modules whose code may have changed, which the
227 full reload of modules whose code may have changed, which the
223 default reload() function does not.
228 default reload() function does not.
224
229
225 When deep_reload is off, IPython will use the normal reload(),
230 When deep_reload is off, IPython will use the normal reload(),
226 but deep_reload will still be available as dreload(). This fea-
231 but deep_reload will still be available as dreload(). This fea-
227 ture is off by default [which means that you have both normal
232 ture is off by default [which means that you have both normal
228 reload() and dreload()].
233 reload() and dreload()].
229
234
230 -editor <name>
235 -editor <name>
231 Which editor to use with the @edit command. By default, IPython
236 Which editor to use with the @edit command. By default, IPython
232 will honor your EDITOR environment variable (if not set, vi is
237 will honor your EDITOR environment variable (if not set, vi is
233 the Unix default and notepad the Windows one). Since this editor
238 the Unix default and notepad the Windows one). Since this editor
234 is invoked on the fly by IPython and is meant for editing small
239 is invoked on the fly by IPython and is meant for editing small
235 code snippets, you may want to use a small, lightweight editor
240 code snippets, you may want to use a small, lightweight editor
236 here (in case your default EDITOR is something like Emacs).
241 here (in case your default EDITOR is something like Emacs).
237
242
238 -ipythondir <name>
243 -ipythondir <name>
239 The name of your IPython configuration directory IPYTHONDIR.
244 The name of your IPython configuration directory IPYTHONDIR.
240 This can also be specified through the environment variable
245 This can also be specified through the environment variable
241 IPYTHONDIR.
246 IPYTHONDIR.
242
247
243 -log|l Generate a log file of all input. The file is named
248 -log|l Generate a log file of all input. The file is named
244 ipython_log.py in your current directory (which prevents logs
249 ipython_log.py in your current directory (which prevents logs
245 from multiple IPython sessions from trampling each other). You
250 from multiple IPython sessions from trampling each other). You
246 can use this to later restore a session by loading your logfile
251 can use this to later restore a session by loading your logfile
247 as a file to be executed with option -logplay (see below).
252 as a file to be executed with option -logplay (see below).
248
253
249 -logfile|lf
254 -logfile|lf
250 Specify the name of your logfile.
255 Specify the name of your logfile.
251
256
252 -logplay|lp
257 -logplay|lp
253 Replay a previous log. For restoring a session as close as pos-
258 Replay a previous log. For restoring a session as close as pos-
254 sible to the state you left it in, use this option (don’t just
259 sible to the state you left it in, use this option (don’t just
255 run the logfile). With -logplay, IPython will try to reconstruct
260 run the logfile). With -logplay, IPython will try to reconstruct
256 the previous working environment in full, not just execute the
261 the previous working environment in full, not just execute the
257 commands in the logfile.
262 commands in the logfile.
258 When a session is restored, logging is automatically turned on
263 When a session is restored, logging is automatically turned on
259 again with the name of the logfile it was invoked with (it is
264 again with the name of the logfile it was invoked with (it is
260 read from the log header). So once you’ve turned logging on for
265 read from the log header). So once you’ve turned logging on for
261 a session, you can quit IPython and reload it as many times as
266 a session, you can quit IPython and reload it as many times as
262 you want and it will continue to log its history and restore
267 you want and it will continue to log its history and restore
263 from the beginning every time.
268 from the beginning every time.
264
269
265 Caveats: there are limitations in this option. The history vari-
270 Caveats: there are limitations in this option. The history vari-
266 ables _i*,_* and _dh don’t get restored properly. In the future
271 ables _i*,_* and _dh don’t get restored properly. In the future
267 we will try to implement full session saving by writing and
272 we will try to implement full session saving by writing and
268 retrieving a failed because of inherent limitations of Python’s
273 retrieving a failed because of inherent limitations of Python’s
269 Pickle module, so this may have to wait.
274 Pickle module, so this may have to wait.
270
275
271 -[no]messages
276 -[no]messages
272 Print messages which IPython collects about its startup process
277 Print messages which IPython collects about its startup process
273 (default on).
278 (default on).
274
279
275 -[no]pdb
280 -[no]pdb
276 Automatically call the pdb debugger after every uncaught excep-
281 Automatically call the pdb debugger after every uncaught excep-
277 tion. If you are used to debugging using pdb, this puts you
282 tion. If you are used to debugging using pdb, this puts you
278 automatically inside of it after any call (either in IPython or
283 automatically inside of it after any call (either in IPython or
279 in code called by it) which triggers an exception which goes
284 in code called by it) which triggers an exception which goes
280 uncaught.
285 uncaught.
281
286
282 -[no]pprint
287 -[no]pprint
283 IPython can optionally use the pprint (pretty printer) module
288 IPython can optionally use the pprint (pretty printer) module
284 for displaying results. pprint tends to give a nicer display of
289 for displaying results. pprint tends to give a nicer display of
285 nested data structures. If you like it, you can turn it on per-
290 nested data structures. If you like it, you can turn it on per-
286 manently in your config file (default off).
291 manently in your config file (default off).
287
292
288 -profile|p <name>
293 -profile|p <name>
289 Assume that your config file is ipythonrc-<name> (looks in cur-
294 Assume that your config file is ipythonrc-<name> (looks in cur-
290 rent dir first, then in IPYTHONDIR). This is a quick way to keep
295 rent dir first, then in IPYTHONDIR). This is a quick way to keep
291 and load multiple config files for different tasks, especially
296 and load multiple config files for different tasks, especially
292 if you use the include option of config files. You can keep a
297 if you use the include option of config files. You can keep a
293 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
298 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
294 which include this one and load extra things for particular
299 which include this one and load extra things for particular
295 tasks. For example:
300 tasks. For example:
296
301
297 1) $HOME/.ipython/ipythonrc : load basic things you always want.
302 1) $HOME/.ipython/ipythonrc : load basic things you always want.
298 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
303 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
299 related modules.
304 related modules.
300 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
305 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
301 plotting modules.
306 plotting modules.
302
307
303 Since it is possible to create an endless loop by having circu-
308 Since it is possible to create an endless loop by having circu-
304 lar file inclusions, IPython will stop if it reaches 15 recur-
309 lar file inclusions, IPython will stop if it reaches 15 recur-
305 sive inclusions.
310 sive inclusions.
306
311
307 -prompt_in1|pi1 <string>
312 -prompt_in1|pi1 <string>
308 Specify the string used for input prompts. Note that if you are
313 Specify the string used for input prompts. Note that if you are
309 using numbered prompts, the number is represented with a ’\#’ in
314 using numbered prompts, the number is represented with a ’\#’ in
310 the string. Don’t forget to quote strings with spaces embedded
315 the string. Don’t forget to quote strings with spaces embedded
311 in them. Default: ’In [\#]:’.
316 in them. Default: ’In [\#]:’.
312
317
313 Most bash-like escapes can be used to customize IPython’s
318 Most bash-like escapes can be used to customize IPython’s
314 prompts, as well as a few additional ones which are IPython-spe-
319 prompts, as well as a few additional ones which are IPython-spe-
315 cific. All valid prompt escapes are described in detail in the
320 cific. All valid prompt escapes are described in detail in the
316 Customization section of the IPython HTML/PDF manual.
321 Customization section of the IPython HTML/PDF manual.
317
322
318 -prompt_in2|pi2 <string>
323 -prompt_in2|pi2 <string>
319 Similar to the previous option, but used for the continuation
324 Similar to the previous option, but used for the continuation
320 prompts. The special sequence ’\D’ is similar to ’\#’, but with
325 prompts. The special sequence ’\D’ is similar to ’\#’, but with
321 all digits replaced dots (so you can have your continuation
326 all digits replaced dots (so you can have your continuation
322 prompt aligned with your input prompt). Default: ’ .\D.:’
327 prompt aligned with your input prompt). Default: ’ .\D.:’
323 (note three spaces at the start for alignment with ’In [\#]’).
328 (note three spaces at the start for alignment with ’In [\#]’).
324
329
325 -prompt_out|po <string>
330 -prompt_out|po <string>
326 String used for output prompts, also uses numbers like
331 String used for output prompts, also uses numbers like
327 prompt_in1. Default: ’Out[\#]:’.
332 prompt_in1. Default: ’Out[\#]:’.
328
333
329 -quick Start in bare bones mode (no config file loaded).
334 -quick Start in bare bones mode (no config file loaded).
330
335
331 -rcfile <name>
336 -rcfile <name>
332 Name of your IPython resource configuration file. normally
337 Name of your IPython resource configuration file. normally
333 IPython loads ipythonrc (from current directory) or
338 IPython loads ipythonrc (from current directory) or
334 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
339 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
335 IPython starts with a bare bones configuration (no modules
340 IPython starts with a bare bones configuration (no modules
336 loaded at all).
341 loaded at all).
337
342
338 -[no]readline
343 -[no]readline
339 Use the readline library, which is needed to support name com-
344 Use the readline library, which is needed to support name com-
340 pletion and command history, among other things. It is enabled
345 pletion and command history, among other things. It is enabled
341 by default, but may cause problems for users of X/Emacs in
346 by default, but may cause problems for users of X/Emacs in
342 Python comint or shell buffers.
347 Python comint or shell buffers.
343
348
344 Note that emacs ’eterm’ buffers (opened with M-x term) support
349 Note that emacs ’eterm’ buffers (opened with M-x term) support
345 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
350 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
346 shell and C-c !) buffers do not.
351 shell and C-c !) buffers do not.
347
352
348 -screen_length|sl <n>
353 -screen_length|sl <n>
349 Number of lines of your screen. This is used to control print-
354 Number of lines of your screen. This is used to control print-
350 ing of very long strings. Strings longer than this number of
355 ing of very long strings. Strings longer than this number of
351 lines will be sent through a pager instead of directly printed.
356 lines will be sent through a pager instead of directly printed.
352
357
353 The default value for this is 0, which means IPython will auto-
358 The default value for this is 0, which means IPython will auto-
354 detect your screen size every time it needs to print certain
359 detect your screen size every time it needs to print certain
355 potentially long strings (this doesn’t change the behavior of
360 potentially long strings (this doesn’t change the behavior of
356 the ’print’ keyword, it’s only triggered internally). If for
361 the ’print’ keyword, it’s only triggered internally). If for
357 some reason this isn’t working well (it needs curses support),
362 some reason this isn’t working well (it needs curses support),
358 specify it yourself. Otherwise don’t change the default.
363 specify it yourself. Otherwise don’t change the default.
359
364
360 -separate_in|si <string>
365 -separate_in|si <string>
361 Separator before input prompts. Default ’0.
366 Separator before input prompts. Default ’0.
362
367
363 -separate_out|so <string>
368 -separate_out|so <string>
364 Separator before output prompts. Default: 0 (nothing).
369 Separator before output prompts. Default: 0 (nothing).
365
370
366 -separate_out2|so2 <string>
371 -separate_out2|so2 <string>
367 Separator after output prompts. Default: 0 (nothing).
372 Separator after output prompts. Default: 0 (nothing).
368
373
369 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
374 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
370 Simply removes all input/output separators.
375 Simply removes all input/output separators.
371
376
372 -upgrade
377 -upgrade
373 Allows you to upgrade your IPYTHONDIR configuration when you
378 Allows you to upgrade your IPYTHONDIR configuration when you
374 install a new version of IPython. Since new versions may
379 install a new version of IPython. Since new versions may
375 include new command lines options or example files, this copies
380 include new command lines options or example files, this copies
376 updated ipythonrc-type files. However, it backs up (with a .old
381 updated ipythonrc-type files. However, it backs up (with a .old
377 extension) all files which it overwrites so that you can merge
382 extension) all files which it overwrites so that you can merge
378 back any custimizations you might have in your personal files.
383 back any custimizations you might have in your personal files.
379
384
380 -Version
385 -Version
381 Print version information and exit.
386 Print version information and exit.
382
387
388 -wxversion <string>
389 Select a specific version of wxPython (used in conjunction with
390 -wthread). Requires the wxversion module, part of recent
391 wxPython distributions.
392
383 -xmode <modename>
393 -xmode <modename>
384 Mode for exception reporting. The valid modes are Plain, Con-
394 Mode for exception reporting. The valid modes are Plain, Con-
385 text, and Verbose.
395 text, and Verbose.
386
396
387 - Plain: similar to python’s normal traceback printing.
397 - Plain: similar to python’s normal traceback printing.
388
398
389 - Context: prints 5 lines of context source code around each
399 - Context: prints 5 lines of context source code around each
390 line in the traceback.
400 line in the traceback.
391
401
392 - Verbose: similar to Context, but additionally prints the vari-
402 - Verbose: similar to Context, but additionally prints the vari-
393 ables currently visible where the exception happened (shortening
403 ables currently visible where the exception happened (shortening
394 their strings if too long). This can potentially be very slow,
404 their strings if too long). This can potentially be very slow,
395 if you happen to have a huge data structure whose string repre-
405 if you happen to have a huge data structure whose string repre-
396 sentation is complex to compute. Your computer may appear to
406 sentation is complex to compute. Your computer may appear to
397 freeze for a while with cpu usage at 100%. If this occurs, you
407 freeze for a while with cpu usage at 100%. If this occurs, you
398 can cancel the traceback with Ctrl-C (maybe hitting it more than
408 can cancel the traceback with Ctrl-C (maybe hitting it more than
399 once).
409 once).
400
410
401
411
402 EMBEDDING
412 EMBEDDING
403 It is possible to start an IPython instance inside your own Python pro-
413 It is possible to start an IPython instance inside your own Python pro-
404 grams. In the documentation example files there are some illustrations
414 grams. In the documentation example files there are some illustrations
405 on how to do this.
415 on how to do this.
406
416
407 This feature allows you to evalutate dynamically the state of your
417 This feature allows you to evalutate dynamically the state of your
408 code, operate with your variables, analyze them, etc. Note however
418 code, operate with your variables, analyze them, etc. Note however
409 that any changes you make to values while in the shell do NOT propagate
419 that any changes you make to values while in the shell do NOT propagate
410 back to the running code, so it is safe to modify your values because
420 back to the running code, so it is safe to modify your values because
411 you won’t break your code in bizarre ways by doing so.
421 you won’t break your code in bizarre ways by doing so.
412 """
422 """
413
423
414 cmd_line_usage = __doc__
424 cmd_line_usage = __doc__
415
425
416 #---------------------------------------------------------------------------
426 #---------------------------------------------------------------------------
417 interactive_usage = """
427 interactive_usage = """
418 IPython -- An enhanced Interactive Python
428 IPython -- An enhanced Interactive Python
419 =========================================
429 =========================================
420
430
421 IPython offers a combination of convenient shell features, special commands
431 IPython offers a combination of convenient shell features, special commands
422 and a history mechanism for both input (command history) and output (results
432 and a history mechanism for both input (command history) and output (results
423 caching, similar to Mathematica). It is intended to be a fully compatible
433 caching, similar to Mathematica). It is intended to be a fully compatible
424 replacement for the standard Python interpreter, while offering vastly
434 replacement for the standard Python interpreter, while offering vastly
425 improved functionality and flexibility.
435 improved functionality and flexibility.
426
436
427 At your system command line, type 'ipython -help' to see the command line
437 At your system command line, type 'ipython -help' to see the command line
428 options available. This document only describes interactive features.
438 options available. This document only describes interactive features.
429
439
430 Warning: IPython relies on the existence of a global variable called __IP which
440 Warning: IPython relies on the existence of a global variable called __IP which
431 controls the shell itself. If you redefine __IP to anything, bizarre behavior
441 controls the shell itself. If you redefine __IP to anything, bizarre behavior
432 will quickly occur.
442 will quickly occur.
433
443
434 MAIN FEATURES
444 MAIN FEATURES
435
445
436 * Access to the standard Python help. As of Python 2.1, a help system is
446 * Access to the standard Python help. As of Python 2.1, a help system is
437 available with access to object docstrings and the Python manuals. Simply
447 available with access to object docstrings and the Python manuals. Simply
438 type 'help' (no quotes) to access it.
448 type 'help' (no quotes) to access it.
439
449
440 * Magic commands: type %magic for information on the magic subsystem.
450 * Magic commands: type %magic for information on the magic subsystem.
441
451
442 * System command aliases, via the %alias command or the ipythonrc config file.
452 * System command aliases, via the %alias command or the ipythonrc config file.
443
453
444 * Dynamic object information:
454 * Dynamic object information:
445
455
446 Typing ?word or word? prints detailed information about an object. If
456 Typing ?word or word? prints detailed information about an object. If
447 certain strings in the object are too long (docstrings, code, etc.) they get
457 certain strings in the object are too long (docstrings, code, etc.) they get
448 snipped in the center for brevity.
458 snipped in the center for brevity.
449
459
450 Typing ??word or word?? gives access to the full information without
460 Typing ??word or word?? gives access to the full information without
451 snipping long strings. Long strings are sent to the screen through the less
461 snipping long strings. Long strings are sent to the screen through the less
452 pager if longer than the screen, printed otherwise.
462 pager if longer than the screen, printed otherwise.
453
463
454 The ?/?? system gives access to the full source code for any object (if
464 The ?/?? system gives access to the full source code for any object (if
455 available), shows function prototypes and other useful information.
465 available), shows function prototypes and other useful information.
456
466
457 If you just want to see an object's docstring, type '%pdoc object' (without
467 If you just want to see an object's docstring, type '%pdoc object' (without
458 quotes, and without % if you have automagic on).
468 quotes, and without % if you have automagic on).
459
469
460 Both %pdoc and ?/?? give you access to documentation even on things which are
470 Both %pdoc and ?/?? give you access to documentation even on things which are
461 not explicitely defined. Try for example typing {}.get? or after import os,
471 not explicitely defined. Try for example typing {}.get? or after import os,
462 type os.path.abspath??. The magic functions %pdef, %source and %file operate
472 type os.path.abspath??. The magic functions %pdef, %source and %file operate
463 similarly.
473 similarly.
464
474
465 * Completion in the local namespace, by typing TAB at the prompt.
475 * Completion in the local namespace, by typing TAB at the prompt.
466
476
467 At any time, hitting tab will complete any available python commands or
477 At any time, hitting tab will complete any available python commands or
468 variable names, and show you a list of the possible completions if there's
478 variable names, and show you a list of the possible completions if there's
469 no unambiguous one. It will also complete filenames in the current directory.
479 no unambiguous one. It will also complete filenames in the current directory.
470
480
471 This feature requires the readline and rlcomplete modules, so it won't work
481 This feature requires the readline and rlcomplete modules, so it won't work
472 if your Python lacks readline support (such as under Windows).
482 if your Python lacks readline support (such as under Windows).
473
483
474 * Search previous command history in two ways (also requires readline):
484 * Search previous command history in two ways (also requires readline):
475
485
476 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
486 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
477 search through only the history items that match what you've typed so
487 search through only the history items that match what you've typed so
478 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
488 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
479 normal arrow keys.
489 normal arrow keys.
480
490
481 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
491 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
482 your history for lines that match what you've typed so far, completing as
492 your history for lines that match what you've typed so far, completing as
483 much as it can.
493 much as it can.
484
494
485 * Persistent command history across sessions (readline required).
495 * Persistent command history across sessions (readline required).
486
496
487 * Logging of input with the ability to save and restore a working session.
497 * Logging of input with the ability to save and restore a working session.
488
498
489 * System escape with !. Typing !ls will run 'ls' in the current directory.
499 * System escape with !. Typing !ls will run 'ls' in the current directory.
490
500
491 * The reload command does a 'deep' reload of a module: changes made to the
501 * The reload command does a 'deep' reload of a module: changes made to the
492 module since you imported will actually be available without having to exit.
502 module since you imported will actually be available without having to exit.
493
503
494 * Verbose and colored exception traceback printouts. See the magic xmode and
504 * Verbose and colored exception traceback printouts. See the magic xmode and
495 xcolor functions for details (just type %magic).
505 xcolor functions for details (just type %magic).
496
506
497 * Input caching system:
507 * Input caching system:
498
508
499 IPython offers numbered prompts (In/Out) with input and output caching. All
509 IPython offers numbered prompts (In/Out) with input and output caching. All
500 input is saved and can be retrieved as variables (besides the usual arrow
510 input is saved and can be retrieved as variables (besides the usual arrow
501 key recall).
511 key recall).
502
512
503 The following GLOBAL variables always exist (so don't overwrite them!):
513 The following GLOBAL variables always exist (so don't overwrite them!):
504 _i: stores previous input.
514 _i: stores previous input.
505 _ii: next previous.
515 _ii: next previous.
506 _iii: next-next previous.
516 _iii: next-next previous.
507 _ih : a list of all input _ih[n] is the input from line n.
517 _ih : a list of all input _ih[n] is the input from line n.
508
518
509 Additionally, global variables named _i<n> are dynamically created (<n>
519 Additionally, global variables named _i<n> are dynamically created (<n>
510 being the prompt counter), such that _i<n> == _ih[<n>]
520 being the prompt counter), such that _i<n> == _ih[<n>]
511
521
512 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
522 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
513
523
514 You can create macros which contain multiple input lines from this history,
524 You can create macros which contain multiple input lines from this history,
515 for later re-execution, with the %macro function.
525 for later re-execution, with the %macro function.
516
526
517 The history function %hist allows you to see any part of your input history
527 The history function %hist allows you to see any part of your input history
518 by printing a range of the _i variables. Note that inputs which contain
528 by printing a range of the _i variables. Note that inputs which contain
519 magic functions (%) appear in the history with a prepended comment. This is
529 magic functions (%) appear in the history with a prepended comment. This is
520 because they aren't really valid Python code, so you can't exec them.
530 because they aren't really valid Python code, so you can't exec them.
521
531
522 * Output caching system:
532 * Output caching system:
523
533
524 For output that is returned from actions, a system similar to the input
534 For output that is returned from actions, a system similar to the input
525 cache exists but using _ instead of _i. Only actions that produce a result
535 cache exists but using _ instead of _i. Only actions that produce a result
526 (NOT assignments, for example) are cached. If you are familiar with
536 (NOT assignments, for example) are cached. If you are familiar with
527 Mathematica, IPython's _ variables behave exactly like Mathematica's %
537 Mathematica, IPython's _ variables behave exactly like Mathematica's %
528 variables.
538 variables.
529
539
530 The following GLOBAL variables always exist (so don't overwrite them!):
540 The following GLOBAL variables always exist (so don't overwrite them!):
531 _ (one underscore): previous output.
541 _ (one underscore): previous output.
532 __ (two underscores): next previous.
542 __ (two underscores): next previous.
533 ___ (three underscores): next-next previous.
543 ___ (three underscores): next-next previous.
534
544
535 Global variables named _<n> are dynamically created (<n> being the prompt
545 Global variables named _<n> are dynamically created (<n> being the prompt
536 counter), such that the result of output <n> is always available as _<n>.
546 counter), such that the result of output <n> is always available as _<n>.
537
547
538 Finally, a global dictionary named _oh exists with entries for all lines
548 Finally, a global dictionary named _oh exists with entries for all lines
539 which generated output.
549 which generated output.
540
550
541 * Directory history:
551 * Directory history:
542
552
543 Your history of visited directories is kept in the global list _dh, and the
553 Your history of visited directories is kept in the global list _dh, and the
544 magic %cd command can be used to go to any entry in that list.
554 magic %cd command can be used to go to any entry in that list.
545
555
546 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
556 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
547
557
548 1. Auto-parentheses
558 1. Auto-parentheses
549 Callable objects (i.e. functions, methods, etc) can be invoked like
559 Callable objects (i.e. functions, methods, etc) can be invoked like
550 this (notice the commas between the arguments):
560 this (notice the commas between the arguments):
551 >>> callable_ob arg1, arg2, arg3
561 >>> callable_ob arg1, arg2, arg3
552 and the input will be translated to this:
562 and the input will be translated to this:
553 --> callable_ob(arg1, arg2, arg3)
563 --> callable_ob(arg1, arg2, arg3)
554 You can force auto-parentheses by using '/' as the first character
564 You can force auto-parentheses by using '/' as the first character
555 of a line. For example:
565 of a line. For example:
556 >>> /globals # becomes 'globals()'
566 >>> /globals # becomes 'globals()'
557 Note that the '/' MUST be the first character on the line! This
567 Note that the '/' MUST be the first character on the line! This
558 won't work:
568 won't work:
559 >>> print /globals # syntax error
569 >>> print /globals # syntax error
560
570
561 In most cases the automatic algorithm should work, so you should
571 In most cases the automatic algorithm should work, so you should
562 rarely need to explicitly invoke /. One notable exception is if you
572 rarely need to explicitly invoke /. One notable exception is if you
563 are trying to call a function with a list of tuples as arguments (the
573 are trying to call a function with a list of tuples as arguments (the
564 parenthesis will confuse IPython):
574 parenthesis will confuse IPython):
565 In [1]: zip (1,2,3),(4,5,6) # won't work
575 In [1]: zip (1,2,3),(4,5,6) # won't work
566 but this will work:
576 but this will work:
567 In [2]: /zip (1,2,3),(4,5,6)
577 In [2]: /zip (1,2,3),(4,5,6)
568 ------> zip ((1,2,3),(4,5,6))
578 ------> zip ((1,2,3),(4,5,6))
569 Out[2]= [(1, 4), (2, 5), (3, 6)]
579 Out[2]= [(1, 4), (2, 5), (3, 6)]
570
580
571 IPython tells you that it has altered your command line by
581 IPython tells you that it has altered your command line by
572 displaying the new command line preceded by -->. e.g.:
582 displaying the new command line preceded by -->. e.g.:
573 In [18]: callable list
583 In [18]: callable list
574 -------> callable (list)
584 -------> callable (list)
575
585
576 2. Auto-Quoting
586 2. Auto-Quoting
577 You can force auto-quoting of a function's arguments by using ',' as
587 You can force auto-quoting of a function's arguments by using ',' as
578 the first character of a line. For example:
588 the first character of a line. For example:
579 >>> ,my_function /home/me # becomes my_function("/home/me")
589 >>> ,my_function /home/me # becomes my_function("/home/me")
580
590
581 If you use ';' instead, the whole argument is quoted as a single
591 If you use ';' instead, the whole argument is quoted as a single
582 string (while ',' splits on whitespace):
592 string (while ',' splits on whitespace):
583 >>> ,my_function a b c # becomes my_function("a","b","c")
593 >>> ,my_function a b c # becomes my_function("a","b","c")
584 >>> ;my_function a b c # becomes my_function("a b c")
594 >>> ;my_function a b c # becomes my_function("a b c")
585
595
586 Note that the ',' MUST be the first character on the line! This
596 Note that the ',' MUST be the first character on the line! This
587 won't work:
597 won't work:
588 >>> x = ,my_function /home/me # syntax error
598 >>> x = ,my_function /home/me # syntax error
589 """
599 """
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,395 +1,406 b''
1 .\" Hey, EMACS: -*- nroff -*-
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "November 30, 2004"
5 .TH IPYTHON 1 "November 30, 2004"
6 .\" Please adjust this date whenever revising the manpage.
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
7 .\"
8 .\" Some roff macros, for reference:
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
13 .\" .nf disable filling
14 .\" .fi enable filling
14 .\" .fi enable filling
15 .\" .br insert line break
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
18 .\" .SH section heading
19 .\" .SS secondary section heading
19 .\" .SS secondary section heading
20 .\"
20 .\"
21 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
23 .\"
24 .SH NAME
24 .SH NAME
25 ipython \- An Enhanced Interactive Python
25 ipython \- An Enhanced Interactive Python
26 .SH SYNOPSIS
26 .SH SYNOPSIS
27 .B ipython
27 .B ipython
28 .RI [ options ] " files" ...
28 .RI [ options ] " files" ...
29 .SH DESCRIPTION
29 .SH DESCRIPTION
30 An interactive Python shell with automatic history (input and output),
30 An interactive Python shell with automatic history (input and output),
31 dynamic object introspection, easier configuration, command
31 dynamic object introspection, easier configuration, command
32 completion, access to the system shell, integration with numerical and
32 completion, access to the system shell, integration with numerical and
33 scientific computing tools, and more.
33 scientific computing tools, and more.
34 .SH SPECIAL THREADING OPTIONS
34 .SH SPECIAL THREADING OPTIONS
35 The following special options are ONLY valid at the beginning of the command
35 The following special options are ONLY valid at the beginning of the command
36 line, and not later. This is because they control the initialization of
36 line, and not later. This is because they control the initialization of
37 ipython itself, before the normal option-handling mechanism is active.
37 ipython itself, before the normal option-handling mechanism is active.
38 .TP
38 .TP
39 .B \-gthread, \-qthread, \-wthread, \-pylab
39 .B \-gthread, \-qthread, \-wthread, \-pylab
40 Only ONE of these can be given, and it can only be given as the first option
40 Only ONE of these can be given, and it can only be given as the first option
41 passed to IPython (it will have no effect in any other position). They
41 passed to IPython (it will have no effect in any other position). They
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
43 matplotlib library.
43 matplotlib library.
44 .br
44 .br
45 .sp 1
45 .sp 1
46 With any of the first three options, IPython starts running a separate thread
46 With any of the first three options, IPython starts running a separate thread
47 for the graphical toolkit's operation, so that you can open and control
47 for the graphical toolkit's operation, so that you can open and control
48 graphical elements from within an IPython command line, without blocking. All
48 graphical elements from within an IPython command line, without blocking. All
49 three provide essentially the same functionality, respectively for GTK, QT and
49 three provide essentially the same functionality, respectively for GTK, QT and
50 WXWidgets (via their Python interfaces).
50 WXWidgets (via their Python interfaces).
51 .br
51 .br
52 .sp 1
52 .sp 1
53 Note that with \-wthread, you can additionally use the \-wxversion option to
54 request a specific version of wx to be used. This requires that you have the
55 'wxversion' Python module installed, which is part of recent wxPython
56 distributions.
57 .br
58 .sp 1
53 If \-pylab is given, IPython loads special support for the matplotlib library
59 If \-pylab is given, IPython loads special support for the matplotlib library
54 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
60 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
55 backends as defined in the user's .matplotlibrc file. It automatically
61 backends as defined in the user's .matplotlibrc file. It automatically
56 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
62 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
57 backend requires it. It also modifies the %run command to correctly execute
63 backend requires it. It also modifies the %run command to correctly execute
58 (without blocking) any matplotlib-based script which calls show() at the end.
64 (without blocking) any matplotlib-based script which calls show() at the end.
59 .TP
65 .TP
60 .B \-tk
66 .B \-tk
61 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
67 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
62 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
68 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
63 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
69 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
64 result in a dead window, and possibly cause the Python interpreter to crash.
70 result in a dead window, and possibly cause the Python interpreter to crash.
65 An extra option, \-tk, is available to address this issue. It can ONLY be
71 An extra option, \-tk, is available to address this issue. It can ONLY be
66 given as a SECOND option after any of the above (\-gthread, \-qthread,
72 given as a SECOND option after any of the above (\-gthread, \-qthread,
67 \-wthread or \-pylab).
73 \-wthread or \-pylab).
68 .br
74 .br
69 .sp 1
75 .sp 1
70 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
76 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
71 WX. This is however potentially unreliable, and you will have to test on your
77 WX. This is however potentially unreliable, and you will have to test on your
72 platform and Python configuration to determine whether it works for you.
78 platform and Python configuration to determine whether it works for you.
73 Debian users have reported success, apparently due to the fact that Debian
79 Debian users have reported success, apparently due to the fact that Debian
74 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
80 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
75 Linux environments (such as Fedora Core 2), this option has caused random
81 Linux environments (such as Fedora Core 2), this option has caused random
76 crashes and lockups of the Python interpreter. Under other operating systems
82 crashes and lockups of the Python interpreter. Under other operating systems
77 (Mac OSX and Windows), you'll need to try it to find out, since currently no
83 (Mac OSX and Windows), you'll need to try it to find out, since currently no
78 user reports are available.
84 user reports are available.
79 .br
85 .br
80 .sp 1
86 .sp 1
81 There is unfortunately no way for IPython to determine at runtime whether \-tk
87 There is unfortunately no way for IPython to determine at runtime whether \-tk
82 will work reliably or not, so you will need to do some experiments before
88 will work reliably or not, so you will need to do some experiments before
83 relying on it for regular work.
89 relying on it for regular work.
84 .
90 .
85 .SS A WARNING ABOUT SIGNALS AND THREADS
91 .SS A WARNING ABOUT SIGNALS AND THREADS
86 When any of the thread systems (GTK, QT or WX) are active, either directly or
92 When any of the thread systems (GTK, QT or WX) are active, either directly or
87 via \-pylab with a threaded backend, it is impossible to interrupt
93 via \-pylab with a threaded backend, it is impossible to interrupt
88 long-running Python code via Ctrl\-C. IPython can not pass the
94 long-running Python code via Ctrl\-C. IPython can not pass the
89 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
95 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
90 long-running process started from IPython will run to completion, or will have
96 long-running process started from IPython will run to completion, or will have
91 to be killed via an external (OS-based) mechanism.
97 to be killed via an external (OS-based) mechanism.
92 .br
98 .br
93 .sp 1
99 .sp 1
94 To the best of my knowledge, this limitation is imposed by the Python
100 To the best of my knowledge, this limitation is imposed by the Python
95 interpreter itself, and it comes from the difficulty of writing portable
101 interpreter itself, and it comes from the difficulty of writing portable
96 signal/threaded code. If any user is an expert on this topic and can suggest
102 signal/threaded code. If any user is an expert on this topic and can suggest
97 a better solution, I would love to hear about it. In the IPython sources,
103 a better solution, I would love to hear about it. In the IPython sources,
98 look at the Shell.py module, and in particular at the runcode() method.
104 look at the Shell.py module, and in particular at the runcode() method.
99 .
105 .
100 .SH REGULAR OPTIONS
106 .SH REGULAR OPTIONS
101 After the above threading options have been given, regular options can follow
107 After the above threading options have been given, regular options can follow
102 in any order. All options can be abbreviated to their shortest non-ambiguous
108 in any order. All options can be abbreviated to their shortest non-ambiguous
103 form and are case-sensitive. One or two dashes can be used. Some options
109 form and are case-sensitive. One or two dashes can be used. Some options
104 have an alternate short form, indicated after a |.
110 have an alternate short form, indicated after a |.
105 .br
111 .br
106 .sp 1
112 .sp 1
107 Most options can also be set from your ipythonrc configuration file.
113 Most options can also be set from your ipythonrc configuration file.
108 See the provided examples for assistance. Options given on the
114 See the provided examples for assistance. Options given on the
109 commandline override the values set in the ipythonrc file.
115 commandline override the values set in the ipythonrc file.
110 .br
116 .br
111 .sp 1
117 .sp 1
112 All options with a [no] prepended can be specified in negated form
118 All options with a [no] prepended can be specified in negated form
113 (\-nooption instead of \-option) to turn the feature off.
119 (\-nooption instead of \-option) to turn the feature off.
114 .TP
120 .TP
115 .B \-h, \-\-help
121 .B \-h, \-\-help
116 Show summary of options.
122 Show summary of options.
117 .TP
123 .TP
118 .B \-autocall <val>
124 .B \-autocall <val>
119 Make IPython automatically call any callable object even if you didn't type
125 Make IPython automatically call any callable object even if you didn't type
120 explicit parentheses. For example, 'str 43' becomes
126 explicit parentheses. For example, 'str 43' becomes
121 'str(43)' automatically. The value can be '0' to disable the
127 'str(43)' automatically. The value can be '0' to disable the
122 feature, '1' for 'smart' autocall, where it is not applied if
128 feature, '1' for 'smart' autocall, where it is not applied if
123 there are no more arguments on the line, and '2' for 'full'
129 there are no more arguments on the line, and '2' for 'full'
124 autocall, where all callable objects are automatically called
130 autocall, where all callable objects are automatically called
125 (even if no arguments are present). The default is '1'.
131 (even if no arguments are present). The default is '1'.
126 .TP
132 .TP
127 .B \-[no]autoindent
133 .B \-[no]autoindent
128 Turn automatic indentation on/off.
134 Turn automatic indentation on/off.
129 .TP
135 .TP
130 .B \-[no]automagic
136 .B \-[no]automagic
131 Make magic commands automatic (without needing their first character
137 Make magic commands automatic (without needing their first character
132 to be %). Type %magic at the IPython prompt for more information.
138 to be %). Type %magic at the IPython prompt for more information.
133 .TP
139 .TP
134 .B \-[no]autoedit_syntax
140 .B \-[no]autoedit_syntax
135 When a syntax error occurs after editing a file, automatically open the file
141 When a syntax error occurs after editing a file, automatically open the file
136 to the trouble causing line for convenient fixing.
142 to the trouble causing line for convenient fixing.
137 .TP
143 .TP
138 .B \-[no]banner
144 .B \-[no]banner
139 Print the intial information banner (default on).
145 Print the intial information banner (default on).
140 .TP
146 .TP
141 .B \-c <command>
147 .B \-c <command>
142 Execute the given command string, and set sys.argv to ['c']. This is similar
148 Execute the given command string, and set sys.argv to ['c']. This is similar
143 to the \-c option in the normal Python interpreter.
149 to the \-c option in the normal Python interpreter.
144 .TP
150 .TP
145 .B \-cache_size|cs <n>
151 .B \-cache_size|cs <n>
146 Size of the output cache (maximum number of entries to hold in
152 Size of the output cache (maximum number of entries to hold in
147 memory). The default is 1000, you can change it permanently in your
153 memory). The default is 1000, you can change it permanently in your
148 config file. Setting it to 0 completely disables the caching system,
154 config file. Setting it to 0 completely disables the caching system,
149 and the minimum value accepted is 20 (if you provide a value less than
155 and the minimum value accepted is 20 (if you provide a value less than
150 20, it is reset to 0 and a warning is issued). This limit is defined
156 20, it is reset to 0 and a warning is issued). This limit is defined
151 because otherwise you'll spend more time re-flushing a too small cache
157 because otherwise you'll spend more time re-flushing a too small cache
152 than working.
158 than working.
153 .TP
159 .TP
154 .B \-classic|cl
160 .B \-classic|cl
155 Gives IPython a similar feel to the classic Python prompt.
161 Gives IPython a similar feel to the classic Python prompt.
156 .TP
162 .TP
157 .B \-colors <scheme>
163 .B \-colors <scheme>
158 Color scheme for prompts and exception reporting. Currently
164 Color scheme for prompts and exception reporting. Currently
159 implemented: NoColor, Linux, and LightBG.
165 implemented: NoColor, Linux, and LightBG.
160 .TP
166 .TP
161 .B \-[no]color_info
167 .B \-[no]color_info
162 IPython can display information about objects via a set of functions,
168 IPython can display information about objects via a set of functions,
163 and optionally can use colors for this, syntax highlighting source
169 and optionally can use colors for this, syntax highlighting source
164 code and various other elements. However, because this information is
170 code and various other elements. However, because this information is
165 passed through a pager (like 'less') and many pagers get confused with
171 passed through a pager (like 'less') and many pagers get confused with
166 color codes, this option is off by default. You can test it and turn
172 color codes, this option is off by default. You can test it and turn
167 it on permanently in your ipythonrc file if it works for you. As a
173 it on permanently in your ipythonrc file if it works for you. As a
168 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
174 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
169 that in RedHat 7.2 doesn't.
175 that in RedHat 7.2 doesn't.
170 .br
176 .br
171 .sp 1
177 .sp 1
172 Test it and turn it on permanently if it works with your system. The
178 Test it and turn it on permanently if it works with your system. The
173 magic function @color_info allows you to toggle this interactively for
179 magic function @color_info allows you to toggle this interactively for
174 testing.
180 testing.
175 .TP
181 .TP
176 .B \-[no]confirm_exit
182 .B \-[no]confirm_exit
177 Set to confirm when you try to exit IPython with an EOF (Control-D in
183 Set to confirm when you try to exit IPython with an EOF (Control-D in
178 Unix, Control-Z/Enter in Windows). Note that using the magic functions
184 Unix, Control-Z/Enter in Windows). Note that using the magic functions
179 @Exit or @Quit you can force a direct exit, bypassing any
185 @Exit or @Quit you can force a direct exit, bypassing any
180 confirmation.
186 confirmation.
181 .TP
187 .TP
182 .B \-[no]debug
188 .B \-[no]debug
183 Show information about the loading process. Very useful to pin down
189 Show information about the loading process. Very useful to pin down
184 problems with your configuration files or to get details about session
190 problems with your configuration files or to get details about session
185 restores.
191 restores.
186 .TP
192 .TP
187 .B \-[no]deep_reload
193 .B \-[no]deep_reload
188 IPython can use the deep_reload module which reloads changes in
194 IPython can use the deep_reload module which reloads changes in
189 modules recursively (it replaces the reload() function, so you don't
195 modules recursively (it replaces the reload() function, so you don't
190 need to change anything to use it). deep_reload() forces a full reload
196 need to change anything to use it). deep_reload() forces a full reload
191 of modules whose code may have changed, which the default reload()
197 of modules whose code may have changed, which the default reload()
192 function does not.
198 function does not.
193 .br
199 .br
194 .sp 1
200 .sp 1
195 When deep_reload is off, IPython will use the normal reload(), but
201 When deep_reload is off, IPython will use the normal reload(), but
196 deep_reload will still be available as dreload(). This feature is off
202 deep_reload will still be available as dreload(). This feature is off
197 by default [which means that you have both normal reload() and
203 by default [which means that you have both normal reload() and
198 dreload()].
204 dreload()].
199 .TP
205 .TP
200 .B \-editor <name>
206 .B \-editor <name>
201 Which editor to use with the @edit command. By default, IPython will
207 Which editor to use with the @edit command. By default, IPython will
202 honor your EDITOR environment variable (if not set, vi is the Unix
208 honor your EDITOR environment variable (if not set, vi is the Unix
203 default and notepad the Windows one). Since this editor is invoked on
209 default and notepad the Windows one). Since this editor is invoked on
204 the fly by IPython and is meant for editing small code snippets, you
210 the fly by IPython and is meant for editing small code snippets, you
205 may want to use a small, lightweight editor here (in case your default
211 may want to use a small, lightweight editor here (in case your default
206 EDITOR is something like Emacs).
212 EDITOR is something like Emacs).
207 .TP
213 .TP
208 .B \-ipythondir <name>
214 .B \-ipythondir <name>
209 The name of your IPython configuration directory IPYTHONDIR. This can
215 The name of your IPython configuration directory IPYTHONDIR. This can
210 also be specified through the environment variable IPYTHONDIR.
216 also be specified through the environment variable IPYTHONDIR.
211 .TP
217 .TP
212 .B \-log|l
218 .B \-log|l
213 Generate a log file of all input. The file is named ipython_log.py in your
219 Generate a log file of all input. The file is named ipython_log.py in your
214 current directory (which prevents logs from multiple IPython sessions from
220 current directory (which prevents logs from multiple IPython sessions from
215 trampling each other). You can use this to later restore a session by loading
221 trampling each other). You can use this to later restore a session by loading
216 your logfile as a file to be executed with option -logplay (see below).
222 your logfile as a file to be executed with option -logplay (see below).
217 .TP
223 .TP
218 .B \-logfile|lf
224 .B \-logfile|lf
219 Specify the name of your logfile.
225 Specify the name of your logfile.
220 .TP
226 .TP
221 .B \-logplay|lp
227 .B \-logplay|lp
222 Replay a previous log. For restoring a session as close as possible to
228 Replay a previous log. For restoring a session as close as possible to
223 the state you left it in, use this option (don't just run the
229 the state you left it in, use this option (don't just run the
224 logfile). With \-logplay, IPython will try to reconstruct the previous
230 logfile). With \-logplay, IPython will try to reconstruct the previous
225 working environment in full, not just execute the commands in the
231 working environment in full, not just execute the commands in the
226 logfile.
232 logfile.
227 .br
233 .br
228 .sh 1
234 .sh 1
229 When a session is restored, logging is automatically turned on again
235 When a session is restored, logging is automatically turned on again
230 with the name of the logfile it was invoked with (it is read from the
236 with the name of the logfile it was invoked with (it is read from the
231 log header). So once you've turned logging on for a session, you can
237 log header). So once you've turned logging on for a session, you can
232 quit IPython and reload it as many times as you want and it will
238 quit IPython and reload it as many times as you want and it will
233 continue to log its history and restore from the beginning every time.
239 continue to log its history and restore from the beginning every time.
234 .br
240 .br
235 .sp 1
241 .sp 1
236 Caveats: there are limitations in this option. The history variables
242 Caveats: there are limitations in this option. The history variables
237 _i*,_* and _dh don't get restored properly. In the future we will try
243 _i*,_* and _dh don't get restored properly. In the future we will try
238 to implement full session saving by writing and retrieving a
244 to implement full session saving by writing and retrieving a
239 'snapshot' of the memory state of IPython. But our first attempts
245 'snapshot' of the memory state of IPython. But our first attempts
240 failed because of inherent limitations of Python's Pickle module, so
246 failed because of inherent limitations of Python's Pickle module, so
241 this may have to wait.
247 this may have to wait.
242 .TP
248 .TP
243 .B \-[no]messages
249 .B \-[no]messages
244 Print messages which IPython collects about its startup process
250 Print messages which IPython collects about its startup process
245 (default on).
251 (default on).
246 .TP
252 .TP
247 .B \-[no]pdb
253 .B \-[no]pdb
248 Automatically call the pdb debugger after every uncaught exception. If
254 Automatically call the pdb debugger after every uncaught exception. If
249 you are used to debugging using pdb, this puts you automatically
255 you are used to debugging using pdb, this puts you automatically
250 inside of it after any call (either in IPython or in code called by
256 inside of it after any call (either in IPython or in code called by
251 it) which triggers an exception which goes uncaught.
257 it) which triggers an exception which goes uncaught.
252 .TP
258 .TP
253 .B \-[no]pprint
259 .B \-[no]pprint
254 IPython can optionally use the pprint (pretty printer) module for
260 IPython can optionally use the pprint (pretty printer) module for
255 displaying results. pprint tends to give a nicer display of nested
261 displaying results. pprint tends to give a nicer display of nested
256 data structures. If you like it, you can turn it on permanently in
262 data structures. If you like it, you can turn it on permanently in
257 your config file (default off).
263 your config file (default off).
258 .TP
264 .TP
259 .B \-profile|p <name>
265 .B \-profile|p <name>
260 Assume that your config file is ipythonrc-<name> (looks in current dir
266 Assume that your config file is ipythonrc-<name> (looks in current dir
261 first, then in IPYTHONDIR). This is a quick way to keep and load
267 first, then in IPYTHONDIR). This is a quick way to keep and load
262 multiple config files for different tasks, especially if you use the
268 multiple config files for different tasks, especially if you use the
263 include option of config files. You can keep a basic
269 include option of config files. You can keep a basic
264 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
270 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
265 this one and load extra things for particular tasks. For example:
271 this one and load extra things for particular tasks. For example:
266 .br
272 .br
267 .sp 1
273 .sp 1
268 1) $HOME/.ipython/ipythonrc : load basic things you always want.
274 1) $HOME/.ipython/ipythonrc : load basic things you always want.
269 .br
275 .br
270 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
276 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
271 modules.
277 modules.
272 .br
278 .br
273 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
279 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
274 plotting modules.
280 plotting modules.
275 .br
281 .br
276 .sp 1
282 .sp 1
277 Since it is possible to create an endless loop by having circular file
283 Since it is possible to create an endless loop by having circular file
278 inclusions, IPython will stop if it reaches 15 recursive inclusions.
284 inclusions, IPython will stop if it reaches 15 recursive inclusions.
279 .TP
285 .TP
280 .B \-prompt_in1|pi1 <string>
286 .B \-prompt_in1|pi1 <string>
281 Specify the string used for input prompts. Note that if you are using
287 Specify the string used for input prompts. Note that if you are using
282 numbered prompts, the number is represented with a '\\#' in the
288 numbered prompts, the number is represented with a '\\#' in the
283 string. Don't forget to quote strings with spaces embedded in
289 string. Don't forget to quote strings with spaces embedded in
284 them. Default: 'In [\\#]:'.
290 them. Default: 'In [\\#]:'.
285 .br
291 .br
286 .sp 1
292 .sp 1
287 Most bash-like escapes can be used to customize IPython's prompts, as well as
293 Most bash-like escapes can be used to customize IPython's prompts, as well as
288 a few additional ones which are IPython-specific. All valid prompt escapes
294 a few additional ones which are IPython-specific. All valid prompt escapes
289 are described in detail in the Customization section of the IPython HTML/PDF
295 are described in detail in the Customization section of the IPython HTML/PDF
290 manual.
296 manual.
291 .TP
297 .TP
292 .B \-prompt_in2|pi2 <string>
298 .B \-prompt_in2|pi2 <string>
293 Similar to the previous option, but used for the continuation prompts. The
299 Similar to the previous option, but used for the continuation prompts. The
294 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
300 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
295 (so you can have your continuation prompt aligned with your input
301 (so you can have your continuation prompt aligned with your input
296 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
302 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
297 with 'In [\\#]').
303 with 'In [\\#]').
298 .TP
304 .TP
299 .B \-prompt_out|po <string>
305 .B \-prompt_out|po <string>
300 String used for output prompts, also uses numbers like prompt_in1.
306 String used for output prompts, also uses numbers like prompt_in1.
301 Default: 'Out[\\#]:'.
307 Default: 'Out[\\#]:'.
302 .TP
308 .TP
303 .B \-quick
309 .B \-quick
304 Start in bare bones mode (no config file loaded).
310 Start in bare bones mode (no config file loaded).
305 .TP
311 .TP
306 .B \-rcfile <name>
312 .B \-rcfile <name>
307 Name of your IPython resource configuration file. normally IPython
313 Name of your IPython resource configuration file. normally IPython
308 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
314 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
309 the loading of your config file fails, IPython starts with a bare
315 the loading of your config file fails, IPython starts with a bare
310 bones configuration (no modules loaded at all).
316 bones configuration (no modules loaded at all).
311 .TP
317 .TP
312 .B \-[no]readline
318 .B \-[no]readline
313 Use the readline library, which is needed to support name completion
319 Use the readline library, which is needed to support name completion
314 and command history, among other things. It is enabled by default, but
320 and command history, among other things. It is enabled by default, but
315 may cause problems for users of X/Emacs in Python comint or shell
321 may cause problems for users of X/Emacs in Python comint or shell
316 buffers.
322 buffers.
317 .br
323 .br
318 .sp 1
324 .sp 1
319 Note that emacs 'eterm' buffers (opened with M-x term) support
325 Note that emacs 'eterm' buffers (opened with M-x term) support
320 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
326 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
321 and C-c !) buffers do not.
327 and C-c !) buffers do not.
322 .TP
328 .TP
323 .B \-screen_length|sl <n>
329 .B \-screen_length|sl <n>
324 Number of lines of your screen. This is used to control printing of
330 Number of lines of your screen. This is used to control printing of
325 very long strings. Strings longer than this number of lines will be
331 very long strings. Strings longer than this number of lines will be
326 sent through a pager instead of directly printed.
332 sent through a pager instead of directly printed.
327 .br
333 .br
328 .sp 1
334 .sp 1
329 The default value for this is 0, which means IPython will auto-detect
335 The default value for this is 0, which means IPython will auto-detect
330 your screen size every time it needs to print certain potentially long
336 your screen size every time it needs to print certain potentially long
331 strings (this doesn't change the behavior of the 'print' keyword, it's
337 strings (this doesn't change the behavior of the 'print' keyword, it's
332 only triggered internally). If for some reason this isn't working well
338 only triggered internally). If for some reason this isn't working well
333 (it needs curses support), specify it yourself. Otherwise don't change
339 (it needs curses support), specify it yourself. Otherwise don't change
334 the default.
340 the default.
335 .TP
341 .TP
336 .B \-separate_in|si <string>
342 .B \-separate_in|si <string>
337 Separator before input prompts. Default '\n'.
343 Separator before input prompts. Default '\n'.
338 .TP
344 .TP
339 .B \-separate_out|so <string>
345 .B \-separate_out|so <string>
340 Separator before output prompts. Default: 0 (nothing).
346 Separator before output prompts. Default: 0 (nothing).
341 .TP
347 .TP
342 .B \-separate_out2|so2 <string>
348 .B \-separate_out2|so2 <string>
343 Separator after output prompts. Default: 0 (nothing).
349 Separator after output prompts. Default: 0 (nothing).
344 .TP
350 .TP
345 .B \-nosep
351 .B \-nosep
346 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
352 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
347 Simply removes all input/output separators.
353 Simply removes all input/output separators.
348 .TP
354 .TP
349 .B \-upgrade
355 .B \-upgrade
350 Allows you to upgrade your IPYTHONDIR configuration when you install a
356 Allows you to upgrade your IPYTHONDIR configuration when you install a
351 new version of IPython. Since new versions may include new command
357 new version of IPython. Since new versions may include new command
352 lines options or example files, this copies updated ipythonrc-type
358 lines options or example files, this copies updated ipythonrc-type
353 files. However, it backs up (with a .old extension) all files which
359 files. However, it backs up (with a .old extension) all files which
354 it overwrites so that you can merge back any custimizations you might
360 it overwrites so that you can merge back any custimizations you might
355 have in your personal files.
361 have in your personal files.
356 .TP
362 .TP
357 .B \-Version
363 .B \-Version
358 Print version information and exit.
364 Print version information and exit.
359 .TP
365 .TP
366 .B -wxversion <string>
367 Select a specific version of wxPython (used in conjunction with
368 \-wthread). Requires the wxversion module, part of recent wxPython
369 distributions.
370 .TP
360 .B \-xmode <modename>
371 .B \-xmode <modename>
361 Mode for exception reporting. The valid modes are Plain, Context, and
372 Mode for exception reporting. The valid modes are Plain, Context, and
362 Verbose.
373 Verbose.
363 .br
374 .br
364 .sp 1
375 .sp 1
365 \- Plain: similar to python's normal traceback printing.
376 \- Plain: similar to python's normal traceback printing.
366 .br
377 .br
367 .sp 1
378 .sp 1
368 \- Context: prints 5 lines of context source code around each line in the
379 \- Context: prints 5 lines of context source code around each line in the
369 traceback.
380 traceback.
370 .br
381 .br
371 .sp 1
382 .sp 1
372 \- Verbose: similar to Context, but additionally prints the variables
383 \- Verbose: similar to Context, but additionally prints the variables
373 currently visible where the exception happened (shortening their strings if
384 currently visible where the exception happened (shortening their strings if
374 too long). This can potentially be very slow, if you happen to have a huge
385 too long). This can potentially be very slow, if you happen to have a huge
375 data structure whose string representation is complex to compute. Your
386 data structure whose string representation is complex to compute. Your
376 computer may appear to freeze for a while with cpu usage at 100%. If this
387 computer may appear to freeze for a while with cpu usage at 100%. If this
377 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
388 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
378 once).
389 once).
379 .
390 .
380 .SH EMBEDDING
391 .SH EMBEDDING
381 It is possible to start an IPython instance inside your own Python
392 It is possible to start an IPython instance inside your own Python
382 programs. In the documentation example files there are some
393 programs. In the documentation example files there are some
383 illustrations on how to do this.
394 illustrations on how to do this.
384 .br
395 .br
385 .sp 1
396 .sp 1
386 This feature allows you to evalutate dynamically the state of your
397 This feature allows you to evalutate dynamically the state of your
387 code, operate with your variables, analyze them, etc. Note however
398 code, operate with your variables, analyze them, etc. Note however
388 that any changes you make to values while in the shell do NOT
399 that any changes you make to values while in the shell do NOT
389 propagate back to the running code, so it is safe to modify your
400 propagate back to the running code, so it is safe to modify your
390 values because you won't break your code in bizarre ways by doing so.
401 values because you won't break your code in bizarre ways by doing so.
391 .SH AUTHOR
402 .SH AUTHOR
392 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
403 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
393 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
404 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
394 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
405 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
395 <jack@xiph.org>, for the Debian project (but may be used by others).
406 <jack@xiph.org>, for the Debian project (but may be used by others).
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now