##// END OF EJS Templates
Merge in all development done in bzr since February 16 2008....
Fernando Perez -
r1218:6b454030 merge
parent child Browse files
Show More
@@ -0,0 +1,2 b''
1 [LF]
2 *.py
@@ -0,0 +1,244 b''
1 """
2 IPython extension: autoreload modules before executing the next line
3
4 Try::
5
6 %autoreload?
7
8 for documentation.
9 """
10
11 # Pauli Virtanen <pav@iki.fi>, 2008.
12 # Thomas Heller, 2000.
13 #
14 # This IPython module is written by Pauli Virtanen, based on the autoreload
15 # code by Thomas Heller.
16
17 #------------------------------------------------------------------------------
18 # Autoreload functionality
19 #------------------------------------------------------------------------------
20
21 import time, os, threading, sys, types, imp, inspect, traceback, atexit
22
23 def _get_compiled_ext():
24 """Official way to get the extension of compiled files (.pyc or .pyo)"""
25 for ext, mode, typ in imp.get_suffixes():
26 if typ == imp.PY_COMPILED:
27 return ext
28
29 PY_COMPILED_EXT = _get_compiled_ext()
30
31 class ModuleReloader(object):
32 skipped = {}
33 """Modules that failed to reload: {module: mtime-on-failed-reload, ...}"""
34
35 modules = {}
36 """Modules specially marked as autoreloadable."""
37
38 skip_modules = {}
39 """Modules specially marked as not autoreloadable."""
40
41 check_all = True
42 """Autoreload all modules, not just those listed in 'modules'"""
43
44 def check(self, check_all=False):
45 """Check whether some modules need to be reloaded."""
46
47 if check_all or self.check_all:
48 modules = sys.modules.keys()
49 else:
50 modules = self.modules.keys()
51
52 for modname in modules:
53 m = sys.modules.get(modname, None)
54
55 if modname in self.skip_modules:
56 continue
57
58 if not hasattr(m, '__file__'):
59 continue
60
61 if m.__name__ == '__main__':
62 # we cannot reload(__main__)
63 continue
64
65 filename = m.__file__
66 dirname = os.path.dirname(filename)
67 path, ext = os.path.splitext(filename)
68
69 if ext.lower() == '.py':
70 ext = PY_COMPILED_EXT
71 filename = os.path.join(dirname, path + PY_COMPILED_EXT)
72
73 if ext != PY_COMPILED_EXT:
74 continue
75
76 try:
77 pymtime = os.stat(filename[:-1]).st_mtime
78 if pymtime <= os.stat(filename).st_mtime:
79 continue
80 if self.skipped.get(filename[:-1], None) == pymtime:
81 continue
82 except OSError:
83 continue
84
85 try:
86 superreload(m)
87 if filename[:-1] in self.skipped:
88 del self.skipped[filename[:-1]]
89 except:
90 self.skipped[filename[:-1]] = pymtime
91
92 def update_function(old, new, attrnames):
93 for name in attrnames:
94 setattr(old, name, getattr(new, name))
95
96 def superreload(module, reload=reload):
97 """Enhanced version of the builtin reload function.
98
99 superreload replaces the class dictionary of every top-level
100 class in the module with the new one automatically,
101 as well as every function's code object.
102
103 """
104
105 module = reload(module)
106
107 # iterate over all objects and update them
108 count = 0
109 for name, new_obj in module.__dict__.items():
110 key = (module.__name__, name)
111 if _old_objects.has_key(key):
112 for old_obj in _old_objects[key]:
113 if type(new_obj) == types.ClassType:
114 old_obj.__dict__.update(new_obj.__dict__)
115 count += 1
116 elif type(new_obj) == types.FunctionType:
117 update_function(old_obj,
118 new_obj,
119 "func_code func_defaults func_doc".split())
120 count += 1
121 elif type(new_obj) == types.MethodType:
122 update_function(old_obj.im_func,
123 new_obj.im_func,
124 "func_code func_defaults func_doc".split())
125 count += 1
126
127 return module
128
129 reloader = ModuleReloader()
130
131 #------------------------------------------------------------------------------
132 # IPython monkey-patching
133 #------------------------------------------------------------------------------
134
135 import IPython.iplib
136
137 autoreload_enabled = False
138
139 def runcode_hook(self):
140 if not autoreload_enabled:
141 raise IPython.ipapi.TryNext
142 try:
143 reloader.check()
144 except:
145 pass
146
147
148 def enable_autoreload():
149 global autoreload_enabled
150 autoreload_enabled = True
151
152
153 def disable_autoreload():
154 global autoreload_enabled
155 autoreload_enabled = False
156
157 #------------------------------------------------------------------------------
158 # IPython connectivity
159 #------------------------------------------------------------------------------
160
161 import IPython.ipapi
162 ip = IPython.ipapi.get()
163
164 def autoreload_f(self, parameter_s=''):
165 r""" %autoreload => Reload modules automatically
166
167 %autoreload
168 Reload all modules (except thoses excluded by %aimport) automatically now.
169
170 %autoreload 1
171 Reload all modules imported with %aimport every time before executing
172 the Python code typed.
173
174 %autoreload 2
175 Reload all modules (except thoses excluded by %aimport) every time
176 before executing the Python code typed.
177
178 Reloading Python modules in a reliable way is in general
179 difficult, and unexpected things may occur. Some of the common
180 caveats relevant for 'autoreload' are:
181
182 - Modules are not reloaded in any specific order, and no dependency
183 analysis is done. For example, modules with 'from xxx import foo'
184 retain old versions of 'foo' when 'xxx' is autoreloaded.
185 - Functions or objects imported from the autoreloaded module to
186 the interactive namespace are not updated.
187 - C extension modules cannot be reloaded, and so cannot be
188 autoreloaded.
189 """
190 if parameter_s == '':
191 reloader.check(True)
192 elif parameter_s == '0':
193 disable_autoreload()
194 elif parameter_s == '1':
195 reloader.check_all = False
196 enable_autoreload()
197 elif parameter_s == '2':
198 reloader.check_all = True
199 enable_autoreload()
200
201 def aimport_f(self, parameter_s=''):
202 """%aimport => Import modules for automatic reloading.
203
204 %aimport
205 List modules to automatically import and not to import.
206
207 %aimport foo
208 Import module 'foo' and mark it to be autoreloaded for %autoreload 1
209
210 %aimport -foo
211 Mark module 'foo' to not be autoreloaded for %autoreload 1
212
213 """
214
215 modname = parameter_s
216 if not modname:
217 to_reload = reloader.modules.keys()
218 to_reload.sort()
219 to_skip = reloader.skip_modules.keys()
220 to_skip.sort()
221 if reloader.check_all:
222 print "Modules to reload:\nall-expect-skipped"
223 else:
224 print "Modules to reload:\n%s" % ' '.join(to_reload)
225 print "\nModules to skip:\n%s" % ' '.join(to_skip)
226 elif modname.startswith('-'):
227 modname = modname[1:]
228 try: del reloader.modules[modname]
229 except KeyError: pass
230 reloader.skip_modules[modname] = True
231 else:
232 try: del reloader.skip_modules[modname]
233 except KeyError: pass
234 reloader.modules[modname] = True
235
236 mod = __import__(modname)
237 ip.to_user_ns({modname: mod})
238
239 def init():
240 ip.expose_magic('autoreload', autoreload_f)
241 ip.expose_magic('aimport', aimport_f)
242 ip.set_hook('pre_runcode_hook', runcode_hook)
243
244 init() No newline at end of file
@@ -0,0 +1,343 b''
1 """ Extension for bzr command tab completer. Supports comlpeting commands and options
2
3 Unlike the core IPython, you should note that this extension is under GPL, not BSD.
4
5 Based on "shell" bzr plugin by Aaron Bentley, license is below. The IPython additions
6 are at the bottom of the file, the rest is left untouched.
7
8 Must be loaded with ip.load('ipy_bzr')
9
10 """
11
12 # Copyright (C) 2004, 2005 Aaron Bentley
13 # <aaron@aaronbentley.com>
14 #
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 2 of the License, or
18 # (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28
29 import cmd
30 from itertools import chain
31 import os
32 import shlex
33 import stat
34 import string
35 import sys
36
37 from bzrlib import osutils
38 from bzrlib.branch import Branch
39 from bzrlib.config import config_dir, ensure_config_dir_exists
40 from bzrlib.commands import get_cmd_object, get_all_cmds, get_alias
41 from bzrlib.errors import BzrError
42 from bzrlib.workingtree import WorkingTree
43 import bzrlib.plugin
44
45
46 SHELL_BLACKLIST = set(['rm', 'ls'])
47 COMPLETION_BLACKLIST = set(['shell'])
48
49
50 class BlackListedCommand(BzrError):
51 def __init__(self, command):
52 BzrError.__init__(self, "The command %s is blacklisted for shell use" %
53 command)
54
55
56 class CompletionContext(object):
57 def __init__(self, text, command=None, prev_opt=None, arg_pos=None):
58 self.text = text
59 self.command = command
60 self.prev_opt = prev_opt
61 self.arg_pos = None
62
63 def get_completions(self):
64 try:
65 return self.get_completions_or_raise()
66 except Exception, e:
67 print e, type(e)
68 return []
69
70 def get_option_completions(self):
71 try:
72 command_obj = get_cmd_object(self.command)
73 except BzrError:
74 return []
75 opts = [o+" " for o in iter_opt_completions(command_obj)]
76 return list(filter_completions(opts, self.text))
77
78 def get_completions_or_raise(self):
79 if self.command is None:
80 if '/' in self.text:
81 iter = iter_executables(self.text)
82 else:
83 iter = (c+" " for c in iter_command_names() if
84 c not in COMPLETION_BLACKLIST)
85 return list(filter_completions(iter, self.text))
86 if self.prev_opt is None:
87 completions = self.get_option_completions()
88 if self.command == "cd":
89 iter = iter_dir_completions(self.text)
90 completions.extend(list(filter_completions(iter, self.text)))
91 else:
92 iter = iter_file_completions(self.text)
93 completions.extend(filter_completions(iter, self.text))
94 return completions
95
96
97 class PromptCmd(cmd.Cmd):
98
99 def __init__(self):
100 cmd.Cmd.__init__(self)
101 self.prompt = "bzr> "
102 try:
103 self.tree = WorkingTree.open_containing('.')[0]
104 except:
105 self.tree = None
106 self.set_title()
107 self.set_prompt()
108 self.identchars += '-'
109 ensure_config_dir_exists()
110 self.history_file = osutils.pathjoin(config_dir(), 'shell-history')
111 readline.set_completer_delims(string.whitespace)
112 if os.access(self.history_file, os.R_OK) and \
113 os.path.isfile(self.history_file):
114 readline.read_history_file(self.history_file)
115 self.cwd = os.getcwd()
116
117 def write_history(self):
118 readline.write_history_file(self.history_file)
119
120 def do_quit(self, args):
121 self.write_history()
122 raise StopIteration
123
124 def do_exit(self, args):
125 self.do_quit(args)
126
127 def do_EOF(self, args):
128 print
129 self.do_quit(args)
130
131 def postcmd(self, line, bar):
132 self.set_title()
133 self.set_prompt()
134
135 def set_prompt(self):
136 if self.tree is not None:
137 try:
138 prompt_data = (self.tree.branch.nick, self.tree.branch.revno(),
139 self.tree.relpath('.'))
140 prompt = " %s:%d/%s" % prompt_data
141 except:
142 prompt = ""
143 else:
144 prompt = ""
145 self.prompt = "bzr%s> " % prompt
146
147 def set_title(self, command=None):
148 try:
149 b = Branch.open_containing('.')[0]
150 version = "%s:%d" % (b.nick, b.revno())
151 except:
152 version = "[no version]"
153 if command is None:
154 command = ""
155 sys.stdout.write(terminal.term_title("bzr %s %s" % (command, version)))
156
157 def do_cd(self, line):
158 if line == "":
159 line = "~"
160 line = os.path.expanduser(line)
161 if os.path.isabs(line):
162 newcwd = line
163 else:
164 newcwd = self.cwd+'/'+line
165 newcwd = os.path.normpath(newcwd)
166 try:
167 os.chdir(newcwd)
168 self.cwd = newcwd
169 except Exception, e:
170 print e
171 try:
172 self.tree = WorkingTree.open_containing(".")[0]
173 except:
174 self.tree = None
175
176 def do_help(self, line):
177 self.default("help "+line)
178
179 def default(self, line):
180 args = shlex.split(line)
181 alias_args = get_alias(args[0])
182 if alias_args is not None:
183 args[0] = alias_args.pop(0)
184
185 commandname = args.pop(0)
186 for char in ('|', '<', '>'):
187 commandname = commandname.split(char)[0]
188 if commandname[-1] in ('|', '<', '>'):
189 commandname = commandname[:-1]
190 try:
191 if commandname in SHELL_BLACKLIST:
192 raise BlackListedCommand(commandname)
193 cmd_obj = get_cmd_object(commandname)
194 except (BlackListedCommand, BzrError):
195 return os.system(line)
196
197 try:
198 if too_complicated(line):
199 return os.system("bzr "+line)
200 else:
201 return (cmd_obj.run_argv_aliases(args, alias_args) or 0)
202 except BzrError, e:
203 print e
204 except KeyboardInterrupt, e:
205 print "Interrupted"
206 except Exception, e:
207 # print "Unhandled error:\n%s" % errors.exception_str(e)
208 print "Unhandled error:\n%s" % (e)
209
210
211 def completenames(self, text, line, begidx, endidx):
212 return CompletionContext(text).get_completions()
213
214 def completedefault(self, text, line, begidx, endidx):
215 """Perform completion for native commands.
216
217 :param text: The text to complete
218 :type text: str
219 :param line: The entire line to complete
220 :type line: str
221 :param begidx: The start of the text in the line
222 :type begidx: int
223 :param endidx: The end of the text in the line
224 :type endidx: int
225 """
226 (cmd, args, foo) = self.parseline(line)
227 if cmd == "bzr":
228 cmd = None
229 return CompletionContext(text, command=cmd).get_completions()
230
231
232 def run_shell():
233 try:
234 prompt = PromptCmd()
235 try:
236 prompt.cmdloop()
237 finally:
238 prompt.write_history()
239 except StopIteration:
240 pass
241
242
243 def iter_opt_completions(command_obj):
244 for option_name, option in command_obj.options().items():
245 yield "--" + option_name
246 short_name = option.short_name()
247 if short_name:
248 yield "-" + short_name
249
250
251 def iter_file_completions(arg, only_dirs = False):
252 """Generate an iterator that iterates through filename completions.
253
254 :param arg: The filename fragment to match
255 :type arg: str
256 :param only_dirs: If true, match only directories
257 :type only_dirs: bool
258 """
259 cwd = os.getcwd()
260 if cwd != "/":
261 extras = [".", ".."]
262 else:
263 extras = []
264 (dir, file) = os.path.split(arg)
265 if dir != "":
266 listingdir = os.path.expanduser(dir)
267 else:
268 listingdir = cwd
269 for file in chain(os.listdir(listingdir), extras):
270 if dir != "":
271 userfile = dir+'/'+file
272 else:
273 userfile = file
274 if userfile.startswith(arg):
275 if os.path.isdir(listingdir+'/'+file):
276 userfile+='/'
277 yield userfile
278 elif not only_dirs:
279 yield userfile + ' '
280
281
282 def iter_dir_completions(arg):
283 """Generate an iterator that iterates through directory name completions.
284
285 :param arg: The directory name fragment to match
286 :type arg: str
287 """
288 return iter_file_completions(arg, True)
289
290
291 def iter_command_names(hidden=False):
292 for real_cmd_name, cmd_class in get_all_cmds():
293 if not hidden and cmd_class.hidden:
294 continue
295 for name in [real_cmd_name] + cmd_class.aliases:
296 # Don't complete on aliases that are prefixes of the canonical name
297 if name == real_cmd_name or not real_cmd_name.startswith(name):
298 yield name
299
300
301 def iter_executables(path):
302 dirname, partial = os.path.split(path)
303 for filename in os.listdir(dirname):
304 if not filename.startswith(partial):
305 continue
306 fullpath = os.path.join(dirname, filename)
307 mode=os.lstat(fullpath)[stat.ST_MODE]
308 if stat.S_ISREG(mode) and 0111 & mode:
309 yield fullpath + ' '
310
311
312 def filter_completions(iter, arg):
313 return (c for c in iter if c.startswith(arg))
314
315
316 def iter_munged_completions(iter, arg, text):
317 for completion in iter:
318 completion = str(completion)
319 if completion.startswith(arg):
320 yield completion[len(arg)-len(text):]+" "
321
322
323 def too_complicated(line):
324 for char in '|<>*?':
325 if char in line:
326 return True
327 return False
328
329
330 ### IPython mods start
331
332 def init_ipython(ip):
333 def bzr_completer(self,ev):
334 #print "bzr complete"
335 tup = ev.line.split(None,2)
336 if len(tup) > 2:
337 cmd = tup[1]
338 else:
339 cmd = None
340
341 return CompletionContext(ev.symbol, command = cmd).get_completions()
342 bzrlib.plugin.load_plugins()
343 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
@@ -0,0 +1,75 b''
1 """ Greedy completer extension for IPython
2
3 Normal tab completer refuses to evaluate nonsafe stuff. This will evaluate
4 everything, so you need to consider the consequences of pressing tab
5 yourself!
6
7 Note that this extension simplifies readline interaction by setting
8 only whitespace as completer delimiter. If this works well, we will
9 do the same in default completer.
10
11 """
12 from IPython import generics,ipapi
13 from IPython.genutils import dir2
14
15 def attr_matches(self, text):
16 """Compute matches when text contains a dot.
17
18 MONKEYPATCHED VERSION (ipy_greedycompleter.py)
19
20 Assuming the text is of the form NAME.NAME....[NAME], and is
21 evaluatable in self.namespace or self.global_namespace, it will be
22 evaluated and its attributes (as revealed by dir()) are used as
23 possible completions. (For class instances, class members are are
24 also considered.)
25
26 WARNING: this can still invoke arbitrary C code, if an object
27 with a __getattr__ hook is evaluated.
28
29 """
30 import re
31
32 force_complete = 1
33 # Another option, seems to work great. Catches things like ''.<tab>
34 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
35
36 if m:
37 expr, attr = m.group(1, 3)
38 else:
39 # force match - eval anything that ends with colon
40 if not force_complete:
41 return []
42
43 m2 = re.match(r"(.+)\.(\w*)$", self.lbuf)
44 if not m2:
45 return []
46 expr, attr = m2.group(1,2)
47
48
49 try:
50 obj = eval(expr, self.namespace)
51 except:
52 try:
53 obj = eval(expr, self.global_namespace)
54 except:
55 return []
56
57 words = dir2(obj)
58
59 try:
60 words = generics.complete_object(obj, words)
61 except ipapi.TryNext:
62 pass
63 # Build match list to return
64 n = len(attr)
65 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
66 return res
67
68 def main():
69 import readline
70 readline.set_completer_delims(" \n\t")
71 # monkeypatch - the code will be folded to normal completer later on
72 import IPython.completer
73 IPython.completer.Completer.attr_matches = attr_matches
74
75 main() No newline at end of file
@@ -0,0 +1,311 b''
1 # -*- coding: utf-8 -*-
2 """
3 %jot magic for lightweight persistence.
4
5 Stores variables in Struct with some notes in PicleShare database
6
7
8 """
9
10 from datetime import datetime
11 import IPython.ipapi
12 ip = IPython.ipapi.get()
13
14 import pickleshare
15
16 import inspect,pickle,os,sys,textwrap
17 from IPython.FakeModule import FakeModule
18 from IPython.ipstruct import Struct
19
20
21 def refresh_variables(ip, key=None):
22 db = ip.db
23 if key is None:
24 keys = db.keys('jot/*')
25 else:
26 keys = db.keys('jot/'+key)
27 for key in keys:
28 # strip autorestore
29 justkey = os.path.basename(key)
30 print "Restoring from", justkey, "..."
31 try:
32 obj = db[key]
33 except KeyError:
34 print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey
35 print "The error was:",sys.exc_info()[0]
36 else:
37 #print "restored",justkey,"=",obj #dbg
38 try:
39 origname = obj.name
40 except:
41 ip.user_ns[justkey] = obj
42 print "Restored", justkey
43 else:
44 ip.user_ns[origname] = obj['val']
45 print "Restored", origname
46
47 def read_variables(ip, key=None):
48 db = ip.db
49 if key is None:
50 return None
51 else:
52 keys = db.keys('jot/'+key)
53 for key in keys:
54 # strip autorestore
55 justkey = os.path.basename(key)
56 print "restoring from ", justkey
57 try:
58 obj = db[key]
59 except KeyError:
60 print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey
61 print "The error was:",sys.exc_info()[0]
62 else:
63 return obj
64
65
66 def detail_variables(ip, key=None):
67 db, get = ip.db, ip.db.get
68
69 if key is None:
70 keys = db.keys('jot/*')
71 else:
72 keys = db.keys('jot/'+key)
73 if keys:
74 size = max(map(len,keys))
75 else:
76 size = 0
77
78 fmthead = '%-'+str(size)+'s [%s]'
79 fmtbody = 'Comment:\n %s'
80 fmtdata = 'Data:\n %s, %s'
81 for key in keys:
82 v = get(key,'<unavailable>')
83 justkey = os.path.basename(key)
84 try:
85 print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>')))
86 print fmtbody % (v.get('comment','<unavailable>'))
87 d = v.get('val','unavailable')
88 print fmtdata % (repr(type(d)), '')
89 print repr(d)[0:200]
90 print
91 print
92 except AttributeError:
93 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
94
95
96 def intm(n):
97 try:
98 return int(n)
99 except:
100 return 0
101
102 def jot_obj(self, obj, name, comment=''):
103 """
104 write obj data to the note database, with whatever that should be noted.
105 """
106 had = self.db.keys('jot/'+name+'*')
107 # if it the same name but a later version, we stupidly add a number to the
108 # so the name doesn't collide. Any better idea?
109 suffix = ''
110 if len(had)>0:
111 pre = os.path.commonprefix(had)
112 suf = [n.split(pre)[1] for n in had]
113 versions = map(intm, suf)
114 suffix = str(max(versions)+1)
115
116 uname = 'jot/'+name+suffix
117
118 # which one works better?
119 #all = ip.IP.shadowhist.all()
120 all = ip.IP.shell.input_hist
121
122 # We may actually want to make snapshot of files that are run-ned.
123
124 # get the comment
125 try:
126 comment = ip.IP.magic_edit('-x').strip()
127 except:
128 print "No comment is recorded."
129 comment = ''
130
131 self.db[uname] = Struct({'val':obj,
132 'time' : datetime.now(),
133 'hist' : all,
134 'name' : name,
135 'comment' : comment,})
136
137 print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__)
138
139
140
141 def magic_jot(self, parameter_s=''):
142 """Lightweight persistence for python variables.
143
144 Example:
145
146 ville@badger[~]|1> A = ['hello',10,'world']\\
147 ville@badger[~]|2> %jot A\\
148 ville@badger[~]|3> Exit
149
150 (IPython session is closed and started again...)
151
152 ville@badger:~$ ipython -p pysh\\
153 ville@badger[~]|1> print A
154
155 ['hello', 10, 'world']
156
157 Usage:
158
159 %jot - Show list of all variables and their current values\\
160 %jot -l - Show list of all variables and their current values in detail\\
161 %jot -l <var> - Show one variable and its current values in detail\\
162 %jot <var> - Store the *current* value of the variable to disk\\
163 %jot -d <var> - Remove the variable and its value from storage\\
164 %jot -z - Remove all variables from storage (disabled)\\
165 %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\
166 %jot foo >a.txt - Store value of foo to new file a.txt\\
167 %jot foo >>a.txt - Append value of foo to file a.txt\\
168
169 It should be noted that if you change the value of a variable, you
170 need to %note it again if you want to persist the new value.
171
172 Note also that the variables will need to be pickleable; most basic
173 python types can be safely %stored.
174
175 """
176
177 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
178 args = argsl.split(None,1)
179 ip = self.getapi()
180 db = ip.db
181 # delete
182 if opts.has_key('d'):
183 try:
184 todel = args[0]
185 except IndexError:
186 error('You must provide the variable to forget')
187 else:
188 try:
189 del db['jot/' + todel]
190 except:
191 error("Can't delete variable '%s'" % todel)
192 # reset the whole database
193 elif opts.has_key('z'):
194 print "reseting the whole database has been disabled."
195 #for k in db.keys('autorestore/*'):
196 # del db[k]
197
198 elif opts.has_key('r'):
199 try:
200 toret = args[0]
201 except:
202 print "restoring all the variables jotted down..."
203 refresh_variables(ip)
204 else:
205 refresh_variables(ip, toret)
206
207 elif opts.has_key('l'):
208 try:
209 tolist = args[0]
210 except:
211 print "List details for all the items."
212 detail_variables(ip)
213 else:
214 print "Details for", tolist, ":"
215 detail_variables(ip, tolist)
216
217 # run without arguments -> list noted variables & notes
218 elif not args:
219 vars = self.db.keys('jot/*')
220 vars.sort()
221 if vars:
222 size = max(map(len,vars)) - 4
223 else:
224 size = 0
225
226 print 'Variables and their in-db values:'
227 fmt = '%-'+str(size)+'s [%s] -> %s'
228 get = db.get
229 for var in vars:
230 justkey = os.path.basename(var)
231 v = get(var,'<unavailable>')
232 try:
233 print fmt % (justkey,\
234 datetime.ctime(v.get('time','<unavailable>')),\
235 v.get('comment','<unavailable>')[:70].replace('\n',' '),)
236 except AttributeError:
237 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
238
239
240 # default action - store the variable
241 else:
242 # %store foo >file.txt or >>file.txt
243 if len(args) > 1 and args[1].startswith('>'):
244 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
245 if args[1].startswith('>>'):
246 fil = open(fnam,'a')
247 else:
248 fil = open(fnam,'w')
249 obj = ip.ev(args[0])
250 print "Writing '%s' (%s) to file '%s'." % (args[0],
251 obj.__class__.__name__, fnam)
252
253
254 if not isinstance (obj,basestring):
255 from pprint import pprint
256 pprint(obj,fil)
257 else:
258 fil.write(obj)
259 if not obj.endswith('\n'):
260 fil.write('\n')
261
262 fil.close()
263 return
264
265 # %note foo
266 try:
267 obj = ip.user_ns[args[0]]
268 except KeyError:
269 # this should not be alias, for aliases, use %store
270 print
271 print "Error: %s doesn't exist." % args[0]
272 print
273 print "Use %note -r <var> to retrieve variables. This should not be used " +\
274 "to store alias, for saving aliases, use %store"
275 return
276 else:
277 if isinstance(inspect.getmodule(obj), FakeModule):
278 print textwrap.dedent("""\
279 Warning:%s is %s
280 Proper storage of interactively declared classes (or instances
281 of those classes) is not possible! Only instances
282 of classes in real modules on file system can be %%store'd.
283 """ % (args[0], obj) )
284 return
285 #pickled = pickle.dumps(obj)
286 #self.db[ 'jot/' + args[0] ] = obj
287 jot_obj(self, obj, args[0])
288
289
290 def magic_read(self, parameter_s=''):
291 """
292 %read <var> - Load variable from data that is jotted down.\\
293
294 """
295
296 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
297 args = argsl.split(None,1)
298 ip = self.getapi()
299 db = ip.db
300 #if opts.has_key('r'):
301 try:
302 toret = args[0]
303 except:
304 print "which record do you want to read out?"
305 return
306 else:
307 return read_variables(ip, toret)
308
309
310 ip.expose_magic('jot',magic_jot)
311 ip.expose_magic('read',magic_read)
@@ -0,0 +1,234 b''
1 """
2 IPython extension: %lookfor command for searching docstrings
3
4 """
5 # Pauli Virtanen <pav@iki.fi>, 2008.
6
7 import re, inspect, pkgutil, pydoc
8
9 #------------------------------------------------------------------------------
10 # Lookfor functionality
11 #------------------------------------------------------------------------------
12
13 # Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...}
14 # where kind: "func", "class", "module", "object"
15 # and index: index in breadth-first namespace traversal
16 _lookfor_caches = {}
17
18 # regexp whose match indicates that the string may contain a function signature
19 _function_signature_re = re.compile(r"[a-z_]+\(.*[,=].*\)", re.I)
20
21 def lookfor(what, modules=None, import_modules=True, regenerate=False):
22 """
23 Search for objects whose documentation contains all given words.
24 Shows a summary of matching objects, sorted roughly by relevance.
25
26 Parameters
27 ----------
28 what : str
29 String containing words to look for.
30
31 module : str, module
32 Module whose docstrings to go through.
33 import_modules : bool
34 Whether to import sub-modules in packages.
35 Will import only modules in __all__
36 regenerate: bool
37 Re-generate the docstring cache
38
39 """
40 # Cache
41 cache = {}
42 for module in modules:
43 try:
44 c = _lookfor_generate_cache(module, import_modules, regenerate)
45 cache.update(c)
46 except ImportError:
47 pass
48
49 # Search
50 # XXX: maybe using a real stemming search engine would be better?
51 found = []
52 whats = str(what).lower().split()
53 if not whats: return
54
55 for name, (docstring, kind, index) in cache.iteritems():
56 if kind in ('module', 'object'):
57 # don't show modules or objects
58 continue
59 ok = True
60 doc = docstring.lower()
61 for w in whats:
62 if w not in doc:
63 ok = False
64 break
65 if ok:
66 found.append(name)
67
68 # Relevance sort
69 # XXX: this is full Harrison-Stetson heuristics now,
70 # XXX: it probably could be improved
71
72 kind_relevance = {'func': 1000, 'class': 1000,
73 'module': -1000, 'object': -1000}
74
75 def relevance(name, docstr, kind, index):
76 r = 0
77 # do the keywords occur within the start of the docstring?
78 first_doc = "\n".join(docstr.lower().strip().split("\n")[:3])
79 r += sum([200 for w in whats if w in first_doc])
80 # do the keywords occur in the function name?
81 r += sum([30 for w in whats if w in name])
82 # is the full name long?
83 r += -len(name) * 5
84 # is the object of bad type?
85 r += kind_relevance.get(kind, -1000)
86 # is the object deep in namespace hierarchy?
87 r += -name.count('.') * 10
88 r += max(-index / 100, -100)
89 return r
90
91 def relevance_sort(a, b):
92 dr = relevance(b, *cache[b]) - relevance(a, *cache[a])
93 if dr != 0: return dr
94 else: return cmp(a, b)
95 found.sort(relevance_sort)
96
97 # Pretty-print
98 s = "Search results for '%s'" % (' '.join(whats))
99 help_text = [s, "-"*len(s)]
100 for name in found:
101 doc, kind, ix = cache[name]
102
103 doclines = [line.strip() for line in doc.strip().split("\n")
104 if line.strip()]
105
106 # find a suitable short description
107 try:
108 first_doc = doclines[0].strip()
109 if _function_signature_re.search(first_doc):
110 first_doc = doclines[1].strip()
111 except IndexError:
112 first_doc = ""
113 help_text.append("%s\n %s" % (name, first_doc))
114
115 # Output
116 if len(help_text) > 10:
117 pager = pydoc.getpager()
118 pager("\n".join(help_text))
119 else:
120 print "\n".join(help_text)
121
122 def _lookfor_generate_cache(module, import_modules, regenerate):
123 """
124 Generate docstring cache for given module.
125
126 Parameters
127 ----------
128 module : str, None, module
129 Module for which to generate docstring cache
130 import_modules : bool
131 Whether to import sub-modules in packages.
132 Will import only modules in __all__
133 regenerate: bool
134 Re-generate the docstring cache
135
136 Returns
137 -------
138 cache : dict {obj_full_name: (docstring, kind, index), ...}
139 Docstring cache for the module, either cached one (regenerate=False)
140 or newly generated.
141
142 """
143 global _lookfor_caches
144
145 if module is None:
146 module = "numpy"
147
148 if isinstance(module, str):
149 module = __import__(module)
150
151 if id(module) in _lookfor_caches and not regenerate:
152 return _lookfor_caches[id(module)]
153
154 # walk items and collect docstrings
155 cache = {}
156 _lookfor_caches[id(module)] = cache
157 seen = {}
158 index = 0
159 stack = [(module.__name__, module)]
160 while stack:
161 name, item = stack.pop(0)
162 if id(item) in seen: continue
163 seen[id(item)] = True
164
165 index += 1
166 kind = "object"
167
168 if inspect.ismodule(item):
169 kind = "module"
170 try:
171 _all = item.__all__
172 except AttributeError:
173 _all = None
174 # import sub-packages
175 if import_modules and hasattr(item, '__path__'):
176 for m in pkgutil.iter_modules(item.__path__):
177 if _all is not None and m[1] not in _all:
178 continue
179 try:
180 __import__("%s.%s" % (name, m[1]))
181 except ImportError:
182 continue
183 for n, v in inspect.getmembers(item):
184 if _all is not None and n not in _all:
185 continue
186 stack.append(("%s.%s" % (name, n), v))
187 elif inspect.isclass(item):
188 kind = "class"
189 for n, v in inspect.getmembers(item):
190 stack.append(("%s.%s" % (name, n), v))
191 elif callable(item):
192 kind = "func"
193
194 doc = inspect.getdoc(item)
195 if doc is not None:
196 cache[name] = (doc, kind, index)
197
198 return cache
199
200 #------------------------------------------------------------------------------
201 # IPython connectivity
202 #------------------------------------------------------------------------------
203
204 import IPython.ipapi
205 ip = IPython.ipapi.get()
206
207 _lookfor_modules = ['numpy', 'scipy']
208
209 def lookfor_f(self, arg=''):
210 r"""
211 Search for objects whose documentation contains all given words.
212 Shows a summary of matching objects, sorted roughly by relevance.
213
214 Usage
215 -----
216 %lookfor +numpy some words
217 Search module 'numpy'
218
219 %lookfor_modules numpy scipy
220 Set default modules whose docstrings to search
221
222 """
223 lookfor(arg, modules=_lookfor_modules)
224
225 def lookfor_modules_f(self, arg=''):
226 global _lookfor_modules
227 if not arg:
228 print "Modules included in %lookfor search:", _lookfor_modules
229 else:
230 _lookfor_modules = arg.split()
231
232 ip.expose_magic('lookfor', lookfor_f)
233 ip.expose_magic('lookfor_modules', lookfor_modules_f)
234
@@ -0,0 +1,239 b''
1 """ Integration with gvim, by Erich Heine
2
3 Provides a %vim magic command, and reuses the same vim session. Uses
4 unix domain sockets for communication between vim and IPython. ipy.vim is
5 available in doc/examples of the IPython distribution.
6
7 Slightly touched up email announcement (and description how to use it) by
8 Erich Heine is here:
9
10 Ive recently been playing with ipython, and like it quite a bit. I did
11 however discover a bit of frustration, namely with editor interaction.
12 I am a gvim user, and using the command edit on a new file causes
13 ipython to try and run that file as soon as the text editor opens
14 up. The -x command of course fixes this, but its still a bit annoying,
15 switching windows to do a run file, then back to the text
16 editor. Being a heavy tab user in gvim, another annoyance is not being
17 able to specify weather a new tab is how I choose to open the file.
18
19 Not being one to shirk my open source duties (and seeing this as a
20 good excuse to poke around ipython internals), Ive created a script
21 for having gvim and ipython work very nicely together. Ive attached
22 both to this email (hoping of course that the mailing list allows such
23 things).
24
25 There are 2 files:
26
27 ipy_vimserver.py -- this file contains the ipython stuff
28 ipy.vim -- this file contains the gvim stuff
29
30 In combination they allow for a few functionalities:
31
32 #1. the vim magic command. This is a fancy wrapper around the edit
33 magic, that allows for a new option, -t, which opens the text in a new
34 gvim tab. Otherwise it works the same as edit -x. (it internally
35 calls edit -x). This magic command also juggles vim server management,
36 so when it is called when there is not a gvim running, it creates a
37 new gvim instance, named after the ipython session name. Once such a
38 gvim instance is running, it will be used for subsequent uses of the
39 vim command.
40
41 #2. ipython - gvim interaction. Once a file has been opened with the
42 vim magic (and a session set up, see below), pressing the F5 key in
43 vim will cause the calling ipython instance to execute run
44 filename.py. (if you typo like I do, this is very useful)
45
46 #3. ipython server - this is a thread wich listens on a unix domain
47 socket, and runs commands sent to that socket.
48
49 Note, this only works on POSIX systems, that allow for AF_UNIX type
50 sockets. It has only been tested on linux (a fairly recent debian
51 testing distro).
52
53 To install it put, the ipserver.py in your favorite locaion for
54 sourcing ipython scripts. I put the ipy.vim in
55 ~/.vim/after/ftplugin/python/.
56
57 To use (this can be scripted im sure, but i usually have 2 or 3
58 ipythons and corresponding gvims open):
59
60 import ipy_vimserver
61 ipy_vimserver.setup('sessionname')
62
63 (Editors note - you can probably add these to your ipy_user_conf.py)
64
65 Then use ipython as you normally would, until you need to edit
66 something. Instead of edit, use the vim magic. Thats it!
67
68 """
69
70 import IPython.ipapi
71 #import ipythonhooks
72 import socket, select
73 import os, threading, subprocess
74 import re
75
76 ERRCONDS = select.POLLHUP|select.POLLERR
77 SERVER = None
78 ip = IPython.ipapi.get()
79
80 # this listens to a unix domain socket in a separate thread, so that comms
81 # between a vim instance and ipython can happen in a fun and productive way
82 class IpyServer(threading.Thread):
83 def __init__(self, sname):
84 super(IpyServer, self).__init__()
85 self.keep_running = True
86 self.__sname = sname
87 self.socket = socket.socket(socket.AF_UNIX)
88 self.poller = select.poll()
89 self.current_conns = dict()
90 self.setDaemon(True)
91
92 def listen(self):
93 self.socket.bind(self.__sname)
94 self.socket.listen(1)
95
96 def __handle_error(self, socket):
97 if socket == self.socket.fileno():
98 self.keep_running = False
99 for a in self.current_conns.values():
100 a.close()
101 return False
102 else:
103 y = self.current_conns[socket]
104 del self.current_conns[socket]
105 y.close()
106 self.poller.unregister(socket)
107
108 def serve_me(self):
109 self.listen()
110 self.poller.register(self.socket,select.POLLIN|ERRCONDS)
111
112 while self.keep_running:
113 try:
114 avail = self.poller.poll(1)
115 except:
116 continue
117
118 if not avail: continue
119
120 for sock, conds in avail:
121 if conds & (ERRCONDS):
122 if self.__handle_error(sock): continue
123 else: break
124
125 if sock == self.socket.fileno():
126 y = self.socket.accept()[0]
127 self.poller.register(y, select.POLLIN|ERRCONDS)
128 self.current_conns[y.fileno()] = y
129 else: y = self.current_conns.get(sock)
130
131 self.handle_request(y)
132
133 os.remove(self.__sname)
134
135 run = serve_me
136
137 def stop(self):
138 self.keep_running = False
139
140 def handle_request(self,sock):
141 sock.settimeout(1)
142 while self.keep_running:
143 try:
144 x = sock.recv(4096)
145 except socket.timeout:
146 pass
147 else:
148 break
149 self.do_it(x)
150
151 def do_it(self, data):
152 data = data.split('\n')
153 cmds = list()
154 for line in data:
155 cmds.append(line)
156 ip.runlines(cmds)
157
158
159 # try to help ensure that the unix domain socket is cleaned up proper
160 def shutdown_server(self):
161 if SERVER:
162 SERVER.stop()
163 SERVER.join(3)
164 raise IPython.ipapi.TryNext
165
166 ip.set_hook('shutdown_hook', shutdown_server, 10)
167
168 # this fun function exists to make setup easier for all, and makes the
169 # vimhook function ready for instance specific communication
170 def setup(sessionname='',socketdir=os.path.expanduser('~/.ipython/')):
171 global SERVER
172
173 if sessionname:
174 session = sessionname
175 elif os.environ.get('IPY_SESSION'):
176 session = os.environ.get('IPY_SESSION')
177 else:
178 session = 'IPYS'
179 vimhook.vimserver=session
180 vimhook.ipyserver = os.path.join(socketdir, session)
181 if not SERVER:
182 SERVER = IpyServer(vimhook.ipyserver)
183 SERVER.start()
184
185
186
187 # calls gvim, with all ops happening on the correct gvim instance for this
188 # ipython instance. it then calls edit -x (since gvim will return right away)
189 # things of note: it sets up a special environment, so that the ipy.vim script
190 # can connect back to the ipython instance and do fun things, like run the file
191 def vimhook(self, fname, line):
192 env = os.environ.copy()
193 vserver = vimhook.vimserver.upper()
194 check = subprocess.Popen('gvim --serverlist', stdout = subprocess.PIPE,
195 shell=True)
196 check.wait()
197 cval = [l for l in check.stdout.readlines() if vserver in l]
198
199 if cval:
200 vimargs = '--remote%s' % (vimhook.extras,)
201 else:
202 vimargs = ''
203 vimhook.extras = ''
204
205 env['IPY_SESSION'] = vimhook.vimserver
206 env['IPY_SERVER'] = vimhook.ipyserver
207
208 if line is None: line = ''
209 else: line = '+' + line
210 vim_cmd = 'gvim --servername %s %s %s %s' % (vimhook.vimserver, vimargs,
211 line, fname)
212 subprocess.call(vim_cmd, env=env, shell=True)
213
214
215 #default values to keep it sane...
216 vimhook.vimserver = ''
217 vimhook.ipyserver = ''
218
219 ip.set_hook('editor',vimhook)
220
221 # this is set up so more vim specific commands can be added, instead of just
222 # the current -t. all thats required is a compiled regex, a call to do_arg(pat)
223 # and the logic to deal with the new feature
224 newtab = re.compile(r'-t(?:\s|$)')
225 def vim(self, argstr):
226 def do_arg(pat, rarg):
227 x = len(pat.findall(argstr))
228 if x:
229 a = pat.sub('',argstr)
230 return rarg, a
231 else: return '', argstr
232
233 t, argstr = do_arg(newtab, '-tab')
234 vimhook.extras = t
235 argstr = 'edit -x ' + argstr
236 ip.magic(argstr)
237
238 ip.expose_magic('vim', vim)
239
@@ -0,0 +1,73 b''
1 """ Debug a script (like %run -d) in IPython process, Using WinPdb
2
3 Usage:
4
5 %wdb test.py
6 run test.py, with a winpdb breakpoint at start of the file
7
8 %wdb pass
9 Change the password (e.g. if you have forgotten the old one)
10 """
11
12 import os
13
14 import IPython.ipapi
15 import rpdb2
16
17 ip = IPython.ipapi.get()
18
19 rpdb_started = False
20
21 def wdb_f(self, arg):
22 """ Debug a script (like %run -d) in IPython process, Using WinPdb
23
24 Usage:
25
26 %wdb test.py
27 run test.py, with a winpdb breakpoint at start of the file
28
29 %wdb pass
30 Change the password (e.g. if you have forgotten the old one)
31
32 Note that after the script has been run, you need to do "Go" (f5)
33 in WinPdb to resume normal IPython operation.
34 """
35
36 global rpdb_started
37 if not arg.strip():
38 print __doc__
39 return
40
41 if arg.strip() == 'pass':
42 passwd = raw_input('Enter new winpdb session password: ')
43 ip.db['winpdb_pass'] = passwd
44 print "Winpdb password changed"
45 if rpdb_started:
46 print "You need to restart IPython to use the new password"
47 return
48
49 path = os.path.abspath(arg)
50 if not os.path.isfile(path):
51 raise IPython.ipapi.UsageError("%%wdb: file %s does not exist" % path)
52 if not rpdb_started:
53 passwd = ip.db.get('winpdb_pass', None)
54 if passwd is None:
55 import textwrap
56 print textwrap.dedent("""\
57 Winpdb sessions need a password that you use for attaching the external
58 winpdb session. IPython will remember this. You can change the password later
59 by '%wpdb pass'
60 """)
61 passwd = raw_input('Enter new winpdb session password: ')
62 ip.db['winpdb_pass'] = passwd
63
64 print "Starting rpdb2 in IPython process"
65 rpdb2.start_embedded_debugger(passwd, timeout = 0)
66 rpdb_started = True
67
68 rpdb2.set_temp_breakpoint(path)
69 print 'It is time to attach with WinPdb (launch WinPdb if needed, File -> Attach)'
70 ip.magic('%run ' + arg)
71
72
73 ip.expose_magic('wdb', wdb_f)
@@ -0,0 +1,460 b''
1 #!/usr/bin/python
2 # -*- coding: iso-8859-15 -*-
3 '''
4 Provides IPython remote instance.
5
6 @author: Laurent Dufrechou
7 laurent.dufrechou _at_ gmail.com
8 @license: BSD
9
10 All rights reserved. This program and the accompanying materials are made
11 available under the terms of the BSD which accompanies this distribution, and
12 is available at U{http://www.opensource.org/licenses/bsd-license.php}
13 '''
14
15 __version__ = 0.9
16 __author__ = "Laurent Dufrechou"
17 __email__ = "laurent.dufrechou _at_ gmail.com"
18 __license__ = "BSD"
19
20 import re
21 import sys
22 import os
23 import locale
24 import time
25 import pydoc,__builtin__,site
26 from thread_ex import ThreadEx
27 from StringIO import StringIO
28
29 try:
30 import IPython
31 except Exception,e:
32 raise "Error importing IPython (%s)" % str(e)
33
34 ##############################################################################
35 class _Helper(object):
36 """Redefine the built-in 'help'.
37 This is a wrapper around pydoc.help (with a twist).
38 """
39
40 def __init__(self,pager):
41 self._pager = pager
42
43 def __repr__(self):
44 return "Type help() for interactive help, " \
45 "or help(object) for help about object."
46
47 def __call__(self, *args, **kwds):
48 class DummyWriter(object):
49 def __init__(self,pager):
50 self._pager = pager
51
52 def write(self,data):
53 self._pager(data)
54
55 import pydoc
56 pydoc.help.output = DummyWriter(self._pager)
57 pydoc.help.interact = lambda :1
58
59 return pydoc.help(*args, **kwds)
60
61
62 ##############################################################################
63 class _CodeExecutor(ThreadEx):
64
65 def __init__(self, instance, after):
66 ThreadEx.__init__(self)
67 self.instance = instance
68 self._afterExecute=after
69
70 def run(self):
71 try:
72 self.instance._doc_text = None
73 self.instance._help_text = None
74 self.instance._execute()
75 # used for uper class to generate event after execution
76 self._afterExecute()
77
78 except KeyboardInterrupt:
79 pass
80
81
82 ##############################################################################
83 class NonBlockingIPShell(object):
84 '''
85 Create an IPython instance, running the commands in a separate,
86 non-blocking thread.
87 This allows embedding in any GUI without blockage.
88
89 Note: The ThreadEx class supports asynchroneous function call
90 via raise_exc()
91 '''
92
93 def __init__(self,argv=[],user_ns={},user_global_ns=None,
94 cin=None, cout=None, cerr=None,
95 ask_exit_handler=None):
96 '''
97 @param argv: Command line options for IPython
98 @type argv: list
99 @param user_ns: User namespace.
100 @type user_ns: dictionary
101 @param user_global_ns: User global namespace.
102 @type user_global_ns: dictionary.
103 @param cin: Console standard input.
104 @type cin: IO stream
105 @param cout: Console standard output.
106 @type cout: IO stream
107 @param cerr: Console standard error.
108 @type cerr: IO stream
109 @param exit_handler: Replacement for builtin exit() function
110 @type exit_handler: function
111 @param time_loop: Define the sleep time between two thread's loop
112 @type int
113 '''
114 #ipython0 initialisation
115 self.initIpython0(argv, user_ns, user_global_ns,
116 cin, cout, cerr,
117 ask_exit_handler)
118
119 #vars used by _execute
120 self._iter_more = 0
121 self._history_level = 0
122 self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]')
123 self._prompt = str(self._IP.outputcache.prompt1).strip()
124
125 #thread working vars
126 self._line_to_execute = ''
127
128 #vars that will be checked by GUI loop to handle thread states...
129 #will be replaced later by PostEvent GUI funtions...
130 self._doc_text = None
131 self._help_text = None
132 self._add_button = None
133
134 def initIpython0(self, argv=[], user_ns={}, user_global_ns=None,
135 cin=None, cout=None, cerr=None,
136 ask_exit_handler=None):
137 #first we redefine in/out/error functions of IPython
138 if cin:
139 IPython.Shell.Term.cin = cin
140 if cout:
141 IPython.Shell.Term.cout = cout
142 if cerr:
143 IPython.Shell.Term.cerr = cerr
144
145 # This is to get rid of the blockage that accurs during
146 # IPython.Shell.InteractiveShell.user_setup()
147 IPython.iplib.raw_input = lambda x: None
148
149 self._term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr)
150
151 excepthook = sys.excepthook
152
153 self._IP = IPython.Shell.make_IPython(
154 argv,user_ns=user_ns,
155 user_global_ns=user_global_ns,
156 embedded=True,
157 shell_class=IPython.Shell.InteractiveShell)
158
159 #we replace IPython default encoding by wx locale encoding
160 loc = locale.getpreferredencoding()
161 if loc:
162 self._IP.stdin_encoding = loc
163 #we replace the ipython default pager by our pager
164 self._IP.set_hook('show_in_pager',self._pager)
165
166 #we replace the ipython default shell command caller by our shell handler
167 self._IP.set_hook('shell_hook',self._shell)
168
169 #we replace the ipython default input command caller by our method
170 IPython.iplib.raw_input_original = self._raw_input
171 #we replace the ipython default exit command by our method
172 self._IP.exit = ask_exit_handler
173 #we replace the help command
174 self._IP.user_ns['help'] = _Helper(self._pager_help)
175
176 #we disable cpase magic... until we found a way to use it properly.
177 #import IPython.ipapi
178 ip = IPython.ipapi.get()
179 def bypassMagic(self, arg):
180 print '%this magic is currently disabled.'
181 ip.expose_magic('cpaste', bypassMagic)
182
183 sys.excepthook = excepthook
184
185 #----------------------- Thread management section ----------------------
186 def doExecute(self,line):
187 """
188 Tell the thread to process the 'line' command
189 """
190
191 self._line_to_execute = line
192 #we launch the ipython line execution in a thread to make it interruptible
193 self.ce = _CodeExecutor(self,self._afterExecute)
194 self.ce.start()
195
196 #----------------------- IPython management section ----------------------
197 def getDocText(self):
198 """
199 Returns the output of the processing that need to be paged (if any)
200
201 @return: The std output string.
202 @rtype: string
203 """
204 return self._doc_text
205
206 def getHelpText(self):
207 """
208 Returns the output of the processing that need to be paged via help pager(if any)
209
210 @return: The std output string.
211 @rtype: string
212 """
213 return self._help_text
214
215 def getBanner(self):
216 """
217 Returns the IPython banner for useful info on IPython instance
218
219 @return: The banner string.
220 @rtype: string
221 """
222 return self._IP.BANNER
223
224 def getPromptCount(self):
225 """
226 Returns the prompt number.
227 Each time a user execute a line in the IPython shell the prompt count is increased
228
229 @return: The prompt number
230 @rtype: int
231 """
232 return self._IP.outputcache.prompt_count
233
234 def getPrompt(self):
235 """
236 Returns current prompt inside IPython instance
237 (Can be In [...]: ot ...:)
238
239 @return: The current prompt.
240 @rtype: string
241 """
242 return self._prompt
243
244 def getIndentation(self):
245 """
246 Returns the current indentation level
247 Usefull to put the caret at the good start position if we want to do autoindentation.
248
249 @return: The indentation level.
250 @rtype: int
251 """
252 return self._IP.indent_current_nsp
253
254 def updateNamespace(self, ns_dict):
255 '''
256 Add the current dictionary to the shell namespace.
257
258 @param ns_dict: A dictionary of symbol-values.
259 @type ns_dict: dictionary
260 '''
261 self._IP.user_ns.update(ns_dict)
262
263 def complete(self, line):
264 '''
265 Returns an auto completed line and/or posibilities for completion.
266
267 @param line: Given line so far.
268 @type line: string
269
270 @return: Line completed as for as possible,
271 and possible further completions.
272 @rtype: tuple
273 '''
274 split_line = self._complete_sep.split(line)
275 possibilities = self._IP.complete(split_line[-1])
276 if possibilities:
277
278 def _commonPrefix(str1, str2):
279 '''
280 Reduction function. returns common prefix of two given strings.
281
282 @param str1: First string.
283 @type str1: string
284 @param str2: Second string
285 @type str2: string
286
287 @return: Common prefix to both strings.
288 @rtype: string
289 '''
290 for i in range(len(str1)):
291 if not str2.startswith(str1[:i+1]):
292 return str1[:i]
293 return str1
294 common_prefix = reduce(_commonPrefix, possibilities)
295 completed = line[:-len(split_line[-1])]+common_prefix
296 else:
297 completed = line
298 return completed, possibilities
299
300 def historyBack(self):
301 '''
302 Provides one history command back.
303
304 @return: The command string.
305 @rtype: string
306 '''
307 history = ''
308 #the below while loop is used to suppress empty history lines
309 while((history == '' or history == '\n') and self._history_level >0):
310 if self._history_level>=1:
311 self._history_level -= 1
312 history = self._getHistory()
313 return history
314
315 def historyForward(self):
316 '''
317 Provides one history command forward.
318
319 @return: The command string.
320 @rtype: string
321 '''
322 history = ''
323 #the below while loop is used to suppress empty history lines
324 while((history == '' or history == '\n') and self._history_level <= self._getHistoryMaxIndex()):
325 if self._history_level < self._getHistoryMaxIndex():
326 self._history_level += 1
327 history = self._getHistory()
328 else:
329 if self._history_level == self._getHistoryMaxIndex():
330 history = self._getHistory()
331 self._history_level += 1
332 else:
333 history = ''
334 return history
335
336 def initHistoryIndex(self):
337 '''
338 set history to last command entered
339 '''
340 self._history_level = self._getHistoryMaxIndex()+1
341
342 #----------------------- IPython PRIVATE management section --------------
343 def _afterExecute(self):
344 '''
345 Can be redefined to generate post event after excution is done
346 '''
347 pass
348
349 #def _askExit(self):
350 # '''
351 # Can be redefined to generate post event to exit the Ipython shell
352 # '''
353 # pass
354
355 def _getHistoryMaxIndex(self):
356 '''
357 returns the max length of the history buffer
358
359 @return: history length
360 @rtype: int
361 '''
362 return len(self._IP.input_hist_raw)-1
363
364 def _getHistory(self):
365 '''
366 Get's the command string of the current history level.
367
368 @return: Historic command stri
369 @rtype: string
370 '''
371 rv = self._IP.input_hist_raw[self._history_level].strip('\n')
372 return rv
373
374 def _pager_help(self,text):
375 '''
376 This function is used as a callback replacment to IPython help pager function
377
378 It puts the 'text' value inside the self._help_text string that can be retrived via getHelpText
379 function.
380 '''
381 if self._help_text == None:
382 self._help_text = text
383 else:
384 self._help_text += text
385
386 def _pager(self,IP,text):
387 '''
388 This function is used as a callback replacment to IPython pager function
389
390 It puts the 'text' value inside the self._doc_text string that can be retrived via getDocText
391 function.
392 '''
393 self._doc_text = text
394
395 def _raw_input(self, prompt=''):
396 '''
397 Custom raw_input() replacement. Get's current line from console buffer.
398
399 @param prompt: Prompt to print. Here for compatability as replacement.
400 @type prompt: string
401
402 @return: The current command line text.
403 @rtype: string
404 '''
405 return self._line_to_execute
406
407 def _execute(self):
408 '''
409 Executes the current line provided by the shell object.
410 '''
411 orig_stdout = sys.stdout
412 sys.stdout = IPython.Shell.Term.cout
413
414 try:
415 line = self._IP.raw_input(None, self._iter_more)
416 if self._IP.autoindent:
417 self._IP.readline_startup_hook(None)
418
419 except KeyboardInterrupt:
420 self._IP.write('\nKeyboardInterrupt\n')
421 self._IP.resetbuffer()
422 # keep cache in sync with the prompt counter:
423 self._IP.outputcache.prompt_count -= 1
424
425 if self._IP.autoindent:
426 self._IP.indent_current_nsp = 0
427 self._iter_more = 0
428 except:
429 self._IP.showtraceback()
430 else:
431 self._iter_more = self._IP.push(line)
432 if (self._IP.SyntaxTB.last_syntax_error and
433 self._IP.rc.autoedit_syntax):
434 self._IP.edit_syntax_error()
435 if self._iter_more:
436 self._prompt = str(self._IP.outputcache.prompt2).strip()
437 if self._IP.autoindent:
438 self._IP.readline_startup_hook(self._IP.pre_readline)
439 else:
440 self._prompt = str(self._IP.outputcache.prompt1).strip()
441 self._IP.indent_current_nsp = 0 #we set indentation to 0
442 sys.stdout = orig_stdout
443
444 def _shell(self, ip, cmd):
445 '''
446 Replacement method to allow shell commands without them blocking.
447
448 @param ip: Ipython instance, same as self._IP
449 @type cmd: Ipython instance
450 @param cmd: Shell command to execute.
451 @type cmd: string
452 '''
453 stdin, stdout = os.popen4(cmd)
454 result = stdout.read().decode('cp437').encode(locale.getpreferredencoding())
455 #we use print command because the shell command is called inside IPython instance and thus is
456 #redirected to thread cout
457 #"\x01\x1b[1;36m\x02" <-- add colour to the text...
458 print "\x01\x1b[1;36m\x02"+result
459 stdout.close()
460 stdin.close()
@@ -0,0 +1,6 b''
1 completion=IPYTHON
2 background_color=BLACK
3 filter_empty=True
4 filter_magic=True
5 filter_doc=True
6 filter_cmd=True
@@ -0,0 +1,96 b''
1 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
2
3 import thread,inspect
4
5 try:
6 import ctypes
7 HAS_CTYPES = True
8 except ImportError:
9 HAS_CTYPES = False
10
11
12 # Globals
13 # global flag to pass around information about Ctrl-C without exceptions
14 KBINT = False
15
16 # global flag to turn on/off Tk support.
17 USE_TK = False
18
19 # ID for the main thread, used for cross-thread exceptions
20 MAIN_THREAD_ID = thread.get_ident()
21
22 # Tag when runcode() is active, for exception handling
23 CODE_RUN = None
24
25
26 #-----------------------------------------------------------------------------
27 # This class is trivial now, but I want to have it in to publish a clean
28 # interface. Later when the internals are reorganized, code that uses this
29 # shouldn't have to change.
30
31
32 if HAS_CTYPES:
33 # Add async exception support. Trick taken from:
34 # http://sebulba.wikispaces.com/recipe+thread2
35 def _async_raise(tid, exctype):
36 """raises the exception, performs cleanup if needed"""
37 if not inspect.isclass(exctype):
38 raise TypeError("Only types can be raised (not instances)")
39 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
40 ctypes.py_object(exctype))
41 if res == 0:
42 raise ValueError("invalid thread id")
43 elif res != 1:
44 # """if it returns a number greater than one, you're in trouble,
45 # and you should call it again with exc=NULL to revert the effect"""
46 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
47 raise SystemError("PyThreadState_SetAsyncExc failed")
48
49 def sigint_handler (signum,stack_frame):
50 """Sigint handler for threaded apps.
51
52 This is a horrible hack to pass information about SIGINT _without_
53 using exceptions, since I haven't been able to properly manage
54 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
55 done (or at least that's my understanding from a c.l.py thread where
56 this was discussed)."""
57
58 global KBINT
59
60 if CODE_RUN:
61 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
62 else:
63 KBINT = True
64 print '\nKeyboardInterrupt - Press <Enter> to continue.',
65 Term.cout.flush()
66
67 else:
68 def sigint_handler (signum,stack_frame):
69 """Sigint handler for threaded apps.
70
71 This is a horrible hack to pass information about SIGINT _without_
72 using exceptions, since I haven't been able to properly manage
73 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
74 done (or at least that's my understanding from a c.l.py thread where
75 this was discussed)."""
76
77 global KBINT
78
79 print '\nKeyboardInterrupt - Press <Enter> to continue.',
80 Term.cout.flush()
81 # Set global flag so that runsource can know that Ctrl-C was hit
82 KBINT = True
83
84 def run_in_frontend(src):
85 """ Check if source snippet can be run in the REPL thread, as opposed to GUI mainloop
86
87 (to prevent unnecessary hanging of mainloop).
88
89 """
90
91 if src.startswith('_ip.system(') and not '\n' in src:
92 return True
93 return False
94
95
96
@@ -0,0 +1,278 b''
1 import sys
2
3 from twisted.internet import reactor, threads
4
5 from IPython.ipmaker import make_IPython
6 from IPython.iplib import InteractiveShell
7 from IPython.ipstruct import Struct
8 import Queue,thread,threading,signal
9 from signal import signal, SIGINT
10 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
11 import shellglobals
12
13 def install_gtk2():
14 """ Install gtk2 reactor, needs to be called bef """
15 from twisted.internet import gtk2reactor
16 gtk2reactor.install()
17
18
19 def hijack_reactor():
20 """Modifies Twisted's reactor with a dummy so user code does
21 not block IPython. This function returns the original
22 'twisted.internet.reactor' that has been hijacked.
23
24 NOTE: Make sure you call this *AFTER* you've installed
25 the reactor of your choice.
26 """
27 from twisted import internet
28 orig_reactor = internet.reactor
29
30 class DummyReactor(object):
31 def run(self):
32 pass
33 def __getattr__(self, name):
34 return getattr(orig_reactor, name)
35 def __setattr__(self, name, value):
36 return setattr(orig_reactor, name, value)
37
38 internet.reactor = DummyReactor()
39 return orig_reactor
40
41 class TwistedInteractiveShell(InteractiveShell):
42 """Simple multi-threaded shell."""
43
44 # Threading strategy taken from:
45 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
46 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
47 # from the pygtk mailing list, to avoid lockups with system calls.
48
49 # class attribute to indicate whether the class supports threads or not.
50 # Subclasses with thread support should override this as needed.
51 isthreaded = True
52
53 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
54 user_ns=None,user_global_ns=None,banner2='',**kw):
55 """Similar to the normal InteractiveShell, but with threading control"""
56
57 InteractiveShell.__init__(self,name,usage,rc,user_ns,
58 user_global_ns,banner2)
59
60
61 # A queue to hold the code to be executed.
62 self.code_queue = Queue.Queue()
63
64 # Stuff to do at closing time
65 self._kill = None
66 on_kill = kw.get('on_kill', [])
67 # Check that all things to kill are callable:
68 for t in on_kill:
69 if not callable(t):
70 raise TypeError,'on_kill must be a list of callables'
71 self.on_kill = on_kill
72 # thread identity of the "worker thread" (that may execute code directly)
73 self.worker_ident = None
74 self.reactor_started = False
75 self.first_run = True
76
77 def runsource(self, source, filename="<input>", symbol="single"):
78 """Compile and run some source in the interpreter.
79
80 Modified version of code.py's runsource(), to handle threading issues.
81 See the original for full docstring details."""
82
83 # If Ctrl-C was typed, we reset the flag and return right away
84 if shellglobals.KBINT:
85 shellglobals.KBINT = False
86 return False
87
88 if self._kill:
89 # can't queue new code if we are being killed
90 return True
91
92 try:
93 code = self.compile(source, filename, symbol)
94 except (OverflowError, SyntaxError, ValueError):
95 # Case 1
96 self.showsyntaxerror(filename)
97 return False
98
99 if code is None:
100 # Case 2
101 return True
102
103 # shortcut - if we are in worker thread, or the worker thread is not running,
104 # execute directly (to allow recursion and prevent deadlock if code is run early
105 # in IPython construction)
106
107 if (not self.reactor_started or (self.worker_ident is None and not self.first_run)
108 or self.worker_ident == thread.get_ident() or shellglobals.run_in_frontend(source)):
109 InteractiveShell.runcode(self,code)
110 return
111
112 # Case 3
113 # Store code in queue, so the execution thread can handle it.
114
115 self.first_run = False
116 completed_ev, received_ev = threading.Event(), threading.Event()
117
118 self.code_queue.put((code,completed_ev, received_ev))
119
120 reactor.callLater(0.0,self.runcode)
121 received_ev.wait(5)
122 if not received_ev.isSet():
123 # the mainloop is dead, start executing code directly
124 print "Warning: Timeout for mainloop thread exceeded"
125 print "switching to nonthreaded mode (until mainloop wakes up again)"
126 self.worker_ident = None
127 else:
128 completed_ev.wait()
129
130 return False
131
132 def runcode(self):
133 """Execute a code object.
134
135 Multithreaded wrapper around IPython's runcode()."""
136
137
138 # we are in worker thread, stash out the id for runsource()
139 self.worker_ident = thread.get_ident()
140
141 if self._kill:
142 print >>Term.cout, 'Closing threads...',
143 Term.cout.flush()
144 for tokill in self.on_kill:
145 tokill()
146 print >>Term.cout, 'Done.'
147 # allow kill() to return
148 self._kill.set()
149 return True
150
151 # Install SIGINT handler. We do it every time to ensure that if user
152 # code modifies it, we restore our own handling.
153 try:
154 pass
155 signal(SIGINT,shellglobals.sigint_handler)
156 except SystemError:
157 # This happens under Windows, which seems to have all sorts
158 # of problems with signal handling. Oh well...
159 pass
160
161 # Flush queue of pending code by calling the run methood of the parent
162 # class with all items which may be in the queue.
163 code_to_run = None
164 while 1:
165 try:
166 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
167 except Queue.Empty:
168 break
169 received_ev.set()
170
171
172 # Exceptions need to be raised differently depending on which
173 # thread is active. This convoluted try/except is only there to
174 # protect against asynchronous exceptions, to ensure that a shellglobals.KBINT
175 # at the wrong time doesn't deadlock everything. The global
176 # CODE_TO_RUN is set to true/false as close as possible to the
177 # runcode() call, so that the KBINT handler is correctly informed.
178 try:
179 try:
180 shellglobals.CODE_RUN = True
181 InteractiveShell.runcode(self,code_to_run)
182 except KeyboardInterrupt:
183 print "Keyboard interrupted in mainloop"
184 while not self.code_queue.empty():
185 code = self.code_queue.get_nowait()
186 break
187 finally:
188 shellglobals.CODE_RUN = False
189 # allow runsource() return from wait
190 completed_ev.set()
191
192 # This MUST return true for gtk threading to work
193 return True
194
195 def kill(self):
196 """Kill the thread, returning when it has been shut down."""
197 self._kill = threading.Event()
198 reactor.callLater(0.0,self.runcode)
199 self._kill.wait()
200
201
202
203 class IPShellTwisted:
204 """Run a Twisted reactor while in an IPython session.
205
206 Python commands can be passed to the thread where they will be
207 executed. This is implemented by periodically checking for
208 passed code using a Twisted reactor callback.
209 """
210
211 TIMEOUT = 0.01 # Millisecond interval between reactor runs.
212
213 def __init__(self, argv=None, user_ns=None, debug=1,
214 shell_class=TwistedInteractiveShell):
215
216 from twisted.internet import reactor
217 self.reactor = hijack_reactor()
218
219 mainquit = self.reactor.stop
220
221 # Make sure IPython keeps going after reactor stop.
222 def reactorstop():
223 pass
224 self.reactor.stop = reactorstop
225 reactorrun_orig = self.reactor.run
226 self.quitting = False
227 def reactorrun():
228 while True and not self.quitting:
229 reactorrun_orig()
230 self.reactor.run = reactorrun
231
232 self.IP = make_IPython(argv, user_ns=user_ns, debug=debug,
233 shell_class=shell_class,
234 on_kill=[mainquit])
235
236 # threading.Thread.__init__(self)
237
238 def run(self):
239 self.IP.mainloop()
240 self.quitting = True
241 self.IP.kill()
242
243 def mainloop(self):
244 def mainLoopThreadDeath(r):
245 print "mainLoopThreadDeath: ", str(r)
246 def spawnMainloopThread():
247 d=threads.deferToThread(self.run)
248 d.addBoth(mainLoopThreadDeath)
249 reactor.callWhenRunning(spawnMainloopThread)
250 self.IP.reactor_started = True
251 self.reactor.run()
252 print "mainloop ending...."
253
254 exists = True
255
256
257 if __name__ == '__main__':
258 # Sample usage.
259
260 # Create the shell object. This steals twisted.internet.reactor
261 # for its own purposes, to make sure you've already installed a
262 # reactor of your choice.
263 shell = IPShellTwisted(
264 argv=[],
265 user_ns={'__name__': '__example__',
266 'hello': 'world',
267 },
268 )
269
270 # Run the mainloop. This runs the actual reactor.run() method.
271 # The twisted.internet.reactor object at this point is a dummy
272 # object that passes through to the actual reactor, but prevents
273 # run() from being called on it again.
274 shell.mainloop()
275
276 # You must exit IPython to terminate your program.
277 print 'Goodbye!'
278
@@ -0,0 +1,1 b''
1 doc/ipython.el usr/share/emacs/site-lisp
@@ -0,0 +1,52 b''
1 .TH IRUNNER 1 "April 24, 2007" "" ""
2 .SH NAME
3 \fBirunner \- interactive runner interface
4 .SH SYNOPSIS
5 .nf
6 .fam C
7 \fBirunner\fP [\fIoptions\fP] \fIfile_to_run\fP
8 .fam T
9 .fi
10 .SH DESCRIPTION
11 irunner is an interface to the various interactive runners
12 available in IPython's \fBirunner\fP module.
13 .PP
14 The already implemented runners are listed below; adding
15 one for a new program is a trivial task, see the source
16 for examples.
17 .SH OPTIONS
18 .TP
19 .B
20 \-h, \-\-help
21 show this help message and exit
22 .TP
23 .B
24 \-\-ipython
25 IPython interactive runner (default).
26 .TP
27 .B
28 \-\-python
29 Python interactive runner.
30 .TP
31 .B
32 \-\-sage
33 SAGE interactive runner.
34 .SH EXAMPLE
35 irunner.py \-\-python \-\- \-\-help
36 will pass \-\-help to the python runner.
37 Similarly,
38 irunner.py \-\-ipython \-\- \-\-interact script.ipy
39 .SH SEE ALSO
40 .BR ipython(1)
41 .br
42 .SH BUGS
43 The SAGE runner only works if you manually configure your SAGE
44 copy to use 'colors NoColor' in the ipythonrc config file, since
45 currently the prompt matching regexp does not identify color sequences.
46 .SH AUTHOR
47 \fBirunner\fP is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s
48 script contributed on the ipython-user list:
49 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
50 .PP
51 This manual page was written by Bernd Zeimetz <bernd@bzed.de>,
52 for the Debian project (but may be used by others).
@@ -0,0 +1,1 b''
1 debian/irunner.1
@@ -0,0 +1,1 b''
1 2
@@ -0,0 +1,2 b''
1 version=3
2 http://ipython.scipy.org/dist/ ipython-(.*)\.tar\.gz
@@ -0,0 +1,74 b''
1 #!/usr/bin/env python
2 """Script to build documentation using Sphinx.
3 """
4
5 import fileinput,os,sys
6
7 def oscmd(c):
8 os.system(c)
9
10 # html manual.
11 oscmd('sphinx-build -d build/doctrees source build/html')
12
13 if sys.platform != 'win32':
14 # LaTeX format.
15 oscmd('sphinx-build -b latex -d build/doctrees source build/latex')
16
17 # Produce pdf.
18 topdir = os.getcwd()
19 os.chdir('build/latex')
20
21 # Change chapter style to section style: allows chapters to start on
22 # the current page. Works much better for the short chapters we have.
23 # This must go in the class file rather than the preamble, so we modify
24 # manual.cls at runtime.
25 chapter_cmds=r'''
26 % Local changes.
27 \renewcommand\chapter{
28 \thispagestyle{plain}
29 \global\@topnum\z@
30 \@afterindentfalse
31 \secdef\@chapter\@schapter
32 }
33 \def\@makechapterhead#1{
34 \vspace*{10\p@}
35 {\raggedright \reset@font \Huge \bfseries \thechapter \quad #1}
36 \par\nobreak
37 \hrulefill
38 \par\nobreak
39 \vspace*{10\p@}
40 }
41 \def\@makeschapterhead#1{
42 \vspace*{10\p@}
43 {\raggedright \reset@font \Huge \bfseries #1}
44 \par\nobreak
45 \hrulefill
46 \par\nobreak
47 \vspace*{10\p@}
48 }
49 '''
50
51 unmodified=True
52 for line in fileinput.FileInput('manual.cls',inplace=1):
53 if 'Support for module synopsis' in line and unmodified:
54 line=chapter_cmds+line
55 elif 'makechapterhead' in line:
56 # Already have altered manual.cls: don't need to again.
57 unmodified=False
58 print line,
59
60 # Copying the makefile produced by sphinx...
61 oscmd('pdflatex ipython.tex')
62 oscmd('pdflatex ipython.tex')
63 oscmd('pdflatex ipython.tex')
64 oscmd('makeindex -s python.ist ipython.idx')
65 oscmd('makeindex -s python.ist modipython.idx')
66 oscmd('pdflatex ipython.tex')
67 oscmd('pdflatex ipython.tex')
68
69 # Create a manual/ directory with final html/pdf output
70 os.chdir(topdir)
71 oscmd('rm -rf manual')
72 oscmd('mkdir manual')
73 oscmd('cp -r build/html/*.html build/html/_static manual/')
74 oscmd('cp build/latex/ipython.pdf manual/')
@@ -0,0 +1,67 b''
1 if !exists("$IPY_SESSION")
2 finish
3 endif
4
5 " set up the python interpreter within vim, to have all the right modules
6 " imported, as well as certain useful globals set
7 python import socket
8 python import os
9 python import vim
10 python IPYSERVER = None
11
12 python << EOF
13 # do we have a connection to the ipython instance?
14 def check_server():
15 global IPYSERVER
16 if IPYSERVER:
17 return True
18 else:
19 return False
20
21 # connect to the ipython server, if we need to
22 def connect():
23 global IPYSERVER
24 if check_server():
25 return
26 try:
27 IPYSERVER = socket.socket(socket.AF_UNIX)
28 IPYSERVER.connect(os.environ.get('IPY_SERVER'))
29 except:
30 IPYSERVER = None
31
32 def disconnect():
33 if IPYSERVER:
34 IPYSERVER.close()
35
36 def send(cmd):
37 x = 0
38 while True:
39 x += IPYSERVER.send(cmd)
40 if x < len(cmd):
41 cmd = cmd[x:]
42 else:
43 break
44
45 def run_this_file():
46 if check_server():
47 send('run %s' % (vim.current.buffer.name,))
48 else:
49 raise Exception, "Not connected to an IPython server"
50 EOF
51
52 fun! <SID>toggle_send_on_save()
53 if exists("s:ssos") && s:ssos == 1
54 let s:ssos = 0
55 au! BufWritePost *.py :py run_this_file()
56 echo "Autosend Off"
57 else
58 let s:ssos = 1
59 au BufWritePost *.py :py run_this_file()
60 echo "Autowsend On"
61 endif
62 endfun
63
64 map <silent> <F5> :python run_this_file()<CR>
65 imap <silent> <C-F5> <ESC><F5>a
66 map <F7> :call <SID>toggle_send_on_save()<CR>
67 py connect()
This diff has been collapsed as it changes many lines, (552 lines changed) Show them Hide them
@@ -0,0 +1,552 b''
1 <?xml version="1.0" encoding="utf-8"?>
2 <?xml-stylesheet ekr_test?>
3 <leo_file>
4 <leo_header file_format="2" tnodes="0" max_tnode_index="0" clone_windows="0"/>
5 <globals body_outline_ratio="0.307814992026">
6 <global_window_position top="257" left="131" height="627" width="1280"/>
7 <global_log_window_position top="0" left="0" height="0" width="0"/>
8 </globals>
9 <preferences/>
10 <find_panel_settings/>
11 <vnodes>
12 <v t="vivainio.20080222193236" a="E"><vh>Documentation</vh>
13 <v t="vivainio.20080223121915" tnodeList="vivainio.20080223121915,vivainio.20080222193236.1,vivainio.20080223133858,vivainio.20080223133922,vivainio.20080223133947,vivainio.20080223134018,vivainio.20080223134100,vivainio.20080223134118,vivainio.20080223134433,vivainio.20080223142207,vivainio.20080223134136"><vh>@nosent ILeo_doc.txt</vh>
14 <v t="vivainio.20080222193236.1"><vh>Documentation</vh>
15 <v t="vivainio.20080223133858"><vh>Introduction</vh></v>
16 <v t="vivainio.20080223133922"><vh>Installation</vh></v>
17 <v t="vivainio.20080223133947"><vh>Accessing IPython from Leo</vh></v>
18 <v t="vivainio.20080223134018"><vh>Accessing Leo nodes from IPython</vh></v>
19 <v t="vivainio.20080223134100"><vh>Cl definitions</vh></v>
20 <v t="vivainio.20080223134118"><vh>Special node types</vh></v>
21 <v t="vivainio.20080223134433"><vh>Custom push</vh></v>
22 <v t="vivainio.20080223142207" a="E"><vh>Code snippets</vh></v>
23 <v t="vivainio.20080223134136"><vh>Acknowledgements and history</vh></v>
24 </v>
25 </v>
26 </v>
27 <v t="vivainio.20080218184525"><vh>@chapters</vh></v>
28 <v t="vivainio.20080223133721" a="E"><vh>@settings</vh>
29 <v t="vivainio.20080316092617"><vh>@@string ipython_argv = ipython -pylab</vh></v>
30 <v t="vivainio.20080223133721.1"><vh>@enabled-plugins</vh></v>
31 </v>
32 <v t="vivainio.20080218184540"><vh>@ipy-startup</vh>
33 <v t="vivainio.20080218184613.1"><vh>b</vh></v>
34 <v t="vivainio.20080218200031"><vh>Some classes P</vh>
35 <v t="vivainio.20080218190816"><vh>File-like access</vh></v>
36 <v t="vivainio.20080218200106"><vh>csv data</vh></v>
37 <v t="vivainio.20080219225120"><vh>String list</vh></v>
38 <v t="vivainio.20080219230342"><vh>slist to leo</vh></v>
39 </v>
40 </v>
41 <v t="vivainio.20080218195413" a="E"><vh>Class tests</vh>
42 <v t="vivainio.20080218200509"><vh>csvr</vh></v>
43 <v t="vivainio.20080218191007"><vh>tempfile</vh></v>
44 <v t="vivainio.20080218195413.1"><vh>rfile</vh></v>
45 <v t="vivainio.20080219225804"><vh>strlist</vh></v>
46 </v>
47 <v t="vivainio.20080222201226" a="V"><vh>IPython script push tests</vh></v>
48 <v t="vivainio.20080218201219" a="E"><vh>Direct variables</vh>
49 <v t="vivainio.20080218201219.2"><vh>bar</vh></v>
50 </v>
51 <v t="vivainio.20080316144536" a="E"><vh>pylab tests</vh>
52 <v t="vivainio.20080316145539.2"><vh>Generate testarr</vh></v>
53 <v t="vivainio.20080316085925"><vh>testarr</vh></v>
54 <v t="vivainio.20080316085950"><vh>Call plotter on testarr</vh></v>
55 </v>
56 <v t="vivainio.20080222202211"><vh>test stuff</vh></v>
57 <v t="vivainio.20080223142403"><vh>@ipy-results</vh>
58 <v t="vivainio.20080223142403.1"><vh>foo</vh></v>
59 </v>
60 <v t="vivainio.20080222202211.1" a="E"><vh>spam</vh></v>
61 </vnodes>
62 <tnodes>
63 <t tx="vivainio.20080218184525">?</t>
64 <t tx="vivainio.20080218184540">?Direct children of this node will be pushed at ipython bridge startup
65
66 This node itself will *not* be pushed</t>
67 <t tx="vivainio.20080218184613.1">print "world"</t>
68 <t tx="vivainio.20080218190816">def rfile(body,n):
69 """ @cl rfile
70
71 produces a StringIO (file like obj of the rest of the body) """
72
73 import StringIO
74 return StringIO.StringIO(body)
75
76 def tmpfile(body,n):
77 """ @cl tmpfile
78
79 Produces a temporary file, with node body as contents
80
81 """
82 import tempfile
83 h, fname = tempfile.mkstemp()
84 f = open(fname,'w')
85 f.write(body)
86 f.close()
87 return fname
88 </t>
89 <t tx="vivainio.20080218191007">@cl tmpfile
90
91 Hello</t>
92 <t tx="vivainio.20080218195413">?</t>
93 <t tx="vivainio.20080218195413.1">@cl rfile
94 These
95 lines
96 should
97 be
98 readable </t>
99 <t tx="vivainio.20080218200031">@others</t>
100 <t tx="vivainio.20080218200106">def csvdata(body,n):
101 import csv
102 d = csv.Sniffer().sniff(body)
103 reader = csv.reader(body.splitlines(), dialect = d)
104 return reader</t>
105 <t tx="vivainio.20080218200509">@cl csvdata
106
107 a,b,b
108 1,2,2</t>
109 <t tx="vivainio.20080218201219"></t>
110 <t tx="vivainio.20080218201219.2">@cl
111 "hello world"</t>
112 <t tx="vivainio.20080219225120">import IPython.genutils
113 def slist(body,n):
114 return IPython.genutils.SList(body.splitlines())
115 </t>
116 <t tx="vivainio.20080219225804">@cl slist
117 hello
118 world
119 on
120 many
121 lines
122 </t>
123 <t tx="vivainio.20080219230342">import ipy_leo
124 @ipy_leo.format_for_leo.when_type(IPython.genutils.SList)
125 def format_slist(obj):
126 return "@cl slist\n" + obj.n
127 </t>
128 <t tx="vivainio.20080222193236">?</t>
129 <t tx="vivainio.20080222193236.1">@wrap
130 @nocolor</t>
131 <t tx="vivainio.20080222201226"># test ipython script 'cleanup' with complex blocks
132 1+2
133 print "hello"
134 3+4
135
136 def f(x):
137 return x.upper()
138
139
140 if 0:
141 print "foo"
142 else:
143 print "bar"
144
145 def g():
146 pass
147
148 g()
149
150 if 1:
151 if 1:
152 print "hello"
153
154 print "world"
155
156 if 1:
157 print "hello"
158
159 print "word"
160 else:
161 print "foo"
162
163 print "bar"
164 print "baz"
165
166 try:
167 raise Exception
168 except:
169 print "exc ok"</t>
170 <t tx="vivainio.20080222202211"></t>
171 <t tx="vivainio.20080222202211.1" ipython="7d71005506636f6f7264737101284b0c4bde747102732e">@cl rfile
172 hello
173 world
174 and whatever</t>
175 <t tx="vivainio.20080223121915">@others
176 </t>
177 <t tx="vivainio.20080223133721"></t>
178 <t tx="vivainio.20080223133721.1">ipython.py</t>
179 <t tx="vivainio.20080223133858">
180 Introduction
181 ============
182
183 The purpose of ILeo, or leo-ipython bridge, is being a two-way communication
184 channel between Leo and IPython. The level of integration is much deeper than
185 conventional integration in IDEs; most notably, you are able to store *data* in
186 Leo nodes, in addition to mere program code. The possibilities of this are
187 endless, and this degree of integration has not been seen previously in the python
188 world.
189
190 IPython users are accustomed to using things like %edit to produce non-trivial
191 functions/classes (i.e. something that they don't want to enter directly on the
192 interactive prompt, but creating a proper script/module involves too much
193 overhead). In ILeo, this task consists just going to the Leo window, creating a node
194 and writing the code there, and pressing alt+I (push-to-ipython).
195
196 Obviously, you can save the Leo document as usual - this is a great advantage
197 of ILeo over using %edit, you can save your experimental scripts all at one
198 time, without having to organize them into script/module files (before you
199 really want to, of course!)
200 </t>
201 <t tx="vivainio.20080223133922">
202 Installation
203 ============
204
205 You need at least Leo 4.4.7, and the development version of IPython (ILeo
206 will be incorporated to IPython 0.8.3).
207
208 You can get IPython from Launchpad by installing bzr and doing
209
210 bzr branch lp:ipython
211
212 and running "setup.py install".
213
214 You need to enable the 'ipython.py' plugin in Leo:
215
216 - Help -&gt; Open LeoSettings.leo
217
218 - Edit @settings--&gt;Plugins--&gt;@enabled-plugins, add/uncomment 'ipython.py'
219
220 - Alternatively, you can add @settings--&gt;@enabled-plugins with body ipython.py to your leo document.
221
222 - Restart Leo. Be sure that you have the console window open (start leo.py from console, or double-click leo.py on windows)
223
224 - Press alt+5 OR alt-x start-ipython to launch IPython in the console that
225 started leo. You can start entering IPython commands normally, and Leo will keep
226 running at the same time.
227 </t>
228 <t tx="vivainio.20080223133947">
229 Accessing IPython from Leo
230 ==========================
231
232 IPython code
233 ------------
234
235 Just enter IPython commands on a Leo node and press alt-I to execute
236 push-to-ipython in order to execute the script in IPython. 'commands' is
237 interpreted loosely here - you can enter function and class definitions, in
238 addition to the things you would usually enter at IPython prompt - calculations,
239 system commands etc.
240
241 Everything that would be legal to enter on IPython prompt is legal to execute
242 from ILeo.
243
244 Results will be shows in Leo log window for convenience, in addition to the console.
245
246 Suppose that a node had the following contents:
247 {{{
248 1+2
249 print "hello"
250 3+4
251
252 def f(x):
253 return x.upper()
254
255 f('hello world')
256 }}}
257
258 If you press alt+I on that node, you will see the following in Leo log window (IPython tab):
259
260 {{{
261 In: 1+2
262 &lt;2&gt; 3
263 In: 3+4
264 &lt;4&gt; 7
265 In: f('hello world')
266 &lt;6&gt; 'HELLO WORLD'
267 }}}
268
269 (numbers like &lt;6&gt; mean IPython output history indices; the actual object can be
270 referenced with _6 as usual in IPython).
271
272
273 Plain Python code
274 -----------------
275
276 If the headline of the node ends with capital P, alt-I will not run the code
277 through IPython translation mechanism but use the direct python 'exec' statement
278 (in IPython user namespace) to execute the code. It wont be shown in IPython
279 history, and sometimes it is safer (and more efficient) to execute things as
280 plain Python statements. Large class definitions are good candidates for P
281 nodes.
282 </t>
283 <t tx="vivainio.20080223134018">
284 Accessing Leo nodes from IPython
285 ================================
286
287 The real fun starts when you start entering text to leo nodes, and are using
288 that as data (input/output) for your IPython work.
289
290 Accessing Leo nodes happens through the variable 'wb' (short for "WorkBook")
291 that exist in the IPython user namespace. Nodes that are directly accessible are
292 the ones that have simple names which could also be Python variable names;
293 'foo_1' will be accessible directly from IPython, whereas 'my scripts' will not.
294 If you want to access a node with arbitrary headline, add a child node '@a foo'
295 (@a stands for 'anchor'). Then, the parent of '@a foo' is accessible through
296 'wb.foo'.
297
298 You can see what nodes are accessible be entering (in IPython) wb.&lt;TAB&gt;. Example:
299
300 [C:leo/src]|12&gt; wb.
301 wb.b wb.tempfile wb.rfile wb.NewHeadline
302 wb.bar wb.Docs wb.strlist wb.csvr
303 [C:leo/src]|12&gt; wb.tempfile
304 &lt;12&gt; &lt;ipy_leo.LeoNode object at 0x044B6D90&gt;
305
306 So here, we meet the 'LeoNode' class that is your key to manipulating Leo
307 content from IPython!
308
309 LeoNode
310 -------
311
312 Suppose that we had a node with headline 'spam' and body:
313
314 ['12',2222+32]
315
316 we can access it from IPython (or from scripts entered into other Leo nodes!) by doing:
317
318 C:leo/src]|19&gt; wb.spam.v
319 &lt;19&gt; ['12', 2254]
320
321 'v' attribute stands for 'value', which means the node contents will be run
322 through 'eval' and everything you would be able to enter into IPython prompt
323 will be converted to objects. This mechanism can be extended far beyond direct
324 evaluation (see '@cl definitions').
325
326 'v' attribute also has a setter, i.e. you can do:
327
328 wb.spam.v = "mystring"
329
330 Which will result in the node 'spam' having the following text:
331
332 'mystring'
333
334 What assignment to 'v' does can be configured through generic functions
335 ('simplegeneric' module, will be explained later).
336
337 Besides v, you can set the body text directly through
338
339 wb.spam.b = "some\nstring",
340
341 headline by
342
343 wb.spam.h = 'new_headline'
344
345 (obviously you must access the node through wb.new_headline from that point
346 onwards), and access the contents as string list (IPython SList) through
347 'wb.spam.l'.
348
349 If you do 'wb.foo.v = 12' when node named 'foo' does not exist, the node titled
350 'foo' will be automatically created and assigned body 12.
351
352 LeoNode also supports go() that focuses the node in the Leo window, and ipush()
353 that simulates pressing alt+I on the node.
354
355 You can access unknownAttributes by .uA property dictionary. Unknown attributes
356 allow you to store arbitrary (pickleable) python objects in the Leo nodes; the
357 attributes are stored when you save the .leo document, and recreated when you
358 open the document again. The attributes are not visible anywhere, but can be
359 used for domain-specific metatada. Example:
360
361 [C:leo/src]|12&gt; wb.spam.uA['coords'] = (12,222)
362 [C:leo/src]|13&gt; wb.spam.uA
363 &lt;13&gt; {'coords': (12, 222)}
364
365 Accessing children with iteration and dict notation
366 ---------------------------------------------------
367
368 Sometimes, you may want to treat a node as a 'database', where the nodes
369 children represent elements in the database. You can create a new child node for
370 node 'spam', with headline 'foo bar' like this:
371
372 wb.spam['foo bar'] = "Hello"
373
374 And assign a new value for it by doing
375
376 wb.spam['foo bar'].v = "Hello again"
377
378 Note how you can't use .v when you first create the node - i.e. the node needs
379 to be initialized by simple assignment, that will be interpreted as assignment
380 to '.v'. This is a conscious design choice.
381
382 If you try to do wb.spam['bar'] = 'Hello', ILeo will assign '@k bar' as the
383 headline for the child instead, because 'bar' is a legal python name (and as
384 such would be incorporated in the workbook namespace). This is done to avoid
385 crowding the workbook namespace with extraneous items. The item will still be
386 accessible as wb.spam['bar']
387
388 LeoNodes are iterable, so to see the headlines of all the children of 'spam' do:
389
390 for n in wb.spam:
391 print n.h
392 </t>
393 <t tx="vivainio.20080223134100">
394 @cl definitions
395 ===============
396
397 If the first line in the body text is of the form '@cl sometext', IPython will
398 evaluate 'sometext' and call the result with the rest of the body when you do
399 'wb.foo.v'. An example is in place here. Suppose that we have defined a class (I
400 use the term class in a non-python sense here)
401
402 {{{
403 def rfile(body,node):
404 """ @cl rfile
405
406 produces a StringIO (file like obj) of the rest of the body """
407
408 import StringIO
409 return StringIO.StringIO(body)
410 }}}
411
412 (note that node is ignored here - but it could be used to access headline,
413 children etc.),
414
415 Now, let's say you have node 'spam' with text
416
417 {{{
418 @cl rfile
419 hello
420 world
421 and whatever
422 }}}
423
424 Now, in IPython, we can do this:
425
426 {{{
427 [C:leo/src]|22&gt; f = wb.spam.v
428 [C:leo/src]|23&gt; f
429 &lt;23&gt; &lt;StringIO.StringIO instance at 0x04E7E490&gt;
430 [C:leo/src]|24&gt; f.readline()
431 &lt;24&gt; u'hello\n'
432 [C:leo/src]|25&gt; f.readline()
433 &lt;25&gt; u'world\n'
434 [C:leo/src]|26&gt; f.readline()
435 &lt;26&gt; u'and whatever'
436 [C:leo/src]|27&gt; f.readline()
437 &lt;27&gt; u''
438 }}}
439
440 You should declare new @cl types to make ILeo as convenient your problem domain
441 as possible. For example, a "@cl etree" could return the elementtree object for
442 xml content.
443 </t>
444 <t tx="vivainio.20080223134118">
445 Special node types
446 ==================
447
448 @ipy-startup
449 ------------
450
451 If this node exist, the *direct children* of this will be pushed to IPython when
452 ILeo is started (you press alt+5). Use it to push your own @cl definitions etc.
453 The contents of of the node itself will be ignored.
454
455 @ipy-results
456 ------------
457
458 When you create a new node (wb.foo.v = 'stuff'), the node foo will be created as
459 a child of this node. If @ipy-results does not exist, the new node will be created after the currently selected node.
460
461 @a nodes
462 --------
463
464 You can attach these as children of existing nodes to provide a way to access
465 nodes with arbitrary headlines, or to provide aliases to other nodes. If
466 multiple @a nodes are attached as children of a node, all the names can be used
467 to access the same object.
468 </t>
469 <t tx="vivainio.20080223134136">
470 Acknowledgements &amp; History
471 ==========================
472
473 This idea got started when I (Ville) saw this post by Edward Ream (the author of
474 Leo) on IPython developer mailing list:
475
476 http://lists.ipython.scipy.org/pipermail/ipython-dev/2008-January/003551.html
477
478 I was using FreeMind as mind mapping software, and so I had an immediate use
479 case for Leo (which, incidentally, is superior to FreeMind as mind mapper). The
480 wheels started rolling, I got obsessed with the power of this concept
481 (everything clicked together), and Edwards excitement paralleled mine.
482 Everything was mind-bogglingly easy/trivial, something that is typical of all
483 revolutionary technologies (think Python here).
484
485 The discussion that "built" ILeo is here:
486 http://sourceforge.net/forum/forum.php?thread_id=1911662&amp;forum_id=10226
487
488 ?</t>
489 <t tx="vivainio.20080223134433">
490 Declaring custom push-to-ipython handlers
491 =========================================
492
493 Sometimes, you might want to configure what alt+I on a node does. You can do
494 that by creating your own push function and expose it using
495 ipy_leo.expose_ileo_push(f, priority). The function should check whether the
496 node should by handled by the function and raise IPython.ipapi.TryNext if it
497 will not do the handling, giving the next function in the chain a chance to see
498 whether it should handle the push.
499
500 This example would print an uppercase version of node body if the node headline ends
501 with U (yes, this is completely useless!):
502
503 {{{
504 def push_upcase(node):
505 if not node.h.endswith('U'):
506 raise TryNext
507 print node.b.upper()
508
509 ipy_leo.expose_ileo_push(push_upcase, 12)
510 }}}
511
512 (the priority should be between 0-100 - typically, you don't need to care about
513 it and can usually omit the argument altogether)
514 </t>
515 <t tx="vivainio.20080223142207">
516 Example code snippets
517 =====================
518
519 Get list of all headlines of all the nodes in leo:
520
521 [node.h for node in wb]
522
523 Create node with headline 'baz', empty body:
524 wb.baz
525
526 Create 10 child nodes for baz, where i is headline and 'Hello ' + i is body:
527
528 for i in range(10):
529 wb.baz[i] = 'Hello %d' % i
530
531
532 </t>
533 <t tx="vivainio.20080223142403"></t>
534 <t tx="vivainio.20080223142403.1">12</t>
535 <t tx="vivainio.20080316085925">array([[ 0, 1, 2],
536 [ 3, 4, 5],
537 [ 6, 7, 8],
538 [ 9, 10, 11]])</t>
539 <t tx="vivainio.20080316085950"># press alt+i here to plot testarr
540
541 plot(wb.testarr.v)</t>
542 <t tx="vivainio.20080316092617"></t>
543 <t tx="vivainio.20080316144536">Quickstart:
544 easy_install numpy
545 easy_install matplotlib
546
547 Make sure you have '@string ipython-argv = ipython -pylab' in @settings. We currently recommend using TkAgg as the backend (it's also the default)</t>
548 <t tx="vivainio.20080316145539.2">#press alt+i here to generate an array for plotter
549
550 wb.testarr.v = arange(12).reshape(4,3)</t>
551 </tnodes>
552 </leo_file>
@@ -0,0 +1,132 b''
1 # -*- coding: utf-8 -*-
2 #
3 # IPython documentation build configuration file, created by
4 # sphinx-quickstart.py on Sat Mar 29 15:36:13 2008.
5 #
6 # This file is execfile()d with the current directory set to its containing dir.
7 #
8 # The contents of this file are pickled, so don't put values in the namespace
9 # that aren't pickleable (module imports are okay, they're removed automatically).
10 #
11 # All configuration values have a default value; values that are commented out
12 # serve to show the default value.
13
14 import sys
15
16 # If your extensions are in another directory, add it here.
17 #sys.path.append('some/directory')
18
19 # General configuration
20 # ---------------------
21
22 # Add any Sphinx extension module names here, as strings. They can be extensions
23 # coming with Sphinx (named 'sphinx.addons.*') or your custom ones.
24 #extensions = []
25
26 # Add any paths that contain templates here, relative to this directory.
27 templates_path = ['_templates']
28
29 # The suffix of source filenames.
30 source_suffix = '.rst'
31
32 # The master toctree document.
33 master_doc = 'ipython'
34
35 # General substitutions.
36 project = 'IPython'
37 copyright = '2008, Fernando Perez'
38
39 # The default replacements for |version| and |release|, also used in various
40 # other places throughout the built documents.
41 #
42 # The short X.Y version.
43 version = '0.8.3'
44 # The full version, including alpha/beta/rc tags.
45 release = '0.8.3'
46
47 # There are two options for replacing |today|: either, you set today to some
48 # non-false value, then it is used:
49 #today = ''
50 # Else, today_fmt is used as the format for a strftime call.
51 today_fmt = '%B %d, %Y'
52
53 # List of documents that shouldn't be included in the build.
54 #unused_docs = []
55
56 # If true, '()' will be appended to :func: etc. cross-reference text.
57 #add_function_parentheses = True
58
59 # If true, the current module name will be prepended to all description
60 # unit titles (such as .. function::).
61 #add_module_names = True
62
63 # If true, sectionauthor and moduleauthor directives will be shown in the
64 # output. They are ignored by default.
65 #show_authors = False
66
67 # The name of the Pygments (syntax highlighting) style to use.
68 pygments_style = 'sphinx'
69
70
71 # Options for HTML output
72 # -----------------------
73
74 # The style sheet to use for HTML and HTML Help pages. A file of that name
75 # must exist either in Sphinx' static/ path, or in one of the custom paths
76 # given in html_static_path.
77 html_style = 'default.css'
78
79 # Add any paths that contain custom static files (such as style sheets) here,
80 # relative to this directory. They are copied after the builtin static files,
81 # so a file named "default.css" will overwrite the builtin "default.css".
82 html_static_path = ['_static']
83
84 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
85 # using the given strftime format.
86 html_last_updated_fmt = '%b %d, %Y'
87
88 # If true, SmartyPants will be used to convert quotes and dashes to
89 # typographically correct entities.
90 #html_use_smartypants = True
91
92 # Content template for the index page.
93 #html_index = ''
94
95 # Custom sidebar templates, maps document names to template names.
96 #html_sidebars = {}
97
98 # Additional templates that should be rendered to pages, maps page names to
99 # template names.
100 #html_additional_pages = {}
101
102 # If false, no module index is generated.
103 #html_use_modindex = True
104
105 # If true, the reST sources are included in the HTML build as _sources/<name>.
106 #html_copy_source = True
107
108 # Output file base name for HTML help builder.
109 htmlhelp_basename = 'IPythondoc'
110
111
112 # Options for LaTeX output
113 # ------------------------
114
115 # The paper size ('letter' or 'a4').
116 latex_paper_size = 'a4'
117
118 # The font size ('10pt', '11pt' or '12pt').
119 latex_font_size = '10pt'
120
121 # Grouping the document tree into LaTeX files. List of tuples
122 # (source start file, target name, title, author, document class [howto/manual]).
123 latex_documents = [('ipython','ipython.tex','IPython Documentation','Fernando Perez (and contributors)','manual')]
124
125 # Additional stuff for the LaTeX preamble.
126 #latex_preamble = ''
127
128 # Documents to append as an appendix to all manuals.
129 #latex_appendices = []
130
131 # If false, no module index is generated.
132 #latex_use_modindex = True
This diff has been collapsed as it changes many lines, (5875 lines changed) Show them Hide them
@@ -0,0 +1,5875 b''
1 .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008.
2 You can adapt this file completely to your liking, but it should at least
3 contain the root 'toctree' directive.
4
5 IPython documentation
6 =====================
7
8 Contents:
9
10 .. toctree::
11 :maxdepth: 2
12
13 Indices and tables
14 ==================
15
16 * :ref:`genindex`
17 * :ref:`modindex`
18 * :ref:`search`
19
20 Introduction
21 ============
22
23 This is the official documentation for IPython 0.x series (i.e. what
24 we are used to refer to just as "IPython"). The original text of the
25 manual (most of which is still in place) has been authored by Fernando
26 Perez, but as recommended usage patterns and new features have
27 emerged, this manual has been updated to reflect that fact. Most of
28 the additions have been authored by Ville M. Vainio.
29
30 The manual has been generated from reStructuredText source markup with
31 Sphinx, which should make it much easier to keep it up-to-date in the
32 future. Some reST artifacts and bugs may still be apparent in the
33 documentation, but this should improve as the toolchain matures.
34
35 Overview
36 ========
37
38 One of Python's most useful features is its interactive interpreter.
39 This system allows very fast testing of ideas without the overhead of
40 creating test files as is typical in most programming languages.
41 However, the interpreter supplied with the standard Python distribution
42 is somewhat limited for extended interactive use.
43
44 IPython is a free software project (released under the BSD license)
45 which tries to:
46
47 1. Provide an interactive shell superior to Python's default. IPython
48 has many features for object introspection, system shell access,
49 and its own special command system for adding functionality when
50 working interactively. It tries to be a very efficient environment
51 both for Python code development and for exploration of problems
52 using Python objects (in situations like data analysis).
53 2. Serve as an embeddable, ready to use interpreter for your own
54 programs. IPython can be started with a single call from inside
55 another program, providing access to the current namespace. This
56 can be very useful both for debugging purposes and for situations
57 where a blend of batch-processing and interactive exploration are
58 needed.
59 3. Offer a flexible framework which can be used as the base
60 environment for other systems with Python as the underlying
61 language. Specifically scientific environments like Mathematica,
62 IDL and Matlab inspired its design, but similar ideas can be
63 useful in many fields.
64 4. Allow interactive testing of threaded graphical toolkits. IPython
65 has support for interactive, non-blocking control of GTK, Qt and
66 WX applications via special threading flags. The normal Python
67 shell can only do this for Tkinter applications.
68
69
70 Main features
71 -------------
72
73 * Dynamic object introspection. One can access docstrings, function
74 definition prototypes, source code, source files and other details
75 of any object accessible to the interpreter with a single
76 keystroke ('?', and using '??' provides additional detail).
77 * Searching through modules and namespaces with '*' wildcards, both
78 when using the '?' system and via the %psearch command.
79 * Completion in the local namespace, by typing TAB at the prompt.
80 This works for keywords, modules, methods, variables and files in the
81 current directory. This is supported via the readline library, and
82 full access to configuring readline's behavior is provided.
83 Custom completers can be implemented easily for different purposes
84 (system commands, magic arguments etc.)
85 * Numbered input/output prompts with command history (persistent
86 across sessions and tied to each profile), full searching in this
87 history and caching of all input and output.
88 * User-extensible 'magic' commands. A set of commands prefixed with
89 % is available for controlling IPython itself and provides
90 directory control, namespace information and many aliases to
91 common system shell commands.
92 * Alias facility for defining your own system aliases.
93 * Complete system shell access. Lines starting with ! are passed
94 directly to the system shell, and using !! or var = !cmd
95 captures shell output into python variables for further use.
96 * Background execution of Python commands in a separate thread.
97 IPython has an internal job manager called jobs, and a
98 conveninence backgrounding magic function called %bg.
99 * The ability to expand python variables when calling the system
100 shell. In a shell command, any python variable prefixed with $ is
101 expanded. A double $$ allows passing a literal $ to the shell (for
102 access to shell and environment variables like $PATH).
103 * Filesystem navigation, via a magic %cd command, along with a
104 persistent bookmark system (using %bookmark) for fast access to
105 frequently visited directories.
106 * A lightweight persistence framework via the %store command, which
107 allows you to save arbitrary Python variables. These get restored
108 automatically when your session restarts.
109 * Automatic indentation (optional) of code as you type (through the
110 readline library).
111 * Macro system for quickly re-executing multiple lines of previous
112 input with a single name. Macros can be stored persistently via
113 %store and edited via %edit.
114 * Session logging (you can then later use these logs as code in your
115 programs). Logs can optionally timestamp all input, and also store
116 session output (marked as comments, so the log remains valid
117 Python source code).
118 * Session restoring: logs can be replayed to restore a previous
119 session to the state where you left it.
120 * Verbose and colored exception traceback printouts. Easier to parse
121 visually, and in verbose mode they produce a lot of useful
122 debugging information (basically a terminal version of the cgitb
123 module).
124 * Auto-parentheses: callable objects can be executed without
125 parentheses: 'sin 3' is automatically converted to 'sin(3)'.
126 * Auto-quoting: using ',' or ';' as the first character forces
127 auto-quoting of the rest of the line: ',my_function a b' becomes
128 automatically 'my_function("a","b")', while ';my_function a b'
129 becomes 'my_function("a b")'.
130 * Extensible input syntax. You can define filters that pre-process
131 user input to simplify input in special situations. This allows
132 for example pasting multi-line code fragments which start with
133 '>>>' or '...' such as those from other python sessions or the
134 standard Python documentation.
135 * Flexible configuration system. It uses a configuration file which
136 allows permanent setting of all command-line options, module
137 loading, code and file execution. The system allows recursive file
138 inclusion, so you can have a base file with defaults and layers
139 which load other customizations for particular projects.
140 * Embeddable. You can call IPython as a python shell inside your own
141 python programs. This can be used both for debugging code or for
142 providing interactive abilities to your programs with knowledge
143 about the local namespaces (very useful in debugging and data
144 analysis situations).
145 * Easy debugger access. You can set IPython to call up an enhanced
146 version of the Python debugger (pdb) every time there is an
147 uncaught exception. This drops you inside the code which triggered
148 the exception with all the data live and it is possible to
149 navigate the stack to rapidly isolate the source of a bug. The
150 %run magic command -with the -d option- can run any script under
151 pdb's control, automatically setting initial breakpoints for you.
152 This version of pdb has IPython-specific improvements, including
153 tab-completion and traceback coloring support. For even easier
154 debugger access, try %debug after seeing an exception. winpdb is
155 also supported, see ipy_winpdb extension.
156 * Profiler support. You can run single statements (similar to
157 profile.run()) or complete programs under the profiler's control.
158 While this is possible with standard cProfile or profile modules,
159 IPython wraps this functionality with magic commands (see '%prun'
160 and '%run -p') convenient for rapid interactive work.
161 * Doctest support. The special %doctest_mode command toggles a mode
162 that allows you to paste existing doctests (with leading '>>>'
163 prompts and whitespace) and uses doctest-compatible prompts and
164 output, so you can use IPython sessions as doctest code.
165
166
167 Portability and Python requirements
168 -----------------------------------
169
170 Python requirements: IPython requires with Python version 2.3 or newer.
171 If you are still using Python 2.2 and can not upgrade, the last version
172 of IPython which worked with Python 2.2 was 0.6.15, so you will have to
173 use that.
174
175 IPython is developed under Linux, but it should work in any reasonable
176 Unix-type system (tested OK under Solaris and the BSD family, for which
177 a port exists thanks to Dryice Liu).
178
179 Mac OS X: it works, apparently without any problems (thanks to Jim Boyle
180 at Lawrence Livermore for the information). Thanks to Andrea Riciputi,
181 Fink support is available.
182
183 CygWin: it works mostly OK, though some users have reported problems
184 with prompt coloring. No satisfactory solution to this has been found so
185 far, you may want to disable colors permanently in the ipythonrc
186 configuration file if you experience problems. If you have proper color
187 support under cygwin, please post to the IPython mailing list so this
188 issue can be resolved for all users.
189
190 Windows: it works well under Windows Vista/XP/2k, and I suspect NT should
191 behave similarly. Section "Installation under windows" describes
192 installation details for Windows, including some additional tools needed
193 on this platform.
194
195 Windows 9x support is present, and has been reported to work fine (at
196 least on WinME).
197
198 Location
199 --------
200
201 IPython is generously hosted at http://ipython.scipy.org by the
202 Enthought, Inc and the SciPy project. This site offers downloads,
203 subversion access, mailing lists and a bug tracking system. I am very
204 grateful to Enthought (http://www.enthought.com) and all of the SciPy
205 team for their contribution.
206
207 Installation
208 ============
209
210 Instant instructions
211 --------------------
212
213 If you are of the impatient kind, under Linux/Unix simply untar/unzip
214 the download, then install with 'python setup.py install'. Under
215 Windows, double-click on the provided .exe binary installer.
216
217 Then, take a look at Customization_ section for configuring things
218 optimally and `Quick tips`_ for quick tips on efficient use of
219 IPython. You can later refer to the rest of the manual for all the
220 gory details.
221
222 See the notes in upgrading_ section for upgrading IPython versions.
223
224
225 Detailed Unix instructions (Linux, Mac OS X, etc.)
226
227 For RPM based systems, simply install the supplied package in the usual
228 manner. If you download the tar archive, the process is:
229
230 1. Unzip/untar the ipython-XXX.tar.gz file wherever you want (XXX is
231 the version number). It will make a directory called ipython-XXX.
232 Change into that directory where you will find the files README
233 and setup.py. Once you've completed the installation, you can
234 safely remove this directory.
235 2. If you are installing over a previous installation of version
236 0.2.0 or earlier, first remove your $HOME/.ipython directory,
237 since the configuration file format has changed somewhat (the '='
238 were removed from all option specifications). Or you can call
239 ipython with the -upgrade option and it will do this automatically
240 for you.
241 3. IPython uses distutils, so you can install it by simply typing at
242 the system prompt (don't type the $)::
243
244 $ python setup.py install
245
246 Note that this assumes you have root access to your machine. If
247 you don't have root access or don't want IPython to go in the
248 default python directories, you'll need to use the ``--home`` option
249 (or ``--prefix``). For example::
250
251 $ python setup.py install --home $HOME/local
252
253 will install IPython into $HOME/local and its subdirectories
254 (creating them if necessary).
255 You can type::
256
257 $ python setup.py --help
258
259 for more details.
260
261 Note that if you change the default location for ``--home`` at
262 installation, IPython may end up installed at a location which is
263 not part of your $PYTHONPATH environment variable. In this case,
264 you'll need to configure this variable to include the actual
265 directory where the IPython/ directory ended (typically the value
266 you give to ``--home`` plus /lib/python).
267
268
269 Mac OSX information
270 -------------------
271
272 Under OSX, there is a choice you need to make. Apple ships its own build
273 of Python, which lives in the core OSX filesystem hierarchy. You can
274 also manually install a separate Python, either purely by hand
275 (typically in /usr/local) or by using Fink, which puts everything under
276 /sw. Which route to follow is a matter of personal preference, as I've
277 seen users who favor each of the approaches. Here I will simply list the
278 known installation issues under OSX, along with their solutions.
279
280 This page: http://geosci.uchicago.edu/~tobis/pylab.html contains
281 information on this topic, with additional details on how to make
282 IPython and matplotlib play nicely under OSX.
283
284 To run IPython and readline on OSX "Leopard" system python, see the
285 wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard
286
287
288 GUI problems
289 ------------
290
291 The following instructions apply to an install of IPython under OSX from
292 unpacking the .tar.gz distribution and installing it for the default
293 Python interpreter shipped by Apple. If you are using a fink install,
294 fink will take care of these details for you, by installing IPython
295 against fink's Python.
296
297 IPython offers various forms of support for interacting with graphical
298 applications from the command line, from simple Tk apps (which are in
299 principle always supported by Python) to interactive control of WX, Qt
300 and GTK apps. Under OSX, however, this requires that ipython is
301 installed by calling the special pythonw script at installation time,
302 which takes care of coordinating things with Apple's graphical environment.
303
304 So when installing under OSX, it is best to use the following command::
305
306 $ sudo pythonw setup.py install --install-scripts=/usr/local/bin
307
308 or
309
310 $ sudo pythonw setup.py install --install-scripts=/usr/bin
311
312 depending on where you like to keep hand-installed executables.
313
314 The resulting script will have an appropriate shebang line (the first
315 line in the script whic begins with #!...) such that the ipython
316 interpreter can interact with the OS X GUI. If the installed version
317 does not work and has a shebang line that points to, for example, just
318 /usr/bin/python, then you might have a stale, cached version in your
319 build/scripts-<python-version> directory. Delete that directory and
320 rerun the setup.py.
321
322 It is also a good idea to use the special flag ``--install-scripts`` as
323 indicated above, to ensure that the ipython scripts end up in a location
324 which is part of your $PATH. Otherwise Apple's Python will put the
325 scripts in an internal directory not available by default at the command
326 line (if you use /usr/local/bin, you need to make sure this is in your
327 $PATH, which may not be true by default).
328
329
330 Readline problems
331 -----------------
332
333 By default, the Python version shipped by Apple does not include the
334 readline library, so central to IPython's behavior. If you install
335 IPython against Apple's Python, you will not have arrow keys, tab
336 completion, etc. For Mac OSX 10.3 (Panther), you can find a prebuilt
337 readline library here:
338 http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip
339
340 If you are using OSX 10.4 (Tiger), after installing this package you
341 need to either:
342
343 1. move readline.so from /Library/Python/2.3 to
344 /Library/Python/2.3/site-packages, or
345 2. install http://pythonmac.org/packages/TigerPython23Compat.pkg.zip
346
347 Users installing against Fink's Python or a properly hand-built one
348 should not have this problem.
349
350
351 DarwinPorts
352 -----------
353
354 I report here a message from an OSX user, who suggests an alternative
355 means of using IPython under this operating system with good results.
356 Please let me know of any updates that may be useful for this section.
357 His message is reproduced verbatim below:
358
359 From: Markus Banfi <markus.banfi-AT-mospheira.net>
360
361 As a MacOS X (10.4.2) user I prefer to install software using
362 DawinPorts instead of Fink. I had no problems installing ipython
363 with DarwinPorts. It's just:
364
365 sudo port install py-ipython
366
367 It automatically resolved all dependencies (python24, readline,
368 py-readline). So far I did not encounter any problems with the
369 DarwinPorts port of ipython.
370
371
372
373 Windows instructions
374 --------------------
375
376 Some of IPython's very useful features are:
377
378 * Integrated readline support (Tab-based file, object and attribute
379 completion, input history across sessions, editable command line,
380 etc.)
381 * Coloring of prompts, code and tracebacks.
382
383 .. _pyreadline:
384
385 These, by default, are only available under Unix-like operating systems.
386 However, thanks to Gary Bishop's work, Windows XP/2k users can also
387 benefit from them. His readline library originally implemented both GNU
388 readline functionality and color support, so that IPython under Windows
389 XP/2k can be as friendly and powerful as under Unix-like environments.
390
391 This library, now named PyReadline, has been absorbed by the IPython
392 team (Jörgen Stenarson, in particular), and it continues to be developed
393 with new features, as well as being distributed directly from the
394 IPython site.
395
396 The PyReadline extension requires CTypes and the windows IPython
397 installer needs PyWin32, so in all you need:
398
399 1. PyWin32 from http://sourceforge.net/projects/pywin32.
400 2. PyReadline for Windows from
401 http://ipython.scipy.org/moin/PyReadline/Intro. That page contains
402 further details on using and configuring the system to your liking.
403 3. Finally, only if you are using Python 2.3 or 2.4, you need CTypes
404 from http://starship.python.net/crew/theller/ctypes(you must use
405 version 0.9.1 or newer). This package is included in Python 2.5,
406 so you don't need to manually get it if your Python version is 2.5
407 or newer.
408
409 Warning about a broken readline-like library: several users have
410 reported problems stemming from using the pseudo-readline library at
411 http://newcenturycomputers.net/projects/readline.html. This is a broken
412 library which, while called readline, only implements an incomplete
413 subset of the readline API. Since it is still called readline, it fools
414 IPython's detection mechanisms and causes unpredictable crashes later.
415 If you wish to use IPython under Windows, you must NOT use this library,
416 which for all purposes is (at least as of version 1.6) terminally broken.
417
418
419 Installation procedure
420 ----------------------
421
422 Once you have the above installed, from the IPython download directory
423 grab the ipython-XXX.win32.exe file, where XXX represents the version
424 number. This is a regular windows executable installer, which you can
425 simply double-click to install. It will add an entry for IPython to your
426 Start Menu, as well as registering IPython in the Windows list of
427 applications, so you can later uninstall it from the Control Panel.
428
429 IPython tries to install the configuration information in a directory
430 named .ipython (_ipython under Windows) located in your 'home'
431 directory. IPython sets this directory by looking for a HOME environment
432 variable; if such a variable does not exist, it uses HOMEDRIVE\HOMEPATH
433 (these are always defined by Windows). This typically gives something
434 like C:\Documents and Settings\YourUserName, but your local details may
435 vary. In this directory you will find all the files that configure
436 IPython's defaults, and you can put there your profiles and extensions.
437 This directory is automatically added by IPython to sys.path, so
438 anything you place there can be found by import statements.
439
440
441 Upgrading
442 ---------
443
444 For an IPython upgrade, you should first uninstall the previous version.
445 This will ensure that all files and directories (such as the
446 documentation) which carry embedded version strings in their names are
447 properly removed.
448
449
450 Manual installation under Win32
451 -------------------------------
452
453 In case the automatic installer does not work for some reason, you can
454 download the ipython-XXX.tar.gz file, which contains the full IPython
455 source distribution (the popular WinZip can read .tar.gz files). After
456 uncompressing the archive, you can install it at a command terminal just
457 like any other Python module, by using 'python setup.py install'.
458
459 After the installation, run the supplied win32_manual_post_install.py
460 script, which creates the necessary Start Menu shortcuts for you.
461
462
463 .. upgrading:
464
465 Upgrading from a previous version
466 ---------------------------------
467
468 If you are upgrading from a previous version of IPython, you may want
469 to upgrade the contents of your ~/.ipython directory. Just run
470 %upgrade, look at the diffs and delete the suggested files manually,
471 if you think you can lose the old versions. %upgrade will never
472 overwrite or delete anything.
473
474 Initial configuration of your environment
475 =========================================
476
477 This section will help you set various things in your environment for
478 your IPython sessions to be as efficient as possible. All of IPython's
479 configuration information, along with several example files, is stored
480 in a directory named by default $HOME/.ipython. You can change this by
481 defining the environment variable IPYTHONDIR, or at runtime with the
482 command line option -ipythondir.
483
484 If all goes well, the first time you run IPython it should
485 automatically create a user copy of the config directory for you,
486 based on its builtin defaults. You can look at the files it creates to
487 learn more about configuring the system. The main file you will modify
488 to configure IPython's behavior is called ipythonrc (with a .ini
489 extension under Windows), included for reference in `ipythonrc`_
490 section. This file is very commented and has many variables you can
491 change to suit your taste, you can find more details in
492 Sec. customization_. Here we discuss the basic things you will want to
493 make sure things are working properly from the beginning.
494
495
496 .. _Accessing help:
497
498 Access to the Python help system
499 --------------------------------
500
501 This is true for Python in general (not just for IPython): you should
502 have an environment variable called PYTHONDOCS pointing to the directory
503 where your HTML Python documentation lives. In my system it's
504 /usr/share/doc/python-docs-2.3.4/html, check your local details or ask
505 your systems administrator.
506
507 This is the directory which holds the HTML version of the Python
508 manuals. Unfortunately it seems that different Linux distributions
509 package these files differently, so you may have to look around a bit.
510 Below I show the contents of this directory on my system for reference::
511
512 [html]> ls
513 about.dat acks.html dist/ ext/ index.html lib/ modindex.html
514 stdabout.dat tut/ about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
515
516 You should really make sure this variable is correctly set so that
517 Python's pydoc-based help system works. It is a powerful and convenient
518 system with full access to the Python manuals and all modules accessible
519 to you.
520
521 Under Windows it seems that pydoc finds the documentation automatically,
522 so no extra setup appears necessary.
523
524
525 Editor
526 ------
527
528 The %edit command (and its alias %ed) will invoke the editor set in your
529 environment as EDITOR. If this variable is not set, it will default to
530 vi under Linux/Unix and to notepad under Windows. You may want to set
531 this variable properly and to a lightweight editor which doesn't take
532 too long to start (that is, something other than a new instance of
533 Emacs). This way you can edit multi-line code quickly and with the power
534 of a real editor right inside IPython.
535
536 If you are a dedicated Emacs user, you should set up the Emacs server so
537 that new requests are handled by the original process. This means that
538 almost no time is spent in handling the request (assuming an Emacs
539 process is already running). For this to work, you need to set your
540 EDITOR environment variable to 'emacsclient'. The code below, supplied
541 by Francois Pinard, can then be used in your .emacs file to enable the
542 server::
543
544 (defvar server-buffer-clients)
545 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
546 (server-start)
547 (defun fp-kill-server-with-buffer-routine ()
548 (and server-buffer-clients (server-done)))
549 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
550
551 You can also set the value of this editor via the commmand-line option
552 '-editor' or in your ipythonrc file. This is useful if you wish to use
553 specifically for IPython an editor different from your typical default
554 (and for Windows users who tend to use fewer environment variables).
555
556
557 Color
558 -----
559
560 The default IPython configuration has most bells and whistles turned on
561 (they're pretty safe). But there's one that may cause problems on some
562 systems: the use of color on screen for displaying information. This is
563 very useful, since IPython can show prompts and exception tracebacks
564 with various colors, display syntax-highlighted source code, and in
565 general make it easier to visually parse information.
566
567 The following terminals seem to handle the color sequences fine:
568
569 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
570 rxvt, xterm.
571 * CDE terminal (tested under Solaris). This one boldfaces light colors.
572 * (X)Emacs buffers. See the emacs_ section for more details on
573 using IPython with (X)Emacs.
574 * A Windows (XP/2k) command prompt with pyreadline_.
575 * A Windows (XP/2k) CygWin shell. Although some users have reported
576 problems; it is not clear whether there is an issue for everyone
577 or only under specific configurations. If you have full color
578 support under cygwin, please post to the IPython mailing list so
579 this issue can be resolved for all users.
580
581 These have shown problems:
582
583 * Windows command prompt in WinXP/2k logged into a Linux machine via
584 telnet or ssh.
585 * Windows native command prompt in WinXP/2k, without Gary Bishop's
586 extensions. Once Gary's readline library is installed, the normal
587 WinXP/2k command prompt works perfectly.
588
589 Currently the following color schemes are available:
590
591 * NoColor: uses no color escapes at all (all escapes are empty '' ''
592 strings). This 'scheme' is thus fully safe to use in any terminal.
593 * Linux: works well in Linux console type environments: dark
594 background with light fonts. It uses bright colors for
595 information, so it is difficult to read if you have a light
596 colored background.
597 * LightBG: the basic colors are similar to those in the Linux scheme
598 but darker. It is easy to read in terminals with light backgrounds.
599
600 IPython uses colors for two main groups of things: prompts and
601 tracebacks which are directly printed to the terminal, and the object
602 introspection system which passes large sets of data through a pager.
603
604
605 Input/Output prompts and exception tracebacks
606 ---------------------------------------------
607
608 You can test whether the colored prompts and tracebacks work on your
609 system interactively by typing '%colors Linux' at the prompt (use
610 '%colors LightBG' if your terminal has a light background). If the input
611 prompt shows garbage like::
612
613 [0;32mIn [[1;32m1[0;32m]: [0;00m
614
615 instead of (in color) something like::
616
617 In [1]:
618
619 this means that your terminal doesn't properly handle color escape
620 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
621
622 You can try using a different terminal emulator program (Emacs users,
623 see below). To permanently set your color preferences, edit the file
624 $HOME/.ipython/ipythonrc and set the colors option to the desired value.
625
626
627 Object details (types, docstrings, source code, etc.)
628 -----------------------------------------------------
629
630 IPython has a set of special functions for studying the objects you
631 are working with, discussed in detail in Sec. `dynamic object
632 information`_. But this system relies on passing information which is
633 longer than your screen through a data pager, such as the common Unix
634 less and more programs. In order to be able to see this information in
635 color, your pager needs to be properly configured. I strongly
636 recommend using less instead of more, as it seems that more simply can
637 not understand colored text correctly.
638
639 In order to configure less as your default pager, do the following:
640
641 1. Set the environment PAGER variable to less.
642 2. Set the environment LESS variable to -r (plus any other options
643 you always want to pass to less by default). This tells less to
644 properly interpret control sequences, which is how color
645 information is given to your terminal.
646
647 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
648
649 setenv PAGER less
650 setenv LESS -r
651
652 There is similar syntax for other Unix shells, look at your system
653 documentation for details.
654
655 If you are on a system which lacks proper data pagers (such as Windows),
656 IPython will use a very limited builtin pager.
657
658 .. _emacs:
659
660 (X)Emacs configuration
661 ----------------------
662
663 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
664 currently (X)Emacs and IPython get along very well.
665
666 Important note: You will need to use a recent enough version of
667 python-mode.el, along with the file ipython.el. You can check that the
668 version you have of python-mode.el is new enough by either looking at
669 the revision number in the file itself, or asking for it in (X)Emacs via
670 M-x py-version. Versions 4.68 and newer contain the necessary fixes for
671 proper IPython support.
672
673 The file ipython.el is included with the IPython distribution, in the
674 documentation directory (where this manual resides in PDF and HTML
675 formats).
676
677 Once you put these files in your Emacs path, all you need in your .emacs
678 file is::
679
680 (require 'ipython)
681
682 This should give you full support for executing code snippets via
683 IPython, opening IPython as your Python shell via C-c !, etc.
684
685 If you happen to get garbage instead of colored prompts as described in
686 the previous section, you may need to set also in your .emacs file::
687
688 (setq ansi-color-for-comint-mode t)
689
690
691 Notes:
692
693 * There is one caveat you should be aware of: you must start the
694 IPython shell before attempting to execute any code regions via
695 ``C-c |``. Simply type C-c ! to start IPython before passing any code
696 regions to the interpreter, and you shouldn't experience any
697 problems.
698 This is due to a bug in Python itself, which has been fixed for
699 Python 2.3, but exists as of Python 2.2.2 (reported as SF bug [
700 737947 ]).
701 * The (X)Emacs support is maintained by Alexander Schmolck, so all
702 comments/requests should be directed to him through the IPython
703 mailing lists.
704 * This code is still somewhat experimental so it's a bit rough
705 around the edges (although in practice, it works quite well).
706 * Be aware that if you customize py-python-command previously, this
707 value will override what ipython.el does (because loading the
708 customization variables comes later).
709
710 .. Quick tips:
711
712 Quick tips
713 ==========
714
715 IPython can be used as an improved replacement for the Python prompt,
716 and for that you don't really need to read any more of this manual. But
717 in this section we'll try to summarize a few tips on how to make the
718 most effective use of it for everyday Python development, highlighting
719 things you might miss in the rest of the manual (which is getting long).
720 We'll give references to parts in the manual which provide more detail
721 when appropriate.
722
723 The following article by Jeremy Jones provides an introductory tutorial
724 about IPython:
725 http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
726
727 * The TAB key. TAB-completion, especially for attributes, is a
728 convenient way to explore the structure of any object you're
729 dealing with. Simply type object_name.<TAB> and a list of the
730 object's attributes will be printed (see readline_ for
731 more). Tab completion also works on
732 file and directory names, which combined with IPython's alias
733 system allows you to do from within IPython many of the things you
734 normally would need the system shell for.
735 * Explore your objects. Typing object_name? will print all sorts of
736 details about any object, including docstrings, function
737 definition lines (for call arguments) and constructor details for
738 classes. The magic commands %pdoc, %pdef, %psource and %pfile will
739 respectively print the docstring, function definition line, full
740 source code and the complete file for any object (when they can be
741 found). If automagic is on (it is by default), you don't need to
742 type the '%' explicitly. See sec. `dynamic object information`_
743 for more.
744 * The %run magic command allows you to run any python script and
745 load all of its data directly into the interactive namespace.
746 Since the file is re-read from disk each time, changes you make to
747 it are reflected immediately (in contrast to the behavior of
748 import). I rarely use import for code I am testing, relying on
749 %run instead. See magic_ section for more on this
750 and other magic commands, or type the name of any magic command
751 and ? to get details on it. See also sec. dreload_ for a
752 recursive reload command.
753 %run also has special flags for timing the execution of your
754 scripts (-t) and for executing them under the control of either
755 Python's pdb debugger (-d) or profiler (-p). With all of these,
756 %run can be used as the main tool for efficient interactive
757 development of code which you write in your editor of choice.
758 * Use the Python debugger, pdb. The %pdb
759 command allows you to toggle on and off the automatic invocation
760 of an IPython-enhanced pdb debugger (with coloring, tab completion
761 and more) at any uncaught exception. The advantage of this is that
762 pdb starts inside the function where the exception occurred, with
763 all data still available. You can print variables, see code,
764 execute statements and even walk up and down the call stack to
765 track down the true source of the problem (which often is many
766 layers in the stack above where the exception gets triggered).
767 Running programs with %run and pdb active can be an efficient to
768 develop and debug code, in many cases eliminating the need for
769 print statements or external debugging tools. I often simply put a
770 1/0 in a place where I want to take a look so that pdb gets
771 called, quickly view whatever variables I need to or test various
772 pieces of code and then remove the 1/0.
773 Note also that '%run -d' activates pdb and automatically sets
774 initial breakpoints for you to step through your code, watch
775 variables, etc. See Sec. `Output caching`_ for
776 details.
777 * Use the output cache. All output results are automatically stored
778 in a global dictionary named Out and variables named _1, _2, etc.
779 alias them. For example, the result of input line 4 is available
780 either as Out[4] or as _4. Additionally, three variables named _,
781 __ and ___ are always kept updated with the for the last three
782 results. This allows you to recall any previous result and further
783 use it for new calculations. See Sec. `Output caching`_ for more.
784 * Put a ';' at the end of a line to supress the printing of output.
785 This is useful when doing calculations which generate long output
786 you are not interested in seeing. The _* variables and the Out[]
787 list do get updated with the contents of the output, even if it is
788 not printed. You can thus still access the generated results this
789 way for further processing.
790 * A similar system exists for caching input. All input is stored in
791 a global list called In , so you can re-execute lines 22 through
792 28 plus line 34 by typing 'exec In[22:29]+In[34]' (using Python
793 slicing notation). If you need to execute the same set of lines
794 often, you can assign them to a macro with the %macro function.
795 See sec. `Input caching`_ for more.
796 * Use your input history. The %hist command can show you all
797 previous input, without line numbers if desired (option -n) so you
798 can directly copy and paste code either back in IPython or in a
799 text editor. You can also save all your history by turning on
800 logging via %logstart; these logs can later be either reloaded as
801 IPython sessions or used as code for your programs.
802 * Define your own system aliases. Even though IPython gives you
803 access to your system shell via the ! prefix, it is convenient to
804 have aliases to the system commands you use most often. This
805 allows you to work seamlessly from inside IPython with the same
806 commands you are used to in your system shell.
807 IPython comes with some pre-defined aliases and a complete system
808 for changing directories, both via a stack (see %pushd, %popd and
809 %dhist) and via direct %cd. The latter keeps a history of visited
810 directories and allows you to go to any previously visited one.
811 * Use Python to manipulate the results of system commands. The '!!'
812 special syntax, and the %sc and %sx magic commands allow you to
813 capture system output into Python variables.
814 * Expand python variables when calling the shell (either via '!' and
815 '!!' or via aliases) by prepending a $ in front of them. You can
816 also expand complete python expressions. See
817 `System shell access`_ for more.
818 * Use profiles to maintain different configurations (modules to
819 load, function definitions, option settings) for particular tasks.
820 You can then have customized versions of IPython for specific
821 purposes. See sec. profiles_ for more.
822 * Embed IPython in your programs. A few lines of code are enough to
823 load a complete IPython inside your own programs, giving you the
824 ability to work with your data interactively after automatic
825 processing has been completed. See sec. embedding_
826 for more.
827 * Use the Python profiler. When dealing with performance issues, the
828 %run command with a -p option allows you to run complete programs
829 under the control of the Python profiler. The %prun command does a
830 similar job for single Python expressions (like function calls).
831 * Use the IPython.demo.Demo class to load any Python script as an
832 interactive demo. With a minimal amount of simple markup, you can
833 control the execution of the script, stopping as needed. See
834 sec. `interactive demos`_ for more.
835 * Run your doctests from within IPython for development and
836 debugging. The special %doctest_mode command toggles a mode where
837 the prompt, output and exceptions display matches as closely as
838 possible that of the default Python interpreter. In addition, this
839 mode allows you to directly paste in code that contains leading
840 '>>>' prompts, even if they have extra leading whitespace (as is
841 common in doctest files). This combined with the '%history -tn'
842 call to see your translated history (with these extra prompts
843 removed and no line numbers) allows for an easy doctest workflow,
844 where you can go from doctest to interactive execution to pasting
845 into valid Python code as needed.
846
847
848 Source code handling tips
849 -------------------------
850
851 IPython is a line-oriented program, without full control of the
852 terminal. Therefore, it doesn't support true multiline editing. However,
853 it has a number of useful tools to help you in dealing effectively with
854 more complex editing.
855
856 The %edit command gives a reasonable approximation of multiline editing,
857 by invoking your favorite editor on the spot. IPython will execute the
858 code you type in there as if it were typed interactively. Type %edit?
859 for the full details on the edit command.
860
861 If you have typed various commands during a session, which you'd like to
862 reuse, IPython provides you with a number of tools. Start by using %hist
863 to see your input history, so you can see the line numbers of all input.
864 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
865 and 28. All the commands below can operate on these with the syntax::
866
867 %command 10-20 24 28
868
869 where the command given can be:
870
871 * %macro <macroname>: this stores the lines into a variable which,
872 when called at the prompt, re-executes the input. Macros can be
873 edited later using '%edit macroname', and they can be stored
874 persistently across sessions with '%store macroname' (the storage
875 system is per-profile). The combination of quick macros,
876 persistent storage and editing, allows you to easily refine
877 quick-and-dirty interactive input into permanent utilities, always
878 available both in IPython and as files for general reuse.
879 * %edit: this will open a text editor with those lines pre-loaded
880 for further modification. It will then execute the resulting
881 file's contents as if you had typed it at the prompt.
882 * %save <filename>: this saves the lines directly to a named file on
883 disk.
884
885 While %macro saves input lines into memory for interactive re-execution,
886 sometimes you'd like to save your input directly to a file. The %save
887 magic does this: its input sytnax is the same as %macro, but it saves
888 your input directly to a Python file. Note that the %logstart command
889 also saves input, but it logs all input to disk (though you can
890 temporarily suspend it and reactivate it with %logoff/%logon); %save
891 allows you to select which lines of input you need to save.
892
893
894 Lightweight 'version control'
895 -----------------------------
896
897 When you call %edit with no arguments, IPython opens an empty editor
898 with a temporary file, and it returns the contents of your editing
899 session as a string variable. Thanks to IPython's output caching
900 mechanism, this is automatically stored::
901
902 In [1]: %edit
903
904 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
905
906 Editing... done. Executing edited code...
907
908 hello - this is a temporary file
909
910 Out[1]: "print 'hello - this is a temporary file'\n"
911
912 Now, if you call '%edit -p', IPython tries to open an editor with the
913 same data as the last time you used %edit. So if you haven't used %edit
914 in the meantime, this same contents will reopen; however, it will be
915 done in a new file. This means that if you make changes and you later
916 want to find an old version, you can always retrieve it by using its
917 output number, via '%edit _NN', where NN is the number of the output
918 prompt.
919
920 Continuing with the example above, this should illustrate this idea::
921
922 In [2]: edit -p
923
924 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
925
926 Editing... done. Executing edited code...
927
928 hello - now I made some changes
929
930 Out[2]: "print 'hello - now I made some changes'\n"
931
932 In [3]: edit _1
933
934 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
935
936 Editing... done. Executing edited code...
937
938 hello - this is a temporary file
939
940 IPython version control at work :)
941
942 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
943
944
945 This section was written after a contribution by Alexander Belchenko on
946 the IPython user list.
947
948
949 Effective logging
950 -----------------
951
952 A very useful suggestion sent in by Robert Kern follows:
953
954 I recently happened on a nifty way to keep tidy per-project log files. I
955 made a profile for my project (which is called "parkfield").
956
957 include ipythonrc
958
959 # cancel earlier logfile invocation:
960
961 logfile ''
962
963 execute import time
964
965 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
966
967 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
968
969 I also added a shell alias for convenience:
970
971 alias parkfield="ipython -pylab -profile parkfield"
972
973 Now I have a nice little directory with everything I ever type in,
974 organized by project and date.
975
976 Contribute your own: If you have your own favorite tip on using IPython
977 efficiently for a certain task (especially things which can't be done in
978 the normal Python interpreter), don't hesitate to send it!
979
980 .. _Command line options:
981
982 Command-line use
983 ================
984
985 You start IPython with the command::
986
987 $ ipython [options] files
988
989 If invoked with no options, it executes all the files listed in sequence
990 and drops you into the interpreter while still acknowledging any options
991 you may have set in your ipythonrc file. This behavior is different from
992 standard Python, which when called as python -i will only execute one
993 file and ignore your configuration setup.
994
995 Please note that some of the configuration options are not available at
996 the command line, simply because they are not practical here. Look into
997 your ipythonrc configuration file for details on those. This file
998 typically installed in the $HOME/.ipython directory. For Windows users,
999 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
1000 instances. In the rest of this text, we will refer to this directory as
1001 IPYTHONDIR.
1002
1003 .. _Threading options:
1004
1005
1006 Special Threading Options
1007 -------------------------
1008
1009 The following special options are ONLY valid at the beginning of the
1010 command line, and not later. This is because they control the initial-
1011 ization of ipython itself, before the normal option-handling mechanism
1012 is active.
1013
1014 -gthread, -qthread, -q4thread, -wthread, -pylab:
1015 Only one of these can be given, and it can only be given as
1016 the first option passed to IPython (it will have no effect in
1017 any other position). They provide threading support for the
1018 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
1019 matplotlib library.
1020
1021 With any of the first four options, IPython starts running a
1022 separate thread for the graphical toolkit's operation, so that
1023 you can open and control graphical elements from within an
1024 IPython command line, without blocking. All four provide
1025 essentially the same functionality, respectively for GTK, Qt3,
1026 Qt4 and WXWidgets (via their Python interfaces).
1027
1028 Note that with -wthread, you can additionally use the
1029 -wxversion option to request a specific version of wx to be
1030 used. This requires that you have the wxversion Python module
1031 installed, which is part of recent wxPython distributions.
1032
1033 If -pylab is given, IPython loads special support for the mat
1034 plotlib library (http://matplotlib.sourceforge.net), allowing
1035 interactive usage of any of its backends as defined in the
1036 user's ~/.matplotlib/matplotlibrc file. It automatically
1037 activates GTK, Qt or WX threading for IPyhton if the choice of
1038 matplotlib backend requires it. It also modifies the %run
1039 command to correctly execute (without blocking) any
1040 matplotlib-based script which calls show() at the end.
1041
1042 -tk
1043 The -g/q/q4/wthread options, and -pylab (if matplotlib is
1044 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
1045 graphical interfaces. This means that when either GTK, Qt or WX
1046 threading is active, any attempt to open a Tk GUI will result in a
1047 dead window, and possibly cause the Python interpreter to crash.
1048 An extra option, -tk, is available to address this issue. It can
1049 only be given as a second option after any of the above (-gthread,
1050 -wthread or -pylab).
1051
1052 If -tk is given, IPython will try to coordinate Tk threading
1053 with GTK, Qt or WX. This is however potentially unreliable, and
1054 you will have to test on your platform and Python configuration to
1055 determine whether it works for you. Debian users have reported
1056 success, apparently due to the fact that Debian builds all of Tcl,
1057 Tk, Tkinter and Python with pthreads support. Under other Linux
1058 environments (such as Fedora Core 2/3), this option has caused
1059 random crashes and lockups of the Python interpreter. Under other
1060 operating systems (Mac OSX and Windows), you'll need to try it to
1061 find out, since currently no user reports are available.
1062
1063 There is unfortunately no way for IPython to determine at run time
1064 whether -tk will work reliably or not, so you will need to do some
1065 experiments before relying on it for regular work.
1066
1067
1068
1069 Regular Options
1070 ---------------
1071
1072 After the above threading options have been given, regular options can
1073 follow in any order. All options can be abbreviated to their shortest
1074 non-ambiguous form and are case-sensitive. One or two dashes can be
1075 used. Some options have an alternate short form, indicated after a ``|``.
1076
1077 Most options can also be set from your ipythonrc configuration file. See
1078 the provided example for more details on what the options do. Options
1079 given at the command line override the values set in the ipythonrc file.
1080
1081 All options with a [no] prepended can be specified in negated form
1082 (-nooption instead of -option) to turn the feature off.
1083
1084 -help print a help message and exit.
1085
1086 -pylab
1087 this can only be given as the first option passed to IPython
1088 (it will have no effect in any other position). It adds
1089 special support for the matplotlib library
1090 (http://matplotlib.sourceforge.ne), allowing interactive usage
1091 of any of its backends as defined in the user's .matplotlibrc
1092 file. It automatically activates GTK or WX threading for
1093 IPyhton if the choice of matplotlib backend requires it. It
1094 also modifies the %run command to correctly execute (without
1095 blocking) any matplotlib-based script which calls show() at
1096 the end. See `Matplotlib support`_ for more details.
1097
1098 -autocall <val>
1099 Make IPython automatically call any callable object even if you
1100 didn't type explicit parentheses. For example, 'str 43' becomes
1101 'str(43)' automatically. The value can be '0' to disable the feature,
1102 '1' for smart autocall, where it is not applied if there are no more
1103 arguments on the line, and '2' for full autocall, where all callable
1104 objects are automatically called (even if no arguments are
1105 present). The default is '1'.
1106
1107 -[no]autoindent
1108 Turn automatic indentation on/off.
1109
1110 -[no]automagic
1111 make magic commands automatic (without needing their first character
1112 to be %). Type %magic at the IPython prompt for more information.
1113
1114 -[no]autoedit_syntax
1115 When a syntax error occurs after editing a file, automatically
1116 open the file to the trouble causing line for convenient
1117 fixing.
1118
1119 -[no]banner Print the initial information banner (default on).
1120
1121 -c <command>
1122 execute the given command string. This is similar to the -c
1123 option in the normal Python interpreter.
1124
1125 -cache_size, cs <n>
1126 size of the output cache (maximum number of entries to hold in
1127 memory). The default is 1000, you can change it permanently in your
1128 config file. Setting it to 0 completely disables the caching system,
1129 and the minimum value accepted is 20 (if you provide a value less than
1130 20, it is reset to 0 and a warning is issued) This limit is defined
1131 because otherwise you'll spend more time re-flushing a too small cache
1132 than working.
1133
1134 -classic, cl
1135 Gives IPython a similar feel to the classic Python
1136 prompt.
1137
1138 -colors <scheme>
1139 Color scheme for prompts and exception reporting. Currently
1140 implemented: NoColor, Linux and LightBG.
1141
1142 -[no]color_info
1143 IPython can display information about objects via a set of functions,
1144 and optionally can use colors for this, syntax highlighting source
1145 code and various other elements. However, because this information is
1146 passed through a pager (like 'less') and many pagers get confused with
1147 color codes, this option is off by default. You can test it and turn
1148 it on permanently in your ipythonrc file if it works for you. As a
1149 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
1150 that in RedHat 7.2 doesn't.
1151
1152 Test it and turn it on permanently if it works with your
1153 system. The magic function %color_info allows you to toggle this
1154 interactively for testing.
1155
1156 -[no]debug
1157 Show information about the loading process. Very useful to pin down
1158 problems with your configuration files or to get details about
1159 session restores.
1160
1161 -[no]deep_reload:
1162 IPython can use the deep_reload module which reloads changes in
1163 modules recursively (it replaces the reload() function, so you don't
1164 need to change anything to use it). deep_reload() forces a full
1165 reload of modules whose code may have changed, which the default
1166 reload() function does not.
1167
1168 When deep_reload is off, IPython will use the normal reload(),
1169 but deep_reload will still be available as dreload(). This
1170 feature is off by default [which means that you have both
1171 normal reload() and dreload()].
1172
1173 -editor <name>
1174 Which editor to use with the %edit command. By default,
1175 IPython will honor your EDITOR environment variable (if not
1176 set, vi is the Unix default and notepad the Windows one).
1177 Since this editor is invoked on the fly by IPython and is
1178 meant for editing small code snippets, you may want to use a
1179 small, lightweight editor here (in case your default EDITOR is
1180 something like Emacs).
1181
1182 -ipythondir <name>
1183 name of your IPython configuration directory IPYTHONDIR. This
1184 can also be specified through the environment variable
1185 IPYTHONDIR.
1186
1187 -log, l
1188 generate a log file of all input. The file is named
1189 ipython_log.py in your current directory (which prevents logs
1190 from multiple IPython sessions from trampling each other). You
1191 can use this to later restore a session by loading your
1192 logfile as a file to be executed with option -logplay (see
1193 below).
1194
1195 -logfile, lf <name> specify the name of your logfile.
1196
1197 -logplay, lp <name>
1198
1199 you can replay a previous log. For restoring a session as close as
1200 possible to the state you left it in, use this option (don't just run
1201 the logfile). With -logplay, IPython will try to reconstruct the
1202 previous working environment in full, not just execute the commands in
1203 the logfile.
1204
1205 When a session is restored, logging is automatically turned on
1206 again with the name of the logfile it was invoked with (it is
1207 read from the log header). So once you've turned logging on for
1208 a session, you can quit IPython and reload it as many times as
1209 you want and it will continue to log its history and restore
1210 from the beginning every time.
1211
1212 Caveats: there are limitations in this option. The history
1213 variables _i*,_* and _dh don't get restored properly. In the
1214 future we will try to implement full session saving by writing
1215 and retrieving a 'snapshot' of the memory state of IPython. But
1216 our first attempts failed because of inherent limitations of
1217 Python's Pickle module, so this may have to wait.
1218
1219 -[no]messages
1220 Print messages which IPython collects about its startup
1221 process (default on).
1222
1223 -[no]pdb
1224 Automatically call the pdb debugger after every uncaught
1225 exception. If you are used to debugging using pdb, this puts
1226 you automatically inside of it after any call (either in
1227 IPython or in code called by it) which triggers an exception
1228 which goes uncaught.
1229
1230 -[no]pprint
1231 ipython can optionally use the pprint (pretty printer) module
1232 for displaying results. pprint tends to give a nicer display
1233 of nested data structures. If you like it, you can turn it on
1234 permanently in your config file (default off).
1235
1236 -profile, p <name>
1237
1238 assume that your config file is ipythonrc-<name> or
1239 ipy_profile_<name>.py (looks in current dir first, then in
1240 IPYTHONDIR). This is a quick way to keep and load multiple
1241 config files for different tasks, especially if you use the
1242 include option of config files. You can keep a basic
1243 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
1244 include this one and load extra things for particular
1245 tasks. For example:
1246
1247 1. $HOME/.ipython/ipythonrc : load basic things you always want.
1248 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
1249 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
1250
1251 Since it is possible to create an endless loop by having
1252 circular file inclusions, IPython will stop if it reaches 15
1253 recursive inclusions.
1254
1255 -prompt_in1, pi1 <string>
1256 Specify the string used for input prompts. Note that if you
1257 are using numbered prompts, the number is represented with a
1258 '\#' in the string. Don't forget to quote strings with spaces
1259 embedded in them. Default: 'In [\#]:'. Sec. Prompts_
1260 discusses in detail all the available escapes to customize
1261 your prompts.
1262
1263 -prompt_in2, pi2 <string>
1264 Similar to the previous option, but used for the continuation
1265 prompts. The special sequence '\D' is similar to '\#', but
1266 with all digits replaced dots (so you can have your
1267 continuation prompt aligned with your input prompt). Default:
1268 ' .\D.:' (note three spaces at the start for alignment with
1269 'In [\#]').
1270
1271 -prompt_out,po <string>
1272 String used for output prompts, also uses numbers like
1273 prompt_in1. Default: 'Out[\#]:'
1274
1275 -quick start in bare bones mode (no config file loaded).
1276
1277 -rcfile <name>
1278 name of your IPython resource configuration file. Normally
1279 IPython loads ipythonrc (from current directory) or
1280 IPYTHONDIR/ipythonrc.
1281
1282 If the loading of your config file fails, IPython starts with
1283 a bare bones configuration (no modules loaded at all).
1284
1285 -[no]readline
1286 use the readline library, which is needed to support name
1287 completion and command history, among other things. It is
1288 enabled by default, but may cause problems for users of
1289 X/Emacs in Python comint or shell buffers.
1290
1291 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
1292 IPython's readline and syntax coloring fine, only 'emacs' (M-x
1293 shell and C-c !) buffers do not.
1294
1295 -screen_length, sl <n>
1296 number of lines of your screen. This is used to control
1297 printing of very long strings. Strings longer than this number
1298 of lines will be sent through a pager instead of directly
1299 printed.
1300
1301 The default value for this is 0, which means IPython will
1302 auto-detect your screen size every time it needs to print certain
1303 potentially long strings (this doesn't change the behavior of the
1304 'print' keyword, it's only triggered internally). If for some
1305 reason this isn't working well (it needs curses support), specify
1306 it yourself. Otherwise don't change the default.
1307
1308 -separate_in, si <string>
1309
1310 separator before input prompts.
1311 Default: '\n'
1312
1313 -separate_out, so <string>
1314 separator before output prompts.
1315 Default: nothing.
1316
1317 -separate_out2, so2
1318 separator after output prompts.
1319 Default: nothing.
1320 For these three options, use the value 0 to specify no separator.
1321
1322 -nosep
1323 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
1324 0'. Simply removes all input/output separators.
1325
1326 -upgrade
1327 allows you to upgrade your IPYTHONDIR configuration when you
1328 install a new version of IPython. Since new versions may
1329 include new command line options or example files, this copies
1330 updated ipythonrc-type files. However, it backs up (with a
1331 .old extension) all files which it overwrites so that you can
1332 merge back any customizations you might have in your personal
1333 files. Note that you should probably use %upgrade instead,
1334 it's a safer alternative.
1335
1336
1337 -Version print version information and exit.
1338
1339 -wxversion <string>
1340 Select a specific version of wxPython (used in conjunction
1341 with -wthread). Requires the wxversion module, part of recent
1342 wxPython distributions
1343
1344 -xmode <modename>
1345
1346 Mode for exception reporting.
1347
1348 Valid modes: Plain, Context and Verbose.
1349
1350 * Plain: similar to python's normal traceback printing.
1351 * Context: prints 5 lines of context source code around each
1352 line in the traceback.
1353 * Verbose: similar to Context, but additionally prints the
1354 variables currently visible where the exception happened
1355 (shortening their strings if too long). This can potentially be
1356 very slow, if you happen to have a huge data structure whose
1357 string representation is complex to compute. Your computer may
1358 appear to freeze for a while with cpu usage at 100%. If this
1359 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
1360 more than once).
1361
1362 Interactive use
1363 ===============
1364
1365 Warning: IPython relies on the existence of a global variable called
1366 _ip which controls the shell itself. If you redefine _ip to anything,
1367 bizarre behavior will quickly occur.
1368
1369 Other than the above warning, IPython is meant to work as a drop-in
1370 replacement for the standard interactive interpreter. As such, any code
1371 which is valid python should execute normally under IPython (cases where
1372 this is not true should be reported as bugs). It does, however, offer
1373 many features which are not available at a standard python prompt. What
1374 follows is a list of these.
1375
1376
1377 Caution for Windows users
1378 -------------------------
1379
1380 Windows, unfortunately, uses the '\' character as a path
1381 separator. This is a terrible choice, because '\' also represents the
1382 escape character in most modern programming languages, including
1383 Python. For this reason, using '/' character is recommended if you
1384 have problems with ``\``. However, in Windows commands '/' flags
1385 options, so you can not use it for the root directory. This means that
1386 paths beginning at the root must be typed in a contrived manner like:
1387 ``%copy \opt/foo/bar.txt \tmp``
1388
1389 .. _magic:
1390
1391 Magic command system
1392 --------------------
1393
1394 IPython will treat any line whose first character is a % as a special
1395 call to a 'magic' function. These allow you to control the behavior of
1396 IPython itself, plus a lot of system-type features. They are all
1397 prefixed with a % character, but parameters are given without
1398 parentheses or quotes.
1399
1400 Example: typing '%cd mydir' (without the quotes) changes you working
1401 directory to 'mydir', if it exists.
1402
1403 If you have 'automagic' enabled (in your ipythonrc file, via the command
1404 line option -automagic or with the %automagic function), you don't need
1405 to type in the % explicitly. IPython will scan its internal list of
1406 magic functions and call one if it exists. With automagic on you can
1407 then just type 'cd mydir' to go to directory 'mydir'. The automagic
1408 system has the lowest possible precedence in name searches, so defining
1409 an identifier with the same name as an existing magic function will
1410 shadow it for automagic use. You can still access the shadowed magic
1411 function by explicitly using the % character at the beginning of the line.
1412
1413 An example (with automagic on) should clarify all this::
1414
1415 In [1]: cd ipython # %cd is called by automagic
1416
1417 /home/fperez/ipython
1418
1419 In [2]: cd=1 # now cd is just a variable
1420
1421 In [3]: cd .. # and doesn't work as a function anymore
1422
1423 ------------------------------
1424
1425 File "<console>", line 1
1426
1427 cd ..
1428
1429 ^
1430
1431 SyntaxError: invalid syntax
1432
1433 In [4]: %cd .. # but %cd always works
1434
1435 /home/fperez
1436
1437 In [5]: del cd # if you remove the cd variable
1438
1439 In [6]: cd ipython # automagic can work again
1440
1441 /home/fperez/ipython
1442
1443 You can define your own magic functions to extend the system. The
1444 following example defines a new magic command, %impall::
1445
1446 import IPython.ipapi
1447
1448 ip = IPython.ipapi.get()
1449
1450 def doimp(self, arg):
1451
1452 ip = self.api
1453
1454 ip.ex("import %s; reload(%s); from %s import *" % (
1455
1456 arg,arg,arg)
1457
1458 )
1459
1460 ip.expose_magic('impall', doimp)
1461
1462 You can also define your own aliased names for magic functions. In your
1463 ipythonrc file, placing a line like:
1464
1465 execute __IP.magic_cl = __IP.magic_clear
1466
1467 will define %cl as a new name for %clear.
1468
1469 Type %magic for more information, including a list of all available
1470 magic functions at any time and their docstrings. You can also type
1471 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
1472 information on the '?' system) to get information about any particular
1473 magic function you are interested in.
1474
1475
1476 Magic commands
1477 --------------
1478
1479 The rest of this section is automatically generated for each release
1480 from the docstrings in the IPython code. Therefore the formatting is
1481 somewhat minimal, but this method has the advantage of having
1482 information always in sync with the code.
1483
1484 A list of all the magic commands available in IPython's default
1485 installation follows. This is similar to what you'll see by simply
1486 typing %magic at the prompt, but that will also give you information
1487 about magic commands you may have added as part of your personal
1488 customizations.
1489
1490 .. magic_start
1491
1492 **%Exit**::
1493
1494 Exit IPython without confirmation.
1495
1496 **%Pprint**::
1497
1498 Toggle pretty printing on/off.
1499
1500 **%alias**::
1501
1502 Define an alias for a system command.
1503
1504 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1505
1506 Then, typing 'alias_name params' will execute the system command 'cmd
1507 params' (from your underlying operating system).
1508
1509 Aliases have lower precedence than magic functions and Python normal
1510 variables, so if 'foo' is both a Python variable and an alias, the
1511 alias can not be executed until 'del foo' removes the Python variable.
1512
1513 You can use the %l specifier in an alias definition to represent the
1514 whole line when the alias is called. For example:
1515
1516 In [2]: alias all echo "Input in brackets: <%l>"\
1517 In [3]: all hello world\
1518 Input in brackets: <hello world>
1519
1520 You can also define aliases with parameters using %s specifiers (one
1521 per parameter):
1522
1523 In [1]: alias parts echo first %s second %s\
1524 In [2]: %parts A B\
1525 first A second B\
1526 In [3]: %parts A\
1527 Incorrect number of arguments: 2 expected.\
1528 parts is an alias to: 'echo first %s second %s'
1529
1530 Note that %l and %s are mutually exclusive. You can only use one or
1531 the other in your aliases.
1532
1533 Aliases expand Python variables just like system calls using ! or !!
1534 do: all expressions prefixed with '$' get expanded. For details of
1535 the semantic rules, see PEP-215:
1536 http://www.python.org/peps/pep-0215.html. This is the library used by
1537 IPython for variable expansion. If you want to access a true shell
1538 variable, an extra $ is necessary to prevent its expansion by IPython:
1539
1540 In [6]: alias show echo\
1541 In [7]: PATH='A Python string'\
1542 In [8]: show $PATH\
1543 A Python string\
1544 In [9]: show $$PATH\
1545 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1546
1547 You can use the alias facility to acess all of $PATH. See the %rehash
1548 and %rehashx functions, which automatically create aliases for the
1549 contents of your $PATH.
1550
1551 If called with no parameters, %alias prints the current alias table.
1552
1553 **%autocall**::
1554
1555 Make functions callable without having to type parentheses.
1556
1557 Usage:
1558
1559 %autocall [mode]
1560
1561 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1562 value is toggled on and off (remembering the previous state).
1563
1564 In more detail, these values mean:
1565
1566 0 -> fully disabled
1567
1568 1 -> active, but do not apply if there are no arguments on the line.
1569
1570 In this mode, you get:
1571
1572 In [1]: callable
1573 Out[1]: <built-in function callable>
1574
1575 In [2]: callable 'hello'
1576 ------> callable('hello')
1577 Out[2]: False
1578
1579 2 -> Active always. Even if no arguments are present, the callable
1580 object is called:
1581
1582 In [4]: callable
1583 ------> callable()
1584
1585 Note that even with autocall off, you can still use '/' at the start of
1586 a line to treat the first argument on the command line as a function
1587 and add parentheses to it:
1588
1589 In [8]: /str 43
1590 ------> str(43)
1591 Out[8]: '43'
1592
1593 **%autoindent**::
1594
1595 Toggle autoindent on/off (if available).
1596
1597 **%automagic**::
1598
1599 Make magic functions callable without having to type the initial %.
1600
1601 Without argumentsl toggles on/off (when off, you must call it as
1602 %automagic, of course). With arguments it sets the value, and you can
1603 use any of (case insensitive):
1604
1605 - on,1,True: to activate
1606
1607 - off,0,False: to deactivate.
1608
1609 Note that magic functions have lowest priority, so if there's a
1610 variable whose name collides with that of a magic fn, automagic won't
1611 work for that function (you get the variable instead). However, if you
1612 delete the variable (del var), the previously shadowed magic function
1613 becomes visible to automagic again.
1614
1615 **%bg**::
1616
1617 Run a job in the background, in a separate thread.
1618
1619 For example,
1620
1621 %bg myfunc(x,y,z=1)
1622
1623 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1624 execution starts, a message will be printed indicating the job
1625 number. If your job number is 5, you can use
1626
1627 myvar = jobs.result(5) or myvar = jobs[5].result
1628
1629 to assign this result to variable 'myvar'.
1630
1631 IPython has a job manager, accessible via the 'jobs' object. You can
1632 type jobs? to get more information about it, and use jobs.<TAB> to see
1633 its attributes. All attributes not starting with an underscore are
1634 meant for public use.
1635
1636 In particular, look at the jobs.new() method, which is used to create
1637 new jobs. This magic %bg function is just a convenience wrapper
1638 around jobs.new(), for expression-based jobs. If you want to create a
1639 new job with an explicit function object and arguments, you must call
1640 jobs.new() directly.
1641
1642 The jobs.new docstring also describes in detail several important
1643 caveats associated with a thread-based model for background job
1644 execution. Type jobs.new? for details.
1645
1646 You can check the status of all jobs with jobs.status().
1647
1648 The jobs variable is set by IPython into the Python builtin namespace.
1649 If you ever declare a variable named 'jobs', you will shadow this
1650 name. You can either delete your global jobs variable to regain
1651 access to the job manager, or make a new name and assign it manually
1652 to the manager (stored in IPython's namespace). For example, to
1653 assign the job manager to the Jobs name, use:
1654
1655 Jobs = __builtins__.jobs
1656
1657 **%bookmark**::
1658
1659 Manage IPython's bookmark system.
1660
1661 %bookmark <name> - set bookmark to current dir
1662 %bookmark <name> <dir> - set bookmark to <dir>
1663 %bookmark -l - list all bookmarks
1664 %bookmark -d <name> - remove bookmark
1665 %bookmark -r - remove all bookmarks
1666
1667 You can later on access a bookmarked folder with:
1668 %cd -b <name>
1669 or simply '%cd <name>' if there is no directory called <name> AND
1670 there is such a bookmark defined.
1671
1672 Your bookmarks persist through IPython sessions, but they are
1673 associated with each profile.
1674
1675 **%cd**::
1676
1677 Change the current working directory.
1678
1679 This command automatically maintains an internal list of directories
1680 you visit during your IPython session, in the variable _dh. The
1681 command %dhist shows this history nicely formatted. You can also
1682 do 'cd -<tab>' to see directory history conveniently.
1683
1684 Usage:
1685
1686 cd 'dir': changes to directory 'dir'.
1687
1688 cd -: changes to the last visited directory.
1689
1690 cd -<n>: changes to the n-th directory in the directory history.
1691
1692 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
1693 (note: cd <bookmark_name> is enough if there is no
1694 directory <bookmark_name>, but a bookmark with the name exists.)
1695 'cd -b <tab>' allows you to tab-complete bookmark names.
1696
1697 Options:
1698
1699 -q: quiet. Do not print the working directory after the cd command is
1700 executed. By default IPython's cd command does print this directory,
1701 since the default prompts do not display path information.
1702
1703 Note that !cd doesn't work for this purpose because the shell where
1704 !command runs is immediately discarded after executing 'command'.
1705
1706 **%clear**::
1707
1708 Clear various data (e.g. stored history data)
1709
1710 %clear out - clear output history
1711 %clear in - clear input history
1712 %clear shadow_compress - Compresses shadow history (to speed up ipython)
1713 %clear shadow_nuke - permanently erase all entries in shadow history
1714 %clear dhist - clear dir history
1715
1716 **%color_info**::
1717
1718 Toggle color_info.
1719
1720 The color_info configuration parameter controls whether colors are
1721 used for displaying object details (by things like %psource, %pfile or
1722 the '?' system). This function toggles this value with each call.
1723
1724 Note that unless you have a fairly recent pager (less works better
1725 than more) in your system, using colored object information displays
1726 will not work properly. Test it and see.
1727
1728 **%colors**::
1729
1730 Switch color scheme for prompts, info system and exception handlers.
1731
1732 Currently implemented schemes: NoColor, Linux, LightBG.
1733
1734 Color scheme names are not case-sensitive.
1735
1736 **%cpaste**::
1737
1738 Allows you to paste & execute a pre-formatted code block from clipboard
1739
1740 You must terminate the block with '--' (two minus-signs) alone on the
1741 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1742 is the new sentinel for this operation)
1743
1744 The block is dedented prior to execution to enable execution of method
1745 definitions. '>' and '+' characters at the beginning of a line are
1746 ignored, to allow pasting directly from e-mails or diff files. The
1747 executed block is also assigned to variable named 'pasted_block' for
1748 later editing with '%edit pasted_block'.
1749
1750 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1751 This assigns the pasted block to variable 'foo' as string, without
1752 dedenting or executing it.
1753
1754 Do not be alarmed by garbled output on Windows (it's a readline bug).
1755 Just press enter and type -- (and press enter again) and the block
1756 will be what was just pasted.
1757
1758 IPython statements (magics, shell escapes) are not supported (yet).
1759
1760 **%debug**::
1761
1762 Activate the interactive debugger in post-mortem mode.
1763
1764 If an exception has just occurred, this lets you inspect its stack
1765 frames interactively. Note that this will always work only on the last
1766 traceback that occurred, so you must call this quickly after an
1767 exception that you wish to inspect has fired, because if another one
1768 occurs, it clobbers the previous one.
1769
1770 If you want IPython to automatically do this on every exception, see
1771 the %pdb magic for more details.
1772
1773 **%dhist**::
1774
1775 Print your history of visited directories.
1776
1777 %dhist -> print full history\
1778 %dhist n -> print last n entries only\
1779 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
1780
1781 This history is automatically maintained by the %cd command, and
1782 always available as the global list variable _dh. You can use %cd -<n>
1783 to go to directory number <n>.
1784
1785 Note that most of time, you should view directory history by entering
1786 cd -<TAB>.
1787
1788 **%dirs**::
1789
1790 Return the current directory stack.
1791
1792 **%doctest_mode**::
1793
1794 Toggle doctest mode on and off.
1795
1796 This mode allows you to toggle the prompt behavior between normal
1797 IPython prompts and ones that are as similar to the default IPython
1798 interpreter as possible.
1799
1800 It also supports the pasting of code snippets that have leading '>>>'
1801 and '...' prompts in them. This means that you can paste doctests from
1802 files or docstrings (even if they have leading whitespace), and the
1803 code will execute correctly. You can then use '%history -tn' to see
1804 the translated history without line numbers; this will give you the
1805 input after removal of all the leading prompts and whitespace, which
1806 can be pasted back into an editor.
1807
1808 With these features, you can switch into this mode easily whenever you
1809 need to do testing and changes to doctests, without having to leave
1810 your existing IPython session.
1811
1812 **%ed**::
1813
1814 Alias to %edit.
1815
1816 **%edit**::
1817
1818 Bring up an editor and execute the resulting code.
1819
1820 Usage:
1821 %edit [options] [args]
1822
1823 %edit runs IPython's editor hook. The default version of this hook is
1824 set to call the __IPYTHON__.rc.editor command. This is read from your
1825 environment variable $EDITOR. If this isn't found, it will default to
1826 vi under Linux/Unix and to notepad under Windows. See the end of this
1827 docstring for how to change the editor hook.
1828
1829 You can also set the value of this editor via the command line option
1830 '-editor' or in your ipythonrc file. This is useful if you wish to use
1831 specifically for IPython an editor different from your typical default
1832 (and for Windows users who typically don't set environment variables).
1833
1834 This command allows you to conveniently edit multi-line code right in
1835 your IPython session.
1836
1837 If called without arguments, %edit opens up an empty editor with a
1838 temporary file and will execute the contents of this file when you
1839 close it (don't forget to save it!).
1840
1841
1842 Options:
1843
1844 -n <number>: open the editor at a specified line number. By default,
1845 the IPython editor hook uses the unix syntax 'editor +N filename', but
1846 you can configure this by providing your own modified hook if your
1847 favorite editor supports line-number specifications with a different
1848 syntax.
1849
1850 -p: this will call the editor with the same data as the previous time
1851 it was used, regardless of how long ago (in your current session) it
1852 was.
1853
1854 -r: use 'raw' input. This option only applies to input taken from the
1855 user's history. By default, the 'processed' history is used, so that
1856 magics are loaded in their transformed version to valid Python. If
1857 this option is given, the raw input as typed as the command line is
1858 used instead. When you exit the editor, it will be executed by
1859 IPython's own processor.
1860
1861 -x: do not execute the edited code immediately upon exit. This is
1862 mainly useful if you are editing programs which need to be called with
1863 command line arguments, which you can then do using %run.
1864
1865
1866 Arguments:
1867
1868 If arguments are given, the following possibilites exist:
1869
1870 - The arguments are numbers or pairs of colon-separated numbers (like
1871 1 4:8 9). These are interpreted as lines of previous input to be
1872 loaded into the editor. The syntax is the same of the %macro command.
1873
1874 - If the argument doesn't start with a number, it is evaluated as a
1875 variable and its contents loaded into the editor. You can thus edit
1876 any string which contains python code (including the result of
1877 previous edits).
1878
1879 - If the argument is the name of an object (other than a string),
1880 IPython will try to locate the file where it was defined and open the
1881 editor at the point where it is defined. You can use `%edit function`
1882 to load an editor exactly at the point where 'function' is defined,
1883 edit it and have the file be executed automatically.
1884
1885 If the object is a macro (see %macro for details), this opens up your
1886 specified editor with a temporary file containing the macro's data.
1887 Upon exit, the macro is reloaded with the contents of the file.
1888
1889 Note: opening at an exact line is only supported under Unix, and some
1890 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1891 '+NUMBER' parameter necessary for this feature. Good editors like
1892 (X)Emacs, vi, jed, pico and joe all do.
1893
1894 - If the argument is not found as a variable, IPython will look for a
1895 file with that name (adding .py if necessary) and load it into the
1896 editor. It will execute its contents with execfile() when you exit,
1897 loading any code in the file into your interactive namespace.
1898
1899 After executing your code, %edit will return as output the code you
1900 typed in the editor (except when it was an existing file). This way
1901 you can reload the code in further invocations of %edit as a variable,
1902 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1903 the output.
1904
1905 Note that %edit is also available through the alias %ed.
1906
1907 This is an example of creating a simple function inside the editor and
1908 then modifying it. First, start up the editor:
1909
1910 In [1]: ed\
1911 Editing... done. Executing edited code...\
1912 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1913
1914 We can then call the function foo():
1915
1916 In [2]: foo()\
1917 foo() was defined in an editing session
1918
1919 Now we edit foo. IPython automatically loads the editor with the
1920 (temporary) file where foo() was previously defined:
1921
1922 In [3]: ed foo\
1923 Editing... done. Executing edited code...
1924
1925 And if we call foo() again we get the modified version:
1926
1927 In [4]: foo()\
1928 foo() has now been changed!
1929
1930 Here is an example of how to edit a code snippet successive
1931 times. First we call the editor:
1932
1933 In [8]: ed\
1934 Editing... done. Executing edited code...\
1935 hello\
1936 Out[8]: "print 'hello'\n"
1937
1938 Now we call it again with the previous output (stored in _):
1939
1940 In [9]: ed _\
1941 Editing... done. Executing edited code...\
1942 hello world\
1943 Out[9]: "print 'hello world'\n"
1944
1945 Now we call it with the output #8 (stored in _8, also as Out[8]):
1946
1947 In [10]: ed _8\
1948 Editing... done. Executing edited code...\
1949 hello again\
1950 Out[10]: "print 'hello again'\n"
1951
1952
1953 Changing the default editor hook:
1954
1955 If you wish to write your own editor hook, you can put it in a
1956 configuration file which you load at startup time. The default hook
1957 is defined in the IPython.hooks module, and you can use that as a
1958 starting example for further modifications. That file also has
1959 general instructions on how to set a new hook for use once you've
1960 defined it.
1961
1962 **%env**::
1963
1964 List environment variables.
1965
1966 **%exit**::
1967
1968 Exit IPython, confirming if configured to do so.
1969
1970 You can configure whether IPython asks for confirmation upon exit by
1971 setting the confirm_exit flag in the ipythonrc file.
1972
1973 **%hist**::
1974
1975 Alternate name for %history.
1976
1977 **%history**::
1978
1979 Print input history (_i<n> variables), with most recent last.
1980
1981 %history -> print at most 40 inputs (some may be multi-line)\
1982 %history n -> print at most n inputs\
1983 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1984
1985 Each input's number <n> is shown, and is accessible as the
1986 automatically generated variable _i<n>. Multi-line statements are
1987 printed starting at a new line for easy copy/paste.
1988
1989
1990 Options:
1991
1992 -n: do NOT print line numbers. This is useful if you want to get a
1993 printout of many lines which can be directly pasted into a text
1994 editor.
1995
1996 This feature is only available if numbered prompts are in use.
1997
1998 -t: (default) print the 'translated' history, as IPython understands it.
1999 IPython filters your input and converts it all into valid Python source
2000 before executing it (things like magics or aliases are turned into
2001 function calls, for example). With this option, you'll see the native
2002 history instead of the user-entered version: '%cd /' will be seen as
2003 '_ip.magic("%cd /")' instead of '%cd /'.
2004
2005 -r: print the 'raw' history, i.e. the actual commands you typed.
2006
2007 -g: treat the arg as a pattern to grep for in (full) history.
2008 This includes the "shadow history" (almost all commands ever written).
2009 Use '%hist -g' to show full shadow history (may be very long).
2010 In shadow history, every index nuwber starts with 0.
2011
2012 -f FILENAME: instead of printing the output to the screen, redirect it to
2013 the given file. The file is always overwritten, though IPython asks for
2014 confirmation first if it already exists.
2015
2016 **%logoff**::
2017
2018 Temporarily stop logging.
2019
2020 You must have previously started logging.
2021
2022 **%logon**::
2023
2024 Restart logging.
2025
2026 This function is for restarting logging which you've temporarily
2027 stopped with %logoff. For starting logging for the first time, you
2028 must use the %logstart function, which allows you to specify an
2029 optional log filename.
2030
2031 **%logstart**::
2032
2033 Start logging anywhere in a session.
2034
2035 %logstart [-o|-r|-t] [log_name [log_mode]]
2036
2037 If no name is given, it defaults to a file named 'ipython_log.py' in your
2038 current directory, in 'rotate' mode (see below).
2039
2040 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
2041 history up to that point and then continues logging.
2042
2043 %logstart takes a second optional parameter: logging mode. This can be one
2044 of (note that the modes are given unquoted):\
2045 append: well, that says it.\
2046 backup: rename (if exists) to name~ and start name.\
2047 global: single logfile in your home dir, appended to.\
2048 over : overwrite existing log.\
2049 rotate: create rotating logs name.1~, name.2~, etc.
2050
2051 Options:
2052
2053 -o: log also IPython's output. In this mode, all commands which
2054 generate an Out[NN] prompt are recorded to the logfile, right after
2055 their corresponding input line. The output lines are always
2056 prepended with a '#[Out]# ' marker, so that the log remains valid
2057 Python code.
2058
2059 Since this marker is always the same, filtering only the output from
2060 a log is very easy, using for example a simple awk call:
2061
2062 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
2063
2064 -r: log 'raw' input. Normally, IPython's logs contain the processed
2065 input, so that user lines are logged in their final form, converted
2066 into valid Python. For example, %Exit is logged as
2067 '_ip.magic("Exit"). If the -r flag is given, all input is logged
2068 exactly as typed, with no transformations applied.
2069
2070 -t: put timestamps before each input line logged (these are put in
2071 comments).
2072
2073 **%logstate**::
2074
2075 Print the status of the logging system.
2076
2077 **%logstop**::
2078
2079 Fully stop logging and close log file.
2080
2081 In order to start logging again, a new %logstart call needs to be made,
2082 possibly (though not necessarily) with a new filename, mode and other
2083 options.
2084
2085 **%lsmagic**::
2086
2087 List currently available magic functions.
2088
2089 **%macro**::
2090
2091 Define a set of input lines as a macro for future re-execution.
2092
2093 Usage:\
2094 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2095
2096 Options:
2097
2098 -r: use 'raw' input. By default, the 'processed' history is used,
2099 so that magics are loaded in their transformed version to valid
2100 Python. If this option is given, the raw input as typed as the
2101 command line is used instead.
2102
2103 This will define a global variable called `name` which is a string
2104 made of joining the slices and lines you specify (n1,n2,... numbers
2105 above) from your input history into a single string. This variable
2106 acts like an automatic function which re-executes those lines as if
2107 you had typed them. You just type 'name' at the prompt and the code
2108 executes.
2109
2110 The notation for indicating number ranges is: n1-n2 means 'use line
2111 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2112 using the lines numbered 5,6 and 7.
2113
2114 Note: as a 'hidden' feature, you can also use traditional python slice
2115 notation, where N:M means numbers N through M-1.
2116
2117 For example, if your history contains (%hist prints it):
2118
2119 44: x=1\
2120 45: y=3\
2121 46: z=x+y\
2122 47: print x\
2123 48: a=5\
2124 49: print 'x',x,'y',y\
2125
2126 you can create a macro with lines 44 through 47 (included) and line 49
2127 called my_macro with:
2128
2129 In [51]: %macro my_macro 44-47 49
2130
2131 Now, typing `my_macro` (without quotes) will re-execute all this code
2132 in one pass.
2133
2134 You don't need to give the line-numbers in order, and any given line
2135 number can appear multiple times. You can assemble macros with any
2136 lines from your input history in any order.
2137
2138 The macro is a simple object which holds its value in an attribute,
2139 but IPython's display system checks for macros and executes them as
2140 code instead of printing them when you type their name.
2141
2142 You can view a macro's contents by explicitly printing it with:
2143
2144 'print macro_name'.
2145
2146 For one-off cases which DON'T contain magic function calls in them you
2147 can obtain similar results by explicitly executing slices from your
2148 input history with:
2149
2150 In [60]: exec In[44:48]+In[49]
2151
2152 **%magic**::
2153
2154 Print information about the magic function system.
2155
2156 **%mglob**::
2157
2158 This program allows specifying filenames with "mglob" mechanism.
2159 Supported syntax in globs (wilcard matching patterns)::
2160
2161 *.cpp ?ellowo*
2162 - obvious. Differs from normal glob in that dirs are not included.
2163 Unix users might want to write this as: "*.cpp" "?ellowo*"
2164 rec:/usr/share=*.txt,*.doc
2165 - get all *.txt and *.doc under /usr/share,
2166 recursively
2167 rec:/usr/share
2168 - All files under /usr/share, recursively
2169 rec:*.py
2170 - All .py files under current working dir, recursively
2171 foo
2172 - File or dir foo
2173 !*.bak readme*
2174 - readme*, exclude files ending with .bak
2175 !.svn/ !.hg/ !*_Data/ rec:.
2176 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
2177 Trailing / is the key, \ does not work!
2178 dir:foo
2179 - the directory foo if it exists (not files in foo)
2180 dir:*
2181 - all directories in current folder
2182 foo.py bar.* !h* rec:*.py
2183 - Obvious. !h* exclusion only applies for rec:*.py.
2184 foo.py is *not* included twice.
2185 @filelist.txt
2186 - All files listed in 'filelist.txt' file, on separate lines.
2187
2188 **%page**::
2189
2190 Pretty print the object and display it through a pager.
2191
2192 %page [options] OBJECT
2193
2194 If no object is given, use _ (last output).
2195
2196 Options:
2197
2198 -r: page str(object), don't pretty-print it.
2199
2200 **%pdb**::
2201
2202 Control the automatic calling of the pdb interactive debugger.
2203
2204 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
2205 argument it works as a toggle.
2206
2207 When an exception is triggered, IPython can optionally call the
2208 interactive pdb debugger after the traceback printout. %pdb toggles
2209 this feature on and off.
2210
2211 The initial state of this feature is set in your ipythonrc
2212 configuration file (the variable is called 'pdb').
2213
2214 If you want to just activate the debugger AFTER an exception has fired,
2215 without having to type '%pdb on' and rerunning your code, you can use
2216 the %debug magic.
2217
2218 **%pdef**::
2219
2220 Print the definition header for any callable object.
2221
2222 If the object is a class, print the constructor information.
2223
2224 **%pdoc**::
2225
2226 Print the docstring for an object.
2227
2228 If the given object is a class, it will print both the class and the
2229 constructor docstrings.
2230
2231 **%pfile**::
2232
2233 Print (or run through pager) the file where an object is defined.
2234
2235 The file opens at the line where the object definition begins. IPython
2236 will honor the environment variable PAGER if set, and otherwise will
2237 do its best to print the file in a convenient form.
2238
2239 If the given argument is not an object currently defined, IPython will
2240 try to interpret it as a filename (automatically adding a .py extension
2241 if needed). You can thus use %pfile as a syntax highlighting code
2242 viewer.
2243
2244 **%pinfo**::
2245
2246 Provide detailed information about an object.
2247
2248 '%pinfo object' is just a synonym for object? or ?object.
2249
2250 **%popd**::
2251
2252 Change to directory popped off the top of the stack.
2253
2254 **%profile**::
2255
2256 Print your currently active IPyhton profile.
2257
2258 **%prun**::
2259
2260 Run a statement through the python code profiler.
2261
2262 Usage:\
2263 %prun [options] statement
2264
2265 The given statement (which doesn't require quote marks) is run via the
2266 python profiler in a manner similar to the profile.run() function.
2267 Namespaces are internally managed to work correctly; profile.run
2268 cannot be used in IPython because it makes certain assumptions about
2269 namespaces which do not hold under IPython.
2270
2271 Options:
2272
2273 -l <limit>: you can place restrictions on what or how much of the
2274 profile gets printed. The limit value can be:
2275
2276 * A string: only information for function names containing this string
2277 is printed.
2278
2279 * An integer: only these many lines are printed.
2280
2281 * A float (between 0 and 1): this fraction of the report is printed
2282 (for example, use a limit of 0.4 to see the topmost 40% only).
2283
2284 You can combine several limits with repeated use of the option. For
2285 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2286 information about class constructors.
2287
2288 -r: return the pstats.Stats object generated by the profiling. This
2289 object has all the information about the profile in it, and you can
2290 later use it for further analysis or in other functions.
2291
2292 -s <key>: sort profile by given key. You can provide more than one key
2293 by using the option several times: '-s key1 -s key2 -s key3...'. The
2294 default sorting key is 'time'.
2295
2296 The following is copied verbatim from the profile documentation
2297 referenced below:
2298
2299 When more than one key is provided, additional keys are used as
2300 secondary criteria when the there is equality in all keys selected
2301 before them.
2302
2303 Abbreviations can be used for any key names, as long as the
2304 abbreviation is unambiguous. The following are the keys currently
2305 defined:
2306
2307 Valid Arg Meaning\
2308 "calls" call count\
2309 "cumulative" cumulative time\
2310 "file" file name\
2311 "module" file name\
2312 "pcalls" primitive call count\
2313 "line" line number\
2314 "name" function name\
2315 "nfl" name/file/line\
2316 "stdname" standard name\
2317 "time" internal time
2318
2319 Note that all sorts on statistics are in descending order (placing
2320 most time consuming items first), where as name, file, and line number
2321 searches are in ascending order (i.e., alphabetical). The subtle
2322 distinction between "nfl" and "stdname" is that the standard name is a
2323 sort of the name as printed, which means that the embedded line
2324 numbers get compared in an odd way. For example, lines 3, 20, and 40
2325 would (if the file names were the same) appear in the string order
2326 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
2327 line numbers. In fact, sort_stats("nfl") is the same as
2328 sort_stats("name", "file", "line").
2329
2330 -T <filename>: save profile results as shown on screen to a text
2331 file. The profile is still shown on screen.
2332
2333 -D <filename>: save (via dump_stats) profile statistics to given
2334 filename. This data is in a format understod by the pstats module, and
2335 is generated by a call to the dump_stats() method of profile
2336 objects. The profile is still shown on screen.
2337
2338 If you want to run complete programs under the profiler's control, use
2339 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2340 contains profiler specific options as described here.
2341
2342 You can read the complete documentation for the profile module with:\
2343 In [1]: import profile; profile.help()
2344
2345 **%psearch**::
2346
2347 Search for object in namespaces by wildcard.
2348
2349 %psearch [options] PATTERN [OBJECT TYPE]
2350
2351 Note: ? can be used as a synonym for %psearch, at the beginning or at
2352 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2353 rest of the command line must be unchanged (options come first), so
2354 for example the following forms are equivalent
2355
2356 %psearch -i a* function
2357 -i a* function?
2358 ?-i a* function
2359
2360 Arguments:
2361
2362 PATTERN
2363
2364 where PATTERN is a string containing * as a wildcard similar to its
2365 use in a shell. The pattern is matched in all namespaces on the
2366 search path. By default objects starting with a single _ are not
2367 matched, many IPython generated objects have a single
2368 underscore. The default is case insensitive matching. Matching is
2369 also done on the attributes of objects and not only on the objects
2370 in a module.
2371
2372 [OBJECT TYPE]
2373
2374 Is the name of a python type from the types module. The name is
2375 given in lowercase without the ending type, ex. StringType is
2376 written string. By adding a type here only objects matching the
2377 given type are matched. Using all here makes the pattern match all
2378 types (this is the default).
2379
2380 Options:
2381
2382 -a: makes the pattern match even objects whose names start with a
2383 single underscore. These names are normally ommitted from the
2384 search.
2385
2386 -i/-c: make the pattern case insensitive/sensitive. If neither of
2387 these options is given, the default is read from your ipythonrc
2388 file. The option name which sets this value is
2389 'wildcards_case_sensitive'. If this option is not specified in your
2390 ipythonrc file, IPython's internal default is to do a case sensitive
2391 search.
2392
2393 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2394 specifiy can be searched in any of the following namespaces:
2395 'builtin', 'user', 'user_global','internal', 'alias', where
2396 'builtin' and 'user' are the search defaults. Note that you should
2397 not use quotes when specifying namespaces.
2398
2399 'Builtin' contains the python module builtin, 'user' contains all
2400 user data, 'alias' only contain the shell aliases and no python
2401 objects, 'internal' contains objects used by IPython. The
2402 'user_global' namespace is only used by embedded IPython instances,
2403 and it contains module-level globals. You can add namespaces to the
2404 search with -s or exclude them with -e (these options can be given
2405 more than once).
2406
2407 Examples:
2408
2409 %psearch a* -> objects beginning with an a
2410 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
2411 %psearch a* function -> all functions beginning with an a
2412 %psearch re.e* -> objects beginning with an e in module re
2413 %psearch r*.e* -> objects that start with e in modules starting in r
2414 %psearch r*.* string -> all strings in modules beginning with r
2415
2416 Case sensitve search:
2417
2418 %psearch -c a* list all object beginning with lower case a
2419
2420 Show objects beginning with a single _:
2421
2422 %psearch -a _* list objects beginning with a single underscore
2423
2424 **%psource**::
2425
2426 Print (or run through pager) the source code for an object.
2427
2428 **%pushd**::
2429
2430 Place the current dir on stack and change directory.
2431
2432 Usage:\
2433 %pushd ['dirname']
2434
2435 **%pwd**::
2436
2437 Return the current working directory path.
2438
2439 **%pycat**::
2440
2441 Show a syntax-highlighted file through a pager.
2442
2443 This magic is similar to the cat utility, but it will assume the file
2444 to be Python source and will show it with syntax highlighting.
2445
2446 **%quickref**::
2447
2448 Show a quick reference sheet
2449
2450 **%quit**::
2451
2452 Exit IPython, confirming if configured to do so (like %exit)
2453
2454 **%r**::
2455
2456 Repeat previous input.
2457
2458 Note: Consider using the more powerfull %rep instead!
2459
2460 If given an argument, repeats the previous command which starts with
2461 the same string, otherwise it just repeats the previous input.
2462
2463 Shell escaped commands (with ! as first character) are not recognized
2464 by this system, only pure python code and magic commands.
2465
2466 **%rehashdir**::
2467
2468 Add executables in all specified dirs to alias table
2469
2470 Usage:
2471
2472 %rehashdir c:/bin;c:/tools
2473 - Add all executables under c:/bin and c:/tools to alias table, in
2474 order to make them directly executable from any directory.
2475
2476 Without arguments, add all executables in current directory.
2477
2478 **%rehashx**::
2479
2480 Update the alias table with all executable files in $PATH.
2481
2482 This version explicitly checks that every entry in $PATH is a file
2483 with execute access (os.X_OK), so it is much slower than %rehash.
2484
2485 Under Windows, it checks executability as a match agains a
2486 '|'-separated string of extensions, stored in the IPython config
2487 variable win_exec_ext. This defaults to 'exe|com|bat'.
2488
2489 This function also resets the root module cache of module completer,
2490 used on slow filesystems.
2491
2492 **%rep**::
2493
2494 Repeat a command, or get command to input line for editing
2495
2496 - %rep (no arguments):
2497
2498 Place a string version of last computation result (stored in the special '_'
2499 variable) to the next input prompt. Allows you to create elaborate command
2500 lines without using copy-paste::
2501
2502 $ l = ["hei", "vaan"]
2503 $ "".join(l)
2504 ==> heivaan
2505 $ %rep
2506 $ heivaan_ <== cursor blinking
2507
2508 %rep 45
2509
2510 Place history line 45 to next input prompt. Use %hist to find out the
2511 number.
2512
2513 %rep 1-4 6-7 3
2514
2515 Repeat the specified lines immediately. Input slice syntax is the same as
2516 in %macro and %save.
2517
2518 %rep foo
2519
2520 Place the most recent line that has the substring "foo" to next input.
2521 (e.g. 'svn ci -m foobar').
2522
2523 **%reset**::
2524
2525 Resets the namespace by removing all names defined by the user.
2526
2527 Input/Output history are left around in case you need them.
2528
2529 **%run**::
2530
2531 Run the named file inside IPython as a program.
2532
2533 Usage:\
2534 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2535
2536 Parameters after the filename are passed as command-line arguments to
2537 the program (put in sys.argv). Then, control returns to IPython's
2538 prompt.
2539
2540 This is similar to running at a system prompt:\
2541 $ python file args\
2542 but with the advantage of giving you IPython's tracebacks, and of
2543 loading all variables into your interactive namespace for further use
2544 (unless -p is used, see below).
2545
2546 The file is executed in a namespace initially consisting only of
2547 __name__=='__main__' and sys.argv constructed as indicated. It thus
2548 sees its environment as if it were being run as a stand-alone program
2549 (except for sharing global objects such as previously imported
2550 modules). But after execution, the IPython interactive namespace gets
2551 updated with all variables defined in the program (except for __name__
2552 and sys.argv). This allows for very convenient loading of code for
2553 interactive work, while giving each program a 'clean sheet' to run in.
2554
2555 Options:
2556
2557 -n: __name__ is NOT set to '__main__', but to the running file's name
2558 without extension (as python does under import). This allows running
2559 scripts and reloading the definitions in them without calling code
2560 protected by an ' if __name__ == "__main__" ' clause.
2561
2562 -i: run the file in IPython's namespace instead of an empty one. This
2563 is useful if you are experimenting with code written in a text editor
2564 which depends on variables defined interactively.
2565
2566 -e: ignore sys.exit() calls or SystemExit exceptions in the script
2567 being run. This is particularly useful if IPython is being used to
2568 run unittests, which always exit with a sys.exit() call. In such
2569 cases you are interested in the output of the test results, not in
2570 seeing a traceback of the unittest module.
2571
2572 -t: print timing information at the end of the run. IPython will give
2573 you an estimated CPU time consumption for your script, which under
2574 Unix uses the resource module to avoid the wraparound problems of
2575 time.clock(). Under Unix, an estimate of time spent on system tasks
2576 is also given (for Windows platforms this is reported as 0.0).
2577
2578 If -t is given, an additional -N<N> option can be given, where <N>
2579 must be an integer indicating how many times you want the script to
2580 run. The final timing report will include total and per run results.
2581
2582 For example (testing the script uniq_stable.py):
2583
2584 In [1]: run -t uniq_stable
2585
2586 IPython CPU timings (estimated):\
2587 User : 0.19597 s.\
2588 System: 0.0 s.\
2589
2590 In [2]: run -t -N5 uniq_stable
2591
2592 IPython CPU timings (estimated):\
2593 Total runs performed: 5\
2594 Times : Total Per run\
2595 User : 0.910862 s, 0.1821724 s.\
2596 System: 0.0 s, 0.0 s.
2597
2598 -d: run your program under the control of pdb, the Python debugger.
2599 This allows you to execute your program step by step, watch variables,
2600 etc. Internally, what IPython does is similar to calling:
2601
2602 pdb.run('execfile("YOURFILENAME")')
2603
2604 with a breakpoint set on line 1 of your file. You can change the line
2605 number for this automatic breakpoint to be <N> by using the -bN option
2606 (where N must be an integer). For example:
2607
2608 %run -d -b40 myscript
2609
2610 will set the first breakpoint at line 40 in myscript.py. Note that
2611 the first breakpoint must be set on a line which actually does
2612 something (not a comment or docstring) for it to stop execution.
2613
2614 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2615 first enter 'c' (without qoutes) to start execution up to the first
2616 breakpoint.
2617
2618 Entering 'help' gives information about the use of the debugger. You
2619 can easily see pdb's full documentation with "import pdb;pdb.help()"
2620 at a prompt.
2621
2622 -p: run program under the control of the Python profiler module (which
2623 prints a detailed report of execution times, function calls, etc).
2624
2625 You can pass other options after -p which affect the behavior of the
2626 profiler itself. See the docs for %prun for details.
2627
2628 In this mode, the program's variables do NOT propagate back to the
2629 IPython interactive namespace (because they remain in the namespace
2630 where the profiler executes them).
2631
2632 Internally this triggers a call to %prun, see its documentation for
2633 details on the options available specifically for profiling.
2634
2635 There is one special usage for which the text above doesn't apply:
2636 if the filename ends with .ipy, the file is run as ipython script,
2637 just as if the commands were written on IPython prompt.
2638
2639 **%runlog**::
2640
2641 Run files as logs.
2642
2643 Usage:\
2644 %runlog file1 file2 ...
2645
2646 Run the named files (treating them as log files) in sequence inside
2647 the interpreter, and return to the prompt. This is much slower than
2648 %run because each line is executed in a try/except block, but it
2649 allows running files with syntax errors in them.
2650
2651 Normally IPython will guess when a file is one of its own logfiles, so
2652 you can typically use %run even for logs. This shorthand allows you to
2653 force any file to be treated as a log file.
2654
2655 **%save**::
2656
2657 Save a set of lines to a given filename.
2658
2659 Usage:\
2660 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2661
2662 Options:
2663
2664 -r: use 'raw' input. By default, the 'processed' history is used,
2665 so that magics are loaded in their transformed version to valid
2666 Python. If this option is given, the raw input as typed as the
2667 command line is used instead.
2668
2669 This function uses the same syntax as %macro for line extraction, but
2670 instead of creating a macro it saves the resulting string to the
2671 filename you specify.
2672
2673 It adds a '.py' extension to the file if you don't do so yourself, and
2674 it asks for confirmation before overwriting existing files.
2675
2676 **%sc**::
2677
2678 Shell capture - execute a shell command and capture its output.
2679
2680 DEPRECATED. Suboptimal, retained for backwards compatibility.
2681
2682 You should use the form 'var = !command' instead. Example:
2683
2684 "%sc -l myfiles = ls ~" should now be written as
2685
2686 "myfiles = !ls ~"
2687
2688 myfiles.s, myfiles.l and myfiles.n still apply as documented
2689 below.
2690
2691 --
2692 %sc [options] varname=command
2693
2694 IPython will run the given command using commands.getoutput(), and
2695 will then update the user's interactive namespace with a variable
2696 called varname, containing the value of the call. Your command can
2697 contain shell wildcards, pipes, etc.
2698
2699 The '=' sign in the syntax is mandatory, and the variable name you
2700 supply must follow Python's standard conventions for valid names.
2701
2702 (A special format without variable name exists for internal use)
2703
2704 Options:
2705
2706 -l: list output. Split the output on newlines into a list before
2707 assigning it to the given variable. By default the output is stored
2708 as a single string.
2709
2710 -v: verbose. Print the contents of the variable.
2711
2712 In most cases you should not need to split as a list, because the
2713 returned value is a special type of string which can automatically
2714 provide its contents either as a list (split on newlines) or as a
2715 space-separated string. These are convenient, respectively, either
2716 for sequential processing or to be passed to a shell command.
2717
2718 For example:
2719
2720 # Capture into variable a
2721 In [9]: sc a=ls *py
2722
2723 # a is a string with embedded newlines
2724 In [10]: a
2725 Out[10]: 'setup.py win32_manual_post_install.py'
2726
2727 # which can be seen as a list:
2728 In [11]: a.l
2729 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2730
2731 # or as a whitespace-separated string:
2732 In [12]: a.s
2733 Out[12]: 'setup.py win32_manual_post_install.py'
2734
2735 # a.s is useful to pass as a single command line:
2736 In [13]: !wc -l $a.s
2737 146 setup.py
2738 130 win32_manual_post_install.py
2739 276 total
2740
2741 # while the list form is useful to loop over:
2742 In [14]: for f in a.l:
2743 ....: !wc -l $f
2744 ....:
2745 146 setup.py
2746 130 win32_manual_post_install.py
2747
2748 Similiarly, the lists returned by the -l option are also special, in
2749 the sense that you can equally invoke the .s attribute on them to
2750 automatically get a whitespace-separated string from their contents:
2751
2752 In [1]: sc -l b=ls *py
2753
2754 In [2]: b
2755 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2756
2757 In [3]: b.s
2758 Out[3]: 'setup.py win32_manual_post_install.py'
2759
2760 In summary, both the lists and strings used for ouptut capture have
2761 the following special attributes:
2762
2763 .l (or .list) : value as list.
2764 .n (or .nlstr): value as newline-separated string.
2765 .s (or .spstr): value as space-separated string.
2766
2767 **%store**::
2768
2769 Lightweight persistence for python variables.
2770
2771 Example:
2772
2773 ville@badger[~]|1> A = ['hello',10,'world']\
2774 ville@badger[~]|2> %store A\
2775 ville@badger[~]|3> Exit
2776
2777 (IPython session is closed and started again...)
2778
2779 ville@badger:~$ ipython -p pysh\
2780 ville@badger[~]|1> print A
2781
2782 ['hello', 10, 'world']
2783
2784 Usage:
2785
2786 %store - Show list of all variables and their current values\
2787 %store <var> - Store the *current* value of the variable to disk\
2788 %store -d <var> - Remove the variable and its value from storage\
2789 %store -z - Remove all variables from storage\
2790 %store -r - Refresh all variables from store (delete current vals)\
2791 %store foo >a.txt - Store value of foo to new file a.txt\
2792 %store foo >>a.txt - Append value of foo to file a.txt\
2793
2794 It should be noted that if you change the value of a variable, you
2795 need to %store it again if you want to persist the new value.
2796
2797 Note also that the variables will need to be pickleable; most basic
2798 python types can be safely %stored.
2799
2800 Also aliases can be %store'd across sessions.
2801
2802 **%sx**::
2803
2804 Shell execute - run a shell command and capture its output.
2805
2806 %sx command
2807
2808 IPython will run the given command using commands.getoutput(), and
2809 return the result formatted as a list (split on '\n'). Since the
2810 output is _returned_, it will be stored in ipython's regular output
2811 cache Out[N] and in the '_N' automatic variables.
2812
2813 Notes:
2814
2815 1) If an input line begins with '!!', then %sx is automatically
2816 invoked. That is, while:
2817 !ls
2818 causes ipython to simply issue system('ls'), typing
2819 !!ls
2820 is a shorthand equivalent to:
2821 %sx ls
2822
2823 2) %sx differs from %sc in that %sx automatically splits into a list,
2824 like '%sc -l'. The reason for this is to make it as easy as possible
2825 to process line-oriented shell output via further python commands.
2826 %sc is meant to provide much finer control, but requires more
2827 typing.
2828
2829 3) Just like %sc -l, this is a list with special attributes:
2830
2831 .l (or .list) : value as list.
2832 .n (or .nlstr): value as newline-separated string.
2833 .s (or .spstr): value as whitespace-separated string.
2834
2835 This is very useful when trying to use such lists as arguments to
2836 system commands.
2837
2838 **%system_verbose**::
2839
2840 Set verbose printing of system calls.
2841
2842 If called without an argument, act as a toggle
2843
2844 **%time**::
2845
2846 Time execution of a Python statement or expression.
2847
2848 The CPU and wall clock times are printed, and the value of the
2849 expression (if any) is returned. Note that under Win32, system time
2850 is always reported as 0, since it can not be measured.
2851
2852 This function provides very basic timing functionality. In Python
2853 2.3, the timeit module offers more control and sophistication, so this
2854 could be rewritten to use it (patches welcome).
2855
2856 Some examples:
2857
2858 In [1]: time 2**128
2859 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2860 Wall time: 0.00
2861 Out[1]: 340282366920938463463374607431768211456L
2862
2863 In [2]: n = 1000000
2864
2865 In [3]: time sum(range(n))
2866 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2867 Wall time: 1.37
2868 Out[3]: 499999500000L
2869
2870 In [4]: time print 'hello world'
2871 hello world
2872 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2873 Wall time: 0.00
2874
2875 Note that the time needed by Python to compile the given expression
2876 will be reported if it is more than 0.1s. In this example, the
2877 actual exponentiation is done by Python at compilation time, so while
2878 the expression can take a noticeable amount of time to compute, that
2879 time is purely due to the compilation:
2880
2881 In [5]: time 3**9999;
2882 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2883 Wall time: 0.00 s
2884
2885 In [6]: time 3**999999;
2886 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2887 Wall time: 0.00 s
2888 Compiler : 0.78 s
2889
2890 **%timeit**::
2891
2892 Time execution of a Python statement or expression
2893
2894 Usage:\
2895 %timeit [-n<N> -r<R> [-t|-c]] statement
2896
2897 Time execution of a Python statement or expression using the timeit
2898 module.
2899
2900 Options:
2901 -n<N>: execute the given statement <N> times in a loop. If this value
2902 is not given, a fitting value is chosen.
2903
2904 -r<R>: repeat the loop iteration <R> times and take the best result.
2905 Default: 3
2906
2907 -t: use time.time to measure the time, which is the default on Unix.
2908 This function measures wall time.
2909
2910 -c: use time.clock to measure the time, which is the default on
2911 Windows and measures wall time. On Unix, resource.getrusage is used
2912 instead and returns the CPU user time.
2913
2914 -p<P>: use a precision of <P> digits to display the timing result.
2915 Default: 3
2916
2917
2918 Examples:\
2919 In [1]: %timeit pass
2920 10000000 loops, best of 3: 53.3 ns per loop
2921
2922 In [2]: u = None
2923
2924 In [3]: %timeit u is None
2925 10000000 loops, best of 3: 184 ns per loop
2926
2927 In [4]: %timeit -r 4 u == None
2928 1000000 loops, best of 4: 242 ns per loop
2929
2930 In [5]: import time
2931
2932 In [6]: %timeit -n1 time.sleep(2)
2933 1 loops, best of 3: 2 s per loop
2934
2935
2936 The times reported by %timeit will be slightly higher than those
2937 reported by the timeit.py script when variables are accessed. This is
2938 due to the fact that %timeit executes the statement in the namespace
2939 of the shell, compared with timeit.py, which uses a single setup
2940 statement to import function or create variables. Generally, the bias
2941 does not matter as long as results from timeit.py are not mixed with
2942 those from %timeit.
2943
2944 **%unalias**::
2945
2946 Remove an alias
2947
2948 **%upgrade**::
2949
2950 Upgrade your IPython installation
2951
2952 This will copy the config files that don't yet exist in your
2953 ipython dir from the system config dir. Use this after upgrading
2954 IPython if you don't wish to delete your .ipython dir.
2955
2956 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2957 new users)
2958
2959 **%which**::
2960
2961 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
2962
2963 Traverses PATH and prints all files (not just executables!) that match the
2964 pattern on command line. Probably more useful in finding stuff
2965 interactively than 'which', which only prints the first matching item.
2966
2967 Also discovers and expands aliases, so you'll see what will be executed
2968 when you call an alias.
2969
2970 Example:
2971
2972 [~]|62> %which d
2973 d -> ls -F --color=auto
2974 == c:\cygwin\bin\ls.exe
2975 c:\cygwin\bin\d.exe
2976
2977 [~]|64> %which diff*
2978 diff3 -> diff3
2979 == c:\cygwin\bin\diff3.exe
2980 diff -> diff
2981 == c:\cygwin\bin\diff.exe
2982 c:\cygwin\bin\diff.exe
2983 c:\cygwin\bin\diff3.exe
2984
2985 **%who**::
2986
2987 Print all interactive variables, with some minimal formatting.
2988
2989 If any arguments are given, only variables whose type matches one of
2990 these are printed. For example:
2991
2992 %who function str
2993
2994 will only list functions and strings, excluding all other types of
2995 variables. To find the proper type names, simply use type(var) at a
2996 command line to see how python prints type names. For example:
2997
2998 In [1]: type('hello')\
2999 Out[1]: <type 'str'>
3000
3001 indicates that the type name for strings is 'str'.
3002
3003 %who always excludes executed names loaded through your configuration
3004 file and things which are internal to IPython.
3005
3006 This is deliberate, as typically you may load many modules and the
3007 purpose of %who is to show you only what you've manually defined.
3008
3009 **%who_ls**::
3010
3011 Return a sorted list of all interactive variables.
3012
3013 If arguments are given, only variables of types matching these
3014 arguments are returned.
3015
3016 **%whos**::
3017
3018 Like %who, but gives some extra information about each variable.
3019
3020 The same type filtering of %who can be applied here.
3021
3022 For all variables, the type is printed. Additionally it prints:
3023
3024 - For {},[],(): their length.
3025
3026 - For numpy and Numeric arrays, a summary with shape, number of
3027 elements, typecode and size in memory.
3028
3029 - Everything else: a string representation, snipping their middle if
3030 too long.
3031
3032 **%xmode**::
3033
3034 Switch modes for the exception handlers.
3035
3036 Valid modes: Plain, Context and Verbose.
3037
3038 If called without arguments, acts as a toggle.
3039
3040 .. magic_end
3041
3042 Access to the standard Python help
3043 ----------------------------------
3044
3045 As of Python 2.1, a help system is available with access to object
3046 docstrings and the Python manuals. Simply type 'help' (no quotes) to
3047 access it. You can also type help(object) to obtain information about a
3048 given object, and help('keyword') for information on a keyword. As noted
3049 in sec. `accessing help`_, you need to properly configure
3050 your environment variable PYTHONDOCS for this feature to work correctly.
3051
3052
3053 Dynamic object information
3054 --------------------------
3055
3056 Typing ?word or word? prints detailed information about an object. If
3057 certain strings in the object are too long (docstrings, code, etc.) they
3058 get snipped in the center for brevity. This system gives access variable
3059 types and values, full source code for any object (if available),
3060 function prototypes and other useful information.
3061
3062 Typing ??word or word?? gives access to the full information without
3063 snipping long strings. Long strings are sent to the screen through the
3064 less pager if longer than the screen and printed otherwise. On systems
3065 lacking the less command, IPython uses a very basic internal pager.
3066
3067 The following magic functions are particularly useful for gathering
3068 information about your working environment. You can get more details by
3069 typing %magic or querying them individually (use %function_name? with or
3070 without the %), this is just a summary:
3071
3072 * **%pdoc <object>**: Print (or run through a pager if too long) the
3073 docstring for an object. If the given object is a class, it will
3074 print both the class and the constructor docstrings.
3075 * **%pdef <object>**: Print the definition header for any callable
3076 object. If the object is a class, print the constructor information.
3077 * **%psource <object>**: Print (or run through a pager if too long)
3078 the source code for an object.
3079 * **%pfile <object>**: Show the entire source file where an object was
3080 defined via a pager, opening it at the line where the object
3081 definition begins.
3082 * **%who/%whos**: These functions give information about identifiers
3083 you have defined interactively (not things you loaded or defined
3084 in your configuration files). %who just prints a list of
3085 identifiers and %whos prints a table with some basic details about
3086 each identifier.
3087
3088 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
3089 %pdef, %psource) give you access to documentation even on things which
3090 are not really defined as separate identifiers. Try for example typing
3091 {}.get? or after doing import os, type os.path.abspath??.
3092
3093
3094 .. _Readline:
3095
3096 Readline-based features
3097 -----------------------
3098
3099 These features require the GNU readline library, so they won't work if
3100 your Python installation lacks readline support. We will first describe
3101 the default behavior IPython uses, and then how to change it to suit
3102 your preferences.
3103
3104
3105 Command line completion
3106 +++++++++++++++++++++++
3107
3108 At any time, hitting TAB will complete any available python commands or
3109 variable names, and show you a list of the possible completions if
3110 there's no unambiguous one. It will also complete filenames in the
3111 current directory if no python names match what you've typed so far.
3112
3113
3114 Search command history
3115 ++++++++++++++++++++++
3116
3117 IPython provides two ways for searching through previous input and thus
3118 reduce the need for repetitive typing:
3119
3120 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
3121 (next,down) to search through only the history items that match
3122 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
3123 prompt, they just behave like normal arrow keys.
3124 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
3125 searches your history for lines that contain what you've typed so
3126 far, completing as much as it can.
3127
3128
3129 Persistent command history across sessions
3130 ++++++++++++++++++++++++++++++++++++++++++
3131
3132 IPython will save your input history when it leaves and reload it next
3133 time you restart it. By default, the history file is named
3134 $IPYTHONDIR/history, but if you've loaded a named profile,
3135 '-PROFILE_NAME' is appended to the name. This allows you to keep
3136 separate histories related to various tasks: commands related to
3137 numerical work will not be clobbered by a system shell history, for
3138 example.
3139
3140
3141 Autoindent
3142 ++++++++++
3143
3144 IPython can recognize lines ending in ':' and indent the next line,
3145 while also un-indenting automatically after 'raise' or 'return'.
3146
3147 This feature uses the readline library, so it will honor your ~/.inputrc
3148 configuration (or whatever file your INPUTRC variable points to). Adding
3149 the following lines to your .inputrc file can make indenting/unindenting
3150 more convenient (M-i indents, M-u unindents)::
3151
3152 $if Python
3153 "\M-i": " "
3154 "\M-u": "\d\d\d\d"
3155 $endif
3156
3157 Note that there are 4 spaces between the quote marks after "M-i" above.
3158
3159 Warning: this feature is ON by default, but it can cause problems with
3160 the pasting of multi-line indented code (the pasted code gets
3161 re-indented on each line). A magic function %autoindent allows you to
3162 toggle it on/off at runtime. You can also disable it permanently on in
3163 your ipythonrc file (set autoindent 0).
3164
3165
3166 Customizing readline behavior
3167 +++++++++++++++++++++++++++++
3168
3169 All these features are based on the GNU readline library, which has an
3170 extremely customizable interface. Normally, readline is configured via a
3171 file which defines the behavior of the library; the details of the
3172 syntax for this can be found in the readline documentation available
3173 with your system or on the Internet. IPython doesn't read this file (if
3174 it exists) directly, but it does support passing to readline valid
3175 options via a simple interface. In brief, you can customize readline by
3176 setting the following options in your ipythonrc configuration file (note
3177 that these options can not be specified at the command line):
3178
3179 * **readline_parse_and_bind**: this option can appear as many times as
3180 you want, each time defining a string to be executed via a
3181 readline.parse_and_bind() command. The syntax for valid commands
3182 of this kind can be found by reading the documentation for the GNU
3183 readline library, as these commands are of the kind which readline
3184 accepts in its configuration file.
3185 * **readline_remove_delims**: a string of characters to be removed
3186 from the default word-delimiters list used by readline, so that
3187 completions may be performed on strings which contain them. Do not
3188 change the default value unless you know what you're doing.
3189 * **readline_omit__names**: when tab-completion is enabled, hitting
3190 <tab> after a '.' in a name will complete all attributes of an
3191 object, including all the special methods whose names include
3192 double underscores (like __getitem__ or __class__). If you'd
3193 rather not see these names by default, you can set this option to
3194 1. Note that even when this option is set, you can still see those
3195 names by explicitly typing a _ after the period and hitting <tab>:
3196 'name._<tab>' will always complete attribute names starting with '_'.
3197
3198 This option is off by default so that new users see all
3199 attributes of any objects they are dealing with.
3200
3201 You will find the default values along with a corresponding detailed
3202 explanation in your ipythonrc file.
3203
3204
3205 Session logging and restoring
3206 -----------------------------
3207
3208 You can log all input from a session either by starting IPython with
3209 the command line switches -log or -logfile (see sec. `command line
3210 options`_) or by activating the logging at any moment with the magic
3211 function %logstart.
3212
3213 Log files can later be reloaded with the -logplay option and IPython
3214 will attempt to 'replay' the log by executing all the lines in it, thus
3215 restoring the state of a previous session. This feature is not quite
3216 perfect, but can still be useful in many cases.
3217
3218 The log files can also be used as a way to have a permanent record of
3219 any code you wrote while experimenting. Log files are regular text files
3220 which you can later open in your favorite text editor to extract code or
3221 to 'clean them up' before using them to replay a session.
3222
3223 The %logstart function for activating logging in mid-session is used as
3224 follows:
3225
3226 %logstart [log_name [log_mode]]
3227
3228 If no name is given, it defaults to a file named 'log' in your
3229 IPYTHONDIR directory, in 'rotate' mode (see below).
3230
3231 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
3232 history up to that point and then continues logging.
3233
3234 %logstart takes a second optional parameter: logging mode. This can be
3235 one of (note that the modes are given unquoted):
3236
3237 * [over:] overwrite existing log_name.
3238 * [backup:] rename (if exists) to log_name~ and start log_name.
3239 * [append:] well, that says it.
3240 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
3241
3242 The %logoff and %logon functions allow you to temporarily stop and
3243 resume logging to a file which had previously been started with
3244 %logstart. They will fail (with an explanation) if you try to use them
3245 before logging has been started.
3246
3247 System shell access
3248 -------------------
3249
3250 Any input line beginning with a ! character is passed verbatim (minus
3251 the !, of course) to the underlying operating system. For example,
3252 typing !ls will run 'ls' in the current directory.
3253
3254 Manual capture of command output
3255 --------------------------------
3256
3257 If the input line begins with two exclamation marks, !!, the command is
3258 executed but its output is captured and returned as a python list, split
3259 on newlines. Any output sent by the subprocess to standard error is
3260 printed separately, so that the resulting list only captures standard
3261 output. The !! syntax is a shorthand for the %sx magic command.
3262
3263 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
3264 but allowing more fine-grained control of the capture details, and
3265 storing the result directly into a named variable. The direct use of
3266 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
3267 instead.
3268
3269 IPython also allows you to expand the value of python variables when
3270 making system calls. Any python variable or expression which you prepend
3271 with $ will get expanded before the system call is made::
3272
3273 In [1]: pyvar='Hello world'
3274 In [2]: !echo "A python variable: $pyvar"
3275 A python variable: Hello world
3276
3277 If you want the shell to actually see a literal $, you need to type it
3278 twice::
3279
3280 In [3]: !echo "A system variable: $$HOME"
3281 A system variable: /home/fperez
3282
3283 You can pass arbitrary expressions, though you'll need to delimit them
3284 with {} if there is ambiguity as to the extent of the expression::
3285
3286 In [5]: x=10
3287 In [6]: y=20
3288 In [13]: !echo $x+y
3289 10+y
3290 In [7]: !echo ${x+y}
3291 30
3292
3293 Even object attributes can be expanded::
3294
3295 In [12]: !echo $sys.argv
3296 [/home/fperez/usr/bin/ipython]
3297
3298
3299 System command aliases
3300 ----------------------
3301
3302 The %alias magic function and the alias option in the ipythonrc
3303 configuration file allow you to define magic functions which are in fact
3304 system shell commands. These aliases can have parameters.
3305
3306 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
3307
3308 Then, typing '%alias_name params' will execute the system command 'cmd
3309 params' (from your underlying operating system).
3310
3311 You can also define aliases with parameters using %s specifiers (one per
3312 parameter). The following example defines the %parts function as an
3313 alias to the command 'echo first %s second %s' where each %s will be
3314 replaced by a positional parameter to the call to %parts::
3315
3316 In [1]: alias parts echo first %s second %s
3317 In [2]: %parts A B
3318 first A second B
3319 In [3]: %parts A
3320 Incorrect number of arguments: 2 expected.
3321 parts is an alias to: 'echo first %s second %s'
3322
3323 If called with no parameters, %alias prints the table of currently
3324 defined aliases.
3325
3326 The %rehash/rehashx magics allow you to load your entire $PATH as
3327 ipython aliases. See their respective docstrings (or sec. 6.2
3328 <#sec:magic> for further details).
3329
3330
3331 .. _dreload:
3332
3333 Recursive reload
3334 ----------------
3335
3336 The dreload function does a recursive reload of a module: changes made
3337 to the module since you imported will actually be available without
3338 having to exit.
3339
3340
3341 Verbose and colored exception traceback printouts
3342 -------------------------------------------------
3343
3344 IPython provides the option to see very detailed exception tracebacks,
3345 which can be especially useful when debugging large programs. You can
3346 run any Python file with the %run function to benefit from these
3347 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
3348 be colored (if your terminal supports it) which makes them much easier
3349 to parse visually.
3350
3351 See the magic xmode and colors functions for details (just type %magic).
3352
3353 These features are basically a terminal version of Ka-Ping Yee's cgitb
3354 module, now part of the standard Python library.
3355
3356
3357 .. _Input caching:
3358
3359 Input caching system
3360 --------------------
3361
3362 IPython offers numbered prompts (In/Out) with input and output caching.
3363 All input is saved and can be retrieved as variables (besides the usual
3364 arrow key recall).
3365
3366 The following GLOBAL variables always exist (so don't overwrite them!):
3367 _i: stores previous input. _ii: next previous. _iii: next-next previous.
3368 _ih : a list of all input _ih[n] is the input from line n and this list
3369 is aliased to the global variable In. If you overwrite In with a
3370 variable of your own, you can remake the assignment to the internal list
3371 with a simple 'In=_ih'.
3372
3373 Additionally, global variables named _i<n> are dynamically created (<n>
3374 being the prompt counter), such that
3375 _i<n> == _ih[<n>] == In[<n>].
3376
3377 For example, what you typed at prompt 14 is available as _i14, _ih[14]
3378 and In[14].
3379
3380 This allows you to easily cut and paste multi line interactive prompts
3381 by printing them out: they print like a clean string, without prompt
3382 characters. You can also manipulate them like regular variables (they
3383 are strings), modify or exec them (typing 'exec _i9' will re-execute the
3384 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
3385 9 through 13 and line 18).
3386
3387 You can also re-execute multiple lines of input easily by using the
3388 magic %macro function (which automates the process and allows
3389 re-execution without having to type 'exec' every time). The macro system
3390 also allows you to re-execute previous lines which include magic
3391 function calls (which require special processing). Type %macro? or see
3392 sec. 6.2 <#sec:magic> for more details on the macro system.
3393
3394 A history function %hist allows you to see any part of your input
3395 history by printing a range of the _i variables.
3396
3397 .. _Output caching:
3398
3399 Output caching system
3400 ---------------------
3401
3402 For output that is returned from actions, a system similar to the input
3403 cache exists but using _ instead of _i. Only actions that produce a
3404 result (NOT assignments, for example) are cached. If you are familiar
3405 with Mathematica, IPython's _ variables behave exactly like
3406 Mathematica's % variables.
3407
3408 The following GLOBAL variables always exist (so don't overwrite them!):
3409
3410 * [_] (a single underscore) : stores previous output, like Python's
3411 default interpreter.
3412 * [__] (two underscores): next previous.
3413 * [___] (three underscores): next-next previous.
3414
3415 Additionally, global variables named _<n> are dynamically created (<n>
3416 being the prompt counter), such that the result of output <n> is always
3417 available as _<n> (don't use the angle brackets, just the number, e.g.
3418 _21).
3419
3420 These global variables are all stored in a global dictionary (not a
3421 list, since it only has entries for lines which returned a result)
3422 available under the names _oh and Out (similar to _ih and In). So the
3423 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
3424 accidentally overwrite the Out variable you can recover it by typing
3425 'Out=_oh' at the prompt.
3426
3427 This system obviously can potentially put heavy memory demands on your
3428 system, since it prevents Python's garbage collector from removing any
3429 previously computed results. You can control how many results are kept
3430 in memory with the option (at the command line or in your ipythonrc
3431 file) cache_size. If you set it to 0, the whole system is completely
3432 disabled and the prompts revert to the classic '>>>' of normal Python.
3433
3434
3435 Directory history
3436 -----------------
3437
3438 Your history of visited directories is kept in the global list _dh, and
3439 the magic %cd command can be used to go to any entry in that list. The
3440 %dhist command allows you to view this history. do ``cd -<TAB`` to
3441 conventiently view the directory history.
3442
3443
3444 Automatic parentheses and quotes
3445 --------------------------------
3446
3447 These features were adapted from Nathan Gray's LazyPython. They are
3448 meant to allow less typing for common situations.
3449
3450
3451 Automatic parentheses
3452 ---------------------
3453
3454 Callable objects (i.e. functions, methods, etc) can be invoked like this
3455 (notice the commas between the arguments)::
3456
3457 >>> callable_ob arg1, arg2, arg3
3458
3459 and the input will be translated to this::
3460
3461 -> callable_ob(arg1, arg2, arg3)
3462
3463 You can force automatic parentheses by using '/' as the first character
3464 of a line. For example::
3465
3466 >>> /globals # becomes 'globals()'
3467
3468 Note that the '/' MUST be the first character on the line! This won't work::
3469
3470 >>> print /globals # syntax error
3471
3472 In most cases the automatic algorithm should work, so you should rarely
3473 need to explicitly invoke /. One notable exception is if you are trying
3474 to call a function with a list of tuples as arguments (the parenthesis
3475 will confuse IPython)::
3476
3477 In [1]: zip (1,2,3),(4,5,6) # won't work
3478
3479 but this will work::
3480
3481 In [2]: /zip (1,2,3),(4,5,6)
3482 ---> zip ((1,2,3),(4,5,6))
3483 Out[2]= [(1, 4), (2, 5), (3, 6)]
3484
3485 IPython tells you that it has altered your command line by displaying
3486 the new command line preceded by ->. e.g.::
3487
3488 In [18]: callable list
3489 ----> callable (list)
3490
3491
3492 Automatic quoting
3493 -----------------
3494
3495 You can force automatic quoting of a function's arguments by using ','
3496 or ';' as the first character of a line. For example::
3497
3498 >>> ,my_function /home/me # becomes my_function("/home/me")
3499
3500 If you use ';' instead, the whole argument is quoted as a single string
3501 (while ',' splits on whitespace)::
3502
3503 >>> ,my_function a b c # becomes my_function("a","b","c")
3504
3505 >>> ;my_function a b c # becomes my_function("a b c")
3506
3507 Note that the ',' or ';' MUST be the first character on the line! This
3508 won't work::
3509
3510 >>> x = ,my_function /home/me # syntax error
3511
3512 .. customization:
3513
3514 Customization
3515 =============
3516
3517 There are 2 ways to configure IPython - the old way of using ipythonrc
3518 files (an INI-file like format), and the new way that involves editing
3519 your ipy_user_conf.py. Both configuration systems work at the same
3520 time, so you can set your options in both, but if you are hesitating
3521 about which alternative to choose, we recommend the ipy_user_conf.py
3522 approach, as it will give you more power and control in the long
3523 run. However, there are few options such as pylab_import_all that can
3524 only be specified in ipythonrc file or command line - the reason for
3525 this is that they are needed before IPython has been started up, and
3526 the IPApi object used in ipy_user_conf.py is not yet available at that
3527 time. A hybrid approach of specifying a few options in ipythonrc and
3528 doing the more advanced configuration in ipy_user_conf.py is also
3529 possible.
3530
3531 The ipythonrc approach
3532 ----------------------
3533
3534 As we've already mentioned, IPython reads a configuration file which can
3535 be specified at the command line (-rcfile) or which by default is
3536 assumed to be called ipythonrc. Such a file is looked for in the current
3537 directory where IPython is started and then in your IPYTHONDIR, which
3538 allows you to have local configuration files for specific projects. In
3539 this section we will call these types of configuration files simply
3540 rcfiles (short for resource configuration file).
3541
3542 The syntax of an rcfile is one of key-value pairs separated by
3543 whitespace, one per line. Lines beginning with a # are ignored as
3544 comments, but comments can not be put on lines with data (the parser is
3545 fairly primitive). Note that these are not python files, and this is
3546 deliberate, because it allows us to do some things which would be quite
3547 tricky to implement if they were normal python files.
3548
3549 First, an rcfile can contain permanent default values for almost all
3550 command line options (except things like -help or -Version). Sec
3551 `command line options`_ contains a description of all command-line
3552 options. However, values you explicitly specify at the command line
3553 override the values defined in the rcfile.
3554
3555 Besides command line option values, the rcfile can specify values for
3556 certain extra special options which are not available at the command
3557 line. These options are briefly described below.
3558
3559 Each of these options may appear as many times as you need it in the file.
3560
3561 * include <file1> <file2> ...: you can name other rcfiles you want
3562 to recursively load up to 15 levels (don't use the <> brackets in
3563 your names!). This feature allows you to define a 'base' rcfile
3564 with general options and special-purpose files which can be loaded
3565 only when needed with particular configuration options. To make
3566 this more convenient, IPython accepts the -profile <name> option
3567 (abbreviates to -p <name>) which tells it to look for an rcfile
3568 named ipythonrc-<name>.
3569 * import_mod <mod1> <mod2> ...: import modules with 'import
3570 <mod1>,<mod2>,...'
3571 * import_some <mod> <f1> <f2> ...: import functions with 'from
3572 <mod> import <f1>,<f2>,...'
3573 * import_all <mod1> <mod2> ...: for each module listed import
3574 functions with ``from <mod> import *``.
3575 * execute <python code>: give any single-line python code to be
3576 executed.
3577 * execfile <filename>: execute the python file given with an
3578 'execfile(filename)' command. Username expansion is performed on
3579 the given names. So if you need any amount of extra fancy
3580 customization that won't fit in any of the above 'canned' options,
3581 you can just put it in a separate python file and execute it.
3582 * alias <alias_def>: this is equivalent to calling
3583 '%alias <alias_def>' at the IPython command line. This way, from
3584 within IPython you can do common system tasks without having to
3585 exit it or use the ! escape. IPython isn't meant to be a shell
3586 replacement, but it is often very useful to be able to do things
3587 with files while testing code. This gives you the flexibility to
3588 have within IPython any aliases you may be used to under your
3589 normal system shell.
3590
3591
3592 .. _ipythonrc:
3593
3594 Sample ipythonrc file
3595 ---------------------
3596
3597 The default rcfile, called ipythonrc and supplied in your IPYTHONDIR
3598 directory contains lots of comments on all of these options. We
3599 reproduce it here for reference::
3600
3601
3602 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
3603 # $Id: ipythonrc 2156 2007-03-19 02:32:19Z fperez $
3604
3605 #***************************************************************************
3606 #
3607 # Configuration file for IPython -- ipythonrc format
3608 #
3609 # ===========================================================
3610 # Deprecation note: you should look into modifying ipy_user_conf.py (located
3611 # in ~/.ipython or ~/_ipython, depending on your platform) instead, it's a
3612 # more flexible and robust (and better supported!) configuration
3613 # method.
3614 # ===========================================================
3615 #
3616 # The format of this file is simply one of 'key value' lines.
3617 # Lines containing only whitespace at the beginning and then a # are ignored
3618 # as comments. But comments can NOT be put on lines with data.
3619
3620 # The meaning and use of each key are explained below.
3621
3622 #---------------------------------------------------------------------------
3623 # Section: included files
3624
3625 # Put one or more *config* files (with the syntax of this file) you want to
3626 # include. For keys with a unique value the outermost file has precedence. For
3627 # keys with multiple values, they all get assembled into a list which then
3628 # gets loaded by IPython.
3629
3630 # In this file, all lists of things should simply be space-separated.
3631
3632 # This allows you to build hierarchies of files which recursively load
3633 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
3634 # should only keep here basic things you always want available. Then you can
3635 # include it in every other special-purpose config file you create.
3636 include
3637
3638 #---------------------------------------------------------------------------
3639 # Section: startup setup
3640
3641 # These are mostly things which parallel a command line option of the same
3642 # name.
3643
3644 # Keys in this section should only appear once. If any key from this section
3645 # is encountered more than once, the last value remains, all earlier ones get
3646 # discarded.
3647
3648
3649 # Automatic calling of callable objects. If set to 1 or 2, callable objects
3650 # are automatically called when invoked at the command line, even if you don't
3651 # type parentheses. IPython adds the parentheses for you. For example:
3652
3653 #In [1]: str 45
3654 #------> str(45)
3655 #Out[1]: '45'
3656
3657 # IPython reprints your line with '---->' indicating that it added
3658 # parentheses. While this option is very convenient for interactive use, it
3659 # may occasionally cause problems with objects which have side-effects if
3660 # called unexpectedly.
3661
3662 # The valid values for autocall are:
3663
3664 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
3665
3666 # autocall 1 -> active, but do not apply if there are no arguments on the line.
3667
3668 # In this mode, you get:
3669
3670 #In [1]: callable
3671 #Out[1]: <built-in function callable>
3672
3673 #In [2]: callable 'hello'
3674 #------> callable('hello')
3675 #Out[2]: False
3676
3677 # 2 -> Active always. Even if no arguments are present, the callable object
3678 # is called:
3679
3680 #In [4]: callable
3681 #------> callable()
3682
3683 # Note that even with autocall off, you can still use '/' at the start of a
3684 # line to treat the first argument on the command line as a function and add
3685 # parentheses to it:
3686
3687 #In [8]: /str 43
3688 #------> str(43)
3689 #Out[8]: '43'
3690
3691 autocall 1
3692
3693 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
3694 # source code (see the 'editor' variable below), it is possible that you save
3695 # a file with syntax errors in it. If this variable is true, IPython will ask
3696 # you whether to re-open the editor immediately to correct such an error.
3697
3698 autoedit_syntax 0
3699
3700 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
3701 # line, while also un-indenting automatically after 'raise' or 'return'.
3702
3703 # This feature uses the readline library, so it will honor your ~/.inputrc
3704 # configuration (or whatever file your INPUTRC variable points to). Adding
3705 # the following lines to your .inputrc file can make indent/unindenting more
3706 # convenient (M-i indents, M-u unindents):
3707
3708 # $if Python
3709 # "\M-i": " "
3710 # "\M-u": "\d\d\d\d"
3711 # $endif
3712
3713 # The feature is potentially a bit dangerous, because it can cause problems
3714 # with pasting of indented code (the pasted code gets re-indented on each
3715 # line). But it's a huge time-saver when working interactively. The magic
3716 # function %autoindent allows you to toggle it on/off at runtime.
3717
3718 autoindent 1
3719
3720 # Auto-magic. This gives you access to all the magic functions without having
3721 # to prepend them with an % sign. If you define a variable with the same name
3722 # as a magic function (say who=1), you will need to access the magic function
3723 # with % (%who in this example). However, if later you delete your variable
3724 # (del who), you'll recover the automagic calling form.
3725
3726 # Considering that many magic functions provide a lot of shell-like
3727 # functionality, automagic gives you something close to a full Python+system
3728 # shell environment (and you can extend it further if you want).
3729
3730 automagic 1
3731
3732 # Size of the output cache. After this many entries are stored, the cache will
3733 # get flushed. Depending on the size of your intermediate calculations, you
3734 # may have memory problems if you make it too big, since keeping things in the
3735 # cache prevents Python from reclaiming the memory for old results. Experiment
3736 # with a value that works well for you.
3737
3738 # If you choose cache_size 0 IPython will revert to python's regular >>>
3739 # unnumbered prompt. You will still have _, __ and ___ for your last three
3740 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
3741 # you are running on a slow machine or with very limited memory, this may
3742 # help.
3743
3744 cache_size 1000
3745
3746 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
3747 # but that's your choice! Classic 1 -> same as IPython -classic.
3748 # Note that this is _not_ the normal python interpreter, it's simply
3749 # IPython emulating most of the classic interpreter's behavior.
3750 classic 0
3751
3752 # colors - Coloring option for prompts and traceback printouts.
3753
3754 # Currently available schemes: NoColor, Linux, LightBG.
3755
3756 # This option allows coloring the prompts and traceback printouts. This
3757 # requires a terminal which can properly handle color escape sequences. If you
3758 # are having problems with this, use the NoColor scheme (uses no color escapes
3759 # at all).
3760
3761 # The Linux option works well in linux console type environments: dark
3762 # background with light fonts.
3763
3764 # LightBG is similar to Linux but swaps dark/light colors to be more readable
3765 # in light background terminals.
3766
3767 # keep uncommented only the one you want:
3768 colors Linux
3769 #colors LightBG
3770 #colors NoColor
3771
3772 ########################
3773 # Note to Windows users
3774 #
3775 # Color and readline support is avaialble to Windows users via Gary Bishop's
3776 # readline library. You can find Gary's tools at
3777 # http://sourceforge.net/projects/uncpythontools.
3778 # Note that his readline module requires in turn the ctypes library, available
3779 # at http://starship.python.net/crew/theller/ctypes.
3780 ########################
3781
3782 # color_info: IPython can display information about objects via a set of
3783 # functions, and optionally can use colors for this, syntax highlighting
3784 # source code and various other elements. This information is passed through a
3785 # pager (it defaults to 'less' if $PAGER is not set).
3786
3787 # If your pager has problems, try to setting it to properly handle escapes
3788 # (see the less manpage for detail), or disable this option. The magic
3789 # function %color_info allows you to toggle this interactively for testing.
3790
3791 color_info 1
3792
3793 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
3794 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
3795 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
3796 # any confirmation.
3797
3798 confirm_exit 1
3799
3800 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
3801 # still available as dreload() and appears as a builtin.
3802
3803 deep_reload 0
3804
3805 # Which editor to use with the %edit command. If you leave this at 0, IPython
3806 # will honor your EDITOR environment variable. Since this editor is invoked on
3807 # the fly by ipython and is meant for editing small code snippets, you may
3808 # want to use a small, lightweight editor here.
3809
3810 # For Emacs users, setting up your Emacs server properly as described in the
3811 # manual is a good idea. An alternative is to use jed, a very light editor
3812 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
3813
3814 editor 0
3815
3816 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
3817 log 0
3818
3819 # Same as ipython -Logfile YourLogfileName.
3820 # Don't use with log 1 (use one or the other)
3821 logfile ''
3822
3823 # banner 0 -> same as ipython -nobanner
3824 banner 1
3825
3826 # messages 0 -> same as ipython -nomessages
3827 messages 1
3828
3829 # Automatically call the pdb debugger after every uncaught exception. If you
3830 # are used to debugging using pdb, this puts you automatically inside of it
3831 # after any call (either in IPython or in code called by it) which triggers an
3832 # exception which goes uncaught.
3833 pdb 0
3834
3835 # Enable the pprint module for printing. pprint tends to give a more readable
3836 # display (than print) for complex nested data structures.
3837 pprint 1
3838
3839 # Prompt strings
3840
3841 # Most bash-like escapes can be used to customize IPython's prompts, as well as
3842 # a few additional ones which are IPython-specific. All valid prompt escapes
3843 # are described in detail in the Customization section of the IPython HTML/PDF
3844 # manual.
3845
3846 # Use \# to represent the current prompt number, and quote them to protect
3847 # spaces.
3848 prompt_in1 'In [\#]: '
3849
3850 # \D is replaced by as many dots as there are digits in the
3851 # current value of \#.
3852 prompt_in2 ' .\D.: '
3853
3854 prompt_out 'Out[\#]: '
3855
3856 # Select whether to left-pad the output prompts to match the length of the
3857 # input ones. This allows you for example to use a simple '>' as an output
3858 # prompt, and yet have the output line up with the input. If set to false,
3859 # the output prompts will be unpadded (flush left).
3860 prompts_pad_left 1
3861
3862 # Pylab support: when ipython is started with the -pylab switch, by default it
3863 # executes 'from matplotlib.pylab import *'. Set this variable to false if you
3864 # want to disable this behavior.
3865
3866 # For details on pylab, see the matplotlib website:
3867 # http://matplotlib.sf.net
3868 pylab_import_all 1
3869
3870
3871 # quick 1 -> same as ipython -quick
3872 quick 0
3873
3874 # Use the readline library (1) or not (0). Most users will want this on, but
3875 # if you experience strange problems with line management (mainly when using
3876 # IPython inside Emacs buffers) you may try disabling it. Not having it on
3877 # prevents you from getting command history with the arrow keys, searching and
3878 # name completion using TAB.
3879
3880 readline 1
3881
3882 # Screen Length: number of lines of your screen. This is used to control
3883 # printing of very long strings. Strings longer than this number of lines will
3884 # be paged with the less command instead of directly printed.
3885
3886 # The default value for this is 0, which means IPython will auto-detect your
3887 # screen size every time it needs to print. If for some reason this isn't
3888 # working well (it needs curses support), specify it yourself. Otherwise don't
3889 # change the default.
3890
3891 screen_length 0
3892
3893 # Prompt separators for input and output.
3894 # Use \n for newline explicitly, without quotes.
3895 # Use 0 (like at the cmd line) to turn off a given separator.
3896
3897 # The structure of prompt printing is:
3898 # (SeparateIn)Input....
3899 # (SeparateOut)Output...
3900 # (SeparateOut2), # that is, no newline is printed after Out2
3901 # By choosing these you can organize your output any way you want.
3902
3903 separate_in \n
3904 separate_out 0
3905 separate_out2 0
3906
3907 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
3908 # Simply removes all input/output separators, overriding the choices above.
3909 nosep 0
3910
3911 # Wildcard searches - IPython has a system for searching names using
3912 # shell-like wildcards; type %psearch? for details. This variables sets
3913 # whether by default such searches should be case sensitive or not. You can
3914 # always override the default at the system command line or the IPython
3915 # prompt.
3916
3917 wildcards_case_sensitive 1
3918
3919 # Object information: at what level of detail to display the string form of an
3920 # object. If set to 0, ipython will compute the string form of any object X,
3921 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
3922 # computed when X?? is given, and if set to 2 or higher, it will never be
3923 # computed (there is no X??? level of detail). This is mostly of use to
3924 # people who frequently manipulate objects whose string representation is
3925 # extremely expensive to compute.
3926
3927 object_info_string_level 0
3928
3929 # xmode - Exception reporting mode.
3930
3931 # Valid modes: Plain, Context and Verbose.
3932
3933 # Plain: similar to python's normal traceback printing.
3934
3935 # Context: prints 5 lines of context source code around each line in the
3936 # traceback.
3937
3938 # Verbose: similar to Context, but additionally prints the variables currently
3939 # visible where the exception happened (shortening their strings if too
3940 # long). This can potentially be very slow, if you happen to have a huge data
3941 # structure whose string representation is complex to compute. Your computer
3942 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
3943 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
3944
3945 #xmode Plain
3946 xmode Context
3947 #xmode Verbose
3948
3949 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
3950 # !cmd) to be used in multi-line input (like for loops). For example, if you
3951 # have this active, the following is valid in IPython:
3952 #
3953 #In [17]: for i in range(3):
3954 # ....: mkdir $i
3955 # ....: !touch $i/hello
3956 # ....: ls -l $i
3957
3958 multi_line_specials 1
3959
3960
3961 # System calls: When IPython makes system calls (e.g. via special syntax like
3962 # !cmd or !!cmd, or magics like %sc or %sx), it can print the command it is
3963 # executing to standard output, prefixed by a header string.
3964
3965 system_header "IPython system call: "
3966
3967 system_verbose 1
3968
3969 # wxversion: request a specific wxPython version (used for -wthread)
3970
3971 # Set this to the value of wxPython you want to use, but note that this
3972 # feature requires you to have the wxversion Python module to work. If you
3973 # don't have the wxversion module (try 'import wxversion' at the prompt to
3974 # check) or simply want to leave the system to pick up the default, leave this
3975 # variable at 0.
3976
3977 wxversion 0
3978
3979 #---------------------------------------------------------------------------
3980 # Section: Readline configuration (readline is not available for MS-Windows)
3981
3982 # This is done via the following options:
3983
3984 # (i) readline_parse_and_bind: this option can appear as many times as you
3985 # want, each time defining a string to be executed via a
3986 # readline.parse_and_bind() command. The syntax for valid commands of this
3987 # kind can be found by reading the documentation for the GNU readline library,
3988 # as these commands are of the kind which readline accepts in its
3989 # configuration file.
3990
3991 # The TAB key can be used to complete names at the command line in one of two
3992 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
3993 # completes as much as possible while 'menu-complete' cycles through all
3994 # possible completions. Leave the one you prefer uncommented.
3995
3996 readline_parse_and_bind tab: complete
3997 #readline_parse_and_bind tab: menu-complete
3998
3999 # This binds Control-l to printing the list of all possible completions when
4000 # there is more than one (what 'complete' does when hitting TAB twice, or at
4001 # the first TAB if show-all-if-ambiguous is on)
4002 readline_parse_and_bind "\C-l": possible-completions
4003
4004 # This forces readline to automatically print the above list when tab
4005 # completion is set to 'complete'. You can still get this list manually by
4006 # using the key bound to 'possible-completions' (Control-l by default) or by
4007 # hitting TAB twice. Turning this on makes the printing happen at the first
4008 # TAB.
4009 readline_parse_and_bind set show-all-if-ambiguous on
4010
4011 # If you have TAB set to complete names, you can rebind any key (Control-o by
4012 # default) to insert a true TAB character.
4013 readline_parse_and_bind "\C-o": tab-insert
4014
4015 # These commands allow you to indent/unindent easily, with the 4-space
4016 # convention of the Python coding standards. Since IPython's internal
4017 # auto-indent system also uses 4 spaces, you should not change the number of
4018 # spaces in the code below.
4019 readline_parse_and_bind "\M-i": " "
4020 readline_parse_and_bind "\M-o": "\d\d\d\d"
4021 readline_parse_and_bind "\M-I": "\d\d\d\d"
4022
4023 # Bindings for incremental searches in the history. These searches use the
4024 # string typed so far on the command line and search anything in the previous
4025 # input history containing them.
4026 readline_parse_and_bind "\C-r": reverse-search-history
4027 readline_parse_and_bind "\C-s": forward-search-history
4028
4029 # Bindings for completing the current line in the history of previous
4030 # commands. This allows you to recall any previous command by typing its first
4031 # few letters and hitting Control-p, bypassing all intermediate commands which
4032 # may be in the history (much faster than hitting up-arrow 50 times!)
4033 readline_parse_and_bind "\C-p": history-search-backward
4034 readline_parse_and_bind "\C-n": history-search-forward
4035
4036 # I also like to have the same functionality on the plain arrow keys. If you'd
4037 # rather have the arrows use all the history (and not just match what you've
4038 # typed so far), comment out or delete the next two lines.
4039 readline_parse_and_bind "\e[A": history-search-backward
4040 readline_parse_and_bind "\e[B": history-search-forward
4041
4042 # These are typically on by default under *nix, but not win32.
4043 readline_parse_and_bind "\C-k": kill-line
4044 readline_parse_and_bind "\C-u": unix-line-discard
4045
4046 # (ii) readline_remove_delims: a string of characters to be removed from the
4047 # default word-delimiters list used by readline, so that completions may be
4048 # performed on strings which contain them.
4049
4050 readline_remove_delims -/~
4051
4052 # (iii) readline_merge_completions: whether to merge the result of all
4053 # possible completions or not. If true, IPython will complete filenames,
4054 # python names and aliases and return all possible completions. If you set it
4055 # to false, each completer is used at a time, and only if it doesn't return
4056 # any completions is the next one used.
4057
4058 # The default order is: [python_matches, file_matches, alias_matches]
4059
4060 readline_merge_completions 1
4061
4062 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
4063 # will complete all attributes of an object, including all the special methods
4064 # whose names start with single or double underscores (like __getitem__ or
4065 # __class__).
4066
4067 # This variable allows you to control this completion behavior:
4068
4069 # readline_omit__names 1 -> completion will omit showing any names starting
4070 # with two __, but it will still show names starting with one _.
4071
4072 # readline_omit__names 2 -> completion will omit all names beginning with one
4073 # _ (which obviously means filtering out the double __ ones).
4074
4075 # Even when this option is set, you can still see those names by explicitly
4076 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
4077 # complete attribute names starting with '_'.
4078
4079 # This option is off by default so that new users see all attributes of any
4080 # objects they are dealing with.
4081
4082 readline_omit__names 0
4083
4084 #---------------------------------------------------------------------------
4085 # Section: modules to be loaded with 'import ...'
4086
4087 # List, separated by spaces, the names of the modules you want to import
4088
4089 # Example:
4090 # import_mod sys os
4091 # will produce internally the statements
4092 # import sys
4093 # import os
4094
4095 # Each import is executed in its own try/except block, so if one module
4096 # fails to load the others will still be ok.
4097
4098 import_mod
4099
4100 #---------------------------------------------------------------------------
4101 # Section: modules to import some functions from: 'from ... import ...'
4102
4103 # List, one per line, the modules for which you want only to import some
4104 # functions. Give the module name first and then the name of functions to be
4105 # imported from that module.
4106
4107 # Example:
4108
4109 # import_some IPython.genutils timing timings
4110 # will produce internally the statement
4111 # from IPython.genutils import timing, timings
4112
4113 # timing() and timings() are two IPython utilities for timing the execution of
4114 # your own functions, which you may find useful. Just commment out the above
4115 # line if you want to test them.
4116
4117 # If you have more than one modules_some line, each gets its own try/except
4118 # block (like modules, see above).
4119
4120 import_some
4121
4122 #---------------------------------------------------------------------------
4123 # Section: modules to import all from : 'from ... import *'
4124
4125 # List (same syntax as import_mod above) those modules for which you want to
4126 # import all functions. Remember, this is a potentially dangerous thing to do,
4127 # since it is very easy to overwrite names of things you need. Use with
4128 # caution.
4129
4130 # Example:
4131 # import_all sys os
4132 # will produce internally the statements
4133 # from sys import *
4134 # from os import *
4135
4136 # As before, each will be called in a separate try/except block.
4137
4138 import_all
4139
4140 #---------------------------------------------------------------------------
4141 # Section: Python code to execute.
4142
4143 # Put here code to be explicitly executed (keep it simple!)
4144 # Put one line of python code per line. All whitespace is removed (this is a
4145 # feature, not a bug), so don't get fancy building loops here.
4146 # This is just for quick convenient creation of things you want available.
4147
4148 # Example:
4149 # execute x = 1
4150 # execute print 'hello world'; y = z = 'a'
4151 # will produce internally
4152 # x = 1
4153 # print 'hello world'; y = z = 'a'
4154 # and each *line* (not each statement, we don't do python syntax parsing) is
4155 # executed in its own try/except block.
4156
4157 execute
4158
4159 # Note for the adventurous: you can use this to define your own names for the
4160 # magic functions, by playing some namespace tricks:
4161
4162 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
4163
4164 # defines %pf as a new name for %profile.
4165
4166 #---------------------------------------------------------------------------
4167 # Section: Pyhton files to load and execute.
4168
4169 # Put here the full names of files you want executed with execfile(file). If
4170 # you want complicated initialization, just write whatever you want in a
4171 # regular python file and load it from here.
4172
4173 # Filenames defined here (which *must* include the extension) are searched for
4174 # through all of sys.path. Since IPython adds your .ipython directory to
4175 # sys.path, they can also be placed in your .ipython dir and will be
4176 # found. Otherwise (if you want to execute things not in .ipyton nor in
4177 # sys.path) give a full path (you can use ~, it gets expanded)
4178
4179 # Example:
4180 # execfile file1.py ~/file2.py
4181 # will generate
4182 # execfile('file1.py')
4183 # execfile('_path_to_your_home/file2.py')
4184
4185 # As before, each file gets its own try/except block.
4186
4187 execfile
4188
4189 # If you are feeling adventurous, you can even add functionality to IPython
4190 # through here. IPython works through a global variable called __ip which
4191 # exists at the time when these files are read. If you know what you are doing
4192 # (read the source) you can add functions to __ip in files loaded here.
4193
4194 # The file example-magic.py contains a simple but correct example. Try it:
4195
4196 # execfile example-magic.py
4197
4198 # Look at the examples in IPython/iplib.py for more details on how these magic
4199 # functions need to process their arguments.
4200
4201 #---------------------------------------------------------------------------
4202 # Section: aliases for system shell commands
4203
4204 # Here you can define your own names for system commands. The syntax is
4205 # similar to that of the builtin %alias function:
4206
4207 # alias alias_name command_string
4208
4209 # The resulting aliases are auto-generated magic functions (hence usable as
4210 # %alias_name)
4211
4212 # For example:
4213
4214 # alias myls ls -la
4215
4216 # will define 'myls' as an alias for executing the system command 'ls -la'.
4217 # This allows you to customize IPython's environment to have the same aliases
4218 # you are accustomed to from your own shell.
4219
4220 # You can also define aliases with parameters using %s specifiers (one per
4221 # parameter):
4222
4223 # alias parts echo first %s second %s
4224
4225 # will give you in IPython:
4226 # >>> %parts A B
4227 # first A second B
4228
4229 # Use one 'alias' statement per alias you wish to define.
4230
4231 # alias
4232
4233 #************************* end of file <ipythonrc> ************************
4234
4235
4236 ipy_user_conf.py
4237 ----------------
4238
4239 There should be a simple template ipy_user_conf.py file in your
4240 ~/.ipython directory. It is a plain python module that is imported
4241 during IPython startup, so you can do pretty much what you want there
4242 - import modules, configure extensions, change options, define magic
4243 commands, put variables and functions in the IPython namespace,
4244 etc. You use the IPython extension api object, acquired by
4245 IPython.ipapi.get() and documented in the "IPython extension API"
4246 chapter, to interact with IPython. A sample ipy_user_conf.py is listed
4247 below for reference::
4248
4249 # Most of your config files and extensions will probably start
4250 # with this import
4251
4252 import IPython.ipapi
4253 ip = IPython.ipapi.get()
4254
4255 # You probably want to uncomment this if you did %upgrade -nolegacy
4256 # import ipy_defaults
4257
4258 import os
4259
4260 def main():
4261
4262 #ip.dbg.debugmode = True
4263 ip.dbg.debug_stack()
4264
4265 # uncomment if you want to get ipython -p sh behaviour
4266 # without having to use command line switches
4267 import ipy_profile_sh
4268 import jobctrl
4269
4270 # Configure your favourite editor?
4271 # Good idea e.g. for %edit os.path.isfile
4272
4273 #import ipy_editors
4274
4275 # Choose one of these:
4276
4277 #ipy_editors.scite()
4278 #ipy_editors.scite('c:/opt/scite/scite.exe')
4279 #ipy_editors.komodo()
4280 #ipy_editors.idle()
4281 # ... or many others, try 'ipy_editors??' after import to see them
4282
4283 # Or roll your own:
4284 #ipy_editors.install_editor("c:/opt/jed +$line $file")
4285
4286
4287 o = ip.options
4288 # An example on how to set options
4289 #o.autocall = 1
4290 o.system_verbose = 0
4291
4292 #import_all("os sys")
4293 #execf('~/_ipython/ns.py')
4294
4295
4296 # -- prompt
4297 # A different, more compact set of prompts from the default ones, that
4298 # always show your current location in the filesystem:
4299
4300 #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
4301 #o.prompt_in2 = r'.\D: '
4302 #o.prompt_out = r'[\#] '
4303
4304 # Try one of these color settings if you can't read the text easily
4305 # autoexec is a list of IPython commands to execute on startup
4306 #o.autoexec.append('%colors LightBG')
4307 #o.autoexec.append('%colors NoColor')
4308 o.autoexec.append('%colors Linux')
4309
4310
4311 # some config helper functions you can use
4312 def import_all(modules):
4313 """ Usage: import_all("os sys") """
4314 for m in modules.split():
4315 ip.ex("from %s import *" % m)
4316
4317 def execf(fname):
4318 """ Execute a file in user namespace """
4319 ip.ex('execfile("%s")' % os.path.expanduser(fname))
4320
4321 main()
4322
4323 .. _Prompts:
4324
4325 Fine-tuning your prompt
4326 -----------------------
4327
4328 IPython's prompts can be customized using a syntax similar to that of
4329 the bash shell. Many of bash's escapes are supported, as well as a few
4330 additional ones. We list them below::
4331
4332 \#
4333 the prompt/history count number. This escape is automatically
4334 wrapped in the coloring codes for the currently active color scheme.
4335 \N
4336 the 'naked' prompt/history count number: this is just the number
4337 itself, without any coloring applied to it. This lets you produce
4338 numbered prompts with your own colors.
4339 \D
4340 the prompt/history count, with the actual digits replaced by dots.
4341 Used mainly in continuation prompts (prompt_in2)
4342 \w
4343 the current working directory
4344 \W
4345 the basename of current working directory
4346 \Xn
4347 where $n=0\ldots5.$ The current working directory, with $HOME
4348 replaced by ~, and filtered out to contain only $n$ path elements
4349 \Yn
4350 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
4351 is similar to the behavior of the %cn escapes in tcsh)
4352 \u
4353 the username of the current user
4354 \$
4355 if the effective UID is 0, a #, otherwise a $
4356 \h
4357 the hostname up to the first '.'
4358 \H
4359 the hostname
4360 \n
4361 a newline
4362 \r
4363 a carriage return
4364 \v
4365 IPython version string
4366
4367 In addition to these, ANSI color escapes can be insterted into the
4368 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
4369 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
4370 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
4371 Yellow.
4372
4373 Finally, IPython supports the evaluation of arbitrary expressions in
4374 your prompt string. The prompt strings are evaluated through the syntax
4375 of PEP 215, but basically you can use $x.y to expand the value of x.y,
4376 and for more complicated expressions you can use braces: ${foo()+x} will
4377 call function foo and add to it the value of x, before putting the
4378 result into your prompt. For example, using
4379 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
4380 will print the result of the uptime command on each prompt (assuming the
4381 commands module has been imported in your ipythonrc file).
4382
4383
4384 Prompt examples
4385
4386 The following options in an ipythonrc file will give you IPython's
4387 default prompts::
4388
4389 prompt_in1 'In [\#]:'
4390 prompt_in2 ' .\D.:'
4391 prompt_out 'Out[\#]:'
4392
4393 which look like this::
4394
4395 In [1]: 1+2
4396 Out[1]: 3
4397
4398 In [2]: for i in (1,2,3):
4399 ...: print i,
4400 ...:
4401 1 2 3
4402
4403 These will give you a very colorful prompt with path information::
4404
4405 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
4406 prompt_in2 ' ..\D>'
4407 prompt_out '<\#>'
4408
4409 which look like this::
4410
4411 fperez[~/ipython]1> 1+2
4412 <1> 3
4413 fperez[~/ipython]2> for i in (1,2,3):
4414 ...> print i,
4415 ...>
4416 1 2 3
4417
4418
4419 .. _Profiles:
4420
4421 IPython profiles
4422 ----------------
4423
4424 As we already mentioned, IPython supports the -profile command-line
4425 option (see sec. `command line options`_). A profile is nothing more
4426 than a particular configuration file like your basic ipythonrc one,
4427 but with particular customizations for a specific purpose. When you
4428 start IPython with 'ipython -profile <name>', it assumes that in your
4429 IPYTHONDIR there is a file called ipythonrc-<name> or
4430 ipy_profile_<name>.py, and loads it instead of the normal ipythonrc.
4431
4432 This system allows you to maintain multiple configurations which load
4433 modules, set options, define functions, etc. suitable for different
4434 tasks and activate them in a very simple manner. In order to avoid
4435 having to repeat all of your basic options (common things that don't
4436 change such as your color preferences, for example), any profile can
4437 include another configuration file. The most common way to use profiles
4438 is then to have each one include your basic ipythonrc file as a starting
4439 point, and then add further customizations.
4440
4441 IPython as your default Python environment
4442 ==========================================
4443
4444 Python honors the environment variable PYTHONSTARTUP and will execute at
4445 startup the file referenced by this variable. If you put at the end of
4446 this file the following two lines of code::
4447
4448 import IPython
4449 IPython.Shell.IPShell().mainloop(sys_exit=1)
4450
4451 then IPython will be your working environment anytime you start Python.
4452 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
4453 it finishes, otherwise you'll be back at the normal Python '>>>'
4454 prompt.
4455
4456 This is probably useful to developers who manage multiple Python
4457 versions and don't want to have correspondingly multiple IPython
4458 versions. Note that in this mode, there is no way to pass IPython any
4459 command-line options, as those are trapped first by Python itself.
4460
4461 .. _Embedding:
4462
4463 Embedding IPython
4464 =================
4465
4466 It is possible to start an IPython instance inside your own Python
4467 programs. This allows you to evaluate dynamically the state of your
4468 code, operate with your variables, analyze them, etc. Note however that
4469 any changes you make to values while in the shell do not propagate back
4470 to the running code, so it is safe to modify your values because you
4471 won't break your code in bizarre ways by doing so.
4472
4473 This feature allows you to easily have a fully functional python
4474 environment for doing object introspection anywhere in your code with a
4475 simple function call. In some cases a simple print statement is enough,
4476 but if you need to do more detailed analysis of a code fragment this
4477 feature can be very valuable.
4478
4479 It can also be useful in scientific computing situations where it is
4480 common to need to do some automatic, computationally intensive part and
4481 then stop to look at data, plots, etc.
4482 Opening an IPython instance will give you full access to your data and
4483 functions, and you can resume program execution once you are done with
4484 the interactive part (perhaps to stop again later, as many times as
4485 needed).
4486
4487 The following code snippet is the bare minimum you need to include in
4488 your Python programs for this to work (detailed examples follow later)::
4489
4490 from IPython.Shell import IPShellEmbed
4491
4492 ipshell = IPShellEmbed()
4493
4494 ipshell() # this call anywhere in your program will start IPython
4495
4496 You can run embedded instances even in code which is itself being run at
4497 the IPython interactive prompt with '%run <filename>'. Since it's easy
4498 to get lost as to where you are (in your top-level IPython or in your
4499 embedded one), it's a good idea in such cases to set the in/out prompts
4500 to something different for the embedded instances. The code examples
4501 below illustrate this.
4502
4503 You can also have multiple IPython instances in your program and open
4504 them separately, for example with different options for data
4505 presentation. If you close and open the same instance multiple times,
4506 its prompt counters simply continue from each execution to the next.
4507
4508 Please look at the docstrings in the Shell.py module for more details on
4509 the use of this system.
4510
4511 The following sample file illustrating how to use the embedding
4512 functionality is provided in the examples directory as example-embed.py.
4513 It should be fairly self-explanatory::
4514
4515
4516 #!/usr/bin/env python
4517
4518 """An example of how to embed an IPython shell into a running program.
4519
4520 Please see the documentation in the IPython.Shell module for more details.
4521
4522 The accompanying file example-embed-short.py has quick code fragments for
4523 embedding which you can cut and paste in your code once you understand how
4524 things work.
4525
4526 The code in this file is deliberately extra-verbose, meant for learning."""
4527
4528 # The basics to get you going:
4529
4530 # IPython sets the __IPYTHON__ variable so you can know if you have nested
4531 # copies running.
4532
4533 # Try running this code both at the command line and from inside IPython (with
4534 # %run example-embed.py)
4535 try:
4536 __IPYTHON__
4537 except NameError:
4538 nested = 0
4539 args = ['']
4540 else:
4541 print "Running nested copies of IPython."
4542 print "The prompts for the nested copy have been modified"
4543 nested = 1
4544 # what the embedded instance will see as sys.argv:
4545 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
4546 '-po','Out<\\#>: ','-nosep']
4547
4548 # First import the embeddable shell class
4549 from IPython.Shell import IPShellEmbed
4550
4551 # Now create an instance of the embeddable shell. The first argument is a
4552 # string with options exactly as you would type them if you were starting
4553 # IPython at the system command line. Any parameters you want to define for
4554 # configuration can thus be specified here.
4555 ipshell = IPShellEmbed(args,
4556 banner = 'Dropping into IPython',
4557 exit_msg = 'Leaving Interpreter, back to program.')
4558
4559 # Make a second instance, you can have as many as you want.
4560 if nested:
4561 args[1] = 'In2<\\#>'
4562 else:
4563 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
4564 '-po','Out<\\#>: ','-nosep']
4565 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
4566
4567 print '\nHello. This is printed from the main controller program.\n'
4568
4569 # You can then call ipshell() anywhere you need it (with an optional
4570 # message):
4571 ipshell('***Called from top level. '
4572 'Hit Ctrl-D to exit interpreter and continue program.\n'
4573 'Note that if you use %kill_embedded, you can fully deactivate\n'
4574 'This embedded instance so it will never turn on again')
4575
4576 print '\nBack in caller program, moving along...\n'
4577
4578 #---------------------------------------------------------------------------
4579 # More details:
4580
4581 # IPShellEmbed instances don't print the standard system banner and
4582 # messages. The IPython banner (which actually may contain initialization
4583 # messages) is available as <instance>.IP.BANNER in case you want it.
4584
4585 # IPShellEmbed instances print the following information everytime they
4586 # start:
4587
4588 # - A global startup banner.
4589
4590 # - A call-specific header string, which you can use to indicate where in the
4591 # execution flow the shell is starting.
4592
4593 # They also print an exit message every time they exit.
4594
4595 # Both the startup banner and the exit message default to None, and can be set
4596 # either at the instance constructor or at any other time with the
4597 # set_banner() and set_exit_msg() methods.
4598
4599 # The shell instance can be also put in 'dummy' mode globally or on a per-call
4600 # basis. This gives you fine control for debugging without having to change
4601 # code all over the place.
4602
4603 # The code below illustrates all this.
4604
4605
4606 # This is how the global banner and exit_msg can be reset at any point
4607 ipshell.set_banner('Entering interpreter - New Banner')
4608 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
4609
4610 def foo(m):
4611 s = 'spam'
4612 ipshell('***In foo(). Try @whos, or print s or m:')
4613 print 'foo says m = ',m
4614
4615 def bar(n):
4616 s = 'eggs'
4617 ipshell('***In bar(). Try @whos, or print s or n:')
4618 print 'bar says n = ',n
4619
4620 # Some calls to the above functions which will trigger IPython:
4621 print 'Main program calling foo("eggs")\n'
4622 foo('eggs')
4623
4624 # The shell can be put in 'dummy' mode where calls to it silently return. This
4625 # allows you, for example, to globally turn off debugging for a program with a
4626 # single call.
4627 ipshell.set_dummy_mode(1)
4628 print '\nTrying to call IPython which is now "dummy":'
4629 ipshell()
4630 print 'Nothing happened...'
4631 # The global 'dummy' mode can still be overridden for a single call
4632 print '\nOverriding dummy mode manually:'
4633 ipshell(dummy=0)
4634
4635 # Reactivate the IPython shell
4636 ipshell.set_dummy_mode(0)
4637
4638 print 'You can even have multiple embedded instances:'
4639 ipshell2()
4640
4641 print '\nMain program calling bar("spam")\n'
4642 bar('spam')
4643
4644 print 'Main program finished. Bye!'
4645
4646 #********************** End of file <example-embed.py> ***********************
4647
4648 Once you understand how the system functions, you can use the following
4649 code fragments in your programs which are ready for cut and paste::
4650
4651
4652 """Quick code snippets for embedding IPython into other programs.
4653
4654 See example-embed.py for full details, this file has the bare minimum code for
4655 cut and paste use once you understand how to use the system."""
4656
4657 #---------------------------------------------------------------------------
4658 # This code loads IPython but modifies a few things if it detects it's running
4659 # embedded in another IPython session (helps avoid confusion)
4660
4661 try:
4662 __IPYTHON__
4663 except NameError:
4664 argv = ['']
4665 banner = exit_msg = ''
4666 else:
4667 # Command-line options for IPython (a list like sys.argv)
4668 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
4669 banner = '*** Nested interpreter ***'
4670 exit_msg = '*** Back in main IPython ***'
4671
4672 # First import the embeddable shell class
4673 from IPython.Shell import IPShellEmbed
4674 # Now create the IPython shell instance. Put ipshell() anywhere in your code
4675 # where you want it to open.
4676 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
4677
4678 #---------------------------------------------------------------------------
4679 # This code will load an embeddable IPython shell always with no changes for
4680 # nested embededings.
4681
4682 from IPython.Shell import IPShellEmbed
4683 ipshell = IPShellEmbed()
4684 # Now ipshell() will open IPython anywhere in the code.
4685
4686 #---------------------------------------------------------------------------
4687 # This code loads an embeddable shell only if NOT running inside
4688 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
4689 # dummy function.
4690
4691 try:
4692 __IPYTHON__
4693 except NameError:
4694 from IPython.Shell import IPShellEmbed
4695 ipshell = IPShellEmbed()
4696 # Now ipshell() will open IPython anywhere in the code
4697 else:
4698 # Define a dummy ipshell() so the same code doesn't crash inside an
4699 # interactive IPython
4700 def ipshell(): pass
4701
4702 #******************* End of file <example-embed-short.py> ********************
4703
4704 Using the Python debugger (pdb)
4705 ===============================
4706
4707 Running entire programs via pdb
4708 -------------------------------
4709
4710 pdb, the Python debugger, is a powerful interactive debugger which
4711 allows you to step through code, set breakpoints, watch variables,
4712 etc. IPython makes it very easy to start any script under the control
4713 of pdb, regardless of whether you have wrapped it into a 'main()'
4714 function or not. For this, simply type '%run -d myscript' at an
4715 IPython prompt. See the %run command's documentation (via '%run?' or
4716 in Sec. magic_ for more details, including how to control where pdb
4717 will stop execution first.
4718
4719 For more information on the use of the pdb debugger, read the included
4720 pdb.doc file (part of the standard Python distribution). On a stock
4721 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
4722 easiest way to read it is by using the help() function of the pdb module
4723 as follows (in an IPython prompt):
4724
4725 In [1]: import pdb
4726 In [2]: pdb.help()
4727
4728 This will load the pdb.doc document in a file viewer for you automatically.
4729
4730
4731 Automatic invocation of pdb on exceptions
4732 -----------------------------------------
4733
4734 IPython, if started with the -pdb option (or if the option is set in
4735 your rc file) can call the Python pdb debugger every time your code
4736 triggers an uncaught exception. This feature
4737 can also be toggled at any time with the %pdb magic command. This can be
4738 extremely useful in order to find the origin of subtle bugs, because pdb
4739 opens up at the point in your code which triggered the exception, and
4740 while your program is at this point 'dead', all the data is still
4741 available and you can walk up and down the stack frame and understand
4742 the origin of the problem.
4743
4744 Furthermore, you can use these debugging facilities both with the
4745 embedded IPython mode and without IPython at all. For an embedded shell
4746 (see sec. Embedding_), simply call the constructor with
4747 '-pdb' in the argument string and automatically pdb will be called if an
4748 uncaught exception is triggered by your code.
4749
4750 For stand-alone use of the feature in your programs which do not use
4751 IPython at all, put the following lines toward the top of your 'main'
4752 routine::
4753
4754 import sys,IPython.ultraTB
4755 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
4756 color_scheme='Linux', call_pdb=1)
4757
4758 The mode keyword can be either 'Verbose' or 'Plain', giving either very
4759 detailed or normal tracebacks respectively. The color_scheme keyword can
4760 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
4761 options which can be set in IPython with -colors and -xmode.
4762
4763 This will give any of your programs detailed, colored tracebacks with
4764 automatic invocation of pdb.
4765
4766
4767 Extensions for syntax processing
4768 ================================
4769
4770 This isn't for the faint of heart, because the potential for breaking
4771 things is quite high. But it can be a very powerful and useful feature.
4772 In a nutshell, you can redefine the way IPython processes the user input
4773 line to accept new, special extensions to the syntax without needing to
4774 change any of IPython's own code.
4775
4776 In the IPython/Extensions directory you will find some examples
4777 supplied, which we will briefly describe now. These can be used 'as is'
4778 (and both provide very useful functionality), or you can use them as a
4779 starting point for writing your own extensions.
4780
4781
4782 Pasting of code starting with '>>> ' or '... '
4783 ----------------------------------------------
4784
4785 In the python tutorial it is common to find code examples which have
4786 been taken from real python sessions. The problem with those is that all
4787 the lines begin with either '>>> ' or '... ', which makes it impossible
4788 to paste them all at once. One must instead do a line by line manual
4789 copying, carefully removing the leading extraneous characters.
4790
4791 This extension identifies those starting characters and removes them
4792 from the input automatically, so that one can paste multi-line examples
4793 directly into IPython, saving a lot of time. Please look at the file
4794 InterpreterPasteInput.py in the IPython/Extensions directory for details
4795 on how this is done.
4796
4797 IPython comes with a special profile enabling this feature, called
4798 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
4799 will be available. In a normal IPython session you can activate the
4800 feature by importing the corresponding module with:
4801 In [1]: import IPython.Extensions.InterpreterPasteInput
4802
4803 The following is a 'screenshot' of how things work when this extension
4804 is on, copying an example from the standard tutorial::
4805
4806 IPython profile: tutorial
4807
4808 *** Pasting of code with ">>>" or "..." has been enabled.
4809
4810 In [1]: >>> def fib2(n): # return Fibonacci series up to n
4811 ...: ... """Return a list containing the Fibonacci series up to
4812 n."""
4813 ...: ... result = []
4814 ...: ... a, b = 0, 1
4815 ...: ... while b < n:
4816 ...: ... result.append(b) # see below
4817 ...: ... a, b = b, a+b
4818 ...: ... return result
4819 ...:
4820
4821 In [2]: fib2(10)
4822 Out[2]: [1, 1, 2, 3, 5, 8]
4823
4824 Note that as currently written, this extension does not recognize
4825 IPython's prompts for pasting. Those are more complicated, since the
4826 user can change them very easily, they involve numbers and can vary in
4827 length. One could however extract all the relevant information from the
4828 IPython instance and build an appropriate regular expression. This is
4829 left as an exercise for the reader.
4830
4831
4832 Input of physical quantities with units
4833 ---------------------------------------
4834
4835 The module PhysicalQInput allows a simplified form of input for physical
4836 quantities with units. This file is meant to be used in conjunction with
4837 the PhysicalQInteractive module (in the same directory) and
4838 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
4839 (http://dirac.cnrs-orleans.fr/ScientificPython/).
4840
4841 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
4842 but these must be declared as instances of a class. For example, to
4843 define v as a velocity of 3 m/s, normally you would write::
4844
4845 In [1]: v = PhysicalQuantity(3,'m/s')
4846
4847 Using the PhysicalQ_Input extension this can be input instead as:
4848 In [1]: v = 3 m/s
4849 which is much more convenient for interactive use (even though it is
4850 blatantly invalid Python syntax).
4851
4852 The physics profile supplied with IPython (enabled via 'ipython -p
4853 physics') uses these extensions, which you can also activate with:
4854
4855 from math import * # math MUST be imported BEFORE PhysicalQInteractive
4856 from IPython.Extensions.PhysicalQInteractive import *
4857 import IPython.Extensions.PhysicalQInput
4858
4859
4860 IPython as a system shell - the 'Sh' profile
4861 ============================================
4862
4863 The 'sh' profile optimizes IPython for system shell usage. Apart from
4864 certain job control functionality that is present in unix (ctrl+z does
4865 "suspend"), the sh profile should provide you with most of the
4866 functionality you use daily in system shell, and more. Invoke IPython
4867 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
4868 the "pysh" shortcut in start menu.
4869
4870 If you want to use the features of sh profile as your defaults (which
4871 might be a good idea if you use other profiles a lot of the time but
4872 still want the convenience of sh profile), add ``import ipy_profile_sh``
4873 to your ~/.ipython/ipy_user_conf.py.
4874
4875 The 'sh' profile is different from the default profile in that:
4876
4877 * Prompt shows the current directory
4878 * Spacing between prompts and input is more compact (no padding with
4879 empty lines). The startup banner is more compact as well.
4880 * System commands are directly available (in alias table) without
4881 requesting %rehashx - however, if you install new programs along
4882 your PATH, you might want to run %rehashx to update the persistent
4883 alias table
4884 * Macros are stored in raw format by default. That is, instead of
4885 '_ip.system("cat foo"), the macro will contain text 'cat foo')
4886 * Autocall is in full mode
4887 * Calling "up" does "cd .."
4888
4889 The 'sh' profile is different from the now-obsolete (and unavailable)
4890 'pysh' profile in that:
4891
4892 * '$$var = command' and '$var = command' syntax is not supported
4893 * anymore. Use 'var = !command' instead (incidentally, this is
4894 * available in all IPython profiles). Note that !!command *will*
4895 * work.
4896
4897 Aliases
4898 -------
4899
4900 All of your $PATH has been loaded as IPython aliases, so you should be
4901 able to type any normal system command and have it executed. See
4902 %alias? and %unalias? for details on the alias facilities. See also
4903 %rehashx? for details on the mechanism used to load $PATH.
4904
4905
4906 Directory management
4907 --------------------
4908
4909 Since each command passed by ipython to the underlying system is executed
4910 in a subshell which exits immediately, you can NOT use !cd to navigate
4911 the filesystem.
4912
4913 IPython provides its own builtin '%cd' magic command to move in the
4914 filesystem (the % is not required with automagic on). It also maintains
4915 a list of visited directories (use %dhist to see it) and allows direct
4916 switching to any of them. Type 'cd?' for more details.
4917
4918 %pushd, %popd and %dirs are provided for directory stack handling.
4919
4920
4921 Enabled extensions
4922 ------------------
4923
4924 Some extensions, listed below, are enabled as default in this profile.
4925
4926 envpersist
4927 ++++++++++
4928
4929 %env can be used to "remember" environment variable manipulations. Examples::
4930
4931 %env - Show all environment variables
4932 %env VISUAL=jed - set VISUAL to jed
4933 %env PATH+=;/foo - append ;foo to PATH
4934 %env PATH+=;/bar - also append ;bar to PATH
4935 %env PATH-=/wbin; - prepend /wbin; to PATH
4936 %env -d VISUAL - forget VISUAL persistent val
4937 %env -p - print all persistent env modifications
4938
4939 ipy_which
4940 +++++++++
4941
4942 %which magic command. Like 'which' in unix, but knows about ipython aliases.
4943
4944 Example::
4945
4946 [C:/ipython]|14> %which st
4947 st -> start .
4948 [C:/ipython]|15> %which d
4949 d -> dir /w /og /on
4950 [C:/ipython]|16> %which cp
4951 cp -> cp
4952 == c:\bin\cp.exe
4953 c:\bin\cp.exe
4954
4955 ipy_app_completers
4956 ++++++++++++++++++
4957
4958 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
4959
4960 ipy_rehashdir
4961 +++++++++++++
4962
4963 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
4964
4965 [~]|22> cd c:/opt/PuTTY/
4966 [c:opt/PuTTY]|23> rehashdir .
4967 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
4968
4969 Now, you can execute any of those commams directly::
4970
4971 [c:opt/PuTTY]|24> cd
4972 [~]|25> putty
4973
4974 (the putty window opens).
4975
4976 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
4977
4978 [~]|27> for a in _23:
4979 |..> %store $a
4980 |..>
4981 |..>
4982 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
4983 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
4984 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
4985 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
4986 ...
4987
4988 mglob
4989 +++++
4990
4991 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
4992
4993 [c:/ipython]|9> mglob *.py
4994 [c:/ipython]|10> mglob *.py rec:*.txt
4995 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
4996
4997 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
4998
4999
5000 Prompt customization
5001 --------------------
5002
5003 The sh profile uses the following prompt configurations::
5004
5005 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
5006 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
5007
5008 You can change the prompt configuration to your liking by editing
5009 ipy_user_conf.py.
5010
5011 String lists
5012 ============
5013
5014 String lists (IPython.genutils.SList) are handy way to process output
5015 from system commands. They are produced by ``var = !cmd`` syntax.
5016
5017 First, we acquire the output of 'ls -l'::
5018
5019 [Q:doc/examples]|2> lines = !ls -l
5020 ==
5021 ['total 23',
5022 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
5023 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
5024 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
5025 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
5026 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
5027 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
5028 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
5029
5030 Now, let's take a look at the contents of 'lines' (the first number is
5031 the list element number)::
5032
5033 [Q:doc/examples]|3> lines
5034 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5035
5036 0: total 23
5037 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
5038 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
5039 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
5040 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
5041 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
5042 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
5043 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
5044
5045 Now, let's filter out the 'embed' lines::
5046
5047 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
5048 [Q:doc/examples]|5> l2
5049 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5050
5051 0: total 23
5052 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
5053 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
5054 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
5055 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
5056 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
5057
5058 Now, we want strings having just file names and permissions::
5059
5060 [Q:doc/examples]|6> l2.fields(8,0)
5061 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5062
5063 0: total
5064 1: example-demo.py -rw-rw-rw-
5065 2: example-gnuplot.py -rwxrwxrwx
5066 3: extension.py -rwxrwxrwx
5067 4: seteditor.py -rwxrwxrwx
5068 5: seteditor.pyc -rwxrwxrwx
5069
5070 Note how the line with 'total' does not raise IndexError.
5071
5072 If you want to split these (yielding lists), call fields() without
5073 arguments::
5074
5075 [Q:doc/examples]|7> _.fields()
5076 <7>
5077 [['total'],
5078 ['example-demo.py', '-rw-rw-rw-'],
5079 ['example-gnuplot.py', '-rwxrwxrwx'],
5080 ['extension.py', '-rwxrwxrwx'],
5081 ['seteditor.py', '-rwxrwxrwx'],
5082 ['seteditor.pyc', '-rwxrwxrwx']]
5083
5084 If you want to pass these separated with spaces to a command (typical
5085 for lists if files), use the .s property::
5086
5087
5088 [Q:doc/examples]|13> files = l2.fields(8).s
5089 [Q:doc/examples]|14> files
5090 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
5091 [Q:doc/examples]|15> ls $files
5092 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
5093
5094 SLists are inherited from normal python lists, so every list method is
5095 available::
5096
5097 [Q:doc/examples]|21> lines.append('hey')
5098
5099
5100 Real world example: remove all files outside version control
5101 ------------------------------------------------------------
5102
5103 First, capture output of "hg status"::
5104
5105 [Q:/ipython]|28> out = !hg status
5106 ==
5107 ['M IPython\\Extensions\\ipy_kitcfg.py',
5108 'M IPython\\Extensions\\ipy_rehashdir.py',
5109 ...
5110 '? build\\lib\\IPython\\Debugger.py',
5111 '? build\\lib\\IPython\\Extensions\\InterpreterExec.py',
5112 '? build\\lib\\IPython\\Extensions\\InterpreterPasteInput.py',
5113 ...
5114
5115 (lines starting with ? are not under version control).
5116
5117 ::
5118
5119 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
5120 [Q:/ipython]|36> junk
5121 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
5122 ...
5123 10: build\bdist.win32\winexe\temp\_ctypes.py
5124 11: build\bdist.win32\winexe\temp\_hashlib.py
5125 12: build\bdist.win32\winexe\temp\_socket.py
5126
5127 Now we can just remove these files by doing 'rm $junk.s'.
5128
5129 The .s, .n, .p properties
5130 -------------------------
5131
5132 The '.s' property returns one string where lines are separated by
5133 single space (for convenient passing to system commands). The '.n'
5134 property return one string where the lines are separated by '\n'
5135 (i.e. the original output of the function). If the items in string
5136 list are file names, '.p' can be used to get a list of "path" objects
5137 for convenient file manipulation.
5138
5139
5140 Threading support
5141 =================
5142
5143 WARNING: The threading support is still somewhat experimental, and it
5144 has only seen reasonable testing under Linux. Threaded code is
5145 particularly tricky to debug, and it tends to show extremely
5146 platform-dependent behavior. Since I only have access to Linux machines,
5147 I will have to rely on user's experiences and assistance for this area
5148 of IPython to improve under other platforms.
5149
5150 IPython, via the -gthread , -qthread, -q4thread and -wthread options
5151 (described in Sec. `Threading options`_), can run in
5152 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
5153 respectively. These GUI toolkits need to control the python main loop of
5154 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
5155 Qt4 or WXPython application will immediately freeze the shell.
5156
5157 IPython, with one of these options (you can only use one at a time),
5158 separates the graphical loop and IPython's code execution run into
5159 different threads. This allows you to test interactively (with %run, for
5160 example) your GUI code without blocking.
5161
5162 A nice mini-tutorial on using IPython along with the Qt Designer
5163 application is available at the SciPy wiki:
5164 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
5165
5166
5167 Tk issues
5168 ---------
5169
5170 As indicated in Sec. `Threading options`_, a special -tk option is
5171 provided to try and allow Tk graphical applications to coexist
5172 interactively with WX, Qt or GTK ones. Whether this works at all,
5173 however, is very platform and configuration dependent. Please
5174 experiment with simple test cases before committing to using this
5175 combination of Tk and GTK/Qt/WX threading in a production environment.
5176
5177
5178 I/O pitfalls
5179 ------------
5180
5181 Be mindful that the Python interpreter switches between threads every
5182 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
5183 value can be read by using the sys.getcheckinterval() function, and it
5184 can be reset via sys.setcheckinterval(N). This switching of threads can
5185 cause subtly confusing effects if one of your threads is doing file I/O.
5186 In text mode, most systems only flush file buffers when they encounter a
5187 '\n'. An instruction as simple as::
5188
5189 print >> filehandle, ''hello world''
5190
5191 actually consists of several bytecodes, so it is possible that the
5192 newline does not reach your file before the next thread switch.
5193 Similarly, if you are writing to a file in binary mode, the file won't
5194 be flushed until the buffer fills, and your other thread may see
5195 apparently truncated files.
5196
5197 For this reason, if you are using IPython's thread support and have (for
5198 example) a GUI application which will read data generated by files
5199 written to from the IPython thread, the safest approach is to open all
5200 of your files in unbuffered mode (the third argument to the file/open
5201 function is the buffering value)::
5202
5203 filehandle = open(filename,mode,0)
5204
5205 This is obviously a brute force way of avoiding race conditions with the
5206 file buffering. If you want to do it cleanly, and you have a resource
5207 which is being shared by the interactive IPython loop and your GUI
5208 thread, you should really handle it with thread locking and
5209 syncrhonization properties. The Python documentation discusses these.
5210
5211 .. _Interactive demos:
5212
5213 Interactive demos with IPython
5214 ==============================
5215
5216 IPython ships with a basic system for running scripts interactively in
5217 sections, useful when presenting code to audiences. A few tags embedded
5218 in comments (so that the script remains valid Python code) divide a file
5219 into separate blocks, and the demo can be run one block at a time, with
5220 IPython printing (with syntax highlighting) the block before executing
5221 it, and returning to the interactive prompt after each block. The
5222 interactive namespace is updated after each block is run with the
5223 contents of the demo's namespace.
5224
5225 This allows you to show a piece of code, run it and then execute
5226 interactively commands based on the variables just created. Once you
5227 want to continue, you simply execute the next block of the demo. The
5228 following listing shows the markup necessary for dividing a script into
5229 sections for execution as a demo::
5230
5231
5232 """A simple interactive demo to illustrate the use of IPython's Demo class.
5233
5234 Any python script can be run as a demo, but that does little more than showing
5235 it on-screen, syntax-highlighted in one shot. If you add a little simple
5236 markup, you can stop at specified intervals and return to the ipython prompt,
5237 resuming execution later.
5238 """
5239
5240 print 'Hello, welcome to an interactive IPython demo.'
5241 print 'Executing this block should require confirmation before proceeding,'
5242 print 'unless auto_all has been set to true in the demo object'
5243
5244 # The mark below defines a block boundary, which is a point where IPython will
5245 # stop execution and return to the interactive prompt.
5246 # Note that in actual interactive execution,
5247 # <demo> --- stop ---
5248
5249 x = 1
5250 y = 2
5251
5252 # <demo> --- stop ---
5253
5254 # the mark below makes this block as silent
5255 # <demo> silent
5256
5257 print 'This is a silent block, which gets executed but not printed.'
5258
5259 # <demo> --- stop ---
5260 # <demo> auto
5261 print 'This is an automatic block.'
5262 print 'It is executed without asking for confirmation, but printed.'
5263 z = x+y
5264
5265 print 'z=',x
5266
5267 # <demo> --- stop ---
5268 # This is just another normal block.
5269 print 'z is now:', z
5270
5271 print 'bye!'
5272
5273 In order to run a file as a demo, you must first make a Demo object out
5274 of it. If the file is named myscript.py, the following code will make a
5275 demo::
5276
5277 from IPython.demo import Demo
5278
5279 mydemo = Demo('myscript.py')
5280
5281 This creates the mydemo object, whose blocks you run one at a time by
5282 simply calling the object with no arguments. If you have autocall active
5283 in IPython (the default), all you need to do is type::
5284
5285 mydemo
5286
5287 and IPython will call it, executing each block. Demo objects can be
5288 restarted, you can move forward or back skipping blocks, re-execute the
5289 last block, etc. Simply use the Tab key on a demo object to see its
5290 methods, and call '?' on them to see their docstrings for more usage
5291 details. In addition, the demo module itself contains a comprehensive
5292 docstring, which you can access via::
5293
5294 from IPython import demo
5295
5296 demo?
5297
5298 Limitations: It is important to note that these demos are limited to
5299 fairly simple uses. In particular, you can not put division marks in
5300 indented code (loops, if statements, function definitions, etc.)
5301 Supporting something like this would basically require tracking the
5302 internal execution state of the Python interpreter, so only top-level
5303 divisions are allowed. If you want to be able to open an IPython
5304 instance at an arbitrary point in a program, you can use IPython's
5305 embedding facilities, described in detail in Sec. 9
5306
5307
5308 .. _Matplotlib support:
5309
5310 Plotting with matplotlib
5311 ========================
5312
5313 The matplotlib library (http://matplotlib.sourceforge.net
5314 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
5315 Python. Matplotlib can produce plots on screen using a variety of GUI
5316 toolkits, including Tk, GTK and WXPython. It also provides a number of
5317 commands useful for scientific computing, all with a syntax compatible
5318 with that of the popular Matlab program.
5319
5320 IPython accepts the special option -pylab (Sec. `Command line
5321 options`_). This configures it to support matplotlib, honoring the
5322 settings in the .matplotlibrc file. IPython will detect the user's
5323 choice of matplotlib GUI backend, and automatically select the proper
5324 threading model to prevent blocking. It also sets matplotlib in
5325 interactive mode and modifies %run slightly, so that any
5326 matplotlib-based script can be executed using %run and the final
5327 show() command does not block the interactive shell.
5328
5329 The -pylab option must be given first in order for IPython to
5330 configure its threading mode. However, you can still issue other
5331 options afterwards. This allows you to have a matplotlib-based
5332 environment customized with additional modules using the standard
5333 IPython profile mechanism (Sec. Profiles_): ''ipython -pylab -p
5334 myprofile'' will load the profile defined in ipythonrc-myprofile after
5335 configuring matplotlib.
5336
5337 IPython Extension Api
5338 =====================
5339
5340 IPython api (defined in IPython/ipapi.py) is the public api that
5341 should be used for
5342
5343 * Configuration of user preferences (.ipython/ipy_user_conf.py)
5344 * Creating new profiles (.ipython/ipy_profile_PROFILENAME.py)
5345 * Writing extensions
5346
5347 Note that by using the extension api for configuration (editing
5348 ipy_user_conf.py instead of ipythonrc), you get better validity checks
5349 and get richer functionality - for example, you can import an
5350 extension and call functions in it to configure it for your purposes.
5351
5352 For an example extension (the 'sh' profile), see
5353 IPython/Extensions/ipy_profile_sh.py.
5354
5355 For the last word on what's available, see the source code of
5356 IPython/ipapi.py.
5357
5358
5359 Getting started
5360 ---------------
5361
5362 If you want to define an extension, create a normal python module that
5363 can be imported. The module will access IPython functionality through
5364 the 'ip' object defined below.
5365
5366 If you are creating a new profile (e.g. foobar), name the module as
5367 'ipy_profile_foobar.py' and put it in your ~/.ipython directory. Then,
5368 when you start ipython with the '-p foobar' argument, the module is
5369 automatically imported on ipython startup.
5370
5371 If you are just doing some per-user configuration, you can either
5372
5373 * Put the commands directly into ipy_user_conf.py.
5374
5375 * Create a new module with your customization code and import *that*
5376 module in ipy_user_conf.py. This is preferable to the first approach,
5377 because now you can reuse and distribute your customization code.
5378
5379 Getting a handle to the api
5380 ---------------------------
5381
5382 Put this in the start of your module::
5383
5384 #!python
5385 import IPython.ipapi
5386 ip = IPython.ipapi.get()
5387
5388 The 'ip' object will then be used for accessing IPython
5389 functionality. 'ip' will mean this api object in all the following
5390 code snippets. The same 'ip' that we just acquired is always
5391 accessible in interactive IPython sessions by the name _ip - play with
5392 it like this::
5393
5394 [~\_ipython]|81> a = 10
5395 [~\_ipython]|82> _ip.e
5396 _ip.ev _ip.ex _ip.expose_magic
5397 [~\_ipython]|82> _ip.ev('a+13')
5398 <82> 23
5399
5400 The _ip object is also used in some examples in this document - it can
5401 be substituted by 'ip' in non-interactive use.
5402
5403 Changing options
5404 ----------------
5405
5406 The ip object has 'options' attribute that can be used te get/set
5407 configuration options (just as in the ipythonrc file)::
5408
5409 o = ip.options
5410 o.autocall = 2
5411 o.automagic = 1
5412
5413 Executing statements in IPython namespace with 'ex' and 'ev'
5414 ------------------------------------------------------------
5415
5416 Often, you want to e.g. import some module or define something that
5417 should be visible in IPython namespace. Use ``ip.ev`` to
5418 *evaluate* (calculate the value of) expression and ``ip.ex`` to
5419 '''execute''' a statement::
5420
5421 # path module will be visible to the interactive session
5422 ip.ex("from path import path" )
5423
5424 # define a handy function 'up' that changes the working directory
5425
5426 ip.ex('import os')
5427 ip.ex("def up(): os.chdir('..')")
5428
5429
5430 # _i2 has the input history entry #2, print its value in uppercase.
5431 print ip.ev('_i2.upper()')
5432
5433 Accessing the IPython namespace
5434 -------------------------------
5435
5436 ip.user_ns attribute has a dictionary containing the IPython global
5437 namespace (the namespace visible in the interactive session).
5438
5439 ::
5440
5441 [~\_ipython]|84> tauno = 555
5442 [~\_ipython]|85> _ip.user_ns['tauno']
5443 <85> 555
5444
5445 Defining new magic commands
5446 ---------------------------
5447
5448 The following example defines a new magic command, %impall. What the
5449 command does should be obvious::
5450
5451 def doimp(self, arg):
5452 ip = self.api
5453 ip.ex("import %s; reload(%s); from %s import *" % (
5454 arg,arg,arg)
5455 )
5456
5457 ip.expose_magic('impall', doimp)
5458
5459 Things to observe in this example:
5460
5461 * Define a function that implements the magic command using the
5462 ipapi methods defined in this document
5463 * The first argument of the function is 'self', i.e. the
5464 interpreter object. It shouldn't be used directly. however.
5465 The interpreter object is probably *not* going to remain stable
5466 through IPython versions.
5467 * Access the ipapi through 'self.api' instead of the global 'ip' object.
5468 * All the text following the magic command on the command line is
5469 contained in the second argument
5470 * Expose the magic by ip.expose_magic()
5471
5472
5473 Calling magic functions and system commands
5474 -------------------------------------------
5475
5476 Use ip.magic() to execute a magic function, and ip.system() to execute
5477 a system command::
5478
5479 # go to a bookmark
5480 ip.magic('%cd -b relfiles')
5481
5482 # execute 'ls -F' system command. Interchangeable with os.system('ls'), really.
5483 ip.system('ls -F')
5484
5485 Launching IPython instance from normal python code
5486 --------------------------------------------------
5487
5488 Use ipapi.launch_new_instance() with an argument that specifies the
5489 namespace to use. This can be useful for trivially embedding IPython
5490 into your program. Here's an example of normal python program test.py
5491 ('''without''' an existing IPython session) that launches an IPython
5492 interpreter and regains control when the interpreter is exited::
5493
5494 [ipython]|1> cat test.py
5495 my_ns = dict(
5496 kissa = 15,
5497 koira = 16)
5498 import IPython.ipapi
5499 print "launching IPython instance"
5500 IPython.ipapi.launch_new_instance(my_ns)
5501 print "Exited IPython instance!"
5502 print "New vals:",my_ns['kissa'], my_ns['koira']
5503
5504 And here's what it looks like when run (note how we don't start it
5505 from an ipython session)::
5506
5507 Q:\ipython>python test.py
5508 launching IPython instance
5509 Py 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] IPy 0.7.3b3.r1975
5510 [ipython]|1> kissa = 444
5511 [ipython]|2> koira = 555
5512 [ipython]|3> Exit
5513 Exited IPython instance!
5514 New vals: 444 555
5515
5516 Accessing unexposed functionality
5517 ---------------------------------
5518
5519 There are still many features that are not exposed via the ipapi. If
5520 you can't avoid using them, you can use the functionality in
5521 InteractiveShell object (central IPython session class, defined in
5522 iplib.py) through ip.IP.
5523
5524 For example::
5525
5526 [~]|7> _ip.IP.expand_aliases('np','myfile.py')
5527 <7> 'c:/opt/Notepad++/notepad++.exe myfile.py'
5528 [~]|8>
5529
5530 Still, it's preferable that if you encounter such a feature, contact
5531 the IPython team and request that the functionality be exposed in a
5532 future version of IPython. Things not in ipapi are more likely to
5533 change over time.
5534
5535 Provided extensions
5536 ===================
5537
5538 You can see the list of available extensions (and profiles) by doing
5539 ``import ipy_<TAB>``. Some extensions don't have the ``ipy_`` prefix in
5540 module name, so you may need to see the contents of IPython/Extensions
5541 folder to see what's available.
5542
5543 You can see a brief documentation of an extension by looking at the
5544 module docstring::
5545
5546 [c:p/ipython_main]|190> import ipy_fsops
5547 [c:p/ipython_main]|191> ipy_fsops?
5548
5549 ...
5550
5551 Docstring:
5552 File system operations
5553
5554 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
5555 imkdir, igrep).
5556
5557 You can also install your own extensions - the recommended way is to
5558 just copy the module to ~/.ipython. Extensions are typically enabled
5559 by just importing them (e.g. in ipy_user_conf.py), but some extensions
5560 require additional steps, for example::
5561
5562 [c:p]|192> import ipy_traits_completer
5563 [c:p]|193> ipy_traits_completer.activate()
5564
5565 Note that extensions, even if provided in the stock IPython
5566 installation, are not guaranteed to have the same requirements as the
5567 rest of IPython - an extension may require external libraries or a
5568 newer version of Python than what IPython officially requires. An
5569 extension may also be under a more restrictive license than IPython
5570 (e.g. ipy_bzr is under GPL).
5571
5572 Just for reference, the list of bundled extensions at the time of
5573 writing is below:
5574
5575 astyle.py clearcmd.py envpersist.py ext_rescapture.py ibrowse.py
5576 igrid.py InterpreterExec.py InterpreterPasteInput.py ipipe.py
5577 ipy_app_completers.py ipy_autoreload.py ipy_bzr.py ipy_completers.py
5578 ipy_constants.py ipy_defaults.py ipy_editors.py ipy_exportdb.py
5579 ipy_extutil.py ipy_fsops.py ipy_gnuglobal.py ipy_kitcfg.py
5580 ipy_legacy.py ipy_leo.py ipy_p4.py ipy_profile_doctest.py
5581 ipy_profile_none.py ipy_profile_scipy.py ipy_profile_sh.py
5582 ipy_profile_zope.py ipy_pydb.py ipy_rehashdir.py ipy_render.py
5583 ipy_server.py ipy_signals.py ipy_stock_completers.py
5584 ipy_system_conf.py ipy_traits_completer.py ipy_vimserver.py
5585 ipy_which.py ipy_workdir.py jobctrl.py ledit.py numeric_formats.py
5586 PhysicalQInput.py PhysicalQInteractive.py pickleshare.py
5587 pspersistence.py win32clip.py __init__.py
5588
5589 Reporting bugs
5590 ==============
5591
5592 Automatic crash reports
5593 -----------------------
5594
5595 Ideally, IPython itself shouldn't crash. It will catch exceptions
5596 produced by you, but bugs in its internals will still crash it.
5597
5598 In such a situation, IPython will leave a file named
5599 IPython_crash_report.txt in your IPYTHONDIR directory (that way if
5600 crashes happen several times it won't litter many directories, the
5601 post-mortem file is always located in the same place and new
5602 occurrences just overwrite the previous one). If you can mail this
5603 file to the developers (see sec. credits_ for names and addresses), it
5604 will help us a lot in understanding the cause of the problem and
5605 fixing it sooner.
5606
5607
5608 The bug tracker
5609 ---------------
5610
5611 IPython also has an online bug-tracker, located at
5612 http://projects.scipy.org/ipython/ipython/report/1. In addition to
5613 mailing the developers, it would be a good idea to file a bug report
5614 here. This will ensure that the issue is properly followed to
5615 conclusion. To report new bugs you will have to register first.
5616
5617 You can also use this bug tracker to file feature requests.
5618
5619 Brief history
5620 =============
5621
5622
5623 Origins
5624 -------
5625
5626 The current IPython system grew out of the following three projects:
5627
5628 * [ipython] by Fernando Pérez. I was working on adding
5629 Mathematica-type prompts and a flexible configuration system
5630 (something better than $PYTHONSTARTUP) to the standard Python
5631 interactive interpreter.
5632 * [IPP] by Janko Hauser. Very well organized, great usability. Had
5633 an old help system. IPP was used as the 'container' code into
5634 which I added the functionality from ipython and LazyPython.
5635 * [LazyPython] by Nathan Gray. Simple but very powerful. The quick
5636 syntax (auto parens, auto quotes) and verbose/colored tracebacks
5637 were all taken from here.
5638
5639 When I found out about IPP and LazyPython I tried to join all three
5640 into a unified system. I thought this could provide a very nice
5641 working environment, both for regular programming and scientific
5642 computing: shell-like features, IDL/Matlab numerics, Mathematica-type
5643 prompt history and great object introspection and help facilities. I
5644 think it worked reasonably well, though it was a lot more work than I
5645 had initially planned.
5646
5647
5648 Current status
5649 --------------
5650
5651 The above listed features work, and quite well for the most part. But
5652 until a major internal restructuring is done (see below), only bug
5653 fixing will be done, no other features will be added (unless very minor
5654 and well localized in the cleaner parts of the code).
5655
5656 IPython consists of some 18000 lines of pure python code, of which
5657 roughly two thirds is reasonably clean. The rest is, messy code which
5658 needs a massive restructuring before any further major work is done.
5659 Even the messy code is fairly well documented though, and most of the
5660 problems in the (non-existent) class design are well pointed to by a
5661 PyChecker run. So the rewriting work isn't that bad, it will just be
5662 time-consuming.
5663
5664
5665 Future
5666 ------
5667
5668 See the separate new_design document for details. Ultimately, I would
5669 like to see IPython become part of the standard Python distribution as a
5670 'big brother with batteries' to the standard Python interactive
5671 interpreter. But that will never happen with the current state of the
5672 code, so all contributions are welcome.
5673
5674 License
5675 =======
5676
5677 IPython is released under the terms of the BSD license, whose general
5678 form can be found at:
5679 http://www.opensource.org/licenses/bsd-license.php. The full text of the
5680 IPython license is reproduced below::
5681
5682 IPython is released under a BSD-type license.
5683
5684 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez
5685 <fperez@colorado.edu>.
5686
5687 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
5688 Nathaniel Gray <n8gray@caltech.edu>.
5689
5690 All rights reserved.
5691
5692 Redistribution and use in source and binary forms, with or without
5693 modification, are permitted provided that the following conditions
5694 are met:
5695
5696 a. Redistributions of source code must retain the above copyright
5697 notice, this list of conditions and the following disclaimer.
5698
5699 b. Redistributions in binary form must reproduce the above copyright
5700 notice, this list of conditions and the following disclaimer in the
5701 documentation and/or other materials provided with the distribution.
5702
5703 c. Neither the name of the copyright holders nor the names of any
5704 contributors to this software may be used to endorse or promote
5705 products derived from this software without specific prior written
5706 permission.
5707
5708 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5709 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5710 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
5711 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5712 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
5713 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
5714 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
5715 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
5716 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
5717 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
5718 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
5719 POSSIBILITY OF SUCH DAMAGE.
5720
5721 Individual authors are the holders of the copyright for their code and
5722 are listed in each file.
5723
5724 Some files (DPyGetOpt.py, for example) may be licensed under different
5725 conditions. Ultimately each file indicates clearly the conditions under
5726 which its author/authors have decided to publish the code.
5727
5728 Versions of IPython up to and including 0.6.3 were released under the
5729 GNU Lesser General Public License (LGPL), available at
5730 http://www.gnu.org/copyleft/lesser.html.
5731
5732 Credits
5733 =======
5734
5735 IPython is mainly developed by Fernando Pérez
5736 <Fernando.Perez@colorado.edu>, but the project was born from mixing in
5737 Fernando's code with the IPP project by Janko Hauser
5738 <jhauser-AT-zscout.de> and LazyPython by Nathan Gray
5739 <n8gray-AT-caltech.edu>. For all IPython-related requests, please
5740 contact Fernando.
5741
5742 As of early 2006, the following developers have joined the core team:
5743
5744 * [Robert Kern] <rkern-AT-enthought.com>: co-mentored the 2005
5745 Google Summer of Code project to develop python interactive
5746 notebooks (XML documents) and graphical interface. This project
5747 was awarded to the students Tzanko Matev <tsanko-AT-gmail.com> and
5748 Toni Alatalo <antont-AT-an.org>
5749 * [Brian Granger] <bgranger-AT-scu.edu>: extending IPython to allow
5750 support for interactive parallel computing.
5751 * [Ville Vainio] <vivainio-AT-gmail.com>: Ville is the new
5752 maintainer for the main trunk of IPython after version 0.7.1.
5753
5754 User or development help should be requested via the IPython mailing lists:
5755
5756 *User list:*
5757 http://scipy.net/mailman/listinfo/ipython-user
5758 *Developer's list:*
5759 http://scipy.net/mailman/listinfo/ipython-dev
5760
5761 The IPython project is also very grateful to:
5762
5763 Bill Bumgarner <bbum-AT-friday.com>: for providing the DPyGetOpt module
5764 which gives very powerful and convenient handling of command-line
5765 options (light years ahead of what Python 2.1.1's getopt module does).
5766
5767 Ka-Ping Yee <ping-AT-lfw.org>: for providing the Itpl module for
5768 convenient and powerful string interpolation with a much nicer syntax
5769 than formatting through the '%' operator.
5770
5771 Arnd Baecker <baecker-AT-physik.tu-dresden.de>: for his many very useful
5772 suggestions and comments, and lots of help with testing and
5773 documentation checking. Many of IPython's newer features are a result of
5774 discussions with him (bugs are still my fault, not his).
5775
5776 Obviously Guido van Rossum and the whole Python development team, that
5777 goes without saying.
5778
5779 IPython's website is generously hosted at http://ipython.scipy.orgby
5780 Enthought (http://www.enthought.com). I am very grateful to them and all
5781 of the SciPy team for their contribution.
5782
5783 Fernando would also like to thank Stephen Figgins <fig-AT-monitor.net>,
5784 an O'Reilly Python editor. His Oct/11/2001 article about IPP and
5785 LazyPython, was what got this project started. You can read it at:
5786 http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html.
5787
5788 And last but not least, all the kind IPython users who have emailed new
5789 code, bug reports, fixes, comments and ideas. A brief list follows,
5790 please let me know if I have ommitted your name by accident:
5791
5792 * [Jack Moffit] <jack-AT-xiph.org> Bug fixes, including the infamous
5793 color problem. This bug alone caused many lost hours and
5794 frustration, many thanks to him for the fix. I've always been a
5795 fan of Ogg & friends, now I have one more reason to like these folks.
5796 Jack is also contributing with Debian packaging and many other
5797 things.
5798 * [Alexander Schmolck] <a.schmolck-AT-gmx.net> Emacs work, bug
5799 reports, bug fixes, ideas, lots more. The ipython.el mode for
5800 (X)Emacs is Alex's code, providing full support for IPython under
5801 (X)Emacs.
5802 * [Andrea Riciputi] <andrea.riciputi-AT-libero.it> Mac OSX
5803 information, Fink package management.
5804 * [Gary Bishop] <gb-AT-cs.unc.edu> Bug reports, and patches to work
5805 around the exception handling idiosyncracies of WxPython. Readline
5806 and color support for Windows.
5807 * [Jeffrey Collins] <Jeff.Collins-AT-vexcel.com> Bug reports. Much
5808 improved readline support, including fixes for Python 2.3.
5809 * [Dryice Liu] <dryice-AT-liu.com.cn> FreeBSD port.
5810 * [Mike Heeter] <korora-AT-SDF.LONESTAR.ORG>
5811 * [Christopher Hart] <hart-AT-caltech.edu> PDB integration.
5812 * [Milan Zamazal] <pdm-AT-zamazal.org> Emacs info.
5813 * [Philip Hisley] <compsys-AT-starpower.net>
5814 * [Holger Krekel] <pyth-AT-devel.trillke.net> Tab completion, lots
5815 more.
5816 * [Robin Siebler] <robinsiebler-AT-starband.net>
5817 * [Ralf Ahlbrink] <ralf_ahlbrink-AT-web.de>
5818 * [Thorsten Kampe] <thorsten-AT-thorstenkampe.de>
5819 * [Fredrik Kant] <fredrik.kant-AT-front.com> Windows setup.
5820 * [Syver Enstad] <syver-en-AT-online.no> Windows setup.
5821 * [Richard] <rxe-AT-renre-europe.com> Global embedding.
5822 * [Hayden Callow] <h.callow-AT-elec.canterbury.ac.nz> Gnuplot.py 1.6
5823 compatibility.
5824 * [Leonardo Santagada] <retype-AT-terra.com.br> Fixes for Windows
5825 installation.
5826 * [Christopher Armstrong] <radix-AT-twistedmatrix.com> Bugfixes.
5827 * [Francois Pinard] <pinard-AT-iro.umontreal.ca> Code and
5828 documentation fixes.
5829 * [Cory Dodt] <cdodt-AT-fcoe.k12.ca.us> Bug reports and Windows
5830 ideas. Patches for Windows installer.
5831 * [Olivier Aubert] <oaubert-AT-bat710.univ-lyon1.fr> New magics.
5832 * [King C. Shu] <kingshu-AT-myrealbox.com> Autoindent patch.
5833 * [Chris Drexler] <chris-AT-ac-drexler.de> Readline packages for
5834 Win32/CygWin.
5835 * [Gustavo Cordova Avila] <gcordova-AT-sismex.com> EvalDict code for
5836 nice, lightweight string interpolation.
5837 * [Kasper Souren] <Kasper.Souren-AT-ircam.fr> Bug reports, ideas.
5838 * [Gever Tulley] <gever-AT-helium.com> Code contributions.
5839 * [Ralf Schmitt] <ralf-AT-brainbot.com> Bug reports & fixes.
5840 * [Oliver Sander] <osander-AT-gmx.de> Bug reports.
5841 * [Rod Holland] <rhh-AT-structurelabs.com> Bug reports and fixes to
5842 logging module.
5843 * [Daniel 'Dang' Griffith] <pythondev-dang-AT-lazytwinacres.net>
5844 Fixes, enhancement suggestions for system shell use.
5845 * [Viktor Ransmayr] <viktor.ransmayr-AT-t-online.de> Tests and
5846 reports on Windows installation issues. Contributed a true Windows
5847 binary installer.
5848 * [Mike Salib] <msalib-AT-mit.edu> Help fixing a subtle bug related
5849 to traceback printing.
5850 * [W.J. van der Laan] <gnufnork-AT-hetdigitalegat.nl> Bash-like
5851 prompt specials.
5852 * [Antoon Pardon] <Antoon.Pardon-AT-rece.vub.ac.be> Critical fix for
5853 the multithreaded IPython.
5854 * [John Hunter] <jdhunter-AT-nitace.bsd.uchicago.edu> Matplotlib
5855 author, helped with all the development of support for matplotlib
5856 in IPyhton, including making necessary changes to matplotlib itself.
5857 * [Matthew Arnison] <maffew-AT-cat.org.au> Bug reports, '%run -d' idea.
5858 * [Prabhu Ramachandran] <prabhu_r-AT-users.sourceforge.net> Help
5859 with (X)Emacs support, threading patches, ideas...
5860 * [Norbert Tretkowski] <tretkowski-AT-inittab.de> help with Debian
5861 packaging and distribution.
5862 * [George Sakkis] <gsakkis-AT-eden.rutgers.edu> New matcher for
5863 tab-completing named arguments of user-defined functions.
5864 * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu> Wildcard
5865 support implementation for searching namespaces.
5866 * [Vivian De Smedt] <vivian-AT-vdesmedt.com> Debugger enhancements,
5867 so that when pdb is activated from within IPython, coloring, tab
5868 completion and other features continue to work seamlessly.
5869 * [Scott Tsai] <scottt958-AT-yahoo.com.tw> Support for automatic
5870 editor invocation on syntax errors (see
5871 http://www.scipy.net/roundup/ipython/issue36).
5872 * [Alexander Belchenko] <bialix-AT-ukr.net> Improvements for win32
5873 paging system.
5874 * [Will Maier] <willmaier-AT-ml1.net> Official OpenBSD port.
5875
@@ -0,0 +1,62 b''
1 """Test cpaste magic"""
2
3 tests = {'pass': ["> > > run()",
4 ">>> > run()",
5 "+++ run()",
6 "++ run()",
7 " >>> run()"],
8
9 'fail': ["+ + run()",
10 " ++ run()"]}
11
12 from StringIO import StringIO
13 import sys
14
15 stdin_save = sys.stdin
16
17 # NOTE: no blank lines allowed in function definition
18 def testcase(code,should_fail=False):
19 """Execute code via 'cpaste' and ensure it was executed, unless
20 should_fail is set.
21
22 """
23 _ip.user_ns['code_ran'] = False
24 #
25 src = StringIO()
26 src.write('\n')
27 src.write(code)
28 src.write('\n--\n')
29 src.seek(0)
30 #
31 sys.stdin = src
32
33 try:
34 cpaste
35 except:
36 if not should_fail:
37 raise AssertionError("Failure not expected : '%s'" %
38 code)
39 else:
40 assert code_ran
41 if should_fail:
42 raise AssertionError("Failure expected : '%s'" % code)
43 #
44 finally:
45 sys.stdin = stdin_save
46 #
47
48 def run():
49 """Marker function: sets a flag when executed.
50
51 """
52 _ip.user_ns['code_ran'] = True
53 return 'run' # return string so '+ run()' doesn't result in success
54
55
56 ### Actual testing happens here
57
58 for code in tests['pass']:
59 testcase(code)
60
61 for code in tests['fail']:
62 testcase(code,should_fail=True)
@@ -1,86 +1,86 b''
1 <?xml version='1.0' encoding='iso-8859-1'?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
6 <link rel="stylesheet" href="igrid_help.css" type="text/css" />
7 <title>igrid help</title>
8 </head>
9 <body>
10 <h1>igrid help</h1>
11
12
13 <h2>Commands</h2>
14
15
16 <h3>pick (P)</h3>
17 <p>Pick the whole row (object is available as "_")</p>
18
19 <h3>pickattr (Shift-P)</h3>
20 <p>Pick the attribute under the cursor</p>
21
22 <h3>pickallattrs (Shift-C)</h3>
23 <p>Pick' the complete column under the cursor (i.e. the attribute under the
24 cursor) from all currently fetched objects. These attributes will be returned
25 as a list.</p>
26
27 <h3>enter (E)</h3>
28 <p>Enter the object under the cursor. (what this mean depends on the object
29 itself, i.e. how it implements iteration). This opens a new browser 'level'.</p>
30
31 <h3>enterattr (Shift-E)</h3>
32 <p>Enter the attribute under the cursor.</p>
33
34 <h3>detail (D)</h3>
35 <p>Show a detail view of the object under the cursor. This shows the name,
36 type, doc string and value of the object attributes (and it might show more
37 attributes than in the list view, depending on the object).</p>
38
39 <h3>detailattr (Shift-D)</h3>
40 <p>Show a detail view of the attribute under the cursor.</p>
41
42 <h3>pickrows (M)</h3>
43 <p>Pick multiple selected rows (M)</p>
44
45 <h3>pickrowsattr (CTRL-M)</h3>
46 <p>From multiple selected rows pick the cells matching the attribute the cursor is in (CTRL-M)</p>
47
48 <h3>find (CTRL-F)</h3>
49 <p>Find text</p>
50
51 <h3>find_next (F3)</h3>
52 <p>Find next occurrence of the searchtext</p>
53
54 <h3>find_previous (Shift-F3)</h3>
55 <p>Find previous occurrence of the searchtext </p>
56
57 <h3>sortattrasc (V)</h3>
58 <p>Sort the objects (in ascending order) using the attribute under the cursor as the sort key.</p>
59
60 <h3>sortattrdesc (Shift-V)</h3>
61 <p>Sort the objects (in descending order) using the attribute under the cursor as the sort key.</p>
62
63 <h3>leave (Backspace, DEL, X)</h3>
64 <p>Close current tab (and all the tabs to the right of the current one).</h3>
65
66 <h3>quit (ESC,Q)</h3>
67 <p>Quit igrid and return to the IPython prompt.</p>
68
69
70 <h2>Navigation</h2>
71
72
73 <h3>Jump to the last column of the current row (END, CTRL-E, CTRL-Right)</h3>
74
75 <h3>Jump to the first column of the current row (HOME, CTRL-A, CTRL-Left)</h3>
76
77 <h3>Move the cursor one column to the left (&lt;)</h3>
78
79 <h3>Move the cursor one column to the right (&gt;)</h3>
80
81 <h3>Jump to the first row in the current column (CTRL-Up)</h3>
82
83 <h3>Jump to the last row in the current column (CTRL-Down)</h3>
84
85 </body>
86 </html>
1 <?xml version='1.0' encoding='iso-8859-1'?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
6 <link rel="stylesheet" href="igrid_help.css" type="text/css" />
7 <title>igrid help</title>
8 </head>
9 <body>
10 <h1>igrid help</h1>
11
12
13 <h2>Commands</h2>
14
15
16 <h3>pick (P)</h3>
17 <p>Pick the whole row (object is available as "_")</p>
18
19 <h3>pickattr (Shift-P)</h3>
20 <p>Pick the attribute under the cursor</p>
21
22 <h3>pickallattrs (Shift-C)</h3>
23 <p>Pick' the complete column under the cursor (i.e. the attribute under the
24 cursor) from all currently fetched objects. These attributes will be returned
25 as a list.</p>
26
27 <h3>enter (E)</h3>
28 <p>Enter the object under the cursor. (what this mean depends on the object
29 itself, i.e. how it implements iteration). This opens a new browser 'level'.</p>
30
31 <h3>enterattr (Shift-E)</h3>
32 <p>Enter the attribute under the cursor.</p>
33
34 <h3>detail (D)</h3>
35 <p>Show a detail view of the object under the cursor. This shows the name,
36 type, doc string and value of the object attributes (and it might show more
37 attributes than in the list view, depending on the object).</p>
38
39 <h3>detailattr (Shift-D)</h3>
40 <p>Show a detail view of the attribute under the cursor.</p>
41
42 <h3>pickrows (M)</h3>
43 <p>Pick multiple selected rows (M)</p>
44
45 <h3>pickrowsattr (CTRL-M)</h3>
46 <p>From multiple selected rows pick the cells matching the attribute the cursor is in (CTRL-M)</p>
47
48 <h3>find (CTRL-F)</h3>
49 <p>Find text</p>
50
51 <h3>find_next (F3)</h3>
52 <p>Find next occurrence of the searchtext</p>
53
54 <h3>find_previous (Shift-F3)</h3>
55 <p>Find previous occurrence of the searchtext </p>
56
57 <h3>sortattrasc (V)</h3>
58 <p>Sort the objects (in ascending order) using the attribute under the cursor as the sort key.</p>
59
60 <h3>sortattrdesc (Shift-V)</h3>
61 <p>Sort the objects (in descending order) using the attribute under the cursor as the sort key.</p>
62
63 <h3>leave (Backspace, DEL, X)</h3>
64 <p>Close current tab (and all the tabs to the right of the current one).</h3>
65
66 <h3>quit (ESC,Q)</h3>
67 <p>Quit igrid and return to the IPython prompt.</p>
68
69
70 <h2>Navigation</h2>
71
72
73 <h3>Jump to the last column of the current row (END, CTRL-E, CTRL-Right)</h3>
74
75 <h3>Jump to the first column of the current row (HOME, CTRL-A, CTRL-Left)</h3>
76
77 <h3>Move the cursor one column to the left (&lt;)</h3>
78
79 <h3>Move the cursor one column to the right (&gt;)</h3>
80
81 <h3>Jump to the first row in the current column (CTRL-Up)</h3>
82
83 <h3>Jump to the last row in the current column (CTRL-Down)</h3>
84
85 </body>
86 </html>
@@ -14,4 +14,6 b' from ipy_completers import *'
14 14 ip.set_hook('complete_command', apt_completer, re_key = '.*apt-get')
15 15 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
16 16 ip.set_hook('complete_command', hg_completer, str_key = 'hg')
17 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
17
18 # the old bzr completer is deprecated, we recommend ipy_bzr
19 #ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 1
3 2 """ Implementations for various useful completers
4 3
@@ -12,6 +11,7 b' import IPython.ipapi'
12 11 import glob,os,shlex,sys
13 12 import inspect
14 13 from time import time
14 from zipimport import zipimporter
15 15 ip = IPython.ipapi.get()
16 16
17 17 try:
@@ -86,13 +86,18 b' def moduleList(path):'
86 86
87 87 if os.path.isdir(path):
88 88 folder_list = os.listdir(path)
89 elif path.endswith('.egg'):
90 try:
91 folder_list = [f for f in zipimporter(path)._files]
92 except:
93 folder_list = []
89 94 else:
90 95 folder_list = []
91 96 #folder_list = glob.glob(os.path.join(path,'*'))
92 97 folder_list = [p for p in folder_list \
93 98 if os.path.exists(os.path.join(path, p,'__init__.py'))\
94 99 or p[-3:] in ('.py','.so')\
95 or p[-4:] in ('.pyc','.pyo')]
100 or p[-4:] in ('.pyc','.pyo','.pyd')]
96 101
97 102 folder_list = [os.path.basename(p).split('.')[0] for p in folder_list]
98 103 return folder_list
@@ -211,15 +216,15 b' def hg_completer(self,event):'
211 216
212 217
213 218
214 bzr_commands = """
215 add annotate bind branch break-lock bundle-revisions cat check
216 checkout commit conflicts deleted diff export gannotate gbranch
217 gcommit gdiff help ignore ignored info init init-repository inventory
218 log merge missing mkdir mv nick pull push reconcile register-branch
219 remerge remove renames resolve revert revno root serve sign-my-commits
220 status testament unbind uncommit unknowns update upgrade version
221 version-info visualise whoami
222 """
219 __bzr_commands = None
220
221 def bzr_commands():
222 global __bzr_commands
223 if __bzr_commands is not None:
224 return __bzr_commands
225 out = os.popen('bzr help commands')
226 __bzr_commands = [l.split()[0] for l in out]
227 return __bzr_commands
223 228
224 229 def bzr_completer(self,event):
225 230 """ Completer for bazaar commands """
@@ -232,7 +237,7 b' def bzr_completer(self,event):'
232 237 param = cmd_param[-1]
233 238 output_file = (param == '--output=')
234 239 if cmd == 'help':
235 return bzr_commands.split()
240 return bzr_commands()
236 241 elif cmd in ['bundle-revisions','conflicts',
237 242 'deleted','nick','register-branch',
238 243 'serve','unbind','upgrade','version',
@@ -242,7 +247,7 b' def bzr_completer(self,event):'
242 247 # the rest are probably file names
243 248 return ip.IP.Completer.file_matches(event.symbol)
244 249
245 return bzr_commands.split()
250 return bzr_commands()
246 251
247 252
248 253 def shlex_split(x):
@@ -326,7 +331,29 b' def cd_completer(self, event):'
326 331 if os.path.isdir(relpath):
327 332 return [relpath]
328 333 raise IPython.ipapi.TryNext
329 return found
334
335
336 def single_dir_expand(matches):
337 "Recursively expand match lists containing a single dir."
338
339 if len(matches) == 1 and os.path.isdir(matches[0]):
340 # Takes care of links to directories also. Use '/'
341 # explicitly, even under Windows, so that name completions
342 # don't end up escaped.
343 d = matches[0]
344 if d[-1] in ['/','\\']:
345 d = d[:-1]
346
347 subdirs = [p for p in os.listdir(d) if os.path.isdir( d + '/' + p)]
348 if subdirs:
349 matches = [ (d + '/' + p) for p in subdirs ]
350 return single_dir_expand(matches)
351 else:
352 return matches
353 else:
354 return matches
355
356 return single_dir_expand(found)
330 357
331 358 def apt_get_packages(prefix):
332 359 out = os.popen('apt-cache pkgnames')
This diff has been collapsed as it changes many lines, (840 lines changed) Show them Hide them
@@ -1,248 +1,592 b''
1 """ Leo plugin for IPython
2
3 Example use:
4
5 nodes.foo = "hello world"
6
7 -> create '@ipy foo' node with text "hello world"
8
9 Access works also, and so does tab completion.
10
11 """
12 import IPython.ipapi
13 import IPython.genutils
14 import IPython.generics
15 import re
16
17
18
19 ip = IPython.ipapi.get()
20 leo = ip.user_ns['leox']
21 c,g = leo.c, leo.g
22
23 # will probably be overwritten by user, but handy for experimentation early on
24 ip.user_ns['c'] = c
25 ip.user_ns['g'] = g
26
27
28 from IPython.external.simplegeneric import generic
29 import pprint
30
31 @generic
32 def format_for_leo(obj):
33 """ Convert obj to string representiation (for editing in Leo)"""
34 return pprint.pformat(obj)
35
36 @format_for_leo.when_type(list)
37 def format_list(obj):
38 return "\n".join(str(s) for s in obj)
39
40 nodename_re = r'(@ipy?[\w-]+)?\s?(\w+)'
41
42 def all_cells():
43 d = {}
44 for p in c.allNodes_iter():
45 h = p.headString()
46 if h.startswith('@') and len(h.split()) == 1:
47 continue
48 mo = re.match(nodename_re, h)
49 if not mo:
50 continue
51 d[mo.group(2)] = p.copy()
52 return d
53
54
55 class TrivialLeoWorkbook:
56 """ class to find cells with simple syntax
57
58 """
59 def __getattr__(self, key):
60 cells = all_cells()
61 p = cells[key]
62 body = p.bodyString()
63 return eval_body(body)
64 def __setattr__(self,key,val):
65 cells = all_cells()
66 p = cells.get(key,None)
67 if p is None:
68 add_var(key,val)
69 else:
70 c.setBodyString(p,format_for_leo(val))
71 def __str__(self):
72 return "<TrivialLeoWorkbook>"
73 __repr__ = __str__
74
75 ip.user_ns['nodes'] = TrivialLeoWorkbook()
76
77
78 class LeoNode(object):
79 def __init__(self,p):
80 self.p = p.copy()
81
82 def get_h(self): return self.p.headString()
83 def set_h(self,val):
84 print "set head",val
85 c.beginUpdate()
86 try:
87 c.setHeadString(self.p,val)
88 finally:
89 c.endUpdate()
90
91 h = property( get_h, set_h)
92
93 def get_b(self): return self.p.bodyString()
94 def set_b(self,val):
95 print "set body",val
96 c.beginUpdate()
97 try:
98 c.setBodyString(self.p, val)
99 finally:
100 c.endUpdate()
101
102 b = property(get_b, set_b)
103
104 def set_val(self, val):
105 self.b = pprint.pformat(val)
106
107 v = property(lambda self: ip.ev(self.b.strip()), set_val)
108
109 def set_l(self,val):
110 self.b = '\n'.join(val )
111 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
112 set_l)
113
114 def __iter__(self):
115 return (LeoNode(p) for p in self.p.children_iter())
116
117
118 class LeoWorkbook:
119 """ class for 'advanced' node access """
120 def __getattr__(self, key):
121 if key.startswith('_') or key == 'trait_names':
122 raise AttributeError
123 cells = all_cells()
124 p = cells.get(key, None)
125 if p is None:
126 p = add_var(key,None)
127
128 return LeoNode(p)
129
130 def __str__(self):
131 return "<LeoWorkbook>"
132 __repr__ = __str__
133 ip.user_ns['wb'] = LeoWorkbook()
134
135
136 _dummyval = object()
137 @IPython.generics.complete_object.when_type(LeoWorkbook)
138 def workbook_complete(obj, prev):
139 return all_cells().keys()
140
141
142 def add_var(varname, value = _dummyval):
143 c.beginUpdate()
144 try:
145
146 nodename = '@ipy-var ' + varname
147 p2 = g.findNodeAnywhere(c,nodename)
148 if not c.positionExists(p2):
149 p2 = c.currentPosition().insertAfter()
150 c.setHeadString(p2,'@ipy ' + varname)
151
152 c.setCurrentPosition(p2)
153 if value is _dummyval:
154 val = ip.user_ns[varname]
155 else:
156 val = value
157 if val is not None:
158 formatted = format_for_leo(val)
159 c.setBodyString(p2,formatted)
160 return p2
161 finally:
162 c.endUpdate()
163
164 def add_file(self,fname):
165 p2 = c.currentPosition().insertAfter()
166
167 def push_script(p):
168 c.beginUpdate()
169 try:
170 ohist = ip.IP.output_hist
171 hstart = len(ip.IP.input_hist)
172 script = g.getScript(c,p,useSelectedText=False,forcePythonSentinels=False,useSentinels=False)
173
174 script = g.splitLines(script + '\n')
175 script = ''.join(z for z in script if z.strip())
176
177 ip.runlines(script)
178
179 has_output = False
180 for idx in range(hstart,len(ip.IP.input_hist)):
181 val = ohist.get(idx,None)
182 if val is None:
183 continue
184 has_output = True
185 inp = ip.IP.input_hist[idx]
186 if inp.strip():
187 g.es('In: %s' % (inp[:40], ), tabName = 'IPython')
188
189 g.es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)), tabName = 'IPython')
190
191 if not has_output:
192 g.es('ipy run: %s' %( p.headString(),), tabName = 'IPython')
193 finally:
194 c.endUpdate()
195
196
197 def eval_body(body):
198 try:
199 val = ip.ev(body)
200 except:
201 # just use stringlist if it's not completely legal python expression
202 val = IPython.genutils.SList(body.splitlines())
203 return val
204
205 def push_variable(p,varname):
206 body = p.bodyString()
207 val = eval_body(body.strip())
208 ip.user_ns[varname] = val
209 g.es('ipy var: %s' % (varname,), tabName = "IPython")
210
211 def push_from_leo(p):
212 tup = p.headString().split(None,1)
213 # @ipy foo is variable foo
214 if len(tup) == 2 and tup[0] == '@ipy':
215 varname = tup[1]
216 push_variable(p,varname)
217 return
218
219 push_script(p)
220 return
221
222
223 ip.user_ns['leox'].push = push_from_leo
224
225 def leo_f(self,s):
226 """ open file(s) in Leo
227
228 Takes an mglob pattern, e.g. '%leo *.cpp' or %leo 'rec:*.cpp'
229 """
230 import os
231 from IPython.external import mglob
232
233 files = mglob.expand(s)
234 c.beginUpdate()
235 try:
236 for fname in files:
237 p = g.findNodeAnywhere(c,'@auto ' + fname)
238 if not p:
239 p = c.currentPosition().insertAfter()
240
241 p.setHeadString('@auto ' + fname)
242 if os.path.isfile(fname):
243 c.setBodyString(p,open(fname).read())
244 c.selectPosition(p)
245 finally:
246 c.endUpdate()
247
248 ip.expose_magic('leo',leo_f)
1 """ ILeo - Leo plugin for IPython
2
3
4 """
5 import IPython.ipapi
6 import IPython.genutils
7 import IPython.generics
8 from IPython.hooks import CommandChainDispatcher
9 import re
10 import UserDict
11 from IPython.ipapi import TryNext
12 import IPython.macro
13 import IPython.Shell
14
15 def init_ipython(ipy):
16 """ This will be run by _ip.load('ipy_leo')
17
18 Leo still needs to run update_commander() after this.
19
20 """
21 global ip
22 ip = ipy
23 IPython.Shell.hijack_tk()
24 ip.set_hook('complete_command', mb_completer, str_key = '%mb')
25 ip.expose_magic('mb',mb_f)
26 ip.expose_magic('lee',lee_f)
27 ip.expose_magic('leoref',leoref_f)
28 expose_ileo_push(push_cl_node,100)
29 # this should be the LAST one that will be executed, and it will never raise TryNext
30 expose_ileo_push(push_ipython_script, 1000)
31 expose_ileo_push(push_plain_python, 100)
32 expose_ileo_push(push_ev_node, 100)
33 global wb
34 wb = LeoWorkbook()
35 ip.user_ns['wb'] = wb
36
37 show_welcome()
38
39
40 def update_commander(new_leox):
41 """ Set the Leo commander to use
42
43 This will be run every time Leo does ipython-launch; basically,
44 when the user switches the document he is focusing on, he should do
45 ipython-launch to tell ILeo what document the commands apply to.
46
47 """
48
49 global c,g
50 c,g = new_leox.c, new_leox.g
51 print "Set Leo Commander:",c.frame.getTitle()
52
53 # will probably be overwritten by user, but handy for experimentation early on
54 ip.user_ns['c'] = c
55 ip.user_ns['g'] = g
56 ip.user_ns['_leo'] = new_leox
57
58 new_leox.push = push_position_from_leo
59 run_leo_startup_node()
60
61 from IPython.external.simplegeneric import generic
62 import pprint
63
64 def es(s):
65 g.es(s, tabName = 'IPython')
66 pass
67
68 @generic
69 def format_for_leo(obj):
70 """ Convert obj to string representiation (for editing in Leo)"""
71 return pprint.pformat(obj)
72
73 @format_for_leo.when_type(list)
74 def format_list(obj):
75 return "\n".join(str(s) for s in obj)
76
77
78 attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
79 def valid_attribute(s):
80 return attribute_re.match(s)
81
82 _rootnode = None
83 def rootnode():
84 """ Get ileo root node (@ipy-root)
85
86 if node has become invalid or has not been set, return None
87
88 Note that the root is the *first* @ipy-root item found
89 """
90 global _rootnode
91 if _rootnode is None:
92 return None
93 if c.positionExists(_rootnode.p):
94 return _rootnode
95 _rootnode = None
96 return None
97
98 def all_cells():
99 global _rootnode
100 d = {}
101 r = rootnode()
102 if r is not None:
103 nodes = r.p.children_iter()
104 else:
105 nodes = c.allNodes_iter()
106
107 for p in nodes:
108 h = p.headString()
109 if h.strip() == '@ipy-root':
110 # update root node (found it for the first time)
111 _rootnode = LeoNode(p)
112 # the next recursive call will use the children of new root
113 return all_cells()
114
115 if h.startswith('@a '):
116 d[h.lstrip('@a ').strip()] = p.parent().copy()
117 elif not valid_attribute(h):
118 continue
119 d[h] = p.copy()
120 return d
121
122 def eval_node(n):
123 body = n.b
124 if not body.startswith('@cl'):
125 # plain python repr node, just eval it
126 return ip.ev(n.b)
127 # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body
128 first, rest = body.split('\n',1)
129 tup = first.split(None, 1)
130 # @cl alone SPECIAL USE-> dump var to user_ns
131 if len(tup) == 1:
132 val = ip.ev(rest)
133 ip.user_ns[n.h] = val
134 es("%s = %s" % (n.h, repr(val)[:20] ))
135 return val
136
137 cl, hd = tup
138
139 xformer = ip.ev(hd.strip())
140 es('Transform w/ %s' % repr(xformer))
141 return xformer(rest, n)
142
143 class LeoNode(object, UserDict.DictMixin):
144 """ Node in Leo outline
145
146 Most important attributes (getters/setters available:
147 .v - evaluate node, can also be alligned
148 .b, .h - body string, headline string
149 .l - value as string list
150
151 Also supports iteration,
152
153 setitem / getitem (indexing):
154 wb.foo['key'] = 12
155 assert wb.foo['key'].v == 12
156
157 Note the asymmetry on setitem and getitem! Also other
158 dict methods are available.
159
160 .ipush() - run push-to-ipython
161
162 Minibuffer command access (tab completion works):
163
164 mb save-to-file
165
166 """
167 def __init__(self,p):
168 self.p = p.copy()
169
170 def __str__(self):
171 return "<LeoNode %s>" % str(self.p)
172
173 __repr__ = __str__
174
175 def __get_h(self): return self.p.headString()
176 def __set_h(self,val):
177 print "set head",val
178 c.beginUpdate()
179 try:
180 c.setHeadString(self.p,val)
181 finally:
182 c.endUpdate()
183
184 h = property( __get_h, __set_h, doc = "Node headline string")
185
186 def __get_b(self): return self.p.bodyString()
187 def __set_b(self,val):
188 print "set body",val
189 c.beginUpdate()
190 try:
191 c.setBodyString(self.p, val)
192 finally:
193 c.endUpdate()
194
195 b = property(__get_b, __set_b, doc = "Nody body string")
196
197 def __set_val(self, val):
198 self.b = format_for_leo(val)
199
200 v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value")
201
202 def __set_l(self,val):
203 self.b = '\n'.join(val )
204 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
205 __set_l, doc = "Node value as string list")
206
207 def __iter__(self):
208 """ Iterate through nodes direct children """
209
210 return (LeoNode(p) for p in self.p.children_iter())
211
212 def __children(self):
213 d = {}
214 for child in self:
215 head = child.h
216 tup = head.split(None,1)
217 if len(tup) > 1 and tup[0] == '@k':
218 d[tup[1]] = child
219 continue
220
221 if not valid_attribute(head):
222 d[head] = child
223 continue
224 return d
225 def keys(self):
226 d = self.__children()
227 return d.keys()
228 def __getitem__(self, key):
229 """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff'
230
231 If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well
232 """
233 key = str(key)
234 d = self.__children()
235 return d[key]
236 def __setitem__(self, key, val):
237 """ You can do wb.foo['My Stuff'] = 12 to create children
238
239 This will create 'My Stuff' as a child of foo (if it does not exist), and
240 do .v = 12 assignment.
241
242 Exception:
243
244 wb.foo['bar'] = 12
245
246 will create a child with headline '@k bar', because bar is a valid python name
247 and we don't want to crowd the WorkBook namespace with (possibly numerous) entries
248 """
249 key = str(key)
250 d = self.__children()
251 if key in d:
252 d[key].v = val
253 return
254
255 if not valid_attribute(key):
256 head = key
257 else:
258 head = '@k ' + key
259 p = c.createLastChildNode(self.p, head, '')
260 LeoNode(p).v = val
261
262 def ipush(self):
263 """ Does push-to-ipython on the node """
264 push_from_leo(self)
265
266 def go(self):
267 """ Set node as current node (to quickly see it in Outline) """
268 c.beginUpdate()
269 try:
270 c.setCurrentPosition(self.p)
271 finally:
272 c.endUpdate()
273
274 def script(self):
275 """ Method to get the 'tangled' contents of the node
276
277 (parse @others, << section >> references etc.)
278 """
279 return g.getScript(c,self.p,useSelectedText=False,useSentinels=False)
280
281 def __get_uA(self):
282 p = self.p
283 # Create the uA if necessary.
284 if not hasattr(p.v.t,'unknownAttributes'):
285 p.v.t.unknownAttributes = {}
286
287 d = p.v.t.unknownAttributes.setdefault('ipython', {})
288 return d
289
290 uA = property(__get_uA, doc = "Access persistent unknownAttributes of node")
291
292
293 class LeoWorkbook:
294 """ class for 'advanced' node access
295
296 Has attributes for all "discoverable" nodes. Node is discoverable if it
297 either
298
299 - has a valid python name (Foo, bar_12)
300 - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo)
301
302 """
303 def __getattr__(self, key):
304 if key.startswith('_') or key == 'trait_names' or not valid_attribute(key):
305 raise AttributeError
306 cells = all_cells()
307 p = cells.get(key, None)
308 if p is None:
309 return add_var(key)
310
311 return LeoNode(p)
312
313 def __str__(self):
314 return "<LeoWorkbook>"
315 def __setattr__(self,key, val):
316 raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val))
317
318 __repr__ = __str__
319
320 def __iter__(self):
321 """ Iterate all (even non-exposed) nodes """
322 cells = all_cells()
323 return (LeoNode(p) for p in c.allNodes_iter())
324
325 current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node")
326
327 def match_h(self, regex):
328 cmp = re.compile(regex)
329 for node in self:
330 if re.match(cmp, node.h, re.IGNORECASE):
331 yield node
332 return
333
334 @IPython.generics.complete_object.when_type(LeoWorkbook)
335 def workbook_complete(obj, prev):
336 return all_cells().keys() + [s for s in prev if not s.startswith('_')]
337
338
339 def add_var(varname):
340 c.beginUpdate()
341 r = rootnode()
342 try:
343 if r is None:
344 p2 = g.findNodeAnywhere(c,varname)
345 else:
346 p2 = g.findNodeInChildren(c, r.p, varname)
347 if p2:
348 return LeoNode(p2)
349
350 if r is not None:
351 p2 = r.p.insertAsLastChild()
352
353 else:
354 p2 = c.currentPosition().insertAfter()
355
356 c.setHeadString(p2,varname)
357 return LeoNode(p2)
358 finally:
359 c.endUpdate()
360
361 def add_file(self,fname):
362 p2 = c.currentPosition().insertAfter()
363
364 push_from_leo = CommandChainDispatcher()
365
366 def expose_ileo_push(f, prio = 0):
367 push_from_leo.add(f, prio)
368
369 def push_ipython_script(node):
370 """ Execute the node body in IPython, as if it was entered in interactive prompt """
371 c.beginUpdate()
372 try:
373 ohist = ip.IP.output_hist
374 hstart = len(ip.IP.input_hist)
375 script = node.script()
376
377 ip.user_ns['_p'] = node
378 ip.runlines(script)
379 ip.user_ns.pop('_p',None)
380
381 has_output = False
382 for idx in range(hstart,len(ip.IP.input_hist)):
383 val = ohist.get(idx,None)
384 if val is None:
385 continue
386 has_output = True
387 inp = ip.IP.input_hist[idx]
388 if inp.strip():
389 es('In: %s' % (inp[:40], ))
390
391 es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)))
392
393 if not has_output:
394 es('ipy run: %s (%d LL)' %( node.h,len(script)))
395 finally:
396 c.endUpdate()
397
398
399 def eval_body(body):
400 try:
401 val = ip.ev(body)
402 except:
403 # just use stringlist if it's not completely legal python expression
404 val = IPython.genutils.SList(body.splitlines())
405 return val
406
407 def push_plain_python(node):
408 if not node.h.endswith('P'):
409 raise TryNext
410 script = node.script()
411 lines = script.count('\n')
412 try:
413 exec script in ip.user_ns
414 except:
415 print " -- Exception in script:\n"+script + "\n --"
416 raise
417 es('ipy plain: %s (%d LL)' % (node.h,lines))
418
419
420 def push_cl_node(node):
421 """ If node starts with @cl, eval it
422
423 The result is put as last child of @ipy-results node, if it exists
424 """
425 if not node.b.startswith('@cl'):
426 raise TryNext
427
428 p2 = g.findNodeAnywhere(c,'@ipy-results')
429 val = node.v
430 if p2:
431 es("=> @ipy-results")
432 LeoNode(p2).v = val
433 es(val)
434
435 def push_ev_node(node):
436 """ If headline starts with @ev, eval it and put result in body """
437 if not node.h.startswith('@ev '):
438 raise TryNext
439 expr = node.h.lstrip('@ev ')
440 es('ipy eval ' + expr)
441 res = ip.ev(expr)
442 node.v = res
443
444
445 def push_position_from_leo(p):
446 try:
447 push_from_leo(LeoNode(p))
448 except AttributeError,e:
449 if e.args == ("Commands instance has no attribute 'frame'",):
450 es("Error: ILeo not associated with .leo document")
451 es("Press alt+shift+I to fix!")
452 else:
453 raise
454
455 @generic
456 def edit_object_in_leo(obj, varname):
457 """ Make it @cl node so it can be pushed back directly by alt+I """
458 node = add_var(varname)
459 formatted = format_for_leo(obj)
460 if not formatted.startswith('@cl'):
461 formatted = '@cl\n' + formatted
462 node.b = formatted
463 node.go()
464
465 @edit_object_in_leo.when_type(IPython.macro.Macro)
466 def edit_macro(obj,varname):
467 bod = '_ip.defmacro("""\\\n' + obj.value + '""")'
468 node = add_var('Macro_' + varname)
469 node.b = bod
470 node.go()
471
472 def get_history(hstart = 0):
473 res = []
474 ohist = ip.IP.output_hist
475
476 for idx in range(hstart, len(ip.IP.input_hist)):
477 val = ohist.get(idx,None)
478 has_output = True
479 inp = ip.IP.input_hist_raw[idx]
480 if inp.strip():
481 res.append('In [%d]: %s' % (idx, inp))
482 if val:
483 res.append(pprint.pformat(val))
484 res.append('\n')
485 return ''.join(res)
486
487
488 def lee_f(self,s):
489 """ Open file(s)/objects in Leo
490
491 - %lee hist -> open full session history in leo
492 - Takes an object. l = [1,2,"hello"]; %lee l. Alt+I in leo pushes the object back
493 - Takes an mglob pattern, e.g. '%lee *.cpp' or %lee 'rec:*.cpp'
494 - Takes input history indices: %lee 4 6-8 10 12-47
495 """
496 import os
497
498 c.beginUpdate()
499 try:
500 if s == 'hist':
501 wb.ipython_history.b = get_history()
502 wb.ipython_history.go()
503 return
504
505
506 if s and s[0].isdigit():
507 # numbers; push input slices to leo
508 lines = self.extract_input_slices(s.strip().split(), True)
509 v = add_var('stored_ipython_input')
510 v.b = '\n'.join(lines)
511 return
512
513
514 # try editing the object directly
515 obj = ip.user_ns.get(s, None)
516 if obj is not None:
517 edit_object_in_leo(obj,s)
518 return
519
520
521 # if it's not object, it's a file name / mglob pattern
522 from IPython.external import mglob
523
524 files = (os.path.abspath(f) for f in mglob.expand(s))
525 for fname in files:
526 p = g.findNodeAnywhere(c,'@auto ' + fname)
527 if not p:
528 p = c.currentPosition().insertAfter()
529
530 p.setHeadString('@auto ' + fname)
531 if os.path.isfile(fname):
532 c.setBodyString(p,open(fname).read())
533 c.selectPosition(p)
534 print "Editing file(s), press ctrl+shift+w in Leo to write @auto nodes"
535 finally:
536 c.endUpdate()
537
538
539
540 def leoref_f(self,s):
541 """ Quick reference for ILeo """
542 import textwrap
543 print textwrap.dedent("""\
544 %leoe file/object - open file / object in leo
545 wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo')
546 wb.foo.v = 12 - assign to body of node foo
547 wb.foo.b - read or write the body of node foo
548 wb.foo.l - body of node foo as string list
549
550 for el in wb.foo:
551 print el.v
552
553 """
554 )
555
556
557
558 def mb_f(self, arg):
559 """ Execute leo minibuffer commands
560
561 Example:
562 mb save-to-file
563 """
564 c.executeMinibufferCommand(arg)
565
566 def mb_completer(self,event):
567 """ Custom completer for minibuffer """
568 cmd_param = event.line.split()
569 if event.line.endswith(' '):
570 cmd_param.append('')
571 if len(cmd_param) > 2:
572 return ip.IP.Completer.file_matches(event.symbol)
573 cmds = c.commandsDict.keys()
574 cmds.sort()
575 return cmds
576
577 def show_welcome():
578 print "------------------"
579 print "Welcome to Leo-enabled IPython session!"
580 print "Try %leoref for quick reference."
581 import IPython.platutils
582 IPython.platutils.set_term_title('ILeo')
583 IPython.platutils.freeze_term_title()
584
585 def run_leo_startup_node():
586 p = g.findNodeAnywhere(c,'@ipy-startup')
587 if p:
588 print "Running @ipy-startup nodes"
589 for n in LeoNode(p):
590 push_from_leo(n)
591
592
@@ -43,11 +43,13 b' def main():'
43 43 # %store foo
44 44 # %store bar
45 45 import ipy_rehashdir
46 import ipy_signals
46
47 # does not work without subprocess module!
48 #import ipy_signals
47 49
48 50 ip.ex('import os')
49 51 ip.ex("def up(): os.chdir('..')")
50
52 ip.user_ns['LA'] = LastArgFinder()
51 53 # Nice prompt
52 54
53 55 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
@@ -117,6 +119,29 b' def main():'
117 119
118 120 extend_shell_behavior(ip)
119 121
122 class LastArgFinder:
123 """ Allow $LA to work as "last argument of previous command", like $! in bash
124
125 To call this in normal IPython code, do LA()
126 """
127 def __call__(self, hist_idx = None):
128 ip = ipapi.get()
129 if hist_idx is None:
130 return str(self)
131 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
132 def __str__(self):
133 ip = ipapi.get()
134 for cmd in reversed(ip.IP.input_hist_raw):
135 parts = cmd.strip().split()
136 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
137 continue
138 return parts[-1]
139 return ""
140
141
142
143
144
120 145 # XXX You do not need to understand the next function!
121 146 # This should probably be moved out of profile
122 147
@@ -41,8 +41,9 b' Now launch a new IPython prompt and kill the process:'
41 41 (you don't need to specify PID for %kill if only one task is running)
42 42 """
43 43
44 from subprocess import Popen,PIPE
44 from subprocess import *
45 45 import os,shlex,sys,time
46 import threading,Queue
46 47
47 48 from IPython import genutils
48 49
@@ -71,15 +72,70 b' def startjob(job):'
71 72 p.line = job
72 73 return p
73 74
75 class AsyncJobQ(threading.Thread):
76 def __init__(self):
77 threading.Thread.__init__(self)
78 self.q = Queue.Queue()
79 self.output = []
80 self.stop = False
81 def run(self):
82 while 1:
83 cmd,cwd = self.q.get()
84 if self.stop:
85 self.output.append("** Discarding: '%s' - %s" % (cmd,cwd))
86 continue
87 self.output.append("** Task started: '%s' - %s" % (cmd,cwd))
88
89 p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd = cwd)
90 out = p.stdout.read()
91 self.output.append("** Task complete: '%s'\n" % cmd)
92 self.output.append(out)
93
94 def add(self,cmd):
95 self.q.put_nowait((cmd, os.getcwd()))
96
97 def dumpoutput(self):
98 while self.output:
99 item = self.output.pop(0)
100 print item
101
102 _jobq = None
103
104 def jobqueue_f(self, line):
105
106 global _jobq
107 if not _jobq:
108 print "Starting jobqueue - do '&some_long_lasting_system_command' to enqueue"
109 _jobq = AsyncJobQ()
110 _jobq.setDaemon(True)
111 _jobq.start()
112 ip.jobq = _jobq.add
113 return
114 if line.strip() == 'stop':
115 print "Stopping and clearing jobqueue, %jobqueue start to start again"
116 _jobq.stop = True
117 return
118 if line.strip() == 'start':
119 _jobq.stop = False
120 return
121
74 122 def jobctrl_prefilter_f(self,line):
75 123 if line.startswith('&'):
76 124 pre,fn,rest = self.split_user_input(line[1:])
77 125
78 126 line = ip.IP.expand_aliases(fn,rest)
79 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
127 if not _jobq:
128 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
129 return '_ip.jobq(%s)' % genutils.make_quoted_expr(line)
80 130
81 131 raise IPython.ipapi.TryNext
82 132
133 def jobq_output_hook(self):
134 if not _jobq:
135 return
136 _jobq.dumpoutput()
137
138
83 139
84 140 def job_list(ip):
85 141 keys = ip.db.keys('tasks/*')
@@ -91,8 +147,16 b' def magic_tasks(self,line):'
91 147
92 148 A 'task' is a process that has been started in IPython when 'jobctrl' extension is enabled.
93 149 Tasks can be killed with %kill.
150
151 '%tasks clear' clears the task list (from stale tasks)
94 152 """
95 153 ip = self.getapi()
154 if line.strip() == 'clear':
155 for k in ip.db.keys('tasks/*'):
156 print "Clearing",ip.db[k]
157 del ip.db[k]
158 return
159
96 160 ents = job_list(ip)
97 161 if not ents:
98 162 print "No tasks running"
@@ -125,7 +189,7 b' def magic_kill(self,line):'
125 189 magic_tasks(self,line)
126 190
127 191 if sys.platform == 'win32':
128 shell_internal_commands = 'break chcp cls copy ctty date del erase dir md mkdir path prompt rd rmdir time type ver vol'.split()
192 shell_internal_commands = 'break chcp cls copy ctty date del erase dir md mkdir path prompt rd rmdir start time type ver vol'.split()
129 193 else:
130 194 # todo linux commands
131 195 shell_internal_commands = []
@@ -133,20 +197,33 b' else:'
133 197
134 198 def jobctrl_shellcmd(ip,cmd):
135 199 """ os.system replacement that stores process info to db['tasks/t1234'] """
200 cmd = cmd.strip()
136 201 cmdname = cmd.split(None,1)[0]
137 if cmdname in shell_internal_commands:
202 if cmdname in shell_internal_commands or '|' in cmd or '>' in cmd or '<' in cmd:
138 203 use_shell = True
139 204 else:
140 205 use_shell = False
141 206
142 p = Popen(cmd,shell = use_shell)
143 jobentry = 'tasks/t' + str(p.pid)
144
207 jobentry = None
145 208 try:
209 try:
210 p = Popen(cmd,shell = use_shell)
211 except WindowsError:
212 if use_shell:
213 # try with os.system
214 os.system(cmd)
215 return
216 else:
217 # have to go via shell, sucks
218 p = Popen(cmd,shell = True)
219
220 jobentry = 'tasks/t' + str(p.pid)
146 221 ip.db[jobentry] = (p.pid,cmd,os.getcwd(),time.time())
147 p.communicate()
222 p.communicate()
223
148 224 finally:
149 del ip.db[jobentry]
225 if jobentry:
226 del ip.db[jobentry]
150 227
151 228
152 229 def install():
@@ -158,5 +235,6 b' def install():'
158 235 ip.set_hook('shell_hook', jobctrl_shellcmd)
159 236 ip.expose_magic('kill',magic_kill)
160 237 ip.expose_magic('tasks',magic_tasks)
161
238 ip.expose_magic('jobqueue',jobqueue_f)
239 ip.set_hook('pre_prompt_hook', jobq_output_hook)
162 240 install()
@@ -94,8 +94,16 b' def matchorfail(text, pos):'
94 94 match = tokenprog.match(text, pos)
95 95 if match is None:
96 96 raise ItplError(text, pos)
97
97 98 return match, match.end()
98 99
100 try:
101 itpl_encoding = sys.stdin.encoding or 'ascii'
102 except AttributeError:
103 itpl_encoding = 'ascii'
104
105
106
99 107 class Itpl:
100 108 """Class representing a string with interpolation abilities.
101 109
@@ -104,7 +112,7 b' class Itpl:'
104 112 evaluation and substitution happens in the namespace of the
105 113 caller when str(instance) is called."""
106 114
107 def __init__(self, format,codec=sys.stdin.encoding,encoding_errors='backslashreplace'):
115 def __init__(self, format,codec=itpl_encoding,encoding_errors='backslashreplace'):
108 116 """The single mandatory argument to this constructor is a format
109 117 string.
110 118
@@ -115,9 +115,9 b' class Magic:'
115 115
116 116 def profile_missing_notice(self, *args, **kwargs):
117 117 error("""\
118 The profile module could not be found. If you are a Debian user,
119 it has been removed from the standard Debian package because of its non-free
120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
118 The profile module could not be found. It has been removed from the standard
119 python packages because of its non-free license. To use profiling, install the
120 python-profiler package from non-free.""")
121 121
122 122 def default_option(self,fn,optstr):
123 123 """Make an entry in the options_table for fn, with value optstr"""
@@ -147,7 +147,7 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
147 147 filter(inst_magic,self.__dict__.keys()) + \
148 148 filter(inst_bound_magic,self.__class__.__dict__.keys())
149 149 out = []
150 for fn in magics:
150 for fn in Set(magics):
151 151 out.append(fn.replace('magic_','',1))
152 152 out.sort()
153 153 return out
@@ -386,7 +386,10 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
386 386 return None
387 387
388 388 def magic_magic(self, parameter_s = ''):
389 """Print information about the magic function system."""
389 """Print information about the magic function system.
390
391 Supported formats: -latex, -brief, -rest
392 """
390 393
391 394 mode = ''
392 395 try:
@@ -394,6 +397,9 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
394 397 mode = 'latex'
395 398 if parameter_s.split()[0] == '-brief':
396 399 mode = 'brief'
400 if parameter_s.split()[0] == '-rest':
401 mode = 'rest'
402 rest_docs = []
397 403 except:
398 404 pass
399 405
@@ -409,14 +415,26 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
409 415 break
410 416 if mode == 'brief':
411 417 # only first line
412 fndoc = fn.__doc__.split('\n',1)[0]
418 if fn.__doc__:
419 fndoc = fn.__doc__.split('\n',1)[0]
420 else:
421 fndoc = 'No documentation'
422 else:
423 fndoc = fn.__doc__.rstrip()
424
425 if mode == 'rest':
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
427 fname,fndoc))
428
413 429 else:
414 fndoc = fn.__doc__
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
431 fname,fndoc))
415 432
416 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
417 fname,fndoc))
418 433 magic_docs = ''.join(magic_docs)
419 434
435 if mode == 'rest':
436 return "".join(rest_docs)
437
420 438 if mode == 'latex':
421 439 print self.format_latex(magic_docs)
422 440 return
@@ -2612,7 +2630,7 b' Defaulting color scheme to \'NoColor\'"""'
2612 2630 os.chdir(pdir)
2613 2631 for ff in os.listdir(pdir):
2614 2632 base, ext = os.path.splitext(ff)
2615 if isexec(ff) and base not in self.shell.no_alias:
2633 if isexec(ff) and base.lower() not in self.shell.no_alias:
2616 2634 if ext.lower() == '.exe':
2617 2635 ff = base
2618 2636 alias_table[base.lower()] = (0,ff)
@@ -2667,6 +2685,7 b' Defaulting color scheme to \'NoColor\'"""'
2667 2685 parameter_s = parameter_s.strip()
2668 2686 #bkms = self.shell.persist.get("bookmarks",{})
2669 2687
2688 oldcwd = os.getcwd()
2670 2689 numcd = re.match(r'(-)(\d+)$',parameter_s)
2671 2690 # jump in directory history by number
2672 2691 if numcd:
@@ -2705,7 +2724,7 b' Defaulting color scheme to \'NoColor\'"""'
2705 2724
2706 2725 # at this point ps should point to the target dir
2707 2726 if ps:
2708 try:
2727 try:
2709 2728 os.chdir(os.path.expanduser(ps))
2710 2729 if self.shell.rc.term_title:
2711 2730 #print 'set term title:',self.shell.rc.term_title # dbg
@@ -2716,8 +2735,9 b' Defaulting color scheme to \'NoColor\'"""'
2716 2735 else:
2717 2736 cwd = os.getcwd()
2718 2737 dhist = self.shell.user_ns['_dh']
2719 dhist.append(cwd)
2720 self.db['dhist'] = compress_dhist(dhist)[-100:]
2738 if oldcwd != cwd:
2739 dhist.append(cwd)
2740 self.db['dhist'] = compress_dhist(dhist)[-100:]
2721 2741
2722 2742 else:
2723 2743 os.chdir(self.shell.home_dir)
@@ -2725,8 +2745,10 b' Defaulting color scheme to \'NoColor\'"""'
2725 2745 platutils.set_term_title("IPy ~")
2726 2746 cwd = os.getcwd()
2727 2747 dhist = self.shell.user_ns['_dh']
2728 dhist.append(cwd)
2729 self.db['dhist'] = compress_dhist(dhist)[-100:]
2748
2749 if oldcwd != cwd:
2750 dhist.append(cwd)
2751 self.db['dhist'] = compress_dhist(dhist)[-100:]
2730 2752 if not 'q' in opts and self.shell.user_ns['_dh']:
2731 2753 print self.shell.user_ns['_dh'][-1]
2732 2754
@@ -3118,7 +3140,7 b' Defaulting color scheme to \'NoColor\'"""'
3118 3140 screen_lines=self.shell.rc.screen_length)
3119 3141
3120 3142 def magic_cpaste(self, parameter_s=''):
3121 """Allows you to paste & execute a pre-formatted code block from clipboard
3143 """Allows you to paste & execute a pre-formatted code block from clipboard.
3122 3144
3123 3145 You must terminate the block with '--' (two minus-signs) alone on the
3124 3146 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
@@ -3126,13 +3148,14 b' Defaulting color scheme to \'NoColor\'"""'
3126 3148
3127 3149 The block is dedented prior to execution to enable execution of method
3128 3150 definitions. '>' and '+' characters at the beginning of a line are
3129 ignored, to allow pasting directly from e-mails or diff files. The
3151 ignored, to allow pasting directly from e-mails, diff files and
3152 doctests (the '...' continuation prompt is also stripped). The
3130 3153 executed block is also assigned to variable named 'pasted_block' for
3131 3154 later editing with '%edit pasted_block'.
3132 3155
3133 3156 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3134 3157 This assigns the pasted block to variable 'foo' as string, without
3135 dedenting or executing it.
3158 dedenting or executing it (preceding >>> and + is still stripped)
3136 3159
3137 3160 Do not be alarmed by garbled output on Windows (it's a readline bug).
3138 3161 Just press enter and type -- (and press enter again) and the block
@@ -3143,6 +3166,15 b' Defaulting color scheme to \'NoColor\'"""'
3143 3166 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3144 3167 par = args.strip()
3145 3168 sentinel = opts.get('s','--')
3169
3170 # Regular expressions that declare text we strip from the input:
3171 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3172 r'^\s*(\s?>)+', # Python input prompt
3173 r'^\s*\.{3,}', # Continuation prompts
3174 r'^\++',
3175 ]
3176
3177 strip_from_start = map(re.compile,strip_re)
3146 3178
3147 3179 from IPython import iplib
3148 3180 lines = []
@@ -3151,7 +3183,11 b' Defaulting color scheme to \'NoColor\'"""'
3151 3183 l = iplib.raw_input_original(':')
3152 3184 if l ==sentinel:
3153 3185 break
3154 lines.append(l.lstrip('>').lstrip('+'))
3186
3187 for pat in strip_from_start:
3188 l = pat.sub('',l)
3189 lines.append(l)
3190
3155 3191 block = "\n".join(lines) + '\n'
3156 3192 #print "block:\n",block
3157 3193 if not par:
@@ -404,7 +404,13 b' class Inspector:'
404 404 # Filename where object was defined
405 405 binary_file = False
406 406 try:
407 fname = inspect.getabsfile(obj)
407 try:
408 fname = inspect.getabsfile(obj)
409 except TypeError:
410 # For an instance, the file that matters is where its class was
411 # declared.
412 if hasattr(obj,'__class__'):
413 fname = inspect.getabsfile(obj.__class__)
408 414 if fname.endswith('<string>'):
409 415 fname = 'Dynamically generated function. No source code available.'
410 416 if (fname.endswith('.so') or fname.endswith('.dll')):
@@ -432,8 +438,13 b' class Inspector:'
432 438 linecache.checkcache()
433 439 source_success = False
434 440 try:
435 source = self.format(getsource(obj,binary_file))
436 if source:
441 try:
442 src = getsource(obj,binary_file)
443 except TypeError:
444 if hasattr(obj,'__class__'):
445 src = getsource(obj.__class__,binary_file)
446 if src is not None:
447 source = self.format(src)
437 448 out.write(header('Source:\n')+source.rstrip())
438 449 source_success = True
439 450 except Exception, msg:
@@ -22,9 +22,15 b" name = 'ipython'"
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25 revision = '3001'
25 revision = '128'
26 branch = 'ipython'
26 27
27 version = '0.8.3.svn.r' + revision.rstrip('M')
28 if branch == 'ipython':
29 version = '0.8.4.bzr.r' + revision
30 else:
31 version = '0.8.4.bzr.r%s.%s' % (revision,branch)
32
33 version = '0.8.4'
28 34
29 35 description = "An enhanced interactive Python shell."
30 36
@@ -46,6 +46,13 b' from IPython.ipmaker import make_IPython'
46 46 from IPython.Magic import Magic
47 47 from IPython.ipstruct import Struct
48 48
49 try: # Python 2.3 compatibility
50 set
51 except NameError:
52 import sets
53 set = sets.Set
54
55
49 56 # Globals
50 57 # global flag to pass around information about Ctrl-C without exceptions
51 58 KBINT = False
@@ -358,36 +365,37 b' class MTInteractiveShell(InteractiveShell):'
358 365 InteractiveShell.__init__(self,name,usage,rc,user_ns,
359 366 user_global_ns,banner2)
360 367
361 # Locking control variable.
362 self.thread_ready = threading.Condition(threading.RLock())
363 368
364 # A queue to hold the code to be executed. A scalar variable is NOT
365 # enough, because uses like macros cause reentrancy.
369 # A queue to hold the code to be executed.
366 370 self.code_queue = Queue.Queue()
367 371
368 372 # Stuff to do at closing time
369 self._kill = False
370 on_kill = kw.get('on_kill')
371 if on_kill is None:
372 on_kill = []
373 self._kill = None
374 on_kill = kw.get('on_kill', [])
373 375 # Check that all things to kill are callable:
374 376 for t in on_kill:
375 377 if not callable(t):
376 378 raise TypeError,'on_kill must be a list of callables'
377 379 self.on_kill = on_kill
378
380 # thread identity of the "worker thread" (that may execute code directly)
381 self.worker_ident = None
382
379 383 def runsource(self, source, filename="<input>", symbol="single"):
380 384 """Compile and run some source in the interpreter.
381 385
382 386 Modified version of code.py's runsource(), to handle threading issues.
383 387 See the original for full docstring details."""
384
388
385 389 global KBINT
386 390
387 391 # If Ctrl-C was typed, we reset the flag and return right away
388 392 if KBINT:
389 393 KBINT = False
390 394 return False
395
396 if self._kill:
397 # can't queue new code if we are being killed
398 return True
391 399
392 400 try:
393 401 code = self.compile(source, filename, symbol)
@@ -400,29 +408,40 b' class MTInteractiveShell(InteractiveShell):'
400 408 # Case 2
401 409 return True
402 410
411 # shortcut - if we are in worker thread, or the worker thread is not running,
412 # execute directly (to allow recursion and prevent deadlock if code is run early
413 # in IPython construction)
414
415 if (self.worker_ident is None or self.worker_ident == thread.get_ident()):
416 InteractiveShell.runcode(self,code)
417 return
418
403 419 # Case 3
404 420 # Store code in queue, so the execution thread can handle it.
405 421
406 # Note that with macros and other applications, we MAY re-enter this
407 # section, so we have to acquire the lock with non-blocking semantics,
408 # else we deadlock.
409 got_lock = self.thread_ready.acquire()
410 self.code_queue.put(code)
411 if got_lock:
412 self.thread_ready.wait() # Wait until processed in timeout interval
413 self.thread_ready.release()
414
422 completed_ev, received_ev = threading.Event(), threading.Event()
423
424 self.code_queue.put((code,completed_ev, received_ev))
425 # first make sure the message was received, with timeout
426 received_ev.wait(5)
427 if not received_ev.isSet():
428 # the mainloop is dead, start executing code directly
429 print "Warning: Timeout for mainloop thread exceeded"
430 print "switching to nonthreaded mode (until mainloop wakes up again)"
431 self.worker_ident = None
432 else:
433 completed_ev.wait()
415 434 return False
416 435
417 436 def runcode(self):
418 437 """Execute a code object.
419 438
420 439 Multithreaded wrapper around IPython's runcode()."""
421
440
422 441 global CODE_RUN
423
424 # lock thread-protected stuff
425 got_lock = self.thread_ready.acquire()
442
443 # we are in worker thread, stash out the id for runsource()
444 self.worker_ident = thread.get_ident()
426 445
427 446 if self._kill:
428 447 print >>Term.cout, 'Closing threads...',
@@ -430,6 +449,9 b' class MTInteractiveShell(InteractiveShell):'
430 449 for tokill in self.on_kill:
431 450 tokill()
432 451 print >>Term.cout, 'Done.'
452 # allow kill() to return
453 self._kill.set()
454 return True
433 455
434 456 # Install sigint handler. We do it every time to ensure that if user
435 457 # code modifies it, we restore our own handling.
@@ -445,10 +467,11 b' class MTInteractiveShell(InteractiveShell):'
445 467 code_to_run = None
446 468 while 1:
447 469 try:
448 code_to_run = self.code_queue.get_nowait()
470 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
449 471 except Queue.Empty:
450 472 break
451
473 received_ev.set()
474
452 475 # Exceptions need to be raised differently depending on which
453 476 # thread is active. This convoluted try/except is only there to
454 477 # protect against asynchronous exceptions, to ensure that a KBINT
@@ -462,28 +485,23 b' class MTInteractiveShell(InteractiveShell):'
462 485 except KeyboardInterrupt:
463 486 print "Keyboard interrupted in mainloop"
464 487 while not self.code_queue.empty():
465 self.code_queue.get_nowait()
488 code, ev1,ev2 = self.code_queue.get_nowait()
489 ev1.set()
490 ev2.set()
466 491 break
467 492 finally:
468 if got_lock:
469 CODE_RUN = False
470
471 # We're done with thread-protected variables
472 if code_to_run is not None:
473 self.thread_ready.notify()
474 self.thread_ready.release()
475
476 # We're done...
477 CODE_RUN = False
493 CODE_RUN = False
494 # allow runsource() return from wait
495 completed_ev.set()
496
497
478 498 # This MUST return true for gtk threading to work
479 499 return True
480 500
481 501 def kill(self):
482 502 """Kill the thread, returning when it has been shut down."""
483 got_lock = self.thread_ready.acquire(False)
484 self._kill = True
485 if got_lock:
486 self.thread_ready.release()
503 self._kill = threading.Event()
504 self._kill.wait()
487 505
488 506 class MatplotlibShellBase:
489 507 """Mixin class to provide the necessary modifications to regular IPython
@@ -1051,7 +1069,9 b' def _load_pylab(user_ns):'
1051 1069
1052 1070 ip = IPython.ipapi.get()
1053 1071 if ip.options.pylab_import_all:
1054 exec "from matplotlib.pylab import *" in user_ns
1072 ip.ex("from matplotlib.pylab import *")
1073 ip.IP.user_config_ns.update(ip.user_ns)
1074
1055 1075
1056 1076 class IPShellMatplotlib(IPShell):
1057 1077 """Subclass IPShell with MatplotlibShell as the internal shell.
@@ -1144,7 +1164,7 b' def _select_shell(argv):'
1144 1164 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1145 1165 'tkthread'])
1146 1166 user_opts = set([s.replace('-','') for s in argv[:3]])
1147 special_opts = user_opts & all_opts
1167 special_opts = user_opts & all_opts
1148 1168
1149 1169 if 'tk' in special_opts:
1150 1170 USE_TK = True
@@ -72,6 +72,27 b' def main():'
72 72 #o.autoexec.append('%colors NoColor')
73 73 #o.autoexec.append('%colors Linux')
74 74
75 # for sane integer division that converts to float (1/2 == 0.5)
76 #o.autoexec.append('from __future__ import division')
77
78 # For %tasks and %kill
79 #import jobctrl
80
81 # For autoreloading of modules (%autoreload, %aimport)
82 #import ipy_autoreload
83
84 # For winpdb support (%wdb)
85 #import ipy_winpdb
86
87 # For bzr completer, requires bzrlib (the python installation of bzr)
88 #ip.load('ipy_bzr')
89
90 # Tab completer that is not quite so picky (i.e.
91 # "foo".<TAB> and str(2).<TAB> will work). Complete
92 # at your own risk!
93 #import ipy_greedycompleter
94
95
75 96
76 97 # some config helper functions you can use
77 98 def import_all(modules):
@@ -321,7 +321,7 b' class IPCompleter(Completer):'
321 321 # don't want to treat as delimiters in filename matching
322 322 # when escaped with backslash
323 323
324 protectables = ' ()[]{}'
324 protectables = ' '
325 325
326 326 if text.startswith('!'):
327 327 text = text[1:]
@@ -32,7 +32,9 b' import imp'
32 32 import sys
33 33
34 34 # Replacement for __import__()
35 def deep_import_hook(name, globals=None, locals=None, fromlist=None):
35 def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
36 # For now level is ignored, it's just there to prevent crash
37 # with from __future__ import absolute_import
36 38 parent = determine_parent(globals)
37 39 q, tail = find_head_package(parent, name)
38 40 m = load_tail(q, tail)
@@ -34,35 +34,35 b' License: MIT Open Source license'
34 34 #Assigned in variable for "usage" printing convenience"
35 35
36 36 globsyntax = """\
37 This program allows specifying filenames with "mglob" mechanism.
38 Supported syntax in globs (wilcard matching patterns)::
39
40 *.cpp ?ellowo*
41 - obvious. Differs from normal glob in that dirs are not included.
42 Unix users might want to write this as: "*.cpp" "?ellowo*"
43 rec:/usr/share=*.txt,*.doc
44 - get all *.txt and *.doc under /usr/share,
45 recursively
46 rec:/usr/share
47 - All files under /usr/share, recursively
48 rec:*.py
49 - All .py files under current working dir, recursively
50 foo
51 - File or dir foo
52 !*.bak readme*
53 - readme*, exclude files ending with .bak
54 !.svn/ !.hg/ !*_Data/ rec:.
55 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
56 Trailing / is the key, \ does not work!
57 dir:foo
58 - the directory foo if it exists (not files in foo)
59 dir:*
60 - all directories in current folder
61 foo.py bar.* !h* rec:*.py
62 - Obvious. !h* exclusion only applies for rec:*.py.
63 foo.py is *not* included twice.
64 @filelist.txt
65 - All files listed in 'filelist.txt' file, on separate lines.
37 This program allows specifying filenames with "mglob" mechanism.
38 Supported syntax in globs (wilcard matching patterns)::
39
40 *.cpp ?ellowo*
41 - obvious. Differs from normal glob in that dirs are not included.
42 Unix users might want to write this as: "*.cpp" "?ellowo*"
43 rec:/usr/share=*.txt,*.doc
44 - get all *.txt and *.doc under /usr/share,
45 recursively
46 rec:/usr/share
47 - All files under /usr/share, recursively
48 rec:*.py
49 - All .py files under current working dir, recursively
50 foo
51 - File or dir foo
52 !*.bak readme*
53 - readme*, exclude files ending with .bak
54 !.svn/ !.hg/ !*_Data/ rec:.
55 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
56 Trailing / is the key, \ does not work!
57 dir:foo
58 - the directory foo if it exists (not files in foo)
59 dir:*
60 - all directories in current folder
61 foo.py bar.* !h* rec:*.py
62 - Obvious. !h* exclusion only applies for rec:*.py.
63 foo.py is *not* included twice.
64 @filelist.txt
65 - All files listed in 'filelist.txt' file, on separate lines.
66 66 """
67 67
68 68
@@ -29,7 +29,10 b' Date: 9 Mar 2007'
29 29
30 30 from __future__ import generators
31 31
32 import sys, warnings, os, fnmatch, glob, shutil, codecs, md5
32 import sys, warnings, os, fnmatch, glob, shutil, codecs
33 # deprecated in python 2.6
34 warnings.filterwarnings('ignore', r'.*md5.*')
35 import md5
33 36
34 37 __version__ = '2.2'
35 38 __all__ = ['path']
@@ -22,7 +22,10 b' __license__ = Release.license'
22 22 # required modules from the Python standard library
23 23 import __main__
24 24 import commands
25 import doctest
25 try:
26 import doctest
27 except ImportError:
28 pass
26 29 import os
27 30 import re
28 31 import shlex
@@ -33,6 +36,18 b' import time'
33 36 import types
34 37 import warnings
35 38
39 # Curses and termios are Unix-only modules
40 try:
41 import curses
42 # We need termios as well, so if its import happens to raise, we bail on
43 # using curses altogether.
44 import termios
45 except ImportError:
46 USE_CURSES = False
47 else:
48 # Curses on Solaris may not be complete, so we can't use it there
49 USE_CURSES = hasattr(curses,'initscr')
50
36 51 # Other IPython utilities
37 52 import IPython
38 53 from IPython.Itpl import Itpl,itpl,printpl
@@ -1052,25 +1067,40 b' class SList(list):'
1052 1067
1053 1068 p = paths = property(get_paths)
1054 1069
1055 def grep(self, pattern, prune = False):
1070 def grep(self, pattern, prune = False, field = None):
1056 1071 """ Return all strings matching 'pattern' (a regex or callable)
1057 1072
1058 1073 This is case-insensitive. If prune is true, return all items
1059 1074 NOT matching the pattern.
1060 1075
1076 If field is specified, the match must occur in the specified
1077 whitespace-separated field.
1078
1061 1079 Examples::
1062 1080
1063 1081 a.grep( lambda x: x.startswith('C') )
1064 1082 a.grep('Cha.*log', prune=1)
1083 a.grep('chm', field=-1)
1065 1084 """
1085
1086 def match_target(s):
1087 if field is None:
1088 return s
1089 parts = s.split()
1090 try:
1091 tgt = parts[field]
1092 return tgt
1093 except IndexError:
1094 return ""
1095
1066 1096 if isinstance(pattern, basestring):
1067 1097 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1068 1098 else:
1069 1099 pred = pattern
1070 1100 if not prune:
1071 return SList([el for el in self if pred(el)])
1101 return SList([el for el in self if pred(match_target(el))])
1072 1102 else:
1073 return SList([el for el in self if not pred(el)])
1103 return SList([el for el in self if not pred(match_target(el))])
1074 1104 def fields(self, *fields):
1075 1105 """ Collect whitespace-separated fields from string list
1076 1106
@@ -1083,6 +1113,7 b' class SList(list):'
1083 1113 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
1084 1114 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
1085 1115 (note the joining by space).
1116 a.fields(-1) is ['ChangeLog', 'IPython']
1086 1117
1087 1118 IndexErrors are ignored.
1088 1119
@@ -1532,26 +1563,30 b' def page(strng,start=0,screen_lines=0,pager_cmd = None):'
1532 1563 # auto-determine screen size
1533 1564 if screen_lines <= 0:
1534 1565 if TERM=='xterm':
1535 try:
1536 import curses
1537 if hasattr(curses,'initscr'):
1538 use_curses = 1
1539 else:
1540 use_curses = 0
1541 except ImportError:
1542 use_curses = 0
1566 use_curses = USE_CURSES
1543 1567 else:
1544 1568 # curses causes problems on many terminals other than xterm.
1545 use_curses = 0
1569 use_curses = False
1546 1570 if use_curses:
1547 scr = curses.initscr()
1548 screen_lines_real,screen_cols = scr.getmaxyx()
1549 curses.endwin()
1550 screen_lines += screen_lines_real
1551 #print '***Screen size:',screen_lines_real,'lines x',\
1552 #screen_cols,'columns.' # dbg
1571 # There is a bug in curses, where *sometimes* it fails to properly
1572 # initialize, and then after the endwin() call is made, the
1573 # terminal is left in an unusable state. Rather than trying to
1574 # check everytime for this (by requesting and comparing termios
1575 # flags each time), we just save the initial terminal state and
1576 # unconditionally reset it every time. It's cheaper than making
1577 # the checks.
1578 term_flags = termios.tcgetattr(sys.stdout)
1579 scr = curses.initscr()
1580 screen_lines_real,screen_cols = scr.getmaxyx()
1581 curses.endwin()
1582 # Restore terminal state in case endwin() didn't.
1583 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1584 # Now we have what we needed: the screen size in rows/columns
1585 screen_lines += screen_lines_real
1586 #print '***Screen size:',screen_lines_real,'lines x',\
1587 #screen_cols,'columns.' # dbg
1553 1588 else:
1554 screen_lines += screen_lines_def
1589 screen_lines += screen_lines_def
1555 1590
1556 1591 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1557 1592 if numlines <= screen_lines :
@@ -28,10 +28,30 b' class IPythonHistoryPanel(wx.Panel):'
28 28 self.filter_cmd = wx.CheckBox(self, -1, "!: Sys commands")
29 29 self.filter_magic = wx.CheckBox(self, -1, "%: Magic keys")
30 30
31 self.filter_empty.SetValue(flt_empty)
32 self.filter_doc.SetValue(flt_doc)
33 self.filter_cmd.SetValue(flt_cmd)
34 self.filter_magic.SetValue(flt_magic)
31 self.options={'filter_empty':{'value':'True',
32 'checkbox':self.filter_empty,'True':True,'False':False,
33 'setfunc':lambda x:None},
34 'filter_doc':{'value':'True',
35 'checkbox':self.filter_doc,'True':True,'False':False,
36 'setfunc':lambda x:None},
37 'filter_cmd':{'value':'True',
38 'checkbox':self.filter_cmd,'True':True,'False':False,
39 'setfunc':lambda x:None},
40 'filter_magic':{'value':'True',
41 'checkbox':self.filter_magic,'True':True,'False':False,
42 'setfunc':lambda x:None},
43 }
44 self.reloadOptions(self.options)
45
46 self.filter_empty.Bind(wx.EVT_CHECKBOX, self.evtCheckEmptyFilter)
47 self.filter_doc.Bind(wx.EVT_CHECKBOX, self.evtCheckDocFilter)
48 self.filter_cmd.Bind(wx.EVT_CHECKBOX, self.evtCheckCmdFilter)
49 self.filter_magic.Bind(wx.EVT_CHECKBOX, self.evtCheckMagicFilter)
50
51 #self.filter_empty.SetValue(flt_empty)
52 #self.filter_doc.SetValue(flt_doc)
53 #self.filter_cmd.SetValue(flt_cmd)
54 #self.filter_magic.SetValue(flt_magic)
35 55
36 56 sizer = wx.BoxSizer(wx.VERTICAL)
37 57
@@ -70,10 +90,54 b' class IPythonHistoryPanel(wx.Panel):'
70 90 add = False
71 91 if self.filter_magic.GetValue() == True and history_line[0] == '%':
72 92 add = False
73 if add:
74 self.text_ctrl.AppendText(history_line+'\n')
93 if add:
94 self.text_ctrl.AppendText(history_line+'\n')
95
96 #------------------------ Option Section -----------------------------------
97 def processOptionCheckedEvt(self, event, name):
98 if event.IsChecked():
99 self.options[name]['value']='True'
100 else:
101 self.options[name]['value']='False'
102 self.updateOptionTracker(name,
103 self.options[name]['value'])
104
105 def evtCheckEmptyFilter(self, event):
106 self.processOptionCheckedEvt(event, 'filter_empty')
107
108 def evtCheckDocFilter(self, event):
109 self.processOptionCheckedEvt(event, 'filter_doc')
75 110
111 def evtCheckCmdFilter(self, event):
112 self.processOptionCheckedEvt(event, 'filter_cmd')
76 113
114 def evtCheckMagicFilter(self, event):
115 self.processOptionCheckedEvt(event, 'filter_magic')
116
117 def getOptions(self):
118 return self.options
119
120 def reloadOptions(self,options):
121 self.options = options
122 for key in self.options.keys():
123 value = self.options[key]['value']
124 self.options[key]['checkbox'].SetValue(self.options[key][value])
125 self.options[key]['setfunc'](value)
126
127 #------------------------ Hook Section -----------------------------------
128 def updateOptionTracker(self,name,value):
129 '''
130 Default history tracker (does nothing)
131 '''
132 pass
133
134 def setOptionTrackerHook(self,func):
135 '''
136 Define a new history tracker
137 '''
138 self.updateOptionTracker = func
139
140
77 141 #----------------------------------------------------------------------
78 142 # Font definition for Styled Text Control
79 143
This diff has been collapsed as it changes many lines, (1147 lines changed) Show them Hide them
@@ -1,7 +1,7 b''
1 1 #!/usr/bin/python
2 2 # -*- coding: iso-8859-15 -*-
3 3 '''
4 Provides IPython WX console widget.
4 Provides IPython WX console widgets.
5 5
6 6 @author: Laurent Dufrechou
7 7 laurent.dufrechou _at_ gmail.com
@@ -26,433 +26,88 b' __license__ = "BSD"'
26 26
27 27 import wx
28 28 import wx.stc as stc
29 import wx.lib.newevent
30 29
31 30 import re
32 31 import sys
33 import os
34 32 import locale
35 import time
36 from ThreadEx import Thread
37 33 from StringIO import StringIO
38
39 34 try:
40 35 import IPython
41 36 except Exception,e:
42 37 raise "Error importing IPython (%s)" % str(e)
43 38
44 class IterableIPShell(Thread):
39 from ipshell_nonblocking import NonBlockingIPShell
40
41 class WxNonBlockingIPShell(NonBlockingIPShell):
45 42 '''
46 Create an IPython instance inside a dedicated thread.
47 Does not start a blocking event loop, instead allow single iterations.
48 This allows embedding in any GUI without blockage.
49 The thread is a slave one, in that it doesn't interact directly with the GUI.
50 Note Thread class comes from ThreadEx that supports asynchroneous function call
51 via raise_exc()
43 An NonBlockingIPShell Thread that is WX dependent.
52 44 '''
53
54 def __init__(self,argv=[],user_ns=None,user_global_ns=None,
45 def __init__(self, parent,
46 argv=[],user_ns={},user_global_ns=None,
55 47 cin=None, cout=None, cerr=None,
56 exit_handler=None,time_loop = 0.1):
57 '''
58 @param argv: Command line options for IPython
59 @type argv: list
60 @param user_ns: User namespace.
61 @type user_ns: dictionary
62 @param user_global_ns: User global namespace.
63 @type user_global_ns: dictionary.
64 @param cin: Console standard input.
65 @type cin: IO stream
66 @param cout: Console standard output.
67 @type cout: IO stream
68 @param cerr: Console standard error.
69 @type cerr: IO stream
70 @param exit_handler: Replacement for builtin exit() function
71 @type exit_handler: function
72 @param time_loop: Define the sleep time between two thread's loop
73 @type int
74 '''
75 Thread.__init__(self)
76
77 #first we redefine in/out/error functions of IPython
78 if cin:
79 IPython.Shell.Term.cin = cin
80 if cout:
81 IPython.Shell.Term.cout = cout
82 if cerr:
83 IPython.Shell.Term.cerr = cerr
84
85 # This is to get rid of the blockage that accurs during
86 # IPython.Shell.InteractiveShell.user_setup()
87 IPython.iplib.raw_input = lambda x: None
88
89 self._term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr)
90
91 excepthook = sys.excepthook
92 self._IP = IPython.Shell.make_IPython(
93 argv,user_ns=user_ns,
94 user_global_ns=user_global_ns,
95 embedded=True,
96 shell_class=IPython.Shell.InteractiveShell)
97
98 #we replace IPython default encoding by wx locale encoding
99 loc = locale.getpreferredencoding()
100 if loc:
101 self._IP.stdin_encoding = loc
102 #we replace the ipython default pager by our pager
103 self._IP.set_hook('show_in_pager',self._pager)
104
105 #we replace the ipython default shell command caller by our shell handler
106 self._IP.set_hook('shell_hook',self._shell)
107
108 #we replace the ipython default input command caller by our method
109 IPython.iplib.raw_input_original = self._raw_input
110 #we replace the ipython default exit command by our method
111 self._IP.exit = self._setAskExit
112
113 sys.excepthook = excepthook
114
115 self._iter_more = 0
116 self._history_level = 0
117 self._complete_sep = re.compile('[\s\{\}\[\]\(\)]')
118 self._prompt = str(self._IP.outputcache.prompt1).strip()
119
120 #thread working vars
121 self._terminate = False
122 self._time_loop = time_loop
123 self._has_doc = False
124 self._do_execute = False
125 self._line_to_execute = ''
126 self._doc_text = None
127 self._ask_exit = False
128
129 #----------------------- Thread management section ----------------------
130 def run (self):
131 """
132 Thread main loop
133 The thread will run until self._terminate will be set to True via shutdown() function
134 Command processing can be interrupted with Instance.raise_exc(KeyboardInterrupt) call in the
135 GUI thread.
136 """
137 while(not self._terminate):
138 try:
139 if self._do_execute:
140 self._doc_text = None
141 self._execute()
142 self._do_execute = False
143
144 except KeyboardInterrupt:
145 pass
146
147 time.sleep(self._time_loop)
148
149 def shutdown(self):
150 """
151 Shutdown the tread
152 """
153 self._terminate = True
154
155 def doExecute(self,line):
156 """
157 Tell the thread to process the 'line' command
158 """
159 self._do_execute = True
160 self._line_to_execute = line
161
162 def isExecuteDone(self):
163 """
164 Returns the processing state
165 """
166 return not self._do_execute
167
168 #----------------------- IPython management section ----------------------
169 def getAskExit(self):
170 '''
171 returns the _ask_exit variable that can be checked by GUI to see if
172 IPython request an exit handling
173 '''
174 return self._ask_exit
175
176 def clearAskExit(self):
177 '''
178 clear the _ask_exit var when GUI as handled the request.
179 '''
180 self._ask_exit = False
181
182 def getDocText(self):
183 """
184 Returns the output of the processing that need to be paged (if any)
185
186 @return: The std output string.
187 @rtype: string
188 """
189 return self._doc_text
190
191 def getBanner(self):
192 """
193 Returns the IPython banner for useful info on IPython instance
194
195 @return: The banner string.
196 @rtype: string
197 """
198 return self._IP.BANNER
199
200 def getPromptCount(self):
201 """
202 Returns the prompt number.
203 Each time a user execute a line in the IPython shell the prompt count is increased
204
205 @return: The prompt number
206 @rtype: int
207 """
208 return self._IP.outputcache.prompt_count
209
210 def getPrompt(self):
211 """
212 Returns current prompt inside IPython instance
213 (Can be In [...]: ot ...:)
214
215 @return: The current prompt.
216 @rtype: string
217 """
218 return self._prompt
219
220 def getIndentation(self):
221 """
222 Returns the current indentation level
223 Usefull to put the caret at the good start position if we want to do autoindentation.
224
225 @return: The indentation level.
226 @rtype: int
227 """
228 return self._IP.indent_current_nsp
48 ask_exit_handler=None):
229 49
230 def updateNamespace(self, ns_dict):
231 '''
232 Add the current dictionary to the shell namespace.
50 NonBlockingIPShell.__init__(self,argv,user_ns,user_global_ns,
51 cin, cout, cerr,
52 ask_exit_handler)
233 53
234 @param ns_dict: A dictionary of symbol-values.
235 @type ns_dict: dictionary
236 '''
237 self._IP.user_ns.update(ns_dict)
54 self.parent = parent
238 55
239 def complete(self, line):
240 '''
241 Returns an auto completed line and/or posibilities for completion.
56 self.ask_exit_callback = ask_exit_handler
57 self._IP.exit = self._askExit
242 58
243 @param line: Given line so far.
244 @type line: string
59 def addGUIShortcut(self,text,func):
60 wx.CallAfter(self.parent.add_button_handler,
61 button_info={ 'text':text,
62 'func':self.parent.doExecuteLine(func)})
245 63
246 @return: Line completed as for as possible,
247 and possible further completions.
248 @rtype: tuple
249 '''
250 split_line = self._complete_sep.split(line)
251 possibilities = self._IP.complete(split_line[-1])
252 if possibilities:
253
254 def _commonPrefix(str1, str2):
255 '''
256 Reduction function. returns common prefix of two given strings.
257
258 @param str1: First string.
259 @type str1: string
260 @param str2: Second string
261 @type str2: string
262
263 @return: Common prefix to both strings.
264 @rtype: string
265 '''
266 for i in range(len(str1)):
267 if not str2.startswith(str1[:i+1]):
268 return str1[:i]
269 return str1
270 common_prefix = reduce(_commonPrefix, possibilities)
271 completed = line[:-len(split_line[-1])]+common_prefix
272 else:
273 completed = line
274 return completed, possibilities
64 def _askExit(self):
65 wx.CallAfter(self.ask_exit_callback, ())
275 66
276 def historyBack(self):
277 '''
278 Provides one history command back.
67 def _afterExecute(self):
68 wx.CallAfter(self.parent.evtStateExecuteDone, ())
279 69
280 @return: The command string.
281 @rtype: string
282 '''
283 history = ''
284 #the below while loop is used to suppress empty history lines
285 while((history == '' or history == '\n') and self._history_level >0):
286 if self._history_level>=1:
287 self._history_level -= 1
288 history = self._getHistory()
289 return history
290
291 def historyForward(self):
292 '''
293 Provides one history command forward.
294
295 @return: The command string.
296 @rtype: string
297 '''
298 history = ''
299 #the below while loop is used to suppress empty history lines
300 while((history == '' or history == '\n') and self._history_level <= self._getHistoryMaxIndex()):
301 if self._history_level < self._getHistoryMaxIndex():
302 self._history_level += 1
303 history = self._getHistory()
304 else:
305 if self._history_level == self._getHistoryMaxIndex():
306 history = self._getHistory()
307 self._history_level += 1
308 else:
309 history = ''
310 return history
311
312 def initHistoryIndex(self):
313 '''
314 set history to last command entered
315 '''
316 self._history_level = self._getHistoryMaxIndex()+1
317
318 #----------------------- IPython PRIVATE management section ----------------------
319 def _setAskExit(self):
320 '''
321 set the _ask_exit variable that can be cjhecked by GUI to see if
322 IPython request an exit handling
323 '''
324 self._ask_exit = True
325
326 def _getHistoryMaxIndex(self):
327 '''
328 returns the max length of the history buffer
329
330 @return: history length
331 @rtype: int
332 '''
333 return len(self._IP.input_hist_raw)-1
334
335 def _getHistory(self):
336 '''
337 Get's the command string of the current history level.
338
339 @return: Historic command string.
340 @rtype: string
341 '''
342 rv = self._IP.input_hist_raw[self._history_level].strip('\n')
343 return rv
344
345 def _pager(self,IP,text):
346 '''
347 This function is used as a callback replacment to IPython pager function
348
349 It puts the 'text' value inside the self._doc_text string that can be retrived via getDocText
350 function.
351 '''
352 self._doc_text = text
353
354 def _raw_input(self, prompt=''):
355 '''
356 Custom raw_input() replacement. Get's current line from console buffer.
357
358 @param prompt: Prompt to print. Here for compatability as replacement.
359 @type prompt: string
360
361 @return: The current command line text.
362 @rtype: string
363 '''
364 return self._line_to_execute
365
366 def _execute(self):
367 '''
368 Executes the current line provided by the shell object.
369 '''
370 orig_stdout = sys.stdout
371 sys.stdout = IPython.Shell.Term.cout
372 70
373 try:
374 line = self._IP.raw_input(None, self._iter_more)
375 if self._IP.autoindent:
376 self._IP.readline_startup_hook(None)
377
378 except KeyboardInterrupt:
379 self._IP.write('\nKeyboardInterrupt\n')
380 self._IP.resetbuffer()
381 # keep cache in sync with the prompt counter:
382 self._IP.outputcache.prompt_count -= 1
383
384 if self._IP.autoindent:
385 self._IP.indent_current_nsp = 0
386 self._iter_more = 0
387 except:
388 self._IP.showtraceback()
389 else:
390 self._iter_more = self._IP.push(line)
391 if (self._IP.SyntaxTB.last_syntax_error and
392 self._IP.rc.autoedit_syntax):
393 self._IP.edit_syntax_error()
394 if self._iter_more:
395 self._prompt = str(self._IP.outputcache.prompt2).strip()
396 if self._IP.autoindent:
397 self._IP.readline_startup_hook(self._IP.pre_readline)
398 else:
399 self._prompt = str(self._IP.outputcache.prompt1).strip()
400 self._IP.indent_current_nsp = 0 #we set indentation to 0
401 sys.stdout = orig_stdout
402
403 def _shell(self, ip, cmd):
404 '''
405 Replacement method to allow shell commands without them blocking.
406
407 @param ip: Ipython instance, same as self._IP
408 @type cmd: Ipython instance
409 @param cmd: Shell command to execute.
410 @type cmd: string
411 '''
412 stdin, stdout = os.popen4(cmd)
413 result = stdout.read().decode('cp437').encode(locale.getpreferredencoding())
414 #we use print command because the shell command is called inside IPython instance and thus is
415 #redirected to thread cout
416 #"\x01\x1b[1;36m\x02" <-- add colour to the text...
417 print "\x01\x1b[1;36m\x02"+result
418 stdout.close()
419 stdin.close()
420
421 71 class WxConsoleView(stc.StyledTextCtrl):
422 72 '''
423 73 Specialized styled text control view for console-like workflow.
424 We use here a scintilla frontend thus it can be reused in any GUI taht supports
425 scintilla with less work.
74 We use here a scintilla frontend thus it can be reused in any GUI that
75 supports scintilla with less work.
426 76
427 @cvar ANSI_COLORS_BLACK: Mapping of terminal colors to X11 names.(with Black background)
77 @cvar ANSI_COLORS_BLACK: Mapping of terminal colors to X11 names.
78 (with Black background)
428 79 @type ANSI_COLORS_BLACK: dictionary
429 80
430 @cvar ANSI_COLORS_WHITE: Mapping of terminal colors to X11 names.(with White background)
81 @cvar ANSI_COLORS_WHITE: Mapping of terminal colors to X11 names.
82 (with White background)
431 83 @type ANSI_COLORS_WHITE: dictionary
432 84
433 85 @ivar color_pat: Regex of terminal color pattern
434 86 @type color_pat: _sre.SRE_Pattern
435 87 '''
436 ANSI_STYLES_BLACK ={'0;30': [0,'WHITE'], '0;31': [1,'RED'],
437 '0;32': [2,'GREEN'], '0;33': [3,'BROWN'],
438 '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'],
439 '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'],
440 '1;30': [8,'DARK GREY'], '1;31': [9,'RED'],
441 '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'],
442 '1;34': [12,'LIGHT BLUE'], '1;35': [13,'MEDIUM VIOLET RED'],
443 '1;36': [14,'LIGHT STEEL BLUE'], '1;37': [15,'YELLOW']}
444
445 ANSI_STYLES_WHITE ={'0;30': [0,'BLACK'], '0;31': [1,'RED'],
446 '0;32': [2,'GREEN'], '0;33': [3,'BROWN'],
447 '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'],
448 '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'],
449 '1;30': [8,'DARK GREY'], '1;31': [9,'RED'],
450 '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'],
451 '1;34': [12,'LIGHT BLUE'], '1;35': [13,'MEDIUM VIOLET RED'],
452 '1;36': [14,'LIGHT STEEL BLUE'], '1;37': [15,'YELLOW']}
453
454 def __init__(self,parent,prompt,intro="",background_color="BLACK",pos=wx.DefaultPosition, ID = -1, size=wx.DefaultSize,
455 style=0):
88 ANSI_STYLES_BLACK={'0;30': [0,'WHITE'], '0;31': [1,'RED'],
89 '0;32': [2,'GREEN'], '0;33': [3,'BROWN'],
90 '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'],
91 '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'],
92 '1;30': [8,'DARK GREY'], '1;31': [9,'RED'],
93 '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'],
94 '1;34': [12,'LIGHT BLUE'], '1;35':
95 [13,'MEDIUM VIOLET RED'],
96 '1;36': [14,'LIGHT STEEL BLUE'],'1;37': [15,'YELLOW']}
97
98 ANSI_STYLES_WHITE={'0;30': [0,'BLACK'], '0;31': [1,'RED'],
99 '0;32': [2,'GREEN'], '0;33': [3,'BROWN'],
100 '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'],
101 '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'],
102 '1;30': [8,'DARK GREY'], '1;31': [9,'RED'],
103 '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'],
104 '1;34': [12,'LIGHT BLUE'], '1;35':
105 [13,'MEDIUM VIOLET RED'],
106 '1;36': [14,'LIGHT STEEL BLUE'],'1;37': [15,'YELLOW']}
107
108 def __init__(self,parent,prompt,intro="",background_color="BLACK",
109 pos=wx.DefaultPosition, ID = -1, size=wx.DefaultSize,
110 style=0, autocomplete_mode = 'IPYTHON'):
456 111 '''
457 112 Initialize console view.
458 113
@@ -464,15 +119,61 b' class WxConsoleView(stc.StyledTextCtrl):'
464 119 @param background_color: Can be BLACK or WHITE
465 120 @type background_color: string
466 121 @param other: init param of styledTextControl (can be used as-is)
122 @param autocomplete_mode: Can be 'IPYTHON' or 'STC'
123 'IPYTHON' show autocompletion the ipython way
124 'STC" show it scintilla text control way
467 125 '''
468 126 stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)
469 127
470 ####### Scintilla configuration ##################################################
128 ####### Scintilla configuration ###################################
471 129
472 # Ctrl + B or Ctrl + N can be used to zoomin/zoomout the text inside the widget
130 # Ctrl + B or Ctrl + N can be used to zoomin/zoomout the text inside
131 # the widget
473 132 self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
474 133 self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
475 134
135 #We draw a line at position 80
136 self.SetEdgeMode(stc.STC_EDGE_LINE)
137 self.SetEdgeColumn(80)
138 self.SetEdgeColour(wx.LIGHT_GREY)
139
140 #self.SetViewWhiteSpace(True)
141 #self.SetViewEOL(True)
142 self.SetEOLMode(stc.STC_EOL_CRLF)
143 #self.SetWrapMode(stc.STC_WRAP_CHAR)
144 #self.SetWrapMode(stc.STC_WRAP_WORD)
145 self.SetBufferedDraw(True)
146 #self.SetUseAntiAliasing(True)
147 self.SetLayoutCache(stc.STC_CACHE_PAGE)
148 self.SetUndoCollection(False)
149 self.SetUseTabs(True)
150 self.SetIndent(4)
151 self.SetTabWidth(4)
152
153 self.EnsureCaretVisible()
154
155 self.SetMargins(3,3) #text is moved away from border with 3px
156 # Suppressing Scintilla margins
157 self.SetMarginWidth(0,0)
158 self.SetMarginWidth(1,0)
159 self.SetMarginWidth(2,0)
160
161 self.background_color = background_color
162 self.buildStyles()
163
164 self.indent = 0
165 self.prompt_count = 0
166 self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?')
167
168 self.write(intro)
169 self.setPrompt(prompt)
170 self.showPrompt()
171
172 self.autocomplete_mode = autocomplete_mode
173
174 self.Bind(wx.EVT_KEY_DOWN, self._onKeypress)
175
176 def buildStyles(self):
476 177 #we define platform specific fonts
477 178 if wx.Platform == '__WXMSW__':
478 179 faces = { 'times': 'Times New Roman',
@@ -499,61 +200,64 b' class WxConsoleView(stc.StyledTextCtrl):'
499 200 'size2': 8,
500 201 }
501 202
502 #We draw a line at position 80
503 self.SetEdgeMode(stc.STC_EDGE_LINE)
504 self.SetEdgeColumn(80)
505 self.SetEdgeColour(wx.LIGHT_GREY)
506
507 #self.SetViewWhiteSpace(True)
508 #self.SetViewEOL(True)
509 self.SetEOLMode(stc.STC_EOL_CRLF)
510 #self.SetWrapMode(stc.STC_WRAP_CHAR)
511 #self.SetWrapMode(stc.STC_WRAP_WORD)
512 self.SetBufferedDraw(True)
513 #self.SetUseAntiAliasing(True)
514 self.SetLayoutCache(stc.STC_CACHE_PAGE)
515
516 self.EnsureCaretVisible()
517
518 self.SetMargins(3,3) #text is moved away from border with 3px
519 # Suppressing Scintilla margins
520 self.SetMarginWidth(0,0)
521 self.SetMarginWidth(1,0)
522 self.SetMarginWidth(2,0)
523
524 203 # make some styles
525 if background_color != "BLACK":
204 if self.background_color != "BLACK":
526 205 self.background_color = "WHITE"
527 206 self.SetCaretForeground("BLACK")
528 207 self.ANSI_STYLES = self.ANSI_STYLES_WHITE
529 208 else:
530 self.background_color = background_color
531 209 self.SetCaretForeground("WHITE")
532 210 self.ANSI_STYLES = self.ANSI_STYLES_BLACK
533 211
534 self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "fore:%s,back:%s,size:%d,face:%s" % (self.ANSI_STYLES['0;30'][1],
535 self.background_color,
536 faces['size'], faces['mono']))
212 self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
213 "fore:%s,back:%s,size:%d,face:%s"
214 % (self.ANSI_STYLES['0;30'][1],
215 self.background_color,
216 faces['size'], faces['mono']))
537 217 self.StyleClearAll()
538 self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FF0000,back:#0000FF,bold")
539 self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
540
218 self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT,
219 "fore:#FF0000,back:#0000FF,bold")
220 self.StyleSetSpec(stc.STC_STYLE_BRACEBAD,
221 "fore:#000000,back:#FF0000,bold")
222
541 223 for style in self.ANSI_STYLES.values():
542 224 self.StyleSetSpec(style[0], "bold,fore:%s" % style[1])
543 225
544 226 #######################################################################
545 227
546 self.indent = 0
547 self.prompt_count = 0
548 self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?')
228 def setBackgroundColor(self,color):
229 self.background_color = color
230 self.buildStyles()
231
232 def getBackgroundColor(self,color):
233 return self.background_color
549 234
550 self.write(intro)
551 self.setPrompt(prompt)
552 self.showPrompt()
235 def asyncWrite(self, text):
236 '''
237 Write given text to buffer in an asynchroneous way.
238 It is used from another thread to be able to acces the GUI.
239 @param text: Text to append
240 @type text: string
241 '''
242 try:
243 #print >>sys.__stdout__,'entering'
244 wx.MutexGuiEnter()
245 #print >>sys.__stdout__,'locking the GUI'
246
247 #be sure not to be interrutpted before the MutexGuiLeave!
248 self.write(text)
249
250 #print >>sys.__stdout__,'done'
251
252 except KeyboardInterrupt:
253 #print >>sys.__stdout__,'got keyboard interrupt'
254 wx.MutexGuiLeave()
255 #print >>sys.__stdout__,'interrupt unlock the GUI'
256 raise KeyboardInterrupt
257 wx.MutexGuiLeave()
258 #print >>sys.__stdout__,'normal unlock the GUI'
553 259
554 self.Bind(wx.EVT_KEY_DOWN, self._onKeypress, self)
555 #self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
556
260
557 261 def write(self, text):
558 262 '''
559 263 Write given text to buffer.
@@ -641,18 +345,6 b' class WxConsoleView(stc.StyledTextCtrl):'
641 345 return self.GetTextRange(self.getCurrentPromptStart(),
642 346 self.getCurrentLineEnd())
643 347
644 def showReturned(self, text):
645 '''
646 Show returned text from last command and print new prompt.
647
648 @param text: Text to show.
649 @type text: string
650 '''
651 self.write('\n'+text)
652 if text:
653 self.write('\n')
654 self.showPrompt()
655
656 348 def moveCursorOnNewValidKey(self):
657 349 #If cursor is at wrong position put it at last line...
658 350 if self.GetCurrentPos() < self.getCurrentPromptStart():
@@ -679,33 +371,53 b' class WxConsoleView(stc.StyledTextCtrl):'
679 371 def writeHistory(self,history):
680 372 self.removeFromTo(self.getCurrentPromptStart(),self.getCurrentLineEnd())
681 373 self.changeLine(history)
374
375 def setCompletionMethod(self, completion):
376 if completion in ['IPYTHON','STC']:
377 self.autocomplete_mode = completion
378 else:
379 raise AttributeError
380
381 def getCompletionMethod(self, completion):
382 return self.autocomplete_mode
682 383
683 384 def writeCompletion(self, possibilities):
684 max_len = len(max(possibilities,key=len))
685 max_symbol =' '*max_len
686
687 #now we check how much symbol we can put on a line...
688 cursor_pos = self.getCursorPos()
689 test_buffer = max_symbol + ' '*4
690 current_lines = self.GetLineCount()
691
692 allowed_symbols = 80/len(test_buffer)
693 if allowed_symbols == 0:
694 allowed_symbols = 1
385 if self.autocomplete_mode == 'IPYTHON':
386 max_len = len(max(possibilities,key=len))
387 max_symbol =' '*max_len
388
389 #now we check how much symbol we can put on a line...
390 cursor_pos = self.getCursorPos()
391 test_buffer = max_symbol + ' '*4
392 current_lines = self.GetLineCount()
393
394 allowed_symbols = 80/len(test_buffer)
395 if allowed_symbols == 0:
396 allowed_symbols = 1
397
398 pos = 1
399 buf = ''
400 for symbol in possibilities:
401 #buf += symbol+'\n'#*spaces)
402 if pos<allowed_symbols:
403 spaces = max_len - len(symbol) + 4
404 buf += symbol+' '*spaces
405 pos += 1
406 else:
407 buf+=symbol+'\n'
408 pos = 1
409 self.write(buf)
410 else:
411 possibilities.sort() # Python sorts are case sensitive
412 self.AutoCompSetIgnoreCase(False)
413 self.AutoCompSetAutoHide(False)
414 #let compute the length ot last word
415 splitter = [' ','(','[','{']
416 last_word = self.getCurrentLine()
417 for breaker in splitter:
418 last_word = last_word.split(breaker)[-1]
419 self.AutoCompShow(len(last_word), " ".join(possibilities))
695 420
696 pos = 1
697 buf = ''
698 for symbol in possibilities:
699 #buf += symbol+'\n'#*spaces)
700 if pos<allowed_symbols:
701 spaces = max_len - len(symbol) + 4
702 buf += symbol+' '*spaces
703 pos += 1
704 else:
705 buf+=symbol+'\n'
706 pos = 1
707 self.write(buf)
708
709 421 def _onKeypress(self, event, skip=True):
710 422 '''
711 423 Key press callback used for correcting behavior for console-like
@@ -720,42 +432,45 b' class WxConsoleView(stc.StyledTextCtrl):'
720 432 @return: Return True if event as been catched.
721 433 @rtype: boolean
722 434 '''
723
724 if event.GetKeyCode() == wx.WXK_HOME:
725 if event.Modifiers == wx.MOD_NONE:
726 self.moveCursorOnNewValidKey()
727 self.moveCursor(self.getCurrentPromptStart())
728 return True
729 elif event.Modifiers == wx.MOD_SHIFT:
730 self.moveCursorOnNewValidKey()
731 self.selectFromTo(self.getCurrentPromptStart(),self.getCursorPos())
732 return True
733 else:
734 return False
735 435
736 elif event.GetKeyCode() == wx.WXK_LEFT:
737 if event.Modifiers == wx.MOD_NONE:
738 self.moveCursorOnNewValidKey()
739
740 self.moveCursor(self.getCursorPos()-1)
741 if self.getCursorPos() < self.getCurrentPromptStart():
436 if not self.AutoCompActive():
437 if event.GetKeyCode() == wx.WXK_HOME:
438 if event.Modifiers == wx.MOD_NONE:
439 self.moveCursorOnNewValidKey()
742 440 self.moveCursor(self.getCurrentPromptStart())
743 return True
744
745 elif event.GetKeyCode() == wx.WXK_BACK:
746 self.moveCursorOnNewValidKey()
747 if self.getCursorPos() > self.getCurrentPromptStart():
748 self.removeFromTo(self.getCursorPos()-1,self.getCursorPos())
749 return True
750
751 if skip:
752 if event.GetKeyCode() not in [wx.WXK_PAGEUP,wx.WXK_PAGEDOWN] and event.Modifiers == wx.MOD_NONE:
441 return True
442 elif event.Modifiers == wx.MOD_SHIFT:
443 self.moveCursorOnNewValidKey()
444 self.selectFromTo(self.getCurrentPromptStart(),self.getCursorPos())
445 return True
446 else:
447 return False
448
449 elif event.GetKeyCode() == wx.WXK_LEFT:
450 if event.Modifiers == wx.MOD_NONE:
451 self.moveCursorOnNewValidKey()
452
453 self.moveCursor(self.getCursorPos()-1)
454 if self.getCursorPos() < self.getCurrentPromptStart():
455 self.moveCursor(self.getCurrentPromptStart())
456 return True
457
458 elif event.GetKeyCode() == wx.WXK_BACK:
753 459 self.moveCursorOnNewValidKey()
754
460 if self.getCursorPos() > self.getCurrentPromptStart():
461 event.Skip()
462 return True
463
464 if skip:
465 if event.GetKeyCode() not in [wx.WXK_PAGEUP,wx.WXK_PAGEDOWN] and event.Modifiers == wx.MOD_NONE:
466 self.moveCursorOnNewValidKey()
467
468 event.Skip()
469 return True
470 return False
471 else:
755 472 event.Skip()
756 return True
757 return False
758
473
759 474 def OnUpdateUI(self, evt):
760 475 # check for matching braces
761 476 braceAtCaret = -1
@@ -791,49 +506,90 b' class WxConsoleView(stc.StyledTextCtrl):'
791 506 #print pt
792 507 #self.Refresh(False)
793 508
794 class WxIPythonViewPanel(wx.Panel):
509 class IPShellWidget(wx.Panel):
795 510 '''
796 511 This is wx.Panel that embbed the IPython Thread and the wx.StyledTextControl
797 If you want to port this to any other GUI toolkit, just replace the WxConsoleView
798 by YOURGUIConsoleView and make YOURGUIIPythonView derivate from whatever container you want.
799 I've choosed to derivate from a wx.Panel because it seems to be ore usefull
800 Any idea to make it more 'genric' welcomed.
512 If you want to port this to any other GUI toolkit, just replace the
513 WxConsoleView by YOURGUIConsoleView and make YOURGUIIPythonView derivate
514 from whatever container you want. I've choosed to derivate from a wx.Panel
515 because it seems to be more useful
516 Any idea to make it more 'generic' welcomed.
801 517 '''
802 def __init__(self,parent,exit_handler=None,intro=None,background_color="BLACK"):
518
519 def __init__(self, parent, intro=None,
520 background_color="BLACK", add_button_handler=None,
521 wx_ip_shell=None, user_ns={},user_global_ns=None,
522 ):
803 523 '''
804 524 Initialize.
805 525 Instanciate an IPython thread.
806 526 Instanciate a WxConsoleView.
807 527 Redirect I/O to console.
808 528 '''
809 wx.Panel.__init__(self,parent,-1)
529 wx.Panel.__init__(self,parent,wx.ID_ANY)
810 530
811 ### IPython thread instanciation ###
531 self.parent = parent
532 ### IPython non blocking shell instanciation ###
812 533 self.cout = StringIO()
813 self.IP = IterableIPShell(cout=self.cout,cerr=self.cout,
814 exit_handler = exit_handler,
815 time_loop = 0.1)
816 self.IP.start()
817
534 self.add_button_handler = add_button_handler
535
536 if wx_ip_shell is not None:
537 self.IP = wx_ip_shell
538 else:
539 self.IP = WxNonBlockingIPShell(self,
540 cout = self.cout, cerr = self.cout,
541 ask_exit_handler = self.askExitCallback)
542
818 543 ### IPython wx console view instanciation ###
819 544 #If user didn't defined an intro text, we create one for him
820 #If you really wnat an empty intrp just call wxIPythonViewPanel with intro=''
821 if intro == None:
545 #If you really wnat an empty intro just call wxIPythonViewPanel
546 #with intro=''
547 if intro is None:
822 548 welcome_text = "Welcome to WxIPython Shell.\n\n"
823 549 welcome_text+= self.IP.getBanner()
824 550 welcome_text+= "!command -> Execute command in shell\n"
825 551 welcome_text+= "TAB -> Autocompletion\n"
552 else:
553 welcome_text = intro
826 554
827 555 self.text_ctrl = WxConsoleView(self,
828 556 self.IP.getPrompt(),
829 557 intro=welcome_text,
830 558 background_color=background_color)
831
832 self.text_ctrl.Bind(wx.EVT_KEY_DOWN, self.keyPress, self.text_ctrl)
833 559
560 self.cout.write = self.text_ctrl.asyncWrite
561
562 option_text = wx.StaticText(self, -1, "Options:")
563 self.completion_option = wx.CheckBox(self, -1, "Scintilla Completion")
564 #self.completion_option.SetValue(False)
565 self.background_option = wx.CheckBox(self, -1, "White Background")
566 #self.background_option.SetValue(False)
567
568 self.options={'completion':{'value':'IPYTHON',
569 'checkbox':self.completion_option,'STC':True,'IPYTHON':False,
570 'setfunc':self.text_ctrl.setCompletionMethod},
571 'background_color':{'value':'BLACK',
572 'checkbox':self.background_option,'WHITE':True,'BLACK':False,
573 'setfunc':self.text_ctrl.setBackgroundColor},
574 }
575 self.reloadOptions(self.options)
576
577 self.text_ctrl.Bind(wx.EVT_KEY_DOWN, self.keyPress)
578 self.completion_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionCompletion)
579 self.background_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionBackgroundColor)
580
834 581 ### making the layout of the panel ###
835 582 sizer = wx.BoxSizer(wx.VERTICAL)
836 583 sizer.Add(self.text_ctrl, 1, wx.EXPAND)
584 option_sizer = wx.BoxSizer(wx.HORIZONTAL)
585 sizer.Add(option_sizer, 0)
586 option_sizer.AddMany([(10, 20),
587 (option_text, 0, wx.ALIGN_CENTER_VERTICAL),
588 (5, 5),
589 (self.completion_option, 0, wx.ALIGN_CENTER_VERTICAL),
590 (8, 8),
591 (self.background_option, 0, wx.ALIGN_CENTER_VERTICAL)
592 ])
837 593 self.SetAutoLayout(True)
838 594 sizer.Fit(self)
839 595 sizer.SetSizeHints(self)
@@ -841,158 +597,151 b' class WxIPythonViewPanel(wx.Panel):'
841 597 #and we focus on the widget :)
842 598 self.SetFocus()
843 599
844 ### below are the thread communication variable ###
845 # the IPython thread is managed via unidirectional communication.
846 # It's a thread slave that can't interact by itself with the GUI.
847 # When the GUI event loop is done runStateMachine() is called and the thread sate is then
848 # managed.
849
850 #Initialize the state machine #kept for information
851 #self.states = ['IDLE',
852 # 'DO_EXECUTE_LINE',
853 # 'WAIT_END_OF_EXECUTION',
854 # 'SHOW_DOC',
855 # 'SHOW_PROMPT']
856
857 self.cur_state = 'IDLE'
858 self.pager_state = 'DONE'
859 #wx.CallAfter(self.runStateMachine)
600 #widget state management (for key handling different cases)
601 self.setCurrentState('IDLE')
602 self.pager_state = 'DONE'
603 self.raw_input_current_line = 0
604
605 def askExitCallback(self, event):
606 self.askExitHandler(event)
607
608 #---------------------- IPython Thread Management ------------------------
609 def stateDoExecuteLine(self):
610 lines=self.text_ctrl.getCurrentLine()
611 self.text_ctrl.write('\n')
612 lines_to_execute = lines.replace('\t',' '*4)
613 lines_to_execute = lines_to_execute.replace('\r','')
614 self.IP.doExecute(lines_to_execute.encode('cp1252'))
615 self.updateHistoryTracker(lines)
616 self.setCurrentState('WAIT_END_OF_EXECUTION')
617
618 def evtStateExecuteDone(self,evt):
619 self.doc = self.IP.getDocText()
620 self.help = self.IP.getHelpText()
621 if self.doc:
622 self.pager_lines = self.doc[7:].split('\n')
623 self.pager_state = 'INIT'
624 self.setCurrentState('SHOW_DOC')
625 self.pager(self.doc)
626 elif self.help:
627 self.pager_lines = self.help.split('\n')
628 self.pager_state = 'INIT'
629 self.setCurrentState('SHOW_DOC')
630 self.pager(self.help)
631 else:
632 self.stateShowPrompt()
633
634 def stateShowPrompt(self):
635 self.setCurrentState('SHOW_PROMPT')
636 self.text_ctrl.setPrompt(self.IP.getPrompt())
637 self.text_ctrl.setIndentation(self.IP.getIndentation())
638 self.text_ctrl.setPromptCount(self.IP.getPromptCount())
639 self.text_ctrl.showPrompt()
640 self.IP.initHistoryIndex()
641 self.setCurrentState('IDLE')
642
643 def setCurrentState(self, state):
644 self.cur_state = state
645 self.updateStatusTracker(self.cur_state)
860 646
861 # This creates a new Event class and a EVT binder function
862 (self.AskExitEvent, EVT_ASK_EXIT) = wx.lib.newevent.NewEvent()
647 def pager(self,text):
863 648
864 self.Bind(wx.EVT_IDLE, self.runStateMachine)
865 self.Bind(EVT_ASK_EXIT, exit_handler)
866
867 def __del__(self):
868 self.IP.shutdown()
869 self.IP.join()
870 WxConsoleView.__del__()
871
872 #---------------------------- IPython Thread Management ---------------------------------------
873 def runStateMachine(self,event):
874 #print >>self.sys_stdout,"state:",self.cur_state
875 self.updateStatusTracker(self.cur_state)
876
877 if self.cur_state == 'DO_EXECUTE_LINE':
878 #print >>self.sys_stdout,"command:",self.getCurrentLine()
879 self.IP.doExecute(self.text_ctrl.getCurrentLine().replace('\t',' '*4))
880 self.updateHistoryTracker(self.text_ctrl.getCurrentLine())
881 self.cur_state = 'WAIT_END_OF_EXECUTION'
882
883 if self.cur_state == 'WAIT_END_OF_EXECUTION':
884 if self.IP.isExecuteDone():
885 self.doc = self.IP.getDocText()
886 if self.IP.getAskExit():
887 evt = self.AskExitEvent()
888 wx.PostEvent(self, evt)
889 self.IP.clearAskExit()
890 if self.doc:
891 self.pager_state = 'INIT'
892 self.cur_state = 'SHOW_DOC'
649 if self.pager_state == 'INIT':
650 #print >>sys.__stdout__,"PAGER state:",self.pager_state
651 self.pager_nb_lines = len(self.pager_lines)
652 self.pager_index = 0
653 self.pager_do_remove = False
654 self.text_ctrl.write('\n')
655 self.pager_state = 'PROCESS_LINES'
656
657 if self.pager_state == 'PROCESS_LINES':
658 #print >>sys.__stdout__,"PAGER state:",self.pager_state
659 if self.pager_do_remove == True:
660 self.text_ctrl.removeCurrentLine()
661 self.pager_do_remove = False
662
663 if self.pager_nb_lines > 10:
664 #print >>sys.__stdout__,"PAGER processing 10 lines"
665 if self.pager_index > 0:
666 self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n')
667 else:
668 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n')
669
670 for line in self.pager_lines[self.pager_index+1:self.pager_index+9]:
671 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n')
672 self.pager_index += 10
673 self.pager_nb_lines -= 10
674 self.text_ctrl.write("--- Push Enter to continue or 'Q' to quit---")
675 self.pager_do_remove = True
676 self.pager_state = 'WAITING'
677 return
893 678 else:
894 self.cur_state = 'SHOW_PROMPT'
895
896 if self.cur_state == 'SHOW_PROMPT':
897 self.text_ctrl.setPrompt(self.IP.getPrompt())
898 self.text_ctrl.setIndentation(self.IP.getIndentation())
899 self.text_ctrl.setPromptCount(self.IP.getPromptCount())
900 rv = self.cout.getvalue()
901 if rv: rv = rv.strip('\n')
902 self.text_ctrl.showReturned(rv)
903 self.cout.truncate(0)
904 self.IP.initHistoryIndex()
905 self.cur_state = 'IDLE'
906
907 if self.cur_state == 'SHOW_DOC':
908 self.pager(self.doc)
909 if self.pager_state == 'DONE':
910 self.cur_state = 'SHOW_PROMPT'
911
912 event.Skip()
913
914 #---------------------------- IPython pager ---------------------------------------
915 def pager(self,text):#,start=0,screen_lines=0,pager_cmd = None):
916 if self.pager_state == 'WAITING':
917 #print >>self.sys_stdout,"PAGER waiting"
918 return
919
920 if self.pager_state == 'INIT':
921 #print >>self.sys_stdout,"PAGER state:",self.pager_state
922 self.pager_lines = text[7:].split('\n')
923 self.pager_nb_lines = len(self.pager_lines)
924 self.pager_index = 0
925 self.pager_do_remove = False
926 self.text_ctrl.write('\n')
927 self.pager_state = 'PROCESS_LINES'
928
929 if self.pager_state == 'PROCESS_LINES':
930 #print >>self.sys_stdout,"PAGER state:",self.pager_state
931 if self.pager_do_remove == True:
932 self.text_ctrl.removeCurrentLine()
933 self.pager_do_remove = False
934
935 if self.pager_nb_lines > 10:
936 #print >>self.sys_stdout,"PAGER processing 10 lines"
937 if self.pager_index > 0:
938 self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n')
939 else:
940 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n')
941
942 for line in self.pager_lines[self.pager_index+1:self.pager_index+9]:
943 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n')
944 self.pager_index += 10
945 self.pager_nb_lines -= 10
946 self.text_ctrl.write("--- Push Enter to continue or 'Q' to quit---")
947 self.pager_do_remove = True
948 self.pager_state = 'WAITING'
949 return
950 else:
951 #print >>self.sys_stdout,"PAGER processing last lines"
952 if self.pager_nb_lines > 0:
953 if self.pager_index > 0:
954 self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n')
955 else:
956 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n')
957
958 self.pager_index += 1
679 #print >>sys.__stdout__,"PAGER processing last lines"
680 if self.pager_nb_lines > 0:
681 if self.pager_index > 0:
682 self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n')
683 else:
684 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n')
685
686 self.pager_index += 1
959 687 self.pager_nb_lines -= 1
960 if self.pager_nb_lines > 0:
961 for line in self.pager_lines[self.pager_index:]:
962 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n')
963 self.pager_nb_lines = 0
964 self.pager_state = 'DONE'
688 if self.pager_nb_lines > 0:
689 for line in self.pager_lines[self.pager_index:]:
690 self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n')
691 self.pager_nb_lines = 0
692 self.pager_state = 'DONE'
693 self.stateShowPrompt()
965 694
966 #---------------------------- Key Handler --------------------------------------------
695 #------------------------ Key Handler ------------------------------------
967 696 def keyPress(self, event):
968 697 '''
969 698 Key press callback with plenty of shell goodness, like history,
970 699 autocompletions, etc.
971 700 '''
972
973 701 if event.GetKeyCode() == ord('C'):
974 if event.Modifiers == wx.MOD_CONTROL:
702 if event.Modifiers == wx.MOD_CONTROL or event.Modifiers == wx.MOD_ALT:
975 703 if self.cur_state == 'WAIT_END_OF_EXECUTION':
976 704 #we raise an exception inside the IPython thread container
977 self.IP.raise_exc(KeyboardInterrupt)
705 self.IP.ce.raise_exc(KeyboardInterrupt)
978 706 return
979 707
708 #let this before 'wx.WXK_RETURN' because we have to put 'IDLE'
709 #mode if AutoComp has been set as inactive
710 if self.cur_state == 'COMPLETING':
711 if not self.text_ctrl.AutoCompActive():
712 self.cur_state = 'IDLE'
713 else:
714 event.Skip()
715
980 716 if event.KeyCode == wx.WXK_RETURN:
981 717 if self.cur_state == 'IDLE':
982 718 #we change the state ot the state machine
983 self.cur_state = 'DO_EXECUTE_LINE'
719 self.setCurrentState('DO_EXECUTE_LINE')
720 self.stateDoExecuteLine()
984 721 return
722
985 723 if self.pager_state == 'WAITING':
986 724 self.pager_state = 'PROCESS_LINES'
725 self.pager(self.doc)
987 726 return
988 727
728 if self.cur_state == 'WAITING_USER_INPUT':
729 line=self.text_ctrl.getCurrentLine()
730 self.text_ctrl.write('\n')
731 self.setCurrentState('WAIT_END_OF_EXECUTION')
732 return
733
989 734 if event.GetKeyCode() in [ord('q'),ord('Q')]:
990 735 if self.pager_state == 'WAITING':
991 736 self.pager_state = 'DONE'
737 self.text_ctrl.write('\n')
738 self.stateShowPrompt()
992 739 return
740
741 if self.cur_state == 'WAITING_USER_INPUT':
742 event.Skip()
993 743
994 #scroll_position = self.text_ctrl.GetScrollPos(wx.VERTICAL)
995 if self.cur_state == 'IDLE':
744 if self.cur_state == 'IDLE':
996 745 if event.KeyCode == wx.WXK_UP:
997 746 history = self.IP.historyBack()
998 747 self.text_ctrl.writeHistory(history)
@@ -1008,19 +757,68 b' class WxIPythonViewPanel(wx.Panel):'
1008 757 return
1009 758 completed, possibilities = self.IP.complete(self.text_ctrl.getCurrentLine())
1010 759 if len(possibilities) > 1:
1011 cur_slice = self.text_ctrl.getCurrentLine()
1012 self.text_ctrl.write('\n')
1013 self.text_ctrl.writeCompletion(possibilities)
1014 self.text_ctrl.write('\n')
1015
1016 self.text_ctrl.showPrompt()
1017 self.text_ctrl.write(cur_slice)
1018 self.text_ctrl.changeLine(completed or cur_slice)
1019
760 if self.text_ctrl.autocomplete_mode == 'IPYTHON':
761 cur_slice = self.text_ctrl.getCurrentLine()
762 self.text_ctrl.write('\n')
763 self.text_ctrl.writeCompletion(possibilities)
764 self.text_ctrl.write('\n')
765
766 self.text_ctrl.showPrompt()
767 self.text_ctrl.write(cur_slice)
768 self.text_ctrl.changeLine(completed or cur_slice)
769 else:
770 self.cur_state = 'COMPLETING'
771 self.text_ctrl.writeCompletion(possibilities)
772 else:
773 self.text_ctrl.changeLine(completed or cur_slice)
1020 774 return
1021 775 event.Skip()
1022
1023 #---------------------------- Hook Section --------------------------------------------
776
777 #------------------------ Option Section ---------------------------------
778 def evtCheckOptionCompletion(self, event):
779 if event.IsChecked():
780 self.options['completion']['value']='STC'
781 else:
782 self.options['completion']['value']='IPYTHON'
783 self.text_ctrl.setCompletionMethod(self.options['completion']['value'])
784 self.updateOptionTracker('completion',
785 self.options['completion']['value'])
786 self.text_ctrl.SetFocus()
787
788 def evtCheckOptionBackgroundColor(self, event):
789 if event.IsChecked():
790 self.options['background_color']['value']='WHITE'
791 else:
792 self.options['background_color']['value']='BLACK'
793 self.text_ctrl.setBackgroundColor(self.options['background_color']['value'])
794 self.updateOptionTracker('background_color',
795 self.options['background_color']['value'])
796 self.text_ctrl.SetFocus()
797
798 def getOptions(self):
799 return self.options
800
801 def reloadOptions(self,options):
802 self.options = options
803 for key in self.options.keys():
804 value = self.options[key]['value']
805 self.options[key]['checkbox'].SetValue(self.options[key][value])
806 self.options[key]['setfunc'](value)
807
808
809 #------------------------ Hook Section -----------------------------------
810 def updateOptionTracker(self,name,value):
811 '''
812 Default history tracker (does nothing)
813 '''
814 pass
815
816 def setOptionTrackerHook(self,func):
817 '''
818 Define a new history tracker
819 '''
820 self.updateOptionTracker = func
821
1024 822 def updateHistoryTracker(self,command_line):
1025 823 '''
1026 824 Default history tracker (does nothing)
@@ -1032,6 +830,7 b' class WxIPythonViewPanel(wx.Panel):'
1032 830 Define a new history tracker
1033 831 '''
1034 832 self.updateHistoryTracker = func
833
1035 834 def updateStatusTracker(self,status):
1036 835 '''
1037 836 Default status tracker (does nothing)
@@ -1043,4 +842,36 b' class WxIPythonViewPanel(wx.Panel):'
1043 842 Define a new status tracker
1044 843 '''
1045 844 self.updateStatusTracker = func
1046
845
846 def askExitHandler(self, event):
847 '''
848 Default exit handler
849 '''
850 self.text_ctrl.write('\nExit callback has not been set.')
851
852 def setAskExitHandler(self, func):
853 '''
854 Define an exit handler
855 '''
856 self.askExitHandler = func
857
858 if __name__ == '__main__':
859 # Some simple code to test the shell widget.
860 class MainWindow(wx.Frame):
861 def __init__(self, parent, id, title):
862 wx.Frame.__init__(self, parent, id, title, size=(300,250))
863 self._sizer = wx.BoxSizer(wx.VERTICAL)
864 self.shell = IPShellWidget(self)
865 self._sizer.Add(self.shell, 1, wx.EXPAND)
866 self.SetSizer(self._sizer)
867 self.SetAutoLayout(1)
868 self.Show(True)
869
870 app = wx.PySimpleApp()
871 frame = MainWindow(None, wx.ID_ANY, 'Ipython')
872 frame.SetSize((780, 460))
873 shell = frame.shell
874
875 app.MainLoop()
876
877
@@ -1,45 +1,50 b''
1 import threading
2 import inspect
3 import ctypes
4
5
6 def _async_raise(tid, exctype):
7 """raises the exception, performs cleanup if needed"""
8 if not inspect.isclass(exctype):
9 raise TypeError("Only types can be raised (not instances)")
10 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
11 if res == 0:
12 raise ValueError("invalid thread id")
13 elif res != 1:
14 # """if it returns a number greater than one, you're in trouble,
15 # and you should call it again with exc=NULL to revert the effect"""
16 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
17 raise SystemError("PyThreadState_SetAsyncExc failed")
18
19
20 class Thread(threading.Thread):
21 def _get_my_tid(self):
22 """determines this (self's) thread id"""
23 if not self.isAlive():
24 raise threading.ThreadError("the thread is not active")
25
26 # do we have it cached?
27 if hasattr(self, "_thread_id"):
28 return self._thread_id
29
30 # no, look for it in the _active dict
31 for tid, tobj in threading._active.items():
32 if tobj is self:
33 self._thread_id = tid
34 return tid
35
36 raise AssertionError("could not determine the thread's id")
37
38 def raise_exc(self, exctype):
39 """raises the given exception type in the context of this thread"""
40 _async_raise(self._get_my_tid(), exctype)
41
42 def kill(self):
43 """raises SystemExit in the context of the given thread, which should
44 cause the thread to exit silently (unless caught)"""
45 self.raise_exc(SystemExit)
1 """
2 Thread subclass that can deal with asynchronously function calls via
3 raise_exc.
4 """
5
6 import threading
7 import inspect
8 import ctypes
9
10
11 def _async_raise(tid, exctype):
12 """raises the exception, performs cleanup if needed"""
13 if not inspect.isclass(exctype):
14 raise TypeError("Only types can be raised (not instances)")
15 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
16 if res == 0:
17 raise ValueError("invalid thread id")
18 elif res != 1:
19 # """if it returns a number greater than one, you're in trouble,
20 # and you should call it again with exc=NULL to revert the effect"""
21 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
22 raise SystemError("PyThreadState_SetAsyncExc failed")
23
24
25 class ThreadEx(threading.Thread):
26 def _get_my_tid(self):
27 """determines this (self's) thread id"""
28 if not self.isAlive():
29 raise threading.ThreadError("the thread is not active")
30
31 # do we have it cached?
32 if hasattr(self, "_thread_id"):
33 return self._thread_id
34
35 # no, look for it in the _active dict
36 for tid, tobj in threading._active.items():
37 if tobj is self:
38 self._thread_id = tid
39 return tid
40
41 raise AssertionError("could not determine the thread's id")
42
43 def raise_exc(self, exctype):
44 """raises the given exception type in the context of this thread"""
45 _async_raise(self._get_my_tid(), exctype)
46
47 def kill(self):
48 """raises SystemExit in the context of the given thread, which should
49 cause the thread to exit silently (unless caught)"""
50 self.raise_exc(SystemExit)
@@ -2,11 +2,13 b''
2 2 # -*- coding: iso-8859-15 -*-
3 3
4 4 import wx.aui
5 import wx.py
5
6 #used for about dialog
6 7 from wx.lib.wordwrap import wordwrap
7 8
8 from ipython_view import *
9 from ipython_history import *
9 #used for ipython GUI objects
10 from IPython.gui.wx.ipython_view import IPShellWidget
11 from IPython.gui.wx.ipython_history import IPythonHistoryPanel
10 12
11 13 __version__ = 0.8
12 14 __author__ = "Laurent Dufrechou"
@@ -20,7 +22,8 b' __license__ = "BSD"'
20 22 class MyFrame(wx.Frame):
21 23 """Creating one main frame for our
22 24 application with movables windows"""
23 def __init__(self, parent=None, id=-1, title="WxIPython", pos=wx.DefaultPosition,
25 def __init__(self, parent=None, id=-1, title="WxIPython",
26 pos=wx.DefaultPosition,
24 27 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):
25 28 wx.Frame.__init__(self, parent, id, title, pos, size, style)
26 29 self._mgr = wx.aui.AuiManager()
@@ -30,15 +33,18 b' class MyFrame(wx.Frame):'
30 33
31 34 #create differents panels and make them persistant
32 35 self.history_panel = IPythonHistoryPanel(self)
36
37 self.history_panel.setOptionTrackerHook(self.optionSave)
33 38
34 self.ipython_panel = WxIPythonViewPanel(self,self.OnExitDlg,
35 background_color = "BLACK")
36
37 #self.ipython_panel = WxIPythonViewPanel(self,self.OnExitDlg,
38 # background_color = "WHITE")
39
39 self.ipython_panel = IPShellWidget(self,background_color = "BLACK")
40 #self.ipython_panel = IPShellWidget(self,background_color = "WHITE")
41
40 42 self.ipython_panel.setHistoryTrackerHook(self.history_panel.write)
41 43 self.ipython_panel.setStatusTrackerHook(self.updateStatus)
44 self.ipython_panel.setAskExitHandler(self.OnExitDlg)
45 self.ipython_panel.setOptionTrackerHook(self.optionSave)
46
47 self.optionLoad()
42 48
43 49 self.statusbar = self.createStatus()
44 50 self.createMenu()
@@ -48,13 +54,11 b' class MyFrame(wx.Frame):'
48 54 # main panels
49 55 self._mgr.AddPane(self.ipython_panel , wx.CENTER, "IPython Shell")
50 56 self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history")
51
57
52 58 # now we specify some panel characteristics
53 59 self._mgr.GetPane(self.ipython_panel).CaptionVisible(True);
54 60 self._mgr.GetPane(self.history_panel).CaptionVisible(True);
55 61 self._mgr.GetPane(self.history_panel).MinSize((200,400));
56
57
58 62
59 63 # tell the manager to "commit" all the changes just made
60 64 self._mgr.Update()
@@ -66,7 +70,7 b' class MyFrame(wx.Frame):'
66 70 self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2)
67 71 self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3)
68 72 self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6)
69
73
70 74 warn_text = 'Hello from IPython and wxPython.\n'
71 75 warn_text +='Please Note that this work is still EXPERIMENTAL\n'
72 76 warn_text +='It does NOT emulate currently all the IPython functions.\n'
@@ -78,7 +82,41 b' class MyFrame(wx.Frame):'
78 82 )
79 83 dlg.ShowModal()
80 84 dlg.Destroy()
81
85
86 def optionSave(self, name, value):
87 opt = open('options.conf','w')
88
89 try:
90 options_ipython_panel = self.ipython_panel.getOptions()
91 options_history_panel = self.history_panel.getOptions()
92
93 for key in options_ipython_panel.keys():
94 opt.write(key + '=' + options_ipython_panel[key]['value']+'\n')
95 for key in options_history_panel.keys():
96 opt.write(key + '=' + options_history_panel[key]['value']+'\n')
97 finally:
98 opt.close()
99
100 def optionLoad(self):
101 opt = open('options.conf','r')
102 lines = opt.readlines()
103 opt.close()
104
105 options_ipython_panel = self.ipython_panel.getOptions()
106 options_history_panel = self.history_panel.getOptions()
107
108 for line in lines:
109 key = line.split('=')[0]
110 value = line.split('=')[1].replace('\n','').replace('\r','')
111 if key in options_ipython_panel.keys():
112 options_ipython_panel[key]['value'] = value
113 elif key in options_history_panel.keys():
114 options_history_panel[key]['value'] = value
115 else:
116 print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf"
117 self.ipython_panel.reloadOptions(options_ipython_panel)
118 self.history_panel.reloadOptions(options_history_panel)
119
82 120 def createMenu(self):
83 121 """local method used to create one menu bar"""
84 122
@@ -121,6 +159,7 b' class MyFrame(wx.Frame):'
121 159 states = {'IDLE':'Idle',
122 160 'DO_EXECUTE_LINE':'Send command',
123 161 'WAIT_END_OF_EXECUTION':'Running command',
162 'WAITING_USER_INPUT':'Waiting user input',
124 163 'SHOW_DOC':'Showing doc',
125 164 'SHOW_PROMPT':'Showing prompt'}
126 165 self.statusbar.SetStatusText(states[text], 0)
@@ -56,7 +56,7 b' from pprint import PrettyPrinter'
56 56 __all__ = ['editor', 'fix_error_editor', 'result_display',
57 57 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
58 58 'generate_prompt', 'generate_output_prompt','shell_hook',
59 'show_in_pager']
59 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook']
60 60
61 61 pformat = PrettyPrinter().pformat
62 62
@@ -227,11 +227,17 b' def show_in_pager(self,s):'
227 227 # raising TryNext here will use the default paging functionality
228 228 raise ipapi.TryNext
229 229
230 def pre_command_hook(self,cmd):
231 """" Executed before starting to execute a command """
230 def pre_prompt_hook(self):
231 """ Run before displaying the next prompt
232
233 Use this e.g. to display output from asynchronous operations (in order
234 to not mess up text entry)
235 """
236
232 237 return None
233 238
234 def post_command_hook(self,cmd):
235 """ Executed after executing a command """
239 def pre_runcode_hook(self):
240 """ Executed before running the (prefiltered) code in IPython """
241 return None
236 242
237 243
@@ -273,15 +273,27 b' class IPApi:'
273 273 """
274 274 res = []
275 275 lines = script.splitlines()
276
276 277 level = 0
277 278 for l in lines:
278 stripped = l.lstrip()
279 if not l.strip():
279 lstripped = l.lstrip()
280 stripped = l.strip()
281 if not stripped:
280 282 continue
281 newlevel = len(l) - len(stripped)
282 if level > 0 and newlevel == 0:
283 newlevel = len(l) - len(lstripped)
284 def is_secondary_block_start(s):
285 if not s.endswith(':'):
286 return False
287 if (s.startswith('elif') or
288 s.startswith('else') or
289 s.startswith('except') or
290 s.startswith('finally')):
291 return True
292
293 if level > 0 and newlevel == 0 and not is_secondary_block_start(stripped):
283 294 # add empty line
284 295 res.append('')
296
285 297 res.append(l)
286 298 level = newlevel
287 299 return '\n'.join(res) + '\n'
@@ -291,7 +303,7 b' class IPApi:'
291 303 else:
292 304 script = '\n'.join(lines)
293 305 clean=cleanup_ipy_script(script)
294
306 # print "_ip.runlines() script:\n",clean #dbg
295 307 self.IP.runlines(clean)
296 308 def to_user_ns(self,vars, interactive = True):
297 309 """Inject a group of variables into the IPython user namespace.
@@ -533,7 +545,7 b' class DebugTools:'
533 545 if name in self.hotnames:
534 546 self.debug_stack( "HotName '%s' caught" % name)
535 547
536 def launch_new_instance(user_ns = None):
548 def launch_new_instance(user_ns = None,shellclass = None):
537 549 """ Make and start a new ipython instance.
538 550
539 551 This can be called even without having an already initialized
@@ -542,7 +554,7 b' def launch_new_instance(user_ns = None):'
542 554 This is also used as the egg entry point for the 'ipython' script.
543 555
544 556 """
545 ses = make_session(user_ns)
557 ses = make_session(user_ns,shellclass)
546 558 ses.mainloop()
547 559
548 560
@@ -578,7 +590,7 b' def make_user_global_ns(ns = None):'
578 590 return ns
579 591
580 592
581 def make_session(user_ns = None):
593 def make_session(user_ns = None, shellclass = None):
582 594 """Makes, but does not launch an IPython session.
583 595
584 596 Later on you can call obj.mainloop() on the returned object.
@@ -591,6 +603,6 b' def make_session(user_ns = None):'
591 603 WARNING: This should *not* be run when a session exists already."""
592 604
593 605 import IPython.Shell
594 return IPython.Shell.start(user_ns)
595
596
606 if shellclass is None:
607 return IPython.Shell.start(user_ns)
608 return shellclass(user_ns = user_ns)
@@ -6,7 +6,6 b' Requires Python 2.3 or newer.'
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 3005 2008-02-01 16:43:34Z vivainio $
10 9 """
11 10
12 11 #*****************************************************************************
@@ -55,6 +54,8 b' import sys'
55 54 import tempfile
56 55 import traceback
57 56 import types
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
58 59 from sets import Set
59 60 from pprint import pprint, pformat
60 61
@@ -377,7 +378,10 b' class InteractiveShell(object,Magic):'
377 378 # Get system encoding at startup time. Certain terminals (like Emacs
378 379 # under Win32 have it set to None, and we need to have a known valid
379 380 # encoding to use in the raw_input() method
380 self.stdin_encoding = sys.stdin.encoding or 'ascii'
381 try:
382 self.stdin_encoding = sys.stdin.encoding or 'ascii'
383 except AttributeError:
384 self.stdin_encoding = 'ascii'
381 385
382 386 # dict of things NOT to alias (keywords, builtins and some magics)
383 387 no_alias = {}
@@ -698,7 +702,10 b' class InteractiveShell(object,Magic):'
698 702
699 703 # Do a proper resetting of doctest, including the necessary displayhook
700 704 # monkeypatching
701 doctest_reload()
705 try:
706 doctest_reload()
707 except ImportError:
708 warn("doctest module does not exist.")
702 709
703 710 # Set user colors (don't do it in the constructor above so that it
704 711 # doesn't crash if colors option is invalid)
@@ -1266,8 +1273,12 b' want to merge them back into the new files.""" % locals()'
1266 1273 """Reload the input history from disk file."""
1267 1274
1268 1275 if self.has_readline:
1269 self.readline.clear_history()
1270 self.readline.read_history_file(self.shell.histfile)
1276 try:
1277 self.readline.clear_history()
1278 self.readline.read_history_file(self.shell.histfile)
1279 except AttributeError:
1280 pass
1281
1271 1282
1272 1283 def history_saving_wrapper(self, func):
1273 1284 """ Wrap func for readline history saving
@@ -1744,6 +1755,7 b' want to merge them back into the new files.""" % locals()'
1744 1755 # exit_now is set by a call to %Exit or %Quit
1745 1756
1746 1757 while not self.exit_now:
1758 self.hooks.pre_prompt_hook()
1747 1759 if more:
1748 1760 try:
1749 1761 prompt = self.hooks.generate_prompt(True)
@@ -2009,7 +2021,7 b' want to merge them back into the new files.""" % locals()'
2009 2021
2010 2022 try:
2011 2023 code = self.compile(source,filename,symbol)
2012 except (OverflowError, SyntaxError, ValueError):
2024 except (OverflowError, SyntaxError, ValueError, TypeError):
2013 2025 # Case 1
2014 2026 self.showsyntaxerror(filename)
2015 2027 return None
@@ -2053,6 +2065,7 b' want to merge them back into the new files.""" % locals()'
2053 2065 outflag = 1 # happens in more places, so it's easier as default
2054 2066 try:
2055 2067 try:
2068 self.hooks.pre_runcode_hook()
2056 2069 # Embedded instances require separate global/local namespaces
2057 2070 # so they can see both the surrounding (local) namespace and
2058 2071 # the module-level globals when called inside another function.
@@ -58,6 +58,14 b' from IPython.iplib import InteractiveShell'
58 58 from IPython.usage import cmd_line_usage,interactive_usage
59 59 from IPython.genutils import *
60 60
61 def force_import(modname):
62 if modname in sys.modules:
63 print "reload",modname
64 reload(sys.modules[modname])
65 else:
66 __import__(modname)
67
68
61 69 #-----------------------------------------------------------------------------
62 70 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
63 71 rc_override=None,shell_class=InteractiveShell,
@@ -95,9 +103,12 b' def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,'
95 103 embedded=embedded,**kw)
96 104
97 105 # Put 'help' in the user namespace
98 from site import _Helper
106 try:
107 from site import _Helper
108 IP.user_ns['help'] = _Helper()
109 except ImportError:
110 warn('help() not available - check site.py')
99 111 IP.user_config_ns = {}
100 IP.user_ns['help'] = _Helper()
101 112
102 113
103 114 if DEVDEBUG:
@@ -176,10 +187,10 b" object? -> Details about 'object'. ?object also works, ?? prints more."
176 187
177 188 # Options that can *only* appear at the cmd line (not in rcfiles).
178 189
179 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
180 # the 'C-c !' command in emacs automatically appends a -i option at the end.
181 190 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
182 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk!')
191 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
192 # 'twisted!' # disabled for now.
193 )
183 194
184 195 # Build the actual name list to be used by DPyGetOpt
185 196 opts_names = qw(cmdline_opts) + qw(cmdline_only)
@@ -203,7 +214,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
203 214 editor = '0',
204 215 gthread = 0,
205 216 help = 0,
206 interact = 1,
217 interact = 0,
207 218 ipythondir = ipythondir_def,
208 219 log = 0,
209 220 logfile = '',
@@ -237,6 +248,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
237 248 system_verbose = 0,
238 249 term_title = 1,
239 250 tk = 0,
251 #twisted= 0, # disabled for now
240 252 upgrade = 0,
241 253 Version = 0,
242 254 wildcards_case_sensitive = 1,
@@ -633,15 +645,17 b" object? -> Details about 'object'. ?object also works, ?? prints more."
633 645 if opts_all.profile and not profile_handled_by_legacy:
634 646 profmodname = 'ipy_profile_' + opts_all.profile
635 647 try:
636 __import__(profmodname)
648
649 force_import(profmodname)
637 650 except:
638 651 IP.InteractiveTB()
639 652 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
640 653 import_fail_info(profmodname)
641 654 else:
642 import ipy_profile_none
643 try:
644 import ipy_user_conf
655 force_import('ipy_profile_none')
656 try:
657
658 force_import('ipy_user_conf')
645 659
646 660 except:
647 661 conf = opts_all.ipythondir + "/ipy_user_conf.py"
@@ -23,12 +23,17 b' __license__ = Release.license'
23 23 import sys
24 24 import os
25 25
26 ignore_termtitle = False
26 27
27 28 def _dummy_op(*a, **b):
28 29 """ A no-op function """
29 30
30 31 def _set_term_title_xterm(title):
31 32 """ Change virtual terminal title in xterm-workalikes """
33
34 if ignore_termtitle:
35 return
36
32 37 sys.stdout.write('\033]%d;%s\007' % (0,title))
33 38
34 39
@@ -37,4 +42,6 b" if os.environ.get('TERM','') == 'xterm':"
37 42 else:
38 43 set_term_title = _dummy_op
39 44
40
45 def freeze_term_title():
46 global ignore_termtitle
47 ignore_termtitle = True
@@ -50,4 +50,7 b' def set_term_title(title):'
50 50 return
51 51 _set_term_title(title)
52 52
53 def freeze_term_title():
54 global ignore_termtitle
55 ignore_termtitle = 1
53 56
@@ -377,8 +377,8 b' class ListTB(TBTools):'
377 377
378 378 def __call__(self, etype, value, elist):
379 379 Term.cout.flush()
380 Term.cerr.flush()
381 380 print >> Term.cerr, self.text(etype,value,elist)
381 Term.cerr.flush()
382 382
383 383 def text(self,etype, value, elist,context=5):
384 384 """Return a color formatted string with the traceback info."""
@@ -855,8 +855,8 b' class VerboseTB(TBTools):'
855 855 (etype, evalue, etb) = info or sys.exc_info()
856 856 self.tb = etb
857 857 Term.cout.flush()
858 Term.cerr.flush()
859 858 print >> Term.cerr, self.text(etype, evalue, etb)
859 Term.cerr.flush()
860 860
861 861 # Changed so an instance can just be called as VerboseTB_inst() and print
862 862 # out the right info on its own.
@@ -977,13 +977,13 b' class AutoFormattedTB(FormattedTB):'
977 977 if out is None:
978 978 out = Term.cerr
979 979 Term.cout.flush()
980 out.flush()
981 980 if tb_offset is not None:
982 981 tb_offset, self.tb_offset = self.tb_offset, tb_offset
983 982 print >> out, self.text(etype, evalue, etb)
984 983 self.tb_offset = tb_offset
985 984 else:
986 985 print >> out, self.text(etype, evalue, etb)
986 out.flush()
987 987 try:
988 988 self.debugger()
989 989 except KeyboardInterrupt:
@@ -9,22 +9,23 b' graft setupext'
9 9 graft IPython/UserConfig
10 10
11 11 graft doc
12 exclude doc/\#*
12 13 exclude doc/*.1
13 exclude doc/manual_base*
14 14 exclude doc/ChangeLog.*
15 exclude doc/\#*
16 exclude doc/update_magic.sh
17 15 exclude doc/update_version.sh
18 exclude doc/manual_base*
19 exclude doc/manual/WARNINGS
20 exclude doc/manual/*.aux
21 exclude doc/manual/*.log
22 exclude doc/manual/*.out
23 exclude doc/manual/*.pl
24 exclude doc/manual/*.tex
16
17 # There seems to be no way of excluding whole subdirectories, other than
18 # manually excluding all their subdirs. distutils really is horrible...
19 exclude doc/attic/*
20 exclude doc/build/doctrees/*
21 exclude doc/build/html/_sources/*
22 exclude doc/build/html/_static/*
23 exclude doc/build/html/*
24 exclude doc/build/latex/*
25 25
26 26 global-exclude *~
27 27 global-exclude *.flc
28 28 global-exclude *.pyc
29 29 global-exclude .dircopy.log
30 30 global-exclude .svn
31 global-exclude .bzr
@@ -1,8 +1,330 b''
1 ipython (0.8.1-2) unstable; urgency=low
2
3 [ Piotr Ożarowski ]
4 * Homepage field added
5 * Rename XS-Vcs-* fields to Vcs-* (dpkg supports them now)
6 * Add 04_remove_shebang patch
7 * Removing lintian overrides, adding proper patches instead.
8
9 [ Bernd Zeimetz ]
10 * Replacing Recommends by Suggests to stop ipython from installing ~500MB
11 of dependencies. Thanks to Marcela Tiznado (Closes: #451887).
12
13 -- Bernd Zeimetz <bernd@bzed.de> Mon, 19 Nov 2007 19:10:14 +0100
14
15 ipython (0.8.1-1) unstable; urgency=low
16
17 [ Bernd Zeimetz ]
18 * debian/control:
19 - adding python-matplotlib to Recommends because
20 it is needed to run ipython -pylab
21
22 [ Norbert Tretkowski ]
23 * New upstream release. (closes: #428398)
24
25 [ Reinhard Tartler ]
26 * Install ipython.el properly.
27
28 -- Norbert Tretkowski <nobse@debian.org> Mon, 11 Jun 2007 20:05:30 +0200
29
30 ipython (0.8.0-2) unstable; urgency=low
31
32 * debian/changelog:
33 - adding missing colons to Closes entries to fix two
34 lintian warnings
35 * debian/compat:
36 - bumping compat level to 5
37 * debian/control:
38 - adding XS-Vcs-Browser
39 - remove no longer needed X*-Python-Version fields
40 - moving python-pexpect from Recommends to Depends because
41 /usr/bin/irunner is not useable without it
42 - moving debhelper and dpatch from Build-Depends-Indep to
43 Build-Depends, fixing the following lintian errors:
44 - clean-should-be-satisfied-by-build-depends debhelper
45 - clean-should-be-satisfied-by-build-depends dpatch
46 - removing unnecessary Build-Depends-Indep on python-all-dev,
47 adding python to Build-Depends instead
48 - replacing python-central by python-support to be able to
49 fix #420134 without hassle
50 - adding ${misc:Depends}
51 - adding the missing identation for Homepage:
52 - adding cdbs as Build-Depends
53 - adding myself to Uploaders
54 - removing the short description from the long description
55 * debian/patches/03_ipy_gnuglobal.dpatch:
56 - fix the location of the global binary - we're not on windows
57 * debian/rules:
58 - removing old crust, using cdbs to make things clear again
59 - using python-support instead of python-central to make
60 modules for 2.5 avaiable now. (Closes: #420134)
61 - making sure the bogus /usr/IPython directory is not
62 included in the package again
63 - do not remove docs/ipython.el (Closes: #198505, #415427)
64 * adding lintian ovverrides for several scripts included in the
65 IPython/Extensions directory.
66 * adding a manpage for /usr/bin/irunner
67
68 -- Bernd Zeimetz <bernd@bzed.de> Tue, 24 Apr 2007 02:47:26 +0200
69
70 ipython (0.8.0-1) unstable; urgency=low
71
72 * New upstream release. (closes: #419716)
73 * Removed patches merged upstream.
74
75 -- Norbert Tretkowski <nobse@debian.org> Tue, 17 Apr 2007 20:26:43 +0200
76
77 ipython (0.7.3-2) unstable; urgency=low
78
79 * Added a new patch from svn to fix jobctrl to work properly on posix.
80
81 -- Norbert Tretkowski <nobse@debian.org> Thu, 21 Dec 2006 20:13:57 +0100
82
83 ipython (0.7.3-1) unstable; urgency=low
84
85 * New upstream release.
86
87 -- Norbert Tretkowski <nobse@debian.org> Mon, 18 Dec 2006 22:23:55 +0100
88
89 ipython (0.7.3~rc2-1) experimental; urgency=low
90
91 * New upstream release candidate.
92
93 -- Norbert Tretkowski <nobse@debian.org> Sat, 16 Dec 2006 02:20:13 +0100
94
95 ipython (0.7.3~beta2-1) experimental; urgency=low
96
97 * New upstream beta release.
98
99 -- Norbert Tretkowski <nobse@debian.org> Fri, 8 Dec 2006 08:02:16 +0100
100
101 ipython (0.7.3~beta1-1) experimental; urgency=low
102
103 * New upstream beta release.
104 * Removed backported patch added in 0.7.2-5 to workaround bugs in python
105 2.3's inspect module.
106
107 -- Norbert Tretkowski <nobse@debian.org> Wed, 29 Nov 2006 12:35:22 +0100
108
109 ipython (0.7.2-6) UNRELEASED; urgency=low
110
111 * Added XS-Vcs-Svn field.
112
113 -- Piotr Ozarowski <ozarow@gmail.com> Thu, 23 Nov 2006 14:44:43 +0100
114
115 ipython (0.7.2-5) unstable; urgency=low
116
117 * Added a new patch from svn to workaround bugs in python 2.3's inspect
118 module. (closes: #374625)
119
120 -- Norbert Tretkowski <nobse@debian.org> Thu, 10 Aug 2006 18:36:12 +0200
121
122 ipython (0.7.2-4) unstable; urgency=low
123
124 * Fixed spelling error in description. (closes: #363976)
125 * Ack NMU 0.7.2-3.1, thanks Matthias. (closes: #377787)
126
127 -- Norbert Tretkowski <nobse@debian.org> Tue, 1 Aug 2006 22:45:11 +0200
128
129 ipython (0.7.2-3.1) unstable; urgency=medium
130
131 * NMU.
132 * Convert to updated Python policy. (closes: #377787)
133
134 -- Matthias Klose <doko@debian.org> Thu, 13 Jul 2006 17:42:06 +0000
135
136 ipython (0.7.2-3ubuntu1) edgy; urgency=low
137
138 * Synchronize with Debian unstable.
139 * Convert to updated Python policy. Collapse all packages into one
140 ipython package, don't handle ipython using alternatives.
141
142 -- Matthias Klose <doko@ubuntu.com> Tue, 11 Jul 2006 09:47:37 +0000
143
144 ipython (0.7.2-3) unstable; urgency=low
145
146 * Removed alternative for irunner manpage.
147
148 -- Norbert Tretkowski <nobse@debian.org> Sat, 17 Jun 2006 09:49:10 +0200
149
150 ipython (0.7.2-2) unstable; urgency=medium
151
152 * Fixed conflict in irunner. (closes: #373874)
153 * Added recommendation for python-pexpect. (closes: #373794)
154
155 -- Norbert Tretkowski <nobse@debian.org> Fri, 16 Jun 2006 10:43:45 +0200
156
157 ipython (0.7.2-1) unstable; urgency=low
158
159 [ Piotr Ozarowski ]
160 * Added watch file.
161
162 [ Norbert Tretkowski ]
163 * New upstream release.
164
165 -- Norbert Tretkowski <nobse@debian.org> Thu, 8 Jun 2006 23:36:03 +0200
166
167 ipython (0.7.1.fix1+0.7.2.rc1-1) experimental; urgency=low
168
169 * New upstream release candidate.
170 * Updated Standards-Version to 3.7.2.0, no changes required.
171
172 -- Norbert Tretkowski <nobse@debian.org> Sat, 27 May 2006 14:49:24 +0200
173
174 ipython (0.7.1.fix1-2) unstable; urgency=low
175
176 * Set maintainer to Debian Python modules team and added myself to
177 uploaders.
178
179 -- Norbert Tretkowski <nobse@debian.org> Sun, 16 Apr 2006 15:53:43 +0200
180
181 ipython (0.7.1.fix1-1) unstable; urgency=low
182
183 * New upstream bugfix release.
184 * Removed backported patch which was added in 0.7.1-3 to catch
185 KeyboardInterrupt exceptions properly, it's part of this release.
186 * Fixed names of pdfs in doc-base file to shut up linda.
187
188 -- Norbert Tretkowski <nobse@debian.org> Tue, 14 Feb 2006 23:51:17 +0100
189
190 ipython (0.7.1-3) unstable; urgency=low
191
192 * Added a new patch from upstream to catch KeyboardInterrupt exceptions
193 properly.
194
195 -- Norbert Tretkowski <nobse@debian.org> Mon, 30 Jan 2006 19:42:31 +0100
196
197 ipython (0.7.1-2) unstable; urgency=low
198
199 * Really remove alternatives on purge, thanks Lars Wirzenius for finding
200 the problem. (closes: #317269)
201
202 -- Norbert Tretkowski <nobse@debian.org> Sun, 29 Jan 2006 23:11:28 +0100
203
204 ipython (0.7.1-1) unstable; urgency=low
205
206 * New upstream release.
207
208 -- Norbert Tretkowski <nobse@debian.org> Tue, 24 Jan 2006 21:42:33 +0100
209
210 ipython (0.7.0-2) unstable; urgency=low
211
212 * Fixed circular dependencies (closes: #341980)
213 * Added version to dependency on ipython dummy package. (closes: #320235)
214 * Removed python2.2 package, ipython now depends on python >= 2.3.
215 * Bumped up standards-version, no changes needed.
216
217 -- Norbert Tretkowski <nobse@debian.org> Sat, 21 Jan 2006 23:27:53 +0100
218
219 ipython (0.7.0-1) unstable; urgency=low
220
221 * New upstream release.
222 * Updated 01_docdir-base.dpatch and 02_profiler-message.dpatch.
223
224 -- Norbert Tretkowski <nobse@debian.org> Sat, 21 Jan 2006 20:08:23 +0100
225
226 ipython (0.6.15-2) unstable; urgency=low
227
228 * New maintainer, thanks Jack for your work.
229
230 -- Norbert Tretkowski <nobse@debian.org> Sun, 28 Aug 2005 19:57:09 +0200
231
232 ipython (0.6.15-1) unstable; urgency=low
233
234 * New upstream release.
235
236 -- Norbert Tretkowski <nobse@debian.org> Thu, 2 Jun 2005 23:51:45 +0200
237
238 ipython (0.6.14-1) unstable; urgency=low
239
240 * New upstream release.
241
242 -- Norbert Tretkowski <nobse@debian.org> Tue, 31 May 2005 22:53:25 +0200
243
244 ipython (0.6.13-1) unstable; urgency=low
245
246 * New upstream release.
247 * Removed backported patch which was added in 0.6.12-3 to fix misleading
248 prompt, it's part of this release.
249
250 -- Norbert Tretkowski <nobse@debian.org> Fri, 15 Apr 2005 09:42:35 +0200
251
252 ipython (0.6.12-4) unstable; urgency=medium
253
254 * Re-added python build-dependency, it got lost in 0.6.12-2.
255 (closes: #301636)
256
257 -- Norbert Tretkowski <nobse@debian.org> Sun, 27 Mar 2005 14:28:26 +0200
258
259 ipython (0.6.12-3) unstable; urgency=low
260
261 * Added a new patch from cvs to fix misleading prompt2. (closes: #300847)
262
263 -- Norbert Tretkowski <nobse@debian.org> Sun, 27 Mar 2005 00:05:26 +0100
264
265 ipython (0.6.12-2) unstable; urgency=low
266
267 * Added packages for python2.2 and python2.4, ipython package is now a dummy
268 package depending on ipython built for Debians default python.
269 (closes: #292537)
270 * Split out generic files into separate ipython-common package.
271 * Enhanced package descriptions.
272 * Removed CFLAGS settings from debian/rules, not required.
273 * Tweaked message displayed when profiler support is missing.
274 * Suggest the python-profiler package.
275
276 -- Norbert Tretkowski <nobse@debian.org> Fri, 25 Mar 2005 20:24:36 +0100
277
278 ipython (0.6.12-1) unstable; urgency=low
279
280 * New upstream release.
281 * Removed patch which was added in 0.6.5-1.1 to make profiling support
282 optional, it was merged upstream.
283
284 -- Norbert Tretkowski <nobse@debian.org> Wed, 2 Mar 2005 12:15:09 +0100
285
286 ipython (0.6.11-1) unstable; urgency=low
287
288 * New upstream release.
289 + Fixed broken profiling support unless -D is specified. (closes: #295779)
290 * Acknowledged NMUs. (closes: #206653, #294500, #294861, #280505)
291 * New co-maintainer, added myself to uploaders.
292
293 -- Norbert Tretkowski <nobse@debian.org> Tue, 1 Mar 2005 12:40:33 +0100
294
295 ipython (0.6.5-1.2) unstable; urgency=low
296
297 * Non-maintainer upload.
298 * Rebuild with a python version that is actually in Debian.
299
300 -- Wichert Akkerman <wichert@wiggy.net> Thu, 17 Feb 2005 23:08:52 +0100
301
302 ipython (0.6.5-1.1) unstable; urgency=low
303
304 * NMU to apply patch making profiling support optional (provided by
305 Torsten Marek). (closes: #294500)
306
307 -- Steven R. Baker <srbaker@debian.org> Thu, 17 Feb 2005 05:02:55 -0400
308
309 ipython (0.6.5-1) unstable; urgency=low
310
311 * New upstream release
312
313 -- Jack Moffitt <jack@xiph.org> Thu, 2 Dec 2004 15:49:27 -0700
314
315 ipython (0.6.4-1.1) unstable; urgency=low
316
317 * NMU from BSP Frankfurt:
318 - Added Build-Depends on dpatch (Closes: #280505)
319
320 -- Joerg Jaspert <joerg@debian.org> Sat, 27 Nov 2004 18:28:17 +0100
321
1 322 ipython (0.6.4-1) unstable; urgency=low
2 323
3 * Fix dpatch dependency (Closes: #280505)
324 * New upstream release
325 * Updated debian/rules to use dpatch and added debian/patches/*
4 326
5 -- Fernando Perez <fperez@colorado.edu> Wed Nov 17 22:54:23 MST 2004
327 -- Jack Moffitt <jack@xiph.org> Tue, 9 Nov 2004 10:38:51 -0700
6 328
7 329 ipython (0.6.3-1) unstable; urgency=low
8 330
@@ -27,8 +349,8 b' ipython (0.4.0-1.1) unstable; urgency=low'
27 349
28 350 ipython (0.4.0-1) unstable; urgency=low
29 351
30 * New upstream release (Closes #195215)
31 * Updated Build-Depends (Closes #200021)
352 * New upstream release (Closes: #195215)
353 * Updated Build-Depends (Closes: #200021)
32 354
33 355 -- Jack Moffitt <jack@xiph.org> Fri, 25 Jul 2003 10:16:12 -0600
34 356
@@ -1,1 +1,1 b''
1 4
1 5
@@ -1,21 +1,26 b''
1 1 Source: ipython
2 Section: devel
2 Section: python
3 3 Priority: optional
4 Maintainer: Jack Moffitt <jack@xiph.org>
5 Build-Depends-Indep: debhelper (>> 4.1.65), dpatch, python-dev
6 Standards-Version: 3.6.1
4 Maintainer: Debian Python Modules Team <python-modules-team@lists.alioth.debian.org>
5 Uploaders: Norbert Tretkowski <nobse@debian.org>, Bernd Zeimetz <bernd@bzed.de>
6 Build-Depends: debhelper (>= 5.0.37.2), dpatch (>= 2.0.10), cdbs (>= 0.4.43), python, python-support (>= 0.4)
7 Homepage: http://ipython.scipy.org/
8 Vcs-Svn: svn://svn.debian.org/python-modules/packages/ipython/trunk/
9 Vcs-Browser: http://svn.debian.org/wsvn/python-modules/packages/ipython/trunk/
10 Standards-Version: 3.7.2.2
7 11
8 12 Package: ipython
9 13 Architecture: all
10 Depends: ${python:Depends}
11 Recommends: python-numeric, python-numeric-ext
12 Description: An enhanced interactive Python shell
13 IPython is an enhanced interactive Python shell. It can be used as a
14 replacement for the standard Python shell, or it can be used as a
15 complete working environment for scientific computing (like Matlab or
16 Mathematica) when paired with the standard Python scientific and
17 numerical tools. It supports dynamic object introspections, numbered
18 input/output prompts, a macro system, session logging, session
19 restoring, complete system shell access, verbose and colored
20 traceback reports, auto-parentheses, auto-quoting, and is
21 embeddedable in other Python programs.
14 Depends: ${python:Depends}, ${misc:Depends}, python-pexpect
15 Conflicts: python2.3-ipython, python2.4-ipython, ipython-common
16 Replaces: python2.3-ipython, python2.4-ipython, ipython-common
17 Suggests: python-profiler, python-numeric, python-numeric-ext, python-matplotlib
18 Description: enhanced interactive Python shell
19 IPython can be used as a replacement for the standard Python shell,
20 or it can be used as a complete working environment for scientific
21 computing (like Matlab or Mathematica) when paired with the standard
22 Python scientific and numerical tools. It supports dynamic object
23 introspections, numbered input/output prompts, a macro system,
24 session logging, session restoring, complete system shell access,
25 verbose and colored traceback reports, auto-parentheses, auto-quoting,
26 and is embeddable in other Python programs.
@@ -4,51 +4,15 b' Wed, 12 Mar 2003 20:38:14 -0700.'
4 4 It was downloaded from http://ipython.scipy.org/
5 5
6 6 Upstream Author: Fernando Perez <fperez@colorado.edu>,
7 Janko Hauser <jhauser@zscout.de>,
7 Janko Hauser <jhauser@ifm.uni-kiel.de>,
8 8 Nathaniel Gray <n8gray@caltech.edu>
9 9
10 10 Copyright:
11 11
12 Most IPython code is copyright (C) 2001-2004 by Fernando Perez, Janko Hauser,
13 and Nathaniel Gray. All code is licensed under a BSD-type License except as
14 explicitly mentioned below. The full IPython license is:
15
16 IPython is released under a BSD-type license.
17
18 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
19
20 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
21 <n8gray@caltech.edu>.
22
23 All rights reserved.
24
25 Redistribution and use in source and binary forms, with or without
26 modification, are permitted provided that the following conditions are met:
27
28 a. Redistributions of source code must retain the above copyright notice,
29 this list of conditions and the following disclaimer.
30
31 b. Redistributions in binary form must reproduce the above copyright
32 notice, this list of conditions and the following disclaimer in the
33 documentation and/or other materials provided with the distribution.
34
35 c. Neither the name of the copyright holders nor the names of any
36 contributors to this software may be used to endorse or promote products
37 derived from this software without specific prior written permission.
38
39
40 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
44 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
46 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
47 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
50 DAMAGE.
51
12 Most IPython code is copyright (C) 2001 by Fernando Perez, Janko
13 Hauser, and Nathaniel Gray. All code is licensed under the GNU Lesser
14 General Public License (LGPL) except as explicitly mentioned below.
15 Its full text is included in the file /usr/share/common-licenses/LGPL.
52 16
53 17 DPyGetOpt.py is copyright (C) 2001 by Bill Bumgarner <bbum@friday.com>
54 18 and is licensed under the MIT license, reproduced below:
@@ -1,98 +1,25 b''
1 1 #!/usr/bin/make -f
2 # Sample debian/rules that uses debhelper.
3 # GNU copyright 1997 to 1999 by Joey Hess.
4
5 # Uncomment this to turn on verbose mode.
6 #export DH_VERBOSE=1
7
8
9
10
11 CFLAGS = -Wall -g
12
13 ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
14 CFLAGS += -O0
15 else
16 CFLAGS += -O2
17 endif
18 ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
19 INSTALL_PROGRAM += -s
20 endif
21
22 configure: configure-stamp
23 configure-stamp:
24 dh_testdir
25
26 python setup.py config
27
28 touch configure-stamp
29
30
31 build: build-stamp
32
33 build-stamp: configure-stamp
34 dh_testdir
35
36 python setup.py build
37
38 touch build-stamp
39
40 clean:
41 dh_testdir
42 dh_testroot
43 rm -f build-stamp configure-stamp
44
45 -python setup.py clean --all
46 rm -f setupext/*.pyc
47
48 dh_clean
49
50 install: build
51 dh_testdir
52 dh_testroot
53 dh_clean -k
54 dh_installdirs
55
56 python setup.py install --prefix $(CURDIR)/debian/ipython/usr
57
58 # remove extra license docs that get installed
59 rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/COPYING
60 #rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/GNU-LGPL
61
2 # ipython debian/rules file
3 DEB_PYTHON_SYSTEM=pysupport
4 include /usr/share/cdbs/1/rules/debhelper.mk
5 include /usr/share/cdbs/1/class/python-distutils.mk
6 include /usr/share/cdbs/1/rules/dpatch.mk
7
8 install/ipython::
9 # remove documentation
10 rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/COPYING
11 rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/ChangeLog
12 rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/README_Windows.txt
13 rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/pycon.ico
14
62 15 # change permission on scripts
63 chmod 755 $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/example-embed.py
64 chmod 755 $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/example-gnuplot.py
65
66 binary-indep: build install
67 dh_testdir
68 dh_testroot
69 dh_installchangelogs doc/ChangeLog
70 dh_installdocs
71 # dh_installexamples
72 dh_install
73 # dh_installmenu
74 # dh_installdebconf
75 # dh_installlogrotate
76 # dh_installemacsen
77 # dh_installpam
78 # dh_installmime
79 # dh_installinit
80 # dh_installcron
81 # dh_installinfo
82 dh_installman doc/ipython.1.gz doc/pycolor.1.gz
83 dh_compress
84 dh_fixperms
85 dh_python
86 # dh_makeshlibs
87 dh_installdeb
88 # dh_shlibdeps
89 dh_gencontrol
90 dh_md5sums
91 dh_builddeb
92
93 # Build architecture-dependent files here.
94 binary-arch: build install
95 # We have nothing to do by default.
96
97 binary: binary-indep binary-arch
98 .PHONY: build clean binary-indep binary-arch binary install configure
16 chmod a-x $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/*
17
18 # removing bogus usr/IPython directory
19 rm -rf $(CURDIR)/debian/ipython/usr/IPython
20
21 binary-fixup/ipython::
22 # fix lintian warnings (see also patches/04_remove_shebang.dpatch)
23 chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/upgrade_dir.py
24 chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/Extensions/pickleshare.py
25 chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/irunner.py
@@ -1,11 +1,232 b''
1 2008-05-31 *** Released version 0.8.4
2
3 2008-05-31 Fernando Perez <Fernando.Perez@berkeley.edu>
4
5 * IPython/ipmaker.py (make_IPython): The -twisted option is fully
6 disabled.
7
8 * IPython/Shell.py (_select_shell): completely disable -twisted.
9 This code is of dubious quality and normal users should not
10 encounter it until we can clarify things further, even under
11 win32. Since we need a quick emergency 0.8.4 release, it is now
12 disabled completely. Users who want to run it can use the
13 following command (it's easy to put it in an alias or script):
14
15 python -c"from IPython import twshell;twshell.IPShellTwisted().mainloop()"
16
17 2008-05-30 Ville Vainio <vivainio@gmail.com>
18
19 * shell.py: disable -twisted on non-win32 platforms.
20 import sets module on python 2.3.
21
22 * ipy_profile_sh.py: disable ipy_signals. Now, ipython
23 is verified to work with python 2.3
24
25 * Release.py: update version to 0.8.4 for quick point fix
26
27 2008-05-28 *** Released version 0.8.3
28
29 2008-05-28 Fernando Perez <Fernando.Perez@berkeley.edu>
30
31 * ../win32_manual_post_install.py (run): Fix the windows installer
32 so the links to the docs are correct.
33
34 * IPython/ultraTB.py: flush stderr after writing to it to fix
35 problems with exception traceback ordering in some platforms.
36 Thanks to a report/fix by Jie Tang <jietang86-AT-gmail.com>.
37
38 * IPython/Magic.py (magic_cpaste): add stripping of continuation
39 prompts, feature requested by Stefan vdW.
40
41 * ../setup.py: updates to build and release tools in preparation
42 for 0.8.3 release.
43
44 2008-05-27 Ville Vainio <vivainio@gmail.com>
45
46 * iplib.py, ipmaker.py: survive lack of doctest and site._Helper
47 for minimal environments (e.g. Maemo sdk python)
48
49 * Magic.py: cpaste strips whitespace before >>> (allow pasting
50 doctests)
51
52 * ipy_completers.py: cd completer now does recursive path expand
53 (old behaviour is buggy on some readline versions)
54
55 2008-05-14 Ville Vainio <vivainio@gmail.com>
56
57 * Extensions/ipy_greedycompleter.py:
58 New extension that enables a bit more "relaxed" tab
59 completer that evaluates code without safety checks
60 (i.e. there can be side effects like function calls)
61
62 2008-04-20 Ville Vainio <vivainio@gmail.com>
63
64 * Extensions/ipy_lookfor.py: add %lookfor magic command
65 (search docstrings for words) by Pauli Virtanen. Close #245.
66
67 * Extension/ipy_jot.py: %jot and %read magics, analogous
68 to %store but you can specify some notes. Not read
69 in automatically on startup, you need %read.
70 Contributed by Yichun Wei.
71
72 2008-04-18 Fernando Perez <Fernando.Perez@berkeley.edu>
73
74 * IPython/genutils.py (page): apply workaround to curses bug that
75 can leave terminal corrupted after a call to initscr().
76
77 2008-04-15 Ville Vainio <vivainio@gmail.com>
78
79 * genutils.py: SList.grep supports 'field' argument
80
81 * ipy_completers.py: module completer looks inside
82 .egg zip files (patch by mc). Close #196.
83
84 2008-04-09 Ville Vainio <vivainio@gmail.com>
85
86 * deep_reload.py: do not crash on from __future__ import
87 absolute_import. Close #244.
88
89 2008-04-02 Ville Vainio <vivainio@gmail.com>
90
91 * ipy_winpdb.py: New extension for winpdb integration. %wdb
92 test.py is winpdb equivalent of %run -d test.py. winpdb is a
93 crossplatform remote GUI debugger based on wxpython.
94
95 2008-03-29 Ville Vainio <vivainio@gmail.com>
96
97 * ipython.rst, do_sphinx.py: New documentation base, based on
98 reStucturedText and Sphinx (html/pdf generation). The old Lyx
99 based documentation will not be updated anymore.
100
101 * jobctrl.py: Use shell in Popen for 'start' command (in windows).
102
103 2008-03-24 Ville Vainio <vivainio@gmail.com>
104
105 * ipython.rst, do_sphinx.py: New documentation base, based on
106 reStucturedText and Sphinx (html/pdf generation). The old Lyx
107 based documentation will not be updated anymore.
108
109 ipython.rst has up to date documentation on matters that were not
110 documented at all, and it also removes various
111 misdocumented/deprecated features.
112
113 2008-03-22 Ville Vainio <vivainio@gmail.com>
114
115 * Shell.py: Merge mtexp branch:
116 https://code.launchpad.net/~ipython/ipython/mtexp
117
118 Privides simpler and more robust MTInteractiveShell that won't
119 deadlock, even when the worker thread (GUI) stops doing runcode()
120 regularly. r71.
121
122 2008-03-20 Ville Vainio <vivainio@gmail.com>
123
124 * twshell.py: New shell that runs IPython code in Twisted reactor.
125 Launch by doing ipython -twisted. r67.
126
127 2008-03-19 Ville Vainio <vivainio@gmail.com>
128
129 * Magic.py: %rehashx works correctly when shadowed system commands
130 have upper case characters (e.g. Print.exe). r64.
131
132 * ipy_bzr.py, ipy_app_completers.py: new bzr completer that also
133 knows options to commands, based on bzrtools. Uses bzrlib
134 directly. r66.
135
136 2008-03-16 Ville Vainio <vivainio@gmail.com>
137
138 * make_tarball.py: Fixed for bzr.
139
140 * ipapi.py: Better _ip.runlines() script cleanup. r56,r79.
141
142 * ipy_vimserver.py, ipy.vim: New extension for vim server mode,
143 by Erich Heine.
144
145 2008-03-12 Ville Vainio <vivainio@gmail.com>
146
147 * ipmaker.py: Force (reload?) import of ipy_user_conf and
148 ipy_profile_foo, so that embedded instances can be relaunched and
149 configuration is still done. r50
150
151 * ipapi.py, test_embed.py: Allow specifying shell class in
152 launch_new_instance & make_new instance. Use this in
153 test_embed.py. r51.
154
155 test_embed.py is also a good and simple demo of embedding IPython.
156
157
158 2008-03-10 Ville Vainio <vivainio@gmail.com>
159
160 * tool/update_revnum.py: Change to bzr revisioning scheme in
161 revision numbers.
162
163 * Shell.py: Threading improvements:
164
165 In multithreaded shells, do not hang on macros and o.autoexec
166 commands (or anything executed with _ip.runlines()) anymore. Allow
167 recursive execution of IPython code in
168 MTInteractiveShell.runsource by checking if we are already in
169 worker thread, and execute code directly if we are. r48.
170
171 MTInteractiveShell.runsource: execute code directly if worker
172 thread is not running yet (this is the case in config files). r49.
173
174 2008-03-09 Ville Vainio <vivainio@gmail.com>
175
176 * ipy_profile_sh.py: You can now use $LA or LA() to refer to last
177 argument of previous command in sh profile. Similar to bash '!$'.
178 LA(3) or $LA(3) stands for last argument of input history command
179 3.
180
181 * Shell.py: -pylab names don't clutter %whos listing.
182
183 2008-03-07 Ville Vainio <vivainio@gmail.com>
184
185 * ipy_autoreload.py: new extension (by Pauli Virtanen) for
186 autoreloading modules; try %autoreload and %aimport. Close #154.
187 Uses the new pre_runcode_hook.
188
189 2008-02-24 Ville Vainio <vivainio@gmail.com>
190
191 * platutils_posix.py: freeze_term_title works
192
193 2008-02-21 Ville Vainio <vivainio@gmail.com>
194
195 * Magic.py: %quickref does not crash with empty docstring
196
197 2008-02-20 Ville Vainio <vivainio@gmail.com>
198
199 * completer.py: do not treat [](){} as protectable chars anymore,
200 close #233.
201
202 * completer.py: do not treat [](){} as protectable chars anymore
203
204 * magic.py, test_cpaste.py: Allow different prefix for pasting
205 from email
206
207 2008-02-17 Ville Vainio <vivainio@gmail.com>
208
209 * Switched over to Launchpad/bzr as primary VCS.
210
211 2008-02-14 Ville Vainio <vivainio@gmail.com>
212
213 * ipapi.py: _ip.runlines() is now much more liberal about
214 indentation - it cleans up the scripts it gets
215
216 2008-02-14 Ville Vainio <vivainio@gmail.com>
217
218 * Extensions/ipy_leo.py: created 'ILeo' IPython-Leo bridge.
219 Changes to it (later on) are too numerous to list in ChangeLog
220 until it stabilizes
221
1 222 2008-02-07 Darren Dale <darren.dale@cornell.edu>
2 223
3 * IPython/Shell.py: Call QtCore.pyqtRemoveInputHook() when creating
4 an IPShellQt4. PyQt4-4.2.1 and later uses PyOS_InputHook to improve
5 interaction in the interpreter (like Tkinter does), but it seems to
6 partially interfere with the IPython implementation and exec_()
7 still seems to block. So we disable the PyQt implementation and
8 stick with the IPython one for now.
224 * IPython/Shell.py: Call QtCore.pyqtRemoveInputHook() when creating
225 an IPShellQt4. PyQt4-4.2.1 and later uses PyOS_InputHook to improve
226 interaction in the interpreter (like Tkinter does), but it seems to
227 partially interfere with the IPython implementation and exec_()
228 still seems to block. So we disable the PyQt implementation and
229 stick with the IPython one for now.
9 230
10 231 2008-02-02 Walter Doerwald <walter@livinglogic.de>
11 232
1 NO CONTENT: file renamed from doc/ipnb_google_soc.lyx to doc/attic/ipnb_google_soc.lyx
1 NO CONTENT: file renamed from doc/nbexample.py to doc/attic/nbexample.py
1 NO CONTENT: file renamed from doc/nbexample_latex.py to doc/attic/nbexample_latex.py
1 NO CONTENT: file renamed from doc/nbexample_output.py to doc/attic/nbexample_output.py
1 NO CONTENT: file renamed from doc/new_design.lyx to doc/attic/new_design.lyx
@@ -1,20 +1,20 b''
1 # -*- coding: utf-8 -*-
2
3 import IPython.ipapi
4 ip = IPython.ipapi.get()
5
6 def ${name}_f(self, arg):
7 r""" Short explanation
8
9 Long explanation, examples
10
11 """
12
13 # opts,args = self.parse_options(arg,'rx')
14 # if 'r' in opts: pass
15
16
17
18 ip.expose_magic("${name}",${name}_f)
19
20
1 # -*- coding: utf-8 -*-
2
3 import IPython.ipapi
4 ip = IPython.ipapi.get()
5
6 def ${name}_f(self, arg):
7 r""" Short explanation
8
9 Long explanation, examples
10
11 """
12
13 # opts,args = self.parse_options(arg,'rx')
14 # if 'r' in opts: pass
15
16
17
18 ip.expose_magic("${name}",${name}_f)
19
20
@@ -1,6 +1,6 b''
1 Windows Registry Editor Version 5.00
2
3 [HKEY_CLASSES_ROOT\Directory\shell\IPython here]
4
5 [HKEY_CLASSES_ROOT\Directory\shell\IPython here\Command]
1 Windows Registry Editor Version 5.00
2
3 [HKEY_CLASSES_ROOT\Directory\shell\IPython here]
4
5 [HKEY_CLASSES_ROOT\Directory\shell\IPython here\Command]
6 6 @="cmd.exe /C ipython.py -p sh -i -c \"%cd %1\"" No newline at end of file
@@ -36,11 +36,11 b' The following special options are ONLY valid at the beginning of the command'
36 36 line, and not later. This is because they control the initialization of
37 37 ipython itself, before the normal option-handling mechanism is active.
38 38 .TP
39 .B \-gthread, \-qthread, \-q4thread, \-wthread, \-pylab
39 .B \-gthread, \-qthread, \-q4thread, \-wthread, \-pylab, \-twisted
40 40 Only ONE of these can be given, and it can only be given as the first option
41 41 passed to IPython (it will have no effect in any other position). They provide
42 threading support for the GTK, QT3, QT4 and WXWidgets toolkits, and for the
43 matplotlib library.
42 threading support for the GTK, QT3, QT4 and WXWidgets toolkits, for the
43 matplotlib library and Twisted reactor.
44 44 .br
45 45 .sp 1
46 46 With any of the first four options, IPython starts running a separate thread
@@ -56,6 +56,10 b' request a specific version of wx to be used. This requires that you have the'
56 56 distributions.
57 57 .br
58 58 .sp 1
59 If \-twisted is given, IPython start a Twisted reactor and runs IPython mainloop
60 in a dedicated thread, passing commands to be run inside the Twisted reactor.
61 .br
62 .sp 1
59 63 If \-pylab is given, IPython loads special support for the matplotlib library
60 64 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
61 65 backends as defined in the user's .matplotlibrc file. It automatically
1 NO CONTENT: modified file, binary diff hidden
@@ -1,106 +1,106 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 r"""Setup script for exe distribution of IPython (does not require python).
4
5 - Requires py2exe
6
7 - install pyreadline *package dir* in ipython root directory by running:
8
9 svn co http://ipython.scipy.org/svn/ipython/pyreadline/branches/maintenance_1.3/pyreadline/
10 wget http://ipython.scipy.org/svn/ipython/pyreadline/branches/maintenance_1.3/readline.py
11
12 OR (if you want the latest trunk):
13
14 svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk/pyreadline
15
16 - Create the distribution in 'dist' by running "python exesetup.py py2exe"
17
18 - Run ipython.exe to go.
19
20 """
21
22 #*****************************************************************************
23 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
24 #
25 # Distributed under the terms of the BSD License. The full license is in
26 # the file COPYING, distributed as part of this software.
27 #*****************************************************************************
28
29 # Stdlib imports
30 import os
31 import sys
32
33 from glob import glob
34
35
36 # A few handy globals
37 isfile = os.path.isfile
38 pjoin = os.path.join
39
40 from distutils.core import setup
41 from distutils import dir_util
42 import py2exe
43
44 # update the manuals when building a source dist
45 # Release.py contains version, authors, license, url, keywords, etc.
46 execfile(pjoin('IPython','Release.py'))
47
48 # A little utility we'll need below, since glob() does NOT allow you to do
49 # exclusion on multiple endings!
50 def file_doesnt_endwith(test,endings):
51 """Return true if test is a file and its name does NOT end with any
52 of the strings listed in endings."""
53 if not isfile(test):
54 return False
55 for e in endings:
56 if test.endswith(e):
57 return False
58 return True
59
60
61 egg_extra_kwds = {}
62
63 # Call the setup() routine which does most of the work
64 setup(name = name,
65 options = {
66 'py2exe': {
67 'packages' : ['IPython', 'IPython.Extensions', 'IPython.external',
68 'pyreadline'],
69 'excludes' : ["Tkconstants","Tkinter","tcl",'IPython.igrid','wx',
70 'wxPython','igrid', 'PyQt4', 'zope', 'Zope', 'Zope2',
71 '_curses','enthought.traits','gtk','qt', 'pydb','idlelib',
72 ]
73
74 }
75 },
76 version = version,
77 description = description,
78 long_description = long_description,
79 author = authors['Fernando'][0],
80 author_email = authors['Fernando'][1],
81 url = url,
82 download_url = download_url,
83 license = license,
84 platforms = platforms,
85 keywords = keywords,
86 console = ['ipykit.py'],
87
88 # extra params needed for eggs
89 **egg_extra_kwds
90 )
91
92 minimal_conf = """
93 import IPython.ipapi
94 ip = IPython.ipapi.get()
95
96 ip.load('ipy_kitcfg')
97 import ipy_profile_sh
98 """
99
100 if not os.path.isdir("dist/_ipython"):
101 print "Creating simple _ipython dir"
102 os.mkdir("dist/_ipython")
103 open("dist/_ipython/ipythonrc.ini","w").write("# intentionally blank\n")
104 open("dist/_ipython/ipy_user_conf.py","w").write(minimal_conf)
105 if os.path.isdir('bin'):
106 dir_util.copy_tree('bin','dist/bin')
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 r"""Setup script for exe distribution of IPython (does not require python).
4
5 - Requires py2exe
6
7 - install pyreadline *package dir* in ipython root directory by running:
8
9 svn co http://ipython.scipy.org/svn/ipython/pyreadline/branches/maintenance_1.3/pyreadline/
10 wget http://ipython.scipy.org/svn/ipython/pyreadline/branches/maintenance_1.3/readline.py
11
12 OR (if you want the latest trunk):
13
14 svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk/pyreadline
15
16 - Create the distribution in 'dist' by running "python exesetup.py py2exe"
17
18 - Run ipython.exe to go.
19
20 """
21
22 #*****************************************************************************
23 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
24 #
25 # Distributed under the terms of the BSD License. The full license is in
26 # the file COPYING, distributed as part of this software.
27 #*****************************************************************************
28
29 # Stdlib imports
30 import os
31 import sys
32
33 from glob import glob
34
35
36 # A few handy globals
37 isfile = os.path.isfile
38 pjoin = os.path.join
39
40 from distutils.core import setup
41 from distutils import dir_util
42 import py2exe
43
44 # update the manuals when building a source dist
45 # Release.py contains version, authors, license, url, keywords, etc.
46 execfile(pjoin('IPython','Release.py'))
47
48 # A little utility we'll need below, since glob() does NOT allow you to do
49 # exclusion on multiple endings!
50 def file_doesnt_endwith(test,endings):
51 """Return true if test is a file and its name does NOT end with any
52 of the strings listed in endings."""
53 if not isfile(test):
54 return False
55 for e in endings:
56 if test.endswith(e):
57 return False
58 return True
59
60
61 egg_extra_kwds = {}
62
63 # Call the setup() routine which does most of the work
64 setup(name = name,
65 options = {
66 'py2exe': {
67 'packages' : ['IPython', 'IPython.Extensions', 'IPython.external',
68 'pyreadline'],
69 'excludes' : ["Tkconstants","Tkinter","tcl",'IPython.igrid','wx',
70 'wxPython','igrid', 'PyQt4', 'zope', 'Zope', 'Zope2',
71 '_curses','enthought.traits','gtk','qt', 'pydb','idlelib',
72 ]
73
74 }
75 },
76 version = version,
77 description = description,
78 long_description = long_description,
79 author = authors['Fernando'][0],
80 author_email = authors['Fernando'][1],
81 url = url,
82 download_url = download_url,
83 license = license,
84 platforms = platforms,
85 keywords = keywords,
86 console = ['ipykit.py'],
87
88 # extra params needed for eggs
89 **egg_extra_kwds
90 )
91
92 minimal_conf = """
93 import IPython.ipapi
94 ip = IPython.ipapi.get()
95
96 ip.load('ipy_kitcfg')
97 import ipy_profile_sh
98 """
99
100 if not os.path.isdir("dist/_ipython"):
101 print "Creating simple _ipython dir"
102 os.mkdir("dist/_ipython")
103 open("dist/_ipython/ipythonrc.ini","w").write("# intentionally blank\n")
104 open("dist/_ipython/ipy_user_conf.py","w").write(minimal_conf)
105 if os.path.isdir('bin'):
106 dir_util.copy_tree('bin','dist/bin')
@@ -1,21 +1,21 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """ IPykit launcher
4
5 w/o args, this launches a full ipykit session.
6
7 If the first arg is a .py script, it will be run WITHOUT ipython,
8 to facilitate running python scripts almost normally on machines w/o python
9 in their own process (as opposed to %run).
10
11 """
12
13 import sys
14 if len(sys.argv) > 1 and sys.argv[1].endswith('.py'):
15 # shortcut for running ipykit.exe directly on a .py file - do not bother
16 # starting ipython, just handle as normal python scripts
17 sys.argv = sys.argv[1:]
18 execfile(sys.argv[0])
19 else:
20 import IPython
21 IPython.Shell.start().mainloop()
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """ IPykit launcher
4
5 w/o args, this launches a full ipykit session.
6
7 If the first arg is a .py script, it will be run WITHOUT ipython,
8 to facilitate running python scripts almost normally on machines w/o python
9 in their own process (as opposed to %run).
10
11 """
12
13 import sys
14 if len(sys.argv) > 1 and sys.argv[1].endswith('.py'):
15 # shortcut for running ipykit.exe directly on a .py file - do not bother
16 # starting ipython, just handle as normal python scripts
17 sys.argv = sys.argv[1:]
18 execfile(sys.argv[0])
19 else:
20 import IPython
21 IPython.Shell.start().mainloop()
@@ -23,5 +23,5 b' this mode, there is no way to pass IPython any command-line options, as those'
23 23 are trapped first by Python itself.
24 24 """
25 25
26 import IPython
26 import IPython.Shell
27 27 IPython.Shell.start().mainloop()
@@ -60,11 +60,11 b' def install():'
60 60 mkshortcut(python,'IPython scipy profile',f,a)
61 61
62 62 # Create documentation shortcuts ...
63 t = prefix + r'\share\doc\ipython-%s\manual.pdf' % version
63 t = prefix + r'\share\doc\ipython\manual\ipython.pdf'
64 64 f = ip_dir + r'\Manual in PDF.lnk'
65 65 mkshortcut(t,r'IPython Manual - PDF-Format',f)
66 66
67 t = prefix + r'\share\doc\ipython-%s\manual\manual.html' % version
67 t = prefix + r'\share\doc\ipython\manual\ipython.html'
68 68 f = ip_dir + r'\Manual in HTML.lnk'
69 69 mkshortcut(t,'IPython Manual - HTML-Format',f)
70 70
@@ -4,7 +4,7 b''
4 4
5 5 Under Posix environments it works like a typical setup.py script.
6 6 Under Windows, the command sdist is not supported, since IPython
7 requires utilities, which are not available under Windows."""
7 requires utilities which are not available under Windows."""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
@@ -18,15 +18,41 b' import os'
18 18 import sys
19 19
20 20 from glob import glob
21
22 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
23 # update it when the contents of directories change.
24 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
25
26 from distutils.core import setup
21 27 from setupext import install_data_ext
22 28
29 # Local imports
30 from IPython.genutils import target_update
31
23 32 # A few handy globals
24 33 isfile = os.path.isfile
25 34 pjoin = os.path.join
26 35
27 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
28 # update it when the contents of directories change.
29 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
36 ##############################################################################
37 # Utility functions
38 def oscmd(s):
39 print ">", s
40 os.system(s)
41
42 # A little utility we'll need below, since glob() does NOT allow you to do
43 # exclusion on multiple endings!
44 def file_doesnt_endwith(test,endings):
45 """Return true if test is a file and its name does NOT end with any
46 of the strings listed in endings."""
47 if not isfile(test):
48 return False
49 for e in endings:
50 if test.endswith(e):
51 return False
52 return True
53
54 ###############################################################################
55 # Main code begins
30 56
31 57 if os.name == 'posix':
32 58 os_name = 'posix'
@@ -36,43 +62,31 b' else:'
36 62 print 'Unsupported operating system:',os.name
37 63 sys.exit(1)
38 64
39 # Under Windows, 'sdist' is not supported, since it requires lyxport (and
40 # hence lyx,perl,latex,pdflatex,latex2html,sh,...)
65 # Under Windows, 'sdist' has not been supported. Now that the docs build with
66 # Sphinx it might work, but let's not turn it on until someone confirms that it
67 # actually works.
41 68 if os_name == 'windows' and 'sdist' in sys.argv:
42 69 print 'The sdist command is not available under Windows. Exiting.'
43 70 sys.exit(1)
44 71
45 from distutils.core import setup
46
47 72 # update the manuals when building a source dist
48 73 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
49 from IPython.genutils import target_update
50 # list of things to be updated. Each entry is a triplet of args for
74 import textwrap
75
76 # List of things to be updated. Each entry is a triplet of args for
51 77 # target_update()
52 to_update = [('doc/magic.tex',
53 ['IPython/Magic.py'],
54 "cd doc && ./update_magic.sh" ),
55
56 ('doc/manual.lyx',
57 ['IPython/Release.py','doc/manual_base.lyx'],
58 "cd doc && ./update_version.sh" ),
59
60 ('doc/manual/manual.html',
61 ['doc/manual.lyx',
62 'doc/magic.tex',
63 'doc/examples/example-gnuplot.py',
64 'doc/examples/example-embed.py',
65 'doc/examples/example-embed-short.py',
66 'IPython/UserConfig/ipythonrc',
67 ],
68 "cd doc && "
69 "lyxport -tt --leave --pdf "
70 "--html -o '-noinfo -split +1 -local_icons' manual.lyx"),
78 to_update = [ # The do_sphinx scripts builds html and pdf, so just one
79 # target is enough to cover all manual generation
80 ('doc/manual/ipython.pdf',
81 ['IPython/Release.py','doc/source/ipython.rst'],
82 "cd doc && python do_sphinx.py" ),
83
84 # FIXME - Disabled for now: we need to redo an automatic way
85 # of generating the magic info inside the rst.
86 #('doc/magic.tex',
87 #['IPython/Magic.py'],
88 #"cd doc && ./update_magic.sh" ),
71 89
72 ('doc/new_design.pdf',
73 ['doc/new_design.lyx'],
74 "cd doc && lyxport -tt --pdf new_design.lyx"),
75
76 90 ('doc/ipython.1.gz',
77 91 ['doc/ipython.1'],
78 92 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
@@ -81,45 +95,33 b" if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):"
81 95 ['doc/pycolor.1'],
82 96 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
83 97 ]
84 for target in to_update:
85 target_update(*target)
98
99 [ target_update(*t) for t in to_update ]
86 100
87 101 # Release.py contains version, authors, license, url, keywords, etc.
88 102 execfile(pjoin('IPython','Release.py'))
89 103
90 # A little utility we'll need below, since glob() does NOT allow you to do
91 # exclusion on multiple endings!
92 def file_doesnt_endwith(test,endings):
93 """Return true if test is a file and its name does NOT end with any
94 of the strings listed in endings."""
95 if not isfile(test):
96 return False
97 for e in endings:
98 if test.endswith(e):
99 return False
100 return True
101
102 104 # I can't find how to make distutils create a nested dir. structure, so
103 105 # in the meantime do it manually. Butt ugly.
104 106 # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain
105 107 # information on how to do this more cleanly once python 2.4 can be assumed.
106 108 # Thanks to Noel for the tip.
107 docdirbase = 'share/doc/ipython-%s' % version
109 docdirbase = 'share/doc/ipython'
108 110 manpagebase = 'share/man/man1'
109 111
110 112 # We only need to exclude from this things NOT already excluded in the
111 113 # MANIFEST.in file.
112 114 exclude = ('.sh','.1.gz')
113 115 docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('doc/*'))
114
115 116 examfiles = filter(isfile, glob('doc/examples/*.py'))
116 manfiles = filter(isfile, glob('doc/manual/*.html')) + \
117 filter(isfile, glob('doc/manual/*.css')) + \
118 filter(isfile, glob('doc/manual/*.png'))
117 manfiles = filter(isfile, glob('doc/manual/*'))
118 manstatic = filter(isfile, glob('doc/manual/_static/*'))
119 119 manpages = filter(isfile, glob('doc/*.1.gz'))
120
120 121 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
121 122 scriptfiles = filter(isfile, ['scripts/ipython','scripts/pycolor',
122 123 'scripts/irunner'])
124
123 125 igridhelpfiles = filter(isfile, glob('IPython/Extensions/igrid_help.*'))
124 126
125 127 # Script to be run by the windows binary installer after the default setup
@@ -135,8 +137,8 b" if 'bdist_wininst' in sys.argv:"
135 137 datafiles = [('data', docdirbase, docfiles),
136 138 ('data', pjoin(docdirbase, 'examples'),examfiles),
137 139 ('data', pjoin(docdirbase, 'manual'),manfiles),
140 ('data', pjoin(docdirbase, 'manual/_static'),manstatic),
138 141 ('data', manpagebase, manpages),
139 ('lib', 'IPython/UserConfig', cfgfiles),
140 142 ('data',pjoin(docdirbase, 'extensions'),igridhelpfiles),
141 143 ]
142 144
@@ -150,14 +152,15 b" if 'setuptools' in sys.modules:"
150 152 ]}
151 153 }
152 154 scriptfiles = []
153 # eggs will lack docs, eaxmples
155 # eggs will lack docs, examples
154 156 datafiles = []
155
156 #datafiles = [('lib', 'IPython/UserConfig', cfgfiles)]
157 157 else:
158 # Normal, non-setuptools install
158 159 egg_extra_kwds = {}
159
160
160 # package_data of setuptools was introduced to distutils in 2.4
161 if sys.version_info < (2,4):
162 datafiles.append(('lib', 'IPython/UserConfig', cfgfiles))
163
161 164 # Call the setup() routine which does most of the work
162 165 setup(name = name,
163 166 version = version,
@@ -170,8 +173,11 b' setup(name = name,'
170 173 license = license,
171 174 platforms = platforms,
172 175 keywords = keywords,
173 packages = ['IPython', 'IPython.Extensions', 'IPython.external'],
176 packages = ['IPython', 'IPython.Extensions', 'IPython.external',
177 'IPython.gui', 'IPython.gui.wx',
178 'IPython.UserConfig'],
174 179 scripts = scriptfiles,
180 package_data = {'IPython.UserConfig' : ['*'] },
175 181
176 182 cmdclass = {'install_data': install_data_ext},
177 183 data_files = datafiles,
@@ -1,32 +1,48 b''
1 """ An example of one way to embed IPython in your own application
2
3 This basically means starting up IPython with some of your programs objects visible in the IPython
4 user namespace.
5
6 """
7
8 import sys
9 sys.path.append('..')
10
11 import IPython.ipapi
12
13 my_ns = dict(a=10)
14
15 ses = IPython.ipapi.make_session(my_ns)
16
17 # Now get the ipapi instance, to be stored somewhere in your program for manipulation of the running
18 # IPython session. See http://ipython.scipy.org/moin/IpythonExtensionApi
19
20 ip = ses.IP.getapi()
21
22 # let's play with the ipapi a bit, creating a magic function for a soon-to-be-started IPython
23 def mymagic_f(self,s):
24 print "mymagic says",s
25
26 ip.expose_magic("mymagic",mymagic_f)
27
28 # And finally, start the IPython interaction! This will block until you say Exit.
29
30 ses.mainloop()
31
32 print "IPython session finished! namespace content:",my_ns
1 """ An example of one way to embed IPython in your own application
2
3 This basically means starting up IPython with some of your programs objects visible in the IPython
4 user namespace.
5
6 """
7
8 import sys
9 sys.path.insert(1,'..')
10
11 import IPython.ipapi
12
13
14
15 def test_session(shellclass):
16 print "*****************\nLaunch shell for",shellclass
17 my_ns = dict(a=10)
18 ses = IPython.ipapi.make_session(my_ns, shellclass=shellclass)
19
20 # Now get the ipapi instance, to be stored somewhere in your program for manipulation of the running
21 # IPython session. See http://ipython.scipy.org/moin/IpythonExtensionApi
22
23 ip = ses.IP.getapi()
24
25 # let's play with the ipapi a bit, creating a magic function for a soon-to-be-started IPython
26 def mymagic_f(self,s):
27 print "mymagic says",s
28
29 ip.expose_magic("mymagic",mymagic_f)
30
31 # And finally, start the IPython interaction! This will block until you say Exit.
32
33 ses.mainloop()
34
35 print "IPython session for shell ",shellclass," finished! namespace content:"
36 for k,v in my_ns.items():
37 print k,':',str(v)[:80].rstrip()
38
39 import IPython.Shell
40
41 def do_test(arg_line):
42 test_session(IPython.Shell._select_shell(arg_line.split()))
43
44 do_test('')
45 do_test('ipython -gthread')
46 do_test('ipython -q4thread')
47 do_test('ipython -pylab')
48 do_test('ipython -pylab -gthread') No newline at end of file
@@ -1,54 +1,54 b''
1 import sys
2 sys.path.append('..')
3
4 import IPython.ipapi
5 IPython.ipapi.make_session()
6 ip = IPython.ipapi.get()
7
8 def test_runlines():
9 import textwrap
10 ip.runlines(['a = 10', 'a+=1'])
11 ip.runlines('assert a == 11\nassert 1')
12
13 assert ip.user_ns['a'] == 11
14 complex = textwrap.dedent("""\
15 if 1:
16 print "hello"
17 if 1:
18 print "world"
19
20 if 1:
21 print "foo"
22 if 1:
23 print "bar"
24
25 if 1:
26 print "bar"
27
28 """)
29
30
31 ip.runlines(complex)
32
33
34 def test_db():
35 ip.db['__unittest_'] = 12
36 assert ip.db['__unittest_'] == 12
37 del ip.db['__unittest_']
38 assert '__unittest_' not in ip.db
39
40 def test_defalias():
41 slot = [None]
42 # test callable alias
43 def cb(localip,s):
44 assert localip is ip
45 slot[0] = s
46
47 ip.defalias('testalias', cb)
48 ip.runlines('testalias foo bar')
49 assert slot[0] == 'testalias foo bar'
50
51
52 test_runlines()
53 test_db()
54 test_defalias
1 import sys
2 sys.path.append('..')
3
4 import IPython.ipapi
5 IPython.ipapi.make_session()
6 ip = IPython.ipapi.get()
7
8 def test_runlines():
9 import textwrap
10 ip.runlines(['a = 10', 'a+=1'])
11 ip.runlines('assert a == 11\nassert 1')
12
13 assert ip.user_ns['a'] == 11
14 complex = textwrap.dedent("""\
15 if 1:
16 print "hello"
17 if 1:
18 print "world"
19
20 if 1:
21 print "foo"
22 if 1:
23 print "bar"
24
25 if 1:
26 print "bar"
27
28 """)
29
30
31 ip.runlines(complex)
32
33
34 def test_db():
35 ip.db['__unittest_'] = 12
36 assert ip.db['__unittest_'] == 12
37 del ip.db['__unittest_']
38 assert '__unittest_' not in ip.db
39
40 def test_defalias():
41 slot = [None]
42 # test callable alias
43 def cb(localip,s):
44 assert localip is ip
45 slot[0] = s
46
47 ip.defalias('testalias', cb)
48 ip.runlines('testalias foo bar')
49 assert slot[0] == 'testalias foo bar'
50
51
52 test_runlines()
53 test_db()
54 test_defalias
@@ -1,12 +1,11 b''
1 import os,sys,shutil
1 #!/usr/bin/env python
2 """Simple script to create a tarball with proper bzr version info.
3 """
2 4
3 repo = "http://ipython.scipy.org/svn/ipython/ipython/branches/0.7.3"
4 basename = 'ipython'
5 workdir = './mkdist'
5 import os,sys,shutil
6 6
7 workdir = os.path.abspath(workdir)
7 basever = '0.8.3'
8 8
9 print "working at",workdir
10 9 def oscmd(c):
11 10 print ">",c
12 11 s = os.system(c)
@@ -14,15 +13,24 b' def oscmd(c):'
14 13 print "Error",s
15 14 sys.exit(s)
16 15
16 def verinfo():
17
18 out = os.popen('bzr version-info')
19 pairs = (l.split(':',1) for l in out)
20 d = dict(((k,v.strip()) for (k,v) in pairs))
21 return d
22
23 basename = 'ipython'
24
25 #tarname = '%s.r%s.tgz' % (basename, ver)
26 oscmd('python update_revnum.py')
27
28 ver = verinfo()
17 29
18 assert not os.path.isdir(workdir)
19 os.mkdir(workdir)
20 os.chdir(workdir)
30 if ver['branch-nick'] == 'ipython':
31 tarname = 'ipython-%s.bzr.r%s.tgz' % (basever, ver['revno'])
32 else:
33 tarname = 'ipython-%s.bzr.r%s.%s.tgz' % (basever, ver['revno'], ver['branch-nick'])
34
35 oscmd('bzr export ' + tarname)
21 36
22 oscmd('svn export %s %s' % (repo,basename))
23 ver = os.popen('svnversion ../..').read().strip()
24 tarname = '%s.r%s.tgz' % (basename, ver)
25 oscmd('tar czvf ../%s %s' % (tarname, basename))
26 print "Produced: ",os.path.abspath('../' + tarname)
27 os.chdir('/')
28 shutil.rmtree(workdir)
@@ -1,11 +1,10 b''
1 """ Create ipykit and exe installer
1 #!/usr/bin/env python
2 """IPython release script
2 3
3 requires py2exe
4 Create ipykit and exe installer
4 5
6 requires py2exe
5 7 """
6 #!/bin/sh
7 # IPython release script
8
9 8
10 9 import os
11 10 import distutils.dir_util
@@ -19,21 +18,31 b' def c(cmd):'
19 18
20 19 ipykit_name = "ipykit-%s" % version
21 20
22
23 21 os.chdir('..')
24 22 if os.path.isdir('dist'):
25 23 distutils.dir_util.remove_tree('dist')
26 24 if os.path.isdir(ipykit_name):
27 25 distutils.dir_util.remove_tree(ipykit_name)
28 26
29 c("python exesetup.py py2exe")
27 if sys.platform == 'win32':
28 c("python exesetup.py py2exe")
30 29
31 os.rename('dist',ipykit_name)
30 os.rename('dist',ipykit_name)
32 31
33 c("zip -r %s.zip %s" % (ipykit_name, ipykit_name))
32 c("zip -r %s.zip %s" % (ipykit_name, ipykit_name))
33
34 # Build source and binary distros
35 c('./setup.py sdist --formats=gztar')
36
37 c("python2.4 ./setup.py bdist_rpm --binary-only --release=py24 --python=/usr/bin/python2.4")
38 c("python2.5 ./setup.py bdist_rpm --binary-only --release=py25 --python=/usr/bin/python2.5")
39
40 # Build eggs
41 c('python2.4 ./eggsetup.py bdist_egg')
42 c('python2.5 ./eggsetup.py bdist_egg')
34 43
35 44 c("python setup.py bdist_wininst --install-script=ipython_win_post_install.py")
36 45
37 os.chdir("dist")
38 #c("svn export http://ipython.scipy.org/svn/ipython/ipython/trunk ipython")
39 #c("zip -r ipython_svn.zip ipython")
46 os.chdir('tools')
47 c('python make_tarball.py')
48
@@ -4,6 +4,7 b''
4 4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
5 5 version=`ipython -Version`
6 6 ipdir=~/ipython/ipython
7 ipbackupdir=~/ipython/backup
7 8
8 9 echo
9 10 echo "Releasing IPython version $version"
@@ -37,7 +38,8 b' rm -rf $ipdir/dist/*'
37 38
38 39 # Perform local backup
39 40 cd $ipdir/tools
40 ./bkp.sh
41 ./make_tarball.py
42 mv ipython-*.tgz $ipbackupdir
41 43
42 44 # Build source and binary distros
43 45 cd $ipdir
@@ -50,8 +52,8 b' python2.4 ./setup.py bdist_rpm --binary-only --release=py24 --python=/usr/bin/py'
50 52 python2.5 ./setup.py bdist_rpm --binary-only --release=py25 --python=/usr/bin/python2.5
51 53
52 54 # Build eggs
53 python2.4 ./eggsetup.py bdist_egg
54 python2.5 ./eggsetup.py bdist_egg
55 python2.4 ./setup_bdist_egg.py
56 python2.5 ./setup_bdist_egg.py
55 57
56 58 # Call the windows build separately, so that the extra Windows scripts don't
57 59 # get pulled into Unix builds (setup.py has code which checks for
@@ -72,28 +74,28 b' echo "Uploading distribution files..."'
72 74 scp * ipython@ipython.scipy.org:www/dist/
73 75
74 76 echo "Uploading backup files..."
75 cd ~/ipython/backup
76 scp `ls -1tr | tail -1` ipython@ipython.scipy.org:www/backup/
77 cd $ipbackupdir
78 scp `ls -1tr *tgz | tail -1` ipython@ipython.scipy.org:www/backup/
77 79
78 80 echo "Updating webpage..."
79 81 cd $ipdir/doc
80 82 www=~/ipython/homepage
81 83 cp ChangeLog NEWS $www
82 84 rm -rf $www/doc/*
83 cp -r manual.pdf manual/ $www/doc
85 cp -r manual/ $www/doc
84 86 cd $www
85 87 ./update
86 88
87 89 # Alert package maintainers
88 echo "Alerting package maintainers..."
89 maintainers='fperez@colorado.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com willmaier@ml1.net'
90 #maintainers='fperez@colorado.edu'
91
92 for email in $maintainers
93 do
94 echo "Emailing $email..."
95 mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
96 $email < NEWS
97 done
90 #echo "Alerting package maintainers..."
91 #maintainers='fernando.perez@berkeley.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com willmaier@ml1.net'
92 # maintainers='fernando.perez@berkeley.edu'
93
94 # for email in $maintainers
95 # do
96 # echo "Emailing $email..."
97 # mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
98 # $email < NEWS
99 # done
98 100
99 101 echo "Done!"
1 NO CONTENT: modified file chmod 100644 => 100755
@@ -2,13 +2,22 b''
2 2
3 3 # release test
4 4
5 cd ~/ipython/ipython
5 ipdir=~/ipython/ipython
6 ipbackupdir=~/ipython/backup
6 7
7 # clean up build/dist directories
8 rm -rf build/*
9 rm -rf dist/*
8 cd $ipdir
9
10 # Clean up build/dist directories
11 rm -rf $ipdir/build/*
12 rm -rf $ipdir/dist/*
13
14 # Perform local backup
15 cd $ipdir/tools
16 ./make_tarball.py
17 mv ipython-*.tgz $ipbackupdir
10 18
11 19 # build source distros
20 cd $ipdir
12 21 ./setup.py sdist --formats=gztar
13 22
14 23 # Build rpms
@@ -16,8 +25,8 b' python2.4 ./setup.py bdist_rpm --binary-only --release=py24 --python=/usr/bin/py'
16 25 python2.5 ./setup.py bdist_rpm --binary-only --release=py25 --python=/usr/bin/python2.5
17 26
18 27 # Build eggs
19 python2.4 ./eggsetup.py bdist_egg
20 python2.5 ./eggsetup.py bdist_egg
28 python2.4 ./setup_bdist_egg.py
29 python2.5 ./setup_bdist_egg.py
21 30
22 31 # Call the windows build separately, so that the extra Windows scripts don't
23 32 # get pulled into Unix builds (setup.py has code which checks for
@@ -25,4 +34,4 b' python2.5 ./eggsetup.py bdist_egg'
25 34 ./setup.py bdist_wininst --install-script=ipython_win_post_install.py
26 35
27 36 # Change name so retarded Vista runs the installer correctly
28 rename 's/win32/win32-setup/' dist/*.exe
37 rename 's/win32/win32-setup/' $ipdir/dist/*.exe
@@ -2,13 +2,22 b''
2 2 """ Change the revision number in Release.py """
3 3
4 4 import os
5 import re
5 import re,pprint
6 6
7 rev = os.popen('svnversion ..').read().strip()
7 def verinfo():
8
9 out = os.popen('bzr version-info')
10 pairs = (l.split(':',1) for l in out)
11 d = dict(((k,v.strip()) for (k,v) in pairs))
12 return d
8 13
9 print "current rev is",rev
10 assert ':' not in rev
14 ver = verinfo()
11 15
12 rfile = open('../IPython/Release.py').read()
13 newcont = re.sub(r'revision\s*=.*', "revision = '%s'" % rev, rfile)
14 open('../IPython/Release.py','w').write(newcont)
16 pprint.pprint(ver)
17
18 rfile = open('../IPython/Release.py','rb').read()
19 newcont = re.sub(r'revision\s*=.*', "revision = '%s'" % ver['revno'], rfile)
20
21 newcont = re.sub(r'^branch\s*=[^=].*', "branch = '%s'" % ver['branch-nick'], newcont )
22
23 open('../IPython/Release.py','wb').write(newcont)
@@ -104,8 +104,8 b' def run(wait=0):'
104 104 os.mkdir(ip_prog_dir)
105 105 os.chdir(ip_prog_dir)
106 106
107 man_pdf = doc_dir + r'\manual.pdf'
108 man_htm = doc_dir + r'\manual\manual.html'
107 man_pdf = doc_dir + r'\manual\ipython.pdf'
108 man_htm = doc_dir + r'\manual\ipython.html'
109 109
110 110 make_shortcut('IPython.lnk',sys.executable, '"%s"' % ip_filename,
111 111 my_documents_dir,
@@ -1,28 +0,0 b''
1 How to generate IPython documentation
2 =====================================
3
4 The doc is written using lyx http://www.lyx.org, which is a gui for latex
5 documents. LyX also requires a latex installation.
6
7 The file manual_base.lyx is the template file that should be edited if you
8 want to do changes to the docs.
9
10 A final version is generated by running
11
12 ./update_manual.py
13
14 or
15
16 ipython update_manual.py
17
18 (note that "python update_manual.py" won't work, it's an ipython script!)
19
20 The script update_manual.py will insert the current version number into the
21 template and also generate magic.tex, a file containing documentation for
22 the doc strings of the magic commands.
23
24 The script creates manual.lyx which can be opened by lyx to generate pdf or
25 postscript versions of the docs.
26
27 update_magic.sh and update_version.sh work too, but are slated for
28 deprecation.
This diff has been collapsed as it changes many lines, (10507 lines changed) Show them Hide them
@@ -1,10507 +0,0 b''
1 #LyX 1.4.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 245
3 \begin_document
4 \begin_header
5 \textclass article
6 \begin_preamble
7 %\usepackage{ae,aecompl}
8 \usepackage{color}
9
10 % A few colors to replace the defaults for certain link types
11 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
12 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
13 \definecolor{darkred}{rgb}{.52,0.08,0.01}
14 \definecolor{darkgreen}{rgb}{.12,.54,.11}
15
16 % Use and configure listings package for nicely formatted code
17 \usepackage{listings}
18 \lstset{
19 language=Python,
20 basicstyle=\small\ttfamily,
21 commentstyle=\ttfamily\color{blue},
22 stringstyle=\ttfamily\color{darkorange},
23 showstringspaces=false,
24 breaklines=true,
25 postbreak = \space\dots
26 }
27
28 \usepackage[%pdftex, % needed for pdflatex
29 breaklinks=true, % so long urls are correctly broken across lines
30 colorlinks=true,
31 urlcolor=blue,
32 linkcolor=darkred,
33 citecolor=darkgreen,
34 ]{hyperref}
35
36 \usepackage{html}
37
38 % This helps prevent overly long lines that stretch beyond the margins
39 \sloppy
40
41 % Define a \codelist command which either uses listings for latex, or
42 % plain verbatim for html (since latex2html doesn't understand the
43 % listings package).
44 \usepackage{verbatim}
45 \newcommand{\codelist}[1] {
46 \latex{\lstinputlisting{#1}}
47 \html{\verbatiminput{#1}}
48 }
49 \end_preamble
50 \language english
51 \inputencoding latin1
52 \fontscheme palatino
53 \graphics default
54 \paperfontsize 11
55 \spacing single
56 \papersize default
57 \use_geometry true
58 \use_amsmath 1
59 \cite_engine basic
60 \use_bibtopic false
61 \paperorientation portrait
62 \leftmargin 1in
63 \topmargin 1in
64 \rightmargin 1in
65 \bottommargin 1in
66 \secnumdepth 3
67 \tocdepth 3
68 \paragraph_separation skip
69 \defskip medskip
70 \quotes_language english
71 \papercolumns 1
72 \papersides 2
73 \paperpagestyle fancy
74 \tracking_changes false
75 \output_changes true
76 \end_header
77
78 \begin_body
79
80 \begin_layout Title
81 IPython
82 \newline
83
84 \size larger
85 An enhanced Interactive Python
86 \size large
87
88 \newline
89 User Manual, v.
90 __version__
91 \end_layout
92
93 \begin_layout Author
94 Fernando P�rez
95 \begin_inset Foot
96 status collapsed
97
98 \begin_layout Standard
99
100 \size scriptsize
101 Department of Applied Mathematics, University of Colorado at Boulder.
102
103 \family typewriter
104 <Fernando.Perez@colorado.edu>
105 \end_layout
106
107 \end_inset
108
109
110 \end_layout
111
112 \begin_layout Standard
113 \begin_inset ERT
114 status collapsed
115
116 \begin_layout Standard
117
118
119 \backslash
120 latex{
121 \end_layout
122
123 \end_inset
124
125
126 \begin_inset LatexCommand \tableofcontents{}
127
128 \end_inset
129
130
131 \begin_inset ERT
132 status collapsed
133
134 \begin_layout Standard
135
136 }
137 \end_layout
138
139 \end_inset
140
141
142 \end_layout
143
144 \begin_layout Standard
145 \begin_inset ERT
146 status open
147
148 \begin_layout Standard
149
150
151 \backslash
152 html{
153 \backslash
154 bodytext{bgcolor=#ffffff}}
155 \end_layout
156
157 \end_inset
158
159
160 \end_layout
161
162 \begin_layout Standard
163
164 \newpage
165
166 \end_layout
167
168 \begin_layout Section
169 Overview
170 \end_layout
171
172 \begin_layout Standard
173 One of Python's most useful features is its interactive interpreter.
174 This system allows very fast testing of ideas without the overhead of creating
175 test files as is typical in most programming languages.
176 However, the interpreter supplied with the standard Python distribution
177 is somewhat limited for extended interactive use.
178 \end_layout
179
180 \begin_layout Standard
181 IPython is a free software project (released under the BSD license) which
182 tries to:
183 \end_layout
184
185 \begin_layout Enumerate
186 Provide an interactive shell superior to Python's default.
187 IPython has many features for object introspection, system shell access,
188 and its own special command system for adding functionality when working
189 interactively.
190 It tries to be a very efficient environment both for Python code development
191 and for exploration of problems using Python objects (in situations like
192 data analysis).
193 \end_layout
194
195 \begin_layout Enumerate
196 Serve as an embeddable, ready to use interpreter for your own programs.
197 IPython can be started with a single call from inside another program,
198 providing access to the current namespace.
199 This can be very useful both for debugging purposes and for situations
200 where a blend of batch-processing and interactive exploration are needed.
201 \end_layout
202
203 \begin_layout Enumerate
204 Offer a flexible framework which can be used as the base environment for
205 other systems with Python as the underlying language.
206 Specifically scientific environments like Mathematica, IDL and Matlab inspired
207 its design, but similar ideas can be useful in many fields.
208 \end_layout
209
210 \begin_layout Enumerate
211 Allow interactive testing of threaded graphical toolkits.
212 IPython has support for interactive, non-blocking control of GTK, Qt and
213 WX applications via special threading flags.
214 The normal Python shell can only do this for Tkinter applications.
215 \end_layout
216
217 \begin_layout Subsection
218 Main features
219 \end_layout
220
221 \begin_layout Itemize
222 Dynamic object introspection.
223 One can access docstrings, function definition prototypes, source code,
224 source files and other details of any object accessible to the interpreter
225 with a single keystroke (`
226 \family typewriter
227 ?
228 \family default
229 ', and using `
230 \family typewriter
231 ??
232 \family default
233 ' provides additional detail).
234 \end_layout
235
236 \begin_layout Itemize
237 Searching through modules and namespaces with `
238 \family typewriter
239 *
240 \family default
241 ' wildcards, both when using the `
242 \family typewriter
243 ?
244 \family default
245 ' system and via the
246 \family typewriter
247 %psearch
248 \family default
249 command.
250 \end_layout
251
252 \begin_layout Itemize
253 Completion in the local namespace, by typing TAB at the prompt.
254 This works for keywords, methods, variables and files in the current directory.
255 This is supported via the readline library, and full access to configuring
256 readline's behavior is provided.
257 \end_layout
258
259 \begin_layout Itemize
260 Numbered input/output prompts with command history (persistent across sessions
261 and tied to each profile), full searching in this history and caching of
262 all input and output.
263 \end_layout
264
265 \begin_layout Itemize
266 User-extensible `magic' commands.
267 A set of commands prefixed with
268 \family typewriter
269 %
270 \family default
271 is available for controlling IPython itself and provides directory control,
272 namespace information and many aliases to common system shell commands.
273 \end_layout
274
275 \begin_layout Itemize
276 Alias facility for defining your own system aliases.
277 \end_layout
278
279 \begin_layout Itemize
280 Complete system shell access.
281 Lines starting with ! are passed directly to the system shell, and using
282 !! captures shell output into python variables for further use.
283 \end_layout
284
285 \begin_layout Itemize
286 Background execution of Python commands in a separate thread.
287 IPython has an internal job manager called
288 \family typewriter
289 jobs
290 \family default
291 , and a conveninence backgrounding magic function called
292 \family typewriter
293 %bg
294 \family default
295 .
296 \end_layout
297
298 \begin_layout Itemize
299 The ability to expand python variables when calling the system shell.
300 In a shell command, any python variable prefixed with
301 \family typewriter
302 $
303 \family default
304 is expanded.
305 A double
306 \family typewriter
307 $$
308 \family default
309 allows passing a literal
310 \family typewriter
311 $
312 \family default
313 to the shell (for access to shell and environment variables like
314 \family typewriter
315 $PATH
316 \family default
317 ).
318 \end_layout
319
320 \begin_layout Itemize
321 Filesystem navigation, via a magic
322 \family typewriter
323 %cd
324 \family default
325 command, along with a persistent bookmark system (using
326 \family typewriter
327 %bookmark
328 \family default
329 ) for fast access to frequently visited directories.
330 \end_layout
331
332 \begin_layout Itemize
333 A lightweight persistence framework via the
334 \family typewriter
335 %store
336 \family default
337 command, which allows you to save arbitrary Python variables.
338 These get restored automatically when your session restarts.
339 \end_layout
340
341 \begin_layout Itemize
342 Automatic indentation (optional) of code as you type (through the readline
343 library).
344 \end_layout
345
346 \begin_layout Itemize
347 Macro system for quickly re-executing multiple lines of previous input with
348 a single name.
349 Macros can be stored persistently via
350 \family typewriter
351 %store
352 \family default
353 and edited via
354 \family typewriter
355 %edit
356 \family default
357 .
358
359 \end_layout
360
361 \begin_layout Itemize
362 Session logging (you can then later use these logs as code in your programs).
363 Logs can optionally timestamp all input, and also store session output
364 (marked as comments, so the log remains valid Python source code).
365 \end_layout
366
367 \begin_layout Itemize
368 Session restoring: logs can be replayed to restore a previous session to
369 the state where you left it.
370 \end_layout
371
372 \begin_layout Itemize
373 Verbose and colored exception traceback printouts.
374 Easier to parse visually, and in verbose mode they produce a lot of useful
375 debugging information (basically a terminal version of the cgitb module).
376 \end_layout
377
378 \begin_layout Itemize
379 Auto-parentheses: callable objects can be executed without parentheses:
380
381 \family typewriter
382 `sin 3'
383 \family default
384 is automatically converted to
385 \family typewriter
386 `sin(3)
387 \family default
388 '.
389 \end_layout
390
391 \begin_layout Itemize
392 Auto-quoting: using `
393 \family typewriter
394 ,
395 \family default
396 ' or `
397 \family typewriter
398 ;
399 \family default
400 ' as the first character forces auto-quoting of the rest of the line:
401 \family typewriter
402 `,my_function a\InsetSpace ~
403 b'
404 \family default
405 becomes automatically
406 \family typewriter
407 `my_function("a","b")'
408 \family default
409 , while
410 \family typewriter
411 `;my_function a\InsetSpace ~
412 b'
413 \family default
414 becomes
415 \family typewriter
416 `my_function("a b")'
417 \family default
418 .
419 \end_layout
420
421 \begin_layout Itemize
422 Extensible input syntax.
423 You can define filters that pre-process user input to simplify input in
424 special situations.
425 This allows for example pasting multi-line code fragments which start with
426
427 \family typewriter
428 `>>>'
429 \family default
430 or
431 \family typewriter
432 `...'
433 \family default
434 such as those from other python sessions or the standard Python documentation.
435 \end_layout
436
437 \begin_layout Itemize
438 Flexible configuration system.
439 It uses a configuration file which allows permanent setting of all command-line
440 options, module loading, code and file execution.
441 The system allows recursive file inclusion, so you can have a base file
442 with defaults and layers which load other customizations for particular
443 projects.
444 \end_layout
445
446 \begin_layout Itemize
447 Embeddable.
448 You can call IPython as a python shell inside your own python programs.
449 This can be used both for debugging code or for providing interactive abilities
450 to your programs with knowledge about the local namespaces (very useful
451 in debugging and data analysis situations).
452 \end_layout
453
454 \begin_layout Itemize
455 Easy debugger access.
456 You can set IPython to call up an enhanced version of the Python debugger
457 (
458 \family typewriter
459 pdb
460 \family default
461 ) every time there is an uncaught exception.
462 This drops you inside the code which triggered the exception with all the
463 data live and it is possible to navigate the stack to rapidly isolate the
464 source of a bug.
465 The
466 \family typewriter
467 %run
468 \family default
469 magic command --with the
470 \family typewriter
471 -d
472 \family default
473 option-- can run any script under
474 \family typewriter
475 pdb
476 \family default
477 's control, automatically setting initial breakpoints for you.
478 This version of
479 \family typewriter
480 pdb
481 \family default
482 has IPython-specific improvements, including tab-completion and traceback
483 coloring support.
484 \end_layout
485
486 \begin_layout Itemize
487 Profiler support.
488 You can run single statements (similar to
489 \family typewriter
490 profile.run()
491 \family default
492 ) or complete programs under the profiler's control.
493 While this is possible with standard
494 \family typewriter
495 cProfile
496 \family default
497 or
498 \family typewriter
499 profile
500 \family default
501 modules, IPython wraps this functionality with magic commands (see
502 \family typewriter
503 `%prun'
504 \family default
505 and
506 \family typewriter
507 `%run -p
508 \family default
509 ') convenient for rapid interactive work.
510 \end_layout
511
512 \begin_layout Itemize
513 Doctest support.
514 The special
515 \family typewriter
516 %doctest_mode
517 \family default
518 command toggles a mode that allows you to paste existing doctests (with
519 leading `
520 \family typewriter
521 >>>
522 \family default
523 ' prompts and whitespace) and uses doctest-compatible prompts and output,
524 so you can use IPython sessions as doctest code.
525 \end_layout
526
527 \begin_layout Subsection
528 Portability and Python requirements
529 \end_layout
530
531 \begin_layout Standard
532
533 \series bold
534 Python requirements:
535 \series default
536 IPython requires with Python version 2.3 or newer.
537 If you are still using Python 2.2 and can not upgrade, the last version
538 of IPython which worked with Python 2.2 was 0.6.15, so you will have to use
539 that.
540 \end_layout
541
542 \begin_layout Standard
543 IPython is developed under
544 \series bold
545 Linux
546 \series default
547 , but it should work in any reasonable Unix-type system (tested OK under
548 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
549 \end_layout
550
551 \begin_layout Standard
552
553 \series bold
554 Mac OS X
555 \series default
556 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
557 Livermore for the information).
558 Thanks to Andrea Riciputi, Fink support is available.
559 \end_layout
560
561 \begin_layout Standard
562
563 \series bold
564 CygWin
565 \series default
566 : it works mostly OK, though some users have reported problems with prompt
567 coloring.
568 No satisfactory solution to this has been found so far, you may want to
569 disable colors permanently in the
570 \family typewriter
571 ipythonrc
572 \family default
573 configuration file if you experience problems.
574 If you have proper color support under cygwin, please post to the IPython
575 mailing list so this issue can be resolved for all users.
576 \end_layout
577
578 \begin_layout Standard
579
580 \series bold
581 Windows
582 \series default
583 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
584 Section\InsetSpace ~
585
586 \begin_inset LatexCommand \ref{sub:Under-Windows}
587
588 \end_inset
589
590 describes installation details for Windows, including some additional tools
591 needed on this platform.
592 \end_layout
593
594 \begin_layout Standard
595 Windows 9x support is present, and has been reported to work fine (at least
596 on WinME).
597 \end_layout
598
599 \begin_layout Standard
600 Note, that I have very little access to and experience with Windows development.
601 However, an excellent group of Win32 users (led by Ville Vainio), consistently
602 contribute bugfixes and platform-specific enhancements, so they more than
603 make up for my deficiencies on that front.
604 In fact, Win32 users report using IPython as a system shell (see Sec.\InsetSpace ~
605
606 \begin_inset LatexCommand \ref{sec:IPython-as-shell}
607
608 \end_inset
609
610 for details), as it offers a level of control and features which the default
611
612 \family typewriter
613 cmd.exe
614 \family default
615 doesn't provide.
616 \end_layout
617
618 \begin_layout Subsection
619 Location
620 \end_layout
621
622 \begin_layout Standard
623 IPython is generously hosted at
624 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
625
626 \end_inset
627
628 by the Enthought, Inc and the SciPy project.
629 This site offers downloads, subversion access, mailing lists and a bug
630 tracking system.
631 I am very grateful to Enthought (
632 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
633
634 \end_inset
635
636 ) and all of the SciPy team for their contribution.
637 \end_layout
638
639 \begin_layout Section
640 \begin_inset LatexCommand \label{sec:install}
641
642 \end_inset
643
644 Installation
645 \end_layout
646
647 \begin_layout Subsection
648 Instant instructions
649 \end_layout
650
651 \begin_layout Standard
652 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
653 download, then install with
654 \family typewriter
655 `python setup.py install'
656 \family default
657 .
658 Under Windows, double-click on the provided
659 \family typewriter
660 .exe
661 \family default
662 binary installer.
663 \end_layout
664
665 \begin_layout Standard
666 Then, take a look at Sections
667 \begin_inset LatexCommand \ref{sec:good_config}
668
669 \end_inset
670
671 for configuring things optimally and
672 \begin_inset LatexCommand \ref{sec:quick_tips}
673
674 \end_inset
675
676 for quick tips on efficient use of IPython.
677 You can later refer to the rest of the manual for all the gory details.
678 \end_layout
679
680 \begin_layout Standard
681 See the notes in sec.
682
683 \begin_inset LatexCommand \ref{sec:upgrade}
684
685 \end_inset
686
687 for upgrading IPython versions.
688 \end_layout
689
690 \begin_layout Subsection
691 Detailed Unix instructions (Linux, Mac OS X, etc.)
692 \end_layout
693
694 \begin_layout Standard
695 For RPM based systems, simply install the supplied package in the usual
696 manner.
697 If you download the tar archive, the process is:
698 \end_layout
699
700 \begin_layout Enumerate
701 Unzip/untar the
702 \family typewriter
703 ipython-XXX.tar.gz
704 \family default
705 file wherever you want (
706 \family typewriter
707 XXX
708 \family default
709 is the version number).
710 It will make a directory called
711 \family typewriter
712 ipython-XXX.
713
714 \family default
715 Change into that directory where you will find the files
716 \family typewriter
717 README
718 \family default
719 and
720 \family typewriter
721 setup.py
722 \family default
723 .
724
725 \family typewriter
726 O
727 \family default
728 nce you've completed the installation, you can safely remove this directory.
729
730 \end_layout
731
732 \begin_layout Enumerate
733 If you are installing over a previous installation of version 0.2.0 or earlier,
734 first remove your
735 \family typewriter
736 $HOME/.ipython
737 \family default
738 directory, since the configuration file format has changed somewhat (the
739 '=' were removed from all option specifications).
740 Or you can call ipython with the
741 \family typewriter
742 -upgrade
743 \family default
744 option and it will do this automatically for you.
745 \end_layout
746
747 \begin_layout Enumerate
748 IPython uses distutils, so you can install it by simply typing at the system
749 prompt (don't type the
750 \family typewriter
751 $
752 \family default
753 )
754 \newline
755
756 \family typewriter
757 $ python setup.py install
758 \family default
759
760 \newline
761 Note that this assumes you have root access to your machine.
762 If you don't have root access or don't want IPython to go in the default
763 python directories, you'll need to use the
764 \begin_inset ERT
765 status collapsed
766
767 \begin_layout Standard
768
769
770 \backslash
771 verb|--home|
772 \end_layout
773
774 \end_inset
775
776 option (or
777 \begin_inset ERT
778 status collapsed
779
780 \begin_layout Standard
781
782
783 \backslash
784 verb|--prefix|
785 \end_layout
786
787 \end_inset
788
789 ).
790 For example:
791 \newline
792
793 \begin_inset ERT
794 status collapsed
795
796 \begin_layout Standard
797
798
799 \backslash
800 verb|$ python setup.py install --home $HOME/local|
801 \end_layout
802
803 \end_inset
804
805
806 \newline
807 will install IPython into
808 \family typewriter
809 $HOME/local
810 \family default
811 and its subdirectories (creating them if necessary).
812 \newline
813 You can type
814 \newline
815
816 \begin_inset ERT
817 status collapsed
818
819 \begin_layout Standard
820
821
822 \backslash
823 verb|$ python setup.py --help|
824 \end_layout
825
826 \end_inset
827
828
829 \newline
830 for more details.
831 \newline
832 Note that if you change the default location for
833 \begin_inset ERT
834 status collapsed
835
836 \begin_layout Standard
837
838
839 \backslash
840 verb|--home|
841 \end_layout
842
843 \end_inset
844
845 at installation, IPython may end up installed at a location which is not
846 part of your
847 \family typewriter
848 $PYTHONPATH
849 \family default
850 environment variable.
851 In this case, you'll need to configure this variable to include the actual
852 directory where the
853 \family typewriter
854 IPython/
855 \family default
856 directory ended (typically the value you give to
857 \begin_inset ERT
858 status collapsed
859
860 \begin_layout Standard
861
862
863 \backslash
864 verb|--home|
865 \end_layout
866
867 \end_inset
868
869 plus
870 \family typewriter
871 /lib/python
872 \family default
873 ).
874 \end_layout
875
876 \begin_layout Subsubsection
877 Mac OSX information
878 \end_layout
879
880 \begin_layout Standard
881 Under OSX, there is a choice you need to make.
882 Apple ships its own build of Python, which lives in the core OSX filesystem
883 hierarchy.
884 You can also manually install a separate Python, either purely by hand
885 (typically in
886 \family typewriter
887 /usr/local
888 \family default
889 ) or by using Fink, which puts everything under
890 \family typewriter
891 /sw
892 \family default
893 .
894 Which route to follow is a matter of personal preference, as I've seen
895 users who favor each of the approaches.
896 Here I will simply list the known installation issues under OSX, along
897 with their solutions.
898 \end_layout
899
900 \begin_layout Standard
901 This page:
902 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
903
904 \end_inset
905
906 contains information on this topic, with additional details on how to make
907 IPython and matplotlib play nicely under OSX.
908 \end_layout
909
910 \begin_layout Subsubsection*
911 GUI problems
912 \end_layout
913
914 \begin_layout Standard
915 The following instructions apply to an install of IPython under OSX from
916 unpacking the
917 \family typewriter
918 .tar.gz
919 \family default
920 distribution and installing it for the default Python interpreter shipped
921 by Apple.
922 If you are using a fink install, fink will take care of these details for
923 you, by installing IPython against fink's Python.
924 \end_layout
925
926 \begin_layout Standard
927 IPython offers various forms of support for interacting with graphical applicati
928 ons from the command line, from simple Tk apps (which are in principle always
929 supported by Python) to interactive control of WX, Qt and GTK apps.
930 Under OSX, however, this requires that ipython is installed by calling
931 the special
932 \family typewriter
933 pythonw
934 \family default
935 script at installation time, which takes care of coordinating things with
936 Apple's graphical environment.
937 \end_layout
938
939 \begin_layout Standard
940 So when installing under OSX, it is best to use the following command:
941 \family typewriter
942
943 \newline
944
945 \family default
946
947 \begin_inset ERT
948 status collapsed
949
950 \begin_layout Standard
951
952
953 \backslash
954 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
955 \end_layout
956
957 \end_inset
958
959
960 \newline
961 or
962 \newline
963
964 \begin_inset ERT
965 status collapsed
966
967 \begin_layout Standard
968
969
970 \backslash
971 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
972 \end_layout
973
974 \end_inset
975
976
977 \newline
978 depending on where you like to keep hand-installed executables.
979 \end_layout
980
981 \begin_layout Standard
982 The resulting script will have an appropriate shebang line (the first line
983 in the script whic begins with
984 \family typewriter
985 #!...
986 \family default
987 ) such that the ipython interpreter can interact with the OS X GUI.
988 If the installed version does not work and has a shebang line that points
989 to, for example, just
990 \family typewriter
991 /usr/bin/python
992 \family default
993 , then you might have a stale, cached version in your
994 \family typewriter
995 build/scripts-<python-version>
996 \family default
997 directory.
998 Delete that directory and rerun the
999 \family typewriter
1000 setup.py
1001 \family default
1002 .
1003
1004 \end_layout
1005
1006 \begin_layout Standard
1007 It is also a good idea to use the special flag
1008 \begin_inset ERT
1009 status collapsed
1010
1011 \begin_layout Standard
1012
1013
1014 \backslash
1015 verb|--install-scripts|
1016 \end_layout
1017
1018 \end_inset
1019
1020 as indicated above, to ensure that the ipython scripts end up in a location
1021 which is part of your
1022 \family typewriter
1023 $PATH
1024 \family default
1025 .
1026 Otherwise Apple's Python will put the scripts in an internal directory
1027 not available by default at the command line (if you use
1028 \family typewriter
1029 /usr/local/bin
1030 \family default
1031 , you need to make sure this is in your
1032 \family typewriter
1033 $PATH
1034 \family default
1035 , which may not be true by default).
1036 \end_layout
1037
1038 \begin_layout Subsubsection*
1039 Readline problems
1040 \end_layout
1041
1042 \begin_layout Standard
1043 By default, the Python version shipped by Apple does
1044 \emph on
1045 not
1046 \emph default
1047 include the readline library, so central to IPython's behavior.
1048 If you install IPython against Apple's Python, you will not have arrow
1049 keys, tab completion, etc.
1050 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
1051 \newline
1052
1053 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
1054
1055 \end_inset
1056
1057
1058 \end_layout
1059
1060 \begin_layout Standard
1061 If you are using OSX 10.4 (Tiger), after installing this package you need
1062 to either:
1063 \end_layout
1064
1065 \begin_layout Enumerate
1066 move
1067 \family typewriter
1068 readline.so
1069 \family default
1070 from
1071 \family typewriter
1072 /Library/Python/2.3
1073 \family default
1074 to
1075 \family typewriter
1076 /Library/Python/2.3/site-packages
1077 \family default
1078 , or
1079 \end_layout
1080
1081 \begin_layout Enumerate
1082 install
1083 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
1084
1085 \end_inset
1086
1087
1088 \end_layout
1089
1090 \begin_layout Standard
1091 Users installing against Fink's Python or a properly hand-built one should
1092 not have this problem.
1093 \end_layout
1094
1095 \begin_layout Subsubsection*
1096 DarwinPorts
1097 \end_layout
1098
1099 \begin_layout Standard
1100 I report here a message from an OSX user, who suggests an alternative means
1101 of using IPython under this operating system with good results.
1102 Please let me know of any updates that may be useful for this section.
1103 His message is reproduced verbatim below:
1104 \end_layout
1105
1106 \begin_layout Quote
1107 From: Markus Banfi
1108 \family typewriter
1109 <markus.banfi-AT-mospheira.net>
1110 \end_layout
1111
1112 \begin_layout Quote
1113 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
1114 of Fink.
1115 I had no problems installing ipython with DarwinPorts.
1116 It's just:
1117 \end_layout
1118
1119 \begin_layout Quote
1120
1121 \family typewriter
1122 sudo port install py-ipython
1123 \end_layout
1124
1125 \begin_layout Quote
1126 It automatically resolved all dependencies (python24, readline, py-readline).
1127 So far I did not encounter any problems with the DarwinPorts port of ipython.
1128
1129 \end_layout
1130
1131 \begin_layout Subsection
1132 \begin_inset LatexCommand \label{sub:Under-Windows}
1133
1134 \end_inset
1135
1136 Windows instructions
1137 \end_layout
1138
1139 \begin_layout Standard
1140 Some of IPython's very useful features are:
1141 \end_layout
1142
1143 \begin_layout Itemize
1144 Integrated readline support (Tab-based file, object and attribute completion,
1145 input history across sessions, editable command line, etc.)
1146 \end_layout
1147
1148 \begin_layout Itemize
1149 Coloring of prompts, code and tracebacks.
1150 \end_layout
1151
1152 \begin_layout Standard
1153 These, by default, are only available under Unix-like operating systems.
1154 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
1155 from them.
1156 His readline library originally implemented both GNU readline functionality
1157 and color support, so that IPython under Windows XP/2k can be as friendly
1158 and powerful as under Unix-like environments.
1159
1160 \end_layout
1161
1162 \begin_layout Standard
1163 This library, now named
1164 \family typewriter
1165 PyReadline
1166 \family default
1167 , has been absorbed by the IPython team (J�rgen Stenarson, in particular),
1168 and it continues to be developed with new features, as well as being distribute
1169 d directly from the IPython site.
1170 \end_layout
1171
1172 \begin_layout Standard
1173 The
1174 \family typewriter
1175 PyReadline
1176 \family default
1177 extension requires
1178 \family typewriter
1179 CTypes
1180 \family default
1181 and the windows IPython installer needs
1182 \family typewriter
1183 PyWin32
1184 \family default
1185 , so in all you need:
1186 \end_layout
1187
1188 \begin_layout Enumerate
1189
1190 \family typewriter
1191 PyWin32
1192 \family default
1193 from
1194 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/pywin32}
1195
1196 \end_inset
1197
1198 .
1199 \end_layout
1200
1201 \begin_layout Enumerate
1202
1203 \family typewriter
1204 PyReadline
1205 \family default
1206 for Windows from
1207 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org/moin/PyReadline/Intro}
1208
1209 \end_inset
1210
1211 .
1212 That page contains further details on using and configuring the system
1213 to your liking.
1214 \end_layout
1215
1216 \begin_layout Enumerate
1217 Finally,
1218 \emph on
1219 only
1220 \emph default
1221 if you are using Python 2.3 or 2.4, you need
1222 \family typewriter
1223 CTypes
1224 \family default
1225 from
1226 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1227
1228 \end_inset
1229
1230 (you
1231 \emph on
1232 must
1233 \emph default
1234 use version 0.9.1 or newer).
1235 This package is included in Python 2.5, so you don't need to manually get
1236 it if your Python version is 2.5 or newer.
1237 \end_layout
1238
1239 \begin_layout Standard
1240
1241 \series bold
1242 Warning about a broken readline-like library:
1243 \series default
1244 several users have reported problems stemming from using the pseudo-readline
1245 library at
1246 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1247
1248 \end_inset
1249
1250 .
1251 This is a broken library which, while called readline, only implements
1252 an incomplete subset of the readline API.
1253 Since it is still called readline, it fools IPython's detection mechanisms
1254 and causes unpredictable crashes later.
1255 If you wish to use IPython under Windows, you must NOT use this library,
1256 which for all purposes is (at least as of version 1.6) terminally broken.
1257 \end_layout
1258
1259 \begin_layout Subsubsection
1260 Installation procedure
1261 \end_layout
1262
1263 \begin_layout Standard
1264 Once you have the above installed, from the IPython download directory grab
1265 the
1266 \family typewriter
1267 ipython-XXX.win32.exe
1268 \family default
1269 file, where
1270 \family typewriter
1271 XXX
1272 \family default
1273 represents the version number.
1274 This is a regular windows executable installer, which you can simply double-cli
1275 ck to install.
1276 It will add an entry for IPython to your Start Menu, as well as registering
1277 IPython in the Windows list of applications, so you can later uninstall
1278 it from the Control Panel.
1279
1280 \end_layout
1281
1282 \begin_layout Standard
1283 IPython tries to install the configuration information in a directory named
1284
1285 \family typewriter
1286 .ipython
1287 \family default
1288 (
1289 \family typewriter
1290 _ipython
1291 \family default
1292 under Windows) located in your `home' directory.
1293 IPython sets this directory by looking for a
1294 \family typewriter
1295 HOME
1296 \family default
1297 environment variable; if such a variable does not exist, it uses
1298 \family typewriter
1299 HOMEDRIVE
1300 \backslash
1301 HOMEPATH
1302 \family default
1303 (these are always defined by Windows).
1304 This typically gives something like
1305 \family typewriter
1306 C:
1307 \backslash
1308 Documents and Settings
1309 \backslash
1310 YourUserName
1311 \family default
1312 , but your local details may vary.
1313 In this directory you will find all the files that configure IPython's
1314 defaults, and you can put there your profiles and extensions.
1315 This directory is automatically added by IPython to
1316 \family typewriter
1317 sys.path
1318 \family default
1319 , so anything you place there can be found by
1320 \family typewriter
1321 import
1322 \family default
1323 statements.
1324 \end_layout
1325
1326 \begin_layout Paragraph
1327 Upgrading
1328 \end_layout
1329
1330 \begin_layout Standard
1331 For an IPython upgrade, you should first uninstall the previous version.
1332 This will ensure that all files and directories (such as the documentation)
1333 which carry embedded version strings in their names are properly removed.
1334 \end_layout
1335
1336 \begin_layout Paragraph
1337 Manual installation under Win32
1338 \end_layout
1339
1340 \begin_layout Standard
1341 In case the automatic installer does not work for some reason, you can download
1342 the
1343 \family typewriter
1344 ipython-XXX.tar.gz
1345 \family default
1346 file, which contains the full IPython source distribution (the popular
1347 WinZip can read
1348 \family typewriter
1349 .tar.gz
1350 \family default
1351 files).
1352 After uncompressing the archive, you can install it at a command terminal
1353 just like any other Python module, by using
1354 \family typewriter
1355 `python setup.py install'
1356 \family default
1357 .
1358
1359 \end_layout
1360
1361 \begin_layout Standard
1362 After the installation, run the supplied
1363 \family typewriter
1364 win32_manual_post_install.py
1365 \family default
1366 script, which creates the necessary Start Menu shortcuts for you.
1367 \end_layout
1368
1369 \begin_layout Subsection
1370 \begin_inset LatexCommand \label{sec:upgrade}
1371
1372 \end_inset
1373
1374 Upgrading from a previous version
1375 \end_layout
1376
1377 \begin_layout Standard
1378 If you are upgrading from a previous version of IPython, after doing the
1379 routine installation described above, you should call IPython with the
1380
1381 \family typewriter
1382 -upgrade
1383 \family default
1384 option the first time you run your new copy.
1385 This will automatically update your configuration directory while preserving
1386 copies of your old files.
1387 You can then later merge back any personal customizations you may have
1388 made into the new files.
1389 It is a good idea to do this as there may be new options available in the
1390 new configuration files which you will not have.
1391 \end_layout
1392
1393 \begin_layout Standard
1394 Under Windows, if you don't know how to call python scripts with arguments
1395 from a command line, simply delete the old config directory and IPython
1396 will make a new one.
1397 Win2k and WinXP users will find it in
1398 \family typewriter
1399 C:
1400 \backslash
1401 Documents and Settings
1402 \backslash
1403 YourUserName
1404 \backslash
1405 _ipython
1406 \family default
1407 , and Win 9x users under
1408 \family typewriter
1409 C:
1410 \backslash
1411 Program Files
1412 \backslash
1413 IPython
1414 \backslash
1415 _ipython.
1416 \end_layout
1417
1418 \begin_layout Section
1419 \begin_inset LatexCommand \label{sec:good_config}
1420
1421 \end_inset
1422
1423
1424 \begin_inset OptArg
1425 status collapsed
1426
1427 \begin_layout Standard
1428 Initial configuration
1429 \begin_inset ERT
1430 status collapsed
1431
1432 \begin_layout Standard
1433
1434
1435 \backslash
1436 ldots
1437 \end_layout
1438
1439 \end_inset
1440
1441
1442 \end_layout
1443
1444 \end_inset
1445
1446 Initial configuration of your environment
1447 \end_layout
1448
1449 \begin_layout Standard
1450 This section will help you set various things in your environment for your
1451 IPython sessions to be as efficient as possible.
1452 All of IPython's configuration information, along with several example
1453 files, is stored in a directory named by default
1454 \family typewriter
1455 $HOME/.ipython
1456 \family default
1457 .
1458 You can change this by defining the environment variable
1459 \family typewriter
1460 IPYTHONDIR
1461 \family default
1462 , or at runtime with the command line option
1463 \family typewriter
1464 -ipythondir
1465 \family default
1466 .
1467 \end_layout
1468
1469 \begin_layout Standard
1470 If all goes well, the first time you run IPython it should automatically
1471 create a user copy of the config directory for you, based on its builtin
1472 defaults.
1473 You can look at the files it creates to learn more about configuring the
1474 system.
1475 The main file you will modify to configure IPython's behavior is called
1476
1477 \family typewriter
1478 ipythonrc
1479 \family default
1480 (with a
1481 \family typewriter
1482 .ini
1483 \family default
1484 extension under Windows), included for reference in Sec.
1485
1486 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1487
1488 \end_inset
1489
1490 .
1491 This file is very commented and has many variables you can change to suit
1492 your taste, you can find more details in Sec.
1493
1494 \begin_inset LatexCommand \ref{sec:customization}
1495
1496 \end_inset
1497
1498 .
1499 Here we discuss the basic things you will want to make sure things are
1500 working properly from the beginning.
1501 \end_layout
1502
1503 \begin_layout Subsection
1504 \begin_inset LatexCommand \label{sec:help-access}
1505
1506 \end_inset
1507
1508 Access to the Python help system
1509 \end_layout
1510
1511 \begin_layout Standard
1512 This is true for Python in general (not just for IPython): you should have
1513 an environment variable called
1514 \family typewriter
1515 PYTHONDOCS
1516 \family default
1517 pointing to the directory where your HTML Python documentation lives.
1518 In my system it's
1519 \family typewriter
1520 /usr/share/doc/python-docs-2.3.4/html
1521 \family default
1522 , check your local details or ask your systems administrator.
1523
1524 \end_layout
1525
1526 \begin_layout Standard
1527 This is the directory which holds the HTML version of the Python manuals.
1528 Unfortunately it seems that different Linux distributions package these
1529 files differently, so you may have to look around a bit.
1530 Below I show the contents of this directory on my system for reference:
1531 \end_layout
1532
1533 \begin_layout Standard
1534
1535 \family typewriter
1536 [html]> ls
1537 \newline
1538 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat
1539 tut/ about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1540 \end_layout
1541
1542 \begin_layout Standard
1543 You should really make sure this variable is correctly set so that Python's
1544 pydoc-based help system works.
1545 It is a powerful and convenient system with full access to the Python manuals
1546 and all modules accessible to you.
1547 \end_layout
1548
1549 \begin_layout Standard
1550 Under Windows it seems that pydoc finds the documentation automatically,
1551 so no extra setup appears necessary.
1552 \end_layout
1553
1554 \begin_layout Subsection
1555 Editor
1556 \end_layout
1557
1558 \begin_layout Standard
1559 The
1560 \family typewriter
1561 %edit
1562 \family default
1563 command (and its alias
1564 \family typewriter
1565 %ed
1566 \family default
1567 ) will invoke the editor set in your environment as
1568 \family typewriter
1569 EDITOR
1570 \family default
1571 .
1572 If this variable is not set, it will default to
1573 \family typewriter
1574 vi
1575 \family default
1576 under Linux/Unix and to
1577 \family typewriter
1578 notepad
1579 \family default
1580 under Windows.
1581 You may want to set this variable properly and to a lightweight editor
1582 which doesn't take too long to start (that is, something other than a new
1583 instance of
1584 \family typewriter
1585 Emacs
1586 \family default
1587 ).
1588 This way you can edit multi-line code quickly and with the power of a real
1589 editor right inside IPython.
1590
1591 \end_layout
1592
1593 \begin_layout Standard
1594 If you are a dedicated
1595 \family typewriter
1596 Emacs
1597 \family default
1598 user, you should set up the
1599 \family typewriter
1600 Emacs
1601 \family default
1602 server so that new requests are handled by the original process.
1603 This means that almost no time is spent in handling the request (assuming
1604 an
1605 \family typewriter
1606 Emacs
1607 \family default
1608 process is already running).
1609 For this to work, you need to set your
1610 \family typewriter
1611 EDITOR
1612 \family default
1613 environment variable to
1614 \family typewriter
1615 'emacsclient'
1616 \family default
1617 .
1618
1619 \family typewriter
1620
1621 \family default
1622 The code below, supplied by Francois Pinard, can then be used in your
1623 \family typewriter
1624 .emacs
1625 \family default
1626 file to enable the server:
1627 \end_layout
1628
1629 \begin_layout Standard
1630
1631 \family typewriter
1632 (defvar server-buffer-clients)
1633 \newline
1634 (when (and (fboundp 'server-start) (string-equal
1635 (getenv "TERM") 'xterm))
1636 \newline
1637
1638 \begin_inset ERT
1639 status collapsed
1640
1641 \begin_layout Standard
1642
1643
1644 \backslash
1645 hspace*{0mm}
1646 \end_layout
1647
1648 \end_inset
1649
1650 \InsetSpace ~
1651 \InsetSpace ~
1652 (server-start)
1653 \newline
1654
1655 \begin_inset ERT
1656 status collapsed
1657
1658 \begin_layout Standard
1659
1660
1661 \backslash
1662 hspace*{0mm}
1663 \end_layout
1664
1665 \end_inset
1666
1667 \InsetSpace ~
1668 \InsetSpace ~
1669 (defun fp-kill-server-with-buffer-routine ()
1670 \newline
1671
1672 \begin_inset ERT
1673 status collapsed
1674
1675 \begin_layout Standard
1676
1677
1678 \backslash
1679 hspace*{0mm}
1680 \end_layout
1681
1682 \end_inset
1683
1684 \InsetSpace ~
1685 \InsetSpace ~
1686 \InsetSpace ~
1687 \InsetSpace ~
1688 (and server-buffer-clients (server-done)))
1689 \newline
1690
1691 \begin_inset ERT
1692 status collapsed
1693
1694 \begin_layout Standard
1695
1696
1697 \backslash
1698 hspace*{0mm}
1699 \end_layout
1700
1701 \end_inset
1702
1703 \InsetSpace ~
1704 \InsetSpace ~
1705 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1706 \end_layout
1707
1708 \begin_layout Standard
1709 You can also set the value of this editor via the commmand-line option '-
1710 \family typewriter
1711 editor'
1712 \family default
1713 or in your
1714 \family typewriter
1715 ipythonrc
1716 \family default
1717 file.
1718 This is useful if you wish to use specifically for IPython an editor different
1719 from your typical default (and for Windows users who tend to use fewer
1720 environment variables).
1721 \end_layout
1722
1723 \begin_layout Subsection
1724 Color
1725 \end_layout
1726
1727 \begin_layout Standard
1728 The default IPython configuration has most bells and whistles turned on
1729 (they're pretty safe).
1730 But there's one that
1731 \emph on
1732 may
1733 \emph default
1734 cause problems on some systems: the use of color on screen for displaying
1735 information.
1736 This is very useful, since IPython can show prompts and exception tracebacks
1737 with various colors, display syntax-highlighted source code, and in general
1738 make it easier to visually parse information.
1739 \end_layout
1740
1741 \begin_layout Standard
1742 The following terminals seem to handle the color sequences fine:
1743 \end_layout
1744
1745 \begin_layout Itemize
1746 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1747 \end_layout
1748
1749 \begin_layout Itemize
1750 CDE terminal (tested under Solaris).
1751 This one boldfaces light colors.
1752 \end_layout
1753
1754 \begin_layout Itemize
1755 (X)Emacs buffers.
1756 See sec.
1757 \begin_inset LatexCommand \ref{sec:emacs}
1758
1759 \end_inset
1760
1761 for more details on using IPython with (X)Emacs.
1762 \end_layout
1763
1764 \begin_layout Itemize
1765 A Windows (XP/2k) command prompt
1766 \emph on
1767 with Gary Bishop's support extensions
1768 \emph default
1769 .
1770 Gary's extensions are discussed in Sec.\InsetSpace ~
1771
1772 \begin_inset LatexCommand \ref{sub:Under-Windows}
1773
1774 \end_inset
1775
1776 .
1777 \end_layout
1778
1779 \begin_layout Itemize
1780 A Windows (XP/2k) CygWin shell.
1781 Although some users have reported problems; it is not clear whether there
1782 is an issue for everyone or only under specific configurations.
1783 If you have full color support under cygwin, please post to the IPython
1784 mailing list so this issue can be resolved for all users.
1785 \end_layout
1786
1787 \begin_layout Standard
1788 These have shown problems:
1789 \end_layout
1790
1791 \begin_layout Itemize
1792 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1793 or ssh.
1794 \end_layout
1795
1796 \begin_layout Itemize
1797 Windows native command prompt in WinXP/2k,
1798 \emph on
1799 without
1800 \emph default
1801 Gary Bishop's extensions.
1802 Once Gary's readline library is installed, the normal WinXP/2k command
1803 prompt works perfectly.
1804 \end_layout
1805
1806 \begin_layout Standard
1807 Currently the following color schemes are available:
1808 \end_layout
1809
1810 \begin_layout Itemize
1811
1812 \family typewriter
1813 NoColor
1814 \family default
1815 : uses no color escapes at all (all escapes are empty
1816 \begin_inset Quotes eld
1817 \end_inset
1818
1819
1820 \begin_inset Quotes eld
1821 \end_inset
1822
1823 strings).
1824 This 'scheme' is thus fully safe to use in any terminal.
1825 \end_layout
1826
1827 \begin_layout Itemize
1828
1829 \family typewriter
1830 Linux
1831 \family default
1832 : works well in Linux console type environments: dark background with light
1833 fonts.
1834 It uses bright colors for information, so it is difficult to read if you
1835 have a light colored background.
1836 \end_layout
1837
1838 \begin_layout Itemize
1839
1840 \family typewriter
1841 LightBG
1842 \family default
1843 : the basic colors are similar to those in the
1844 \family typewriter
1845 Linux
1846 \family default
1847 scheme but darker.
1848 It is easy to read in terminals with light backgrounds.
1849 \end_layout
1850
1851 \begin_layout Standard
1852 IPython uses colors for two main groups of things: prompts and tracebacks
1853 which are directly printed to the terminal, and the object introspection
1854 system which passes large sets of data through a pager.
1855 \end_layout
1856
1857 \begin_layout Subsubsection
1858 Input/Output prompts and exception tracebacks
1859 \end_layout
1860
1861 \begin_layout Standard
1862 You can test whether the colored prompts and tracebacks work on your system
1863 interactively by typing
1864 \family typewriter
1865 '%colors Linux'
1866 \family default
1867 at the prompt (use '
1868 \family typewriter
1869 %colors LightBG'
1870 \family default
1871 if your terminal has a light background).
1872 If the input prompt shows garbage like:
1873 \newline
1874
1875 \family typewriter
1876 [0;32mIn [[1;32m1[0;32m]: [0;00m
1877 \family default
1878
1879 \newline
1880 instead of (in color) something like:
1881 \newline
1882
1883 \family typewriter
1884 In [1]:
1885 \family default
1886
1887 \newline
1888 this means that your terminal doesn't properly handle color escape sequences.
1889 You can go to a 'no color' mode by typing '
1890 \family typewriter
1891 %colors NoColor
1892 \family default
1893 '.
1894
1895 \end_layout
1896
1897 \begin_layout Standard
1898 You can try using a different terminal emulator program (Emacs users, see
1899 below).
1900 To permanently set your color preferences, edit the file
1901 \family typewriter
1902 $HOME/.ipython/ipythonrc
1903 \family default
1904 and set the
1905 \family typewriter
1906 colors
1907 \family default
1908 option to the desired value.
1909 \end_layout
1910
1911 \begin_layout Subsubsection
1912 Object details (types, docstrings, source code, etc.)
1913 \end_layout
1914
1915 \begin_layout Standard
1916 IPython has a set of special functions for studying the objects you are
1917 working with, discussed in detail in Sec.
1918
1919 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1920
1921 \end_inset
1922
1923 .
1924 But this system relies on passing information which is longer than your
1925 screen through a data pager, such as the common Unix
1926 \family typewriter
1927 less
1928 \family default
1929 and
1930 \family typewriter
1931 more
1932 \family default
1933 programs.
1934 In order to be able to see this information in color, your pager needs
1935 to be properly configured.
1936 I strongly recommend using
1937 \family typewriter
1938 less
1939 \family default
1940 instead of
1941 \family typewriter
1942 more
1943 \family default
1944 , as it seems that
1945 \family typewriter
1946 more
1947 \family default
1948 simply can not understand colored text correctly.
1949 \end_layout
1950
1951 \begin_layout Standard
1952 In order to configure
1953 \family typewriter
1954 less
1955 \family default
1956 as your default pager, do the following:
1957 \end_layout
1958
1959 \begin_layout Enumerate
1960 Set the environment
1961 \family typewriter
1962 PAGER
1963 \family default
1964 variable to
1965 \family typewriter
1966 less
1967 \family default
1968 .
1969 \end_layout
1970
1971 \begin_layout Enumerate
1972 Set the environment
1973 \family typewriter
1974 LESS
1975 \family default
1976 variable to
1977 \family typewriter
1978 -r
1979 \family default
1980 (plus any other options you always want to pass to
1981 \family typewriter
1982 less
1983 \family default
1984 by default).
1985 This tells
1986 \family typewriter
1987 less
1988 \family default
1989 to properly interpret control sequences, which is how color information
1990 is given to your terminal.
1991 \end_layout
1992
1993 \begin_layout Standard
1994 For the
1995 \family typewriter
1996 csh
1997 \family default
1998 or
1999 \family typewriter
2000 tcsh
2001 \family default
2002 shells, add to your
2003 \family typewriter
2004 ~/.cshrc
2005 \family default
2006 file the lines:
2007 \end_layout
2008
2009 \begin_layout Standard
2010
2011 \family typewriter
2012 setenv PAGER less
2013 \newline
2014 setenv LESS -r
2015 \end_layout
2016
2017 \begin_layout Standard
2018 There is similar syntax for other Unix shells, look at your system documentation
2019 for details.
2020 \end_layout
2021
2022 \begin_layout Standard
2023 If you are on a system which lacks proper data pagers (such as Windows),
2024 IPython will use a very limited builtin pager.
2025 \end_layout
2026
2027 \begin_layout Subsection
2028 \begin_inset LatexCommand \label{sec:emacs}
2029
2030 \end_inset
2031
2032 (X)Emacs configuration
2033 \end_layout
2034
2035 \begin_layout Standard
2036 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
2037 (X)Emacs and IPython get along very well.
2038
2039 \end_layout
2040
2041 \begin_layout Standard
2042
2043 \series bold
2044 Important note:
2045 \series default
2046 You will need to use a recent enough version of
2047 \family typewriter
2048 python-mode.el
2049 \family default
2050 , along with the file
2051 \family typewriter
2052 ipython.el
2053 \family default
2054 .
2055 You can check that the version you have of
2056 \family typewriter
2057 python-mode.el
2058 \family default
2059 is new enough by either looking at the revision number in the file itself,
2060 or asking for it in (X)Emacs via
2061 \family typewriter
2062 M-x py-version
2063 \family default
2064 .
2065 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
2066 \end_layout
2067
2068 \begin_layout Standard
2069 The file
2070 \family typewriter
2071 ipython.el
2072 \family default
2073 is included with the IPython distribution, in the documentation directory
2074 (where this manual resides in PDF and HTML formats).
2075 \end_layout
2076
2077 \begin_layout Standard
2078 Once you put these files in your Emacs path, all you need in your
2079 \family typewriter
2080 .emacs
2081 \family default
2082 file is:
2083 \end_layout
2084
2085 \begin_layout LyX-Code
2086 (require 'ipython)
2087 \end_layout
2088
2089 \begin_layout Standard
2090 This should give you full support for executing code snippets via IPython,
2091 opening IPython as your Python shell via
2092 \family typewriter
2093 C-c\InsetSpace ~
2094 !
2095 \family default
2096 , etc.
2097
2098 \end_layout
2099
2100 \begin_layout Standard
2101 If you happen to get garbage instead of colored prompts as described in
2102 the previous section, you may need to set also in your
2103 \family typewriter
2104 .emacs
2105 \family default
2106 file:
2107 \end_layout
2108
2109 \begin_layout LyX-Code
2110 (setq ansi-color-for-comint-mode t)
2111 \end_layout
2112
2113 \begin_layout Subsubsection*
2114 Notes
2115 \end_layout
2116
2117 \begin_layout Itemize
2118 There is one caveat you should be aware of: you must start the IPython shell
2119
2120 \emph on
2121 before
2122 \emph default
2123 attempting to execute any code regions via
2124 \family typewriter
2125 C-c\InsetSpace ~
2126 |
2127 \family default
2128 .
2129 Simply type
2130 \family typewriter
2131 C-c\InsetSpace ~
2132 !
2133 \family default
2134 to start IPython before passing any code regions to the interpreter, and
2135 you shouldn't experience any problems.
2136 \newline
2137 This is due to a bug in Python itself,
2138 which has been fixed for Python 2.3, but exists as of Python 2.2.2 (reported
2139 as SF bug [ 737947 ]).
2140 \end_layout
2141
2142 \begin_layout Itemize
2143 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
2144 ts should be directed to him through the IPython mailing lists.
2145
2146 \end_layout
2147
2148 \begin_layout Itemize
2149 This code is still somewhat experimental so it's a bit rough around the
2150 edges (although in practice, it works quite well).
2151 \end_layout
2152
2153 \begin_layout Itemize
2154 Be aware that if you customize
2155 \family typewriter
2156 py-python-command
2157 \family default
2158 previously, this value will override what
2159 \family typewriter
2160 ipython.el
2161 \family default
2162 does (because loading the customization variables comes later).
2163 \end_layout
2164
2165 \begin_layout Section
2166 \begin_inset LatexCommand \label{sec:quick_tips}
2167
2168 \end_inset
2169
2170 Quick tips
2171 \end_layout
2172
2173 \begin_layout Standard
2174 IPython can be used as an improved replacement for the Python prompt, and
2175 for that you don't really need to read any more of this manual.
2176 But in this section we'll try to summarize a few tips on how to make the
2177 most effective use of it for everyday Python development, highlighting
2178 things you might miss in the rest of the manual (which is getting long).
2179 We'll give references to parts in the manual which provide more detail
2180 when appropriate.
2181 \end_layout
2182
2183 \begin_layout Standard
2184 The following article by Jeremy Jones provides an introductory tutorial
2185 about IPython:
2186 \newline
2187
2188 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
2189
2190 \end_inset
2191
2192
2193 \end_layout
2194
2195 \begin_layout Itemize
2196 The TAB key.
2197 TAB-completion, especially for attributes, is a convenient way to explore
2198 the structure of any object you're dealing with.
2199 Simply type
2200 \family typewriter
2201 object_name.<TAB>
2202 \family default
2203 and a list of the object's attributes will be printed (see sec.
2204
2205 \begin_inset LatexCommand \ref{sec:readline}
2206
2207 \end_inset
2208
2209 for more).
2210 Tab completion also works on file and directory names, which combined with
2211 IPython's alias system allows you to do from within IPython many of the
2212 things you normally would need the system shell for.
2213
2214 \end_layout
2215
2216 \begin_layout Itemize
2217 Explore your objects.
2218 Typing
2219 \family typewriter
2220 object_name?
2221 \family default
2222 will print all sorts of details about any object, including docstrings,
2223 function definition lines (for call arguments) and constructor details
2224 for classes.
2225 The magic commands
2226 \family typewriter
2227 %pdoc
2228 \family default
2229 ,
2230 \family typewriter
2231 %pdef
2232 \family default
2233 ,
2234 \family typewriter
2235 %psource
2236 \family default
2237 and
2238 \family typewriter
2239 %pfile
2240 \family default
2241 will respectively print the docstring, function definition line, full source
2242 code and the complete file for any object (when they can be found).
2243 If automagic is on (it is by default), you don't need to type the '
2244 \family typewriter
2245 %
2246 \family default
2247 ' explicitly.
2248 See sec.
2249
2250 \begin_inset LatexCommand \ref{sec:dyn-object-info}
2251
2252 \end_inset
2253
2254 for more.
2255 \end_layout
2256
2257 \begin_layout Itemize
2258 The
2259 \family typewriter
2260 %run
2261 \family default
2262 magic command allows you to run any python script and load all of its data
2263 directly into the interactive namespace.
2264 Since the file is re-read from disk each time, changes you make to it are
2265 reflected immediately (in contrast to the behavior of
2266 \family typewriter
2267 import
2268 \family default
2269 ).
2270 I rarely use
2271 \family typewriter
2272 import
2273 \family default
2274 for code I am testing, relying on
2275 \family typewriter
2276 %run
2277 \family default
2278 instead.
2279 See sec.
2280
2281 \begin_inset LatexCommand \ref{sec:magic}
2282
2283 \end_inset
2284
2285 for more on this and other magic commands, or type the name of any magic
2286 command and ? to get details on it.
2287 See also sec.
2288
2289 \begin_inset LatexCommand \ref{sec:dreload}
2290
2291 \end_inset
2292
2293 for a recursive reload command.
2294 \newline
2295
2296 \family typewriter
2297 %run
2298 \family default
2299 also has special flags for timing the execution of your scripts (
2300 \family typewriter
2301 -t
2302 \family default
2303 ) and for executing them under the control of either Python's
2304 \family typewriter
2305 pdb
2306 \family default
2307 debugger (
2308 \family typewriter
2309 -d
2310 \family default
2311 ) or profiler (
2312 \family typewriter
2313 -p
2314 \family default
2315 ).
2316 With all of these,
2317 \family typewriter
2318 %run
2319 \family default
2320 can be used as the main tool for efficient interactive development of code
2321 which you write in your editor of choice.
2322 \end_layout
2323
2324 \begin_layout Itemize
2325 Use the Python debugger,
2326 \family typewriter
2327 pdb
2328 \family default
2329
2330 \begin_inset Foot
2331 status collapsed
2332
2333 \begin_layout Standard
2334 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2335 to IPython's improved debugger and profiler support.
2336 \end_layout
2337
2338 \end_inset
2339
2340 .
2341 The
2342 \family typewriter
2343 %pdb
2344 \family default
2345 command allows you to toggle on and off the automatic invocation of an
2346 IPython-enhanced
2347 \family typewriter
2348 pdb
2349 \family default
2350 debugger (with coloring, tab completion and more) at any uncaught exception.
2351 The advantage of this is that
2352 \family typewriter
2353 pdb
2354 \family default
2355 starts
2356 \emph on
2357 inside
2358 \emph default
2359 the function where the exception occurred, with all data still available.
2360 You can print variables, see code, execute statements and even walk up
2361 and down the call stack to track down the true source of the problem (which
2362 often is many layers in the stack above where the exception gets triggered).
2363 \newline
2364 Runn
2365 ing programs with
2366 \family typewriter
2367 %run
2368 \family default
2369 and pdb active can be an efficient to develop and debug code, in many cases
2370 eliminating the need for
2371 \family typewriter
2372 print
2373 \family default
2374 statements or external debugging tools.
2375 I often simply put a
2376 \family typewriter
2377 1/0
2378 \family default
2379 in a place where I want to take a look so that pdb gets called, quickly
2380 view whatever variables I need to or test various pieces of code and then
2381 remove the
2382 \family typewriter
2383 1/0
2384 \family default
2385 .
2386 \newline
2387 Note also that `
2388 \family typewriter
2389 %run -d
2390 \family default
2391 ' activates
2392 \family typewriter
2393 pdb
2394 \family default
2395 and automatically sets initial breakpoints for you to step through your
2396 code, watch variables, etc.
2397 See Sec.\InsetSpace ~
2398
2399 \begin_inset LatexCommand \ref{sec:cache_output}
2400
2401 \end_inset
2402
2403 for details.
2404 \end_layout
2405
2406 \begin_layout Itemize
2407 Use the output cache.
2408 All output results are automatically stored in a global dictionary named
2409
2410 \family typewriter
2411 Out
2412 \family default
2413 and variables named
2414 \family typewriter
2415 _1
2416 \family default
2417 ,
2418 \family typewriter
2419 _2
2420 \family default
2421 , etc.
2422 alias them.
2423 For example, the result of input line 4 is available either as
2424 \family typewriter
2425 Out[4]
2426 \family default
2427 or as
2428 \family typewriter
2429 _4
2430 \family default
2431 .
2432 Additionally, three variables named
2433 \family typewriter
2434 _
2435 \family default
2436 ,
2437 \family typewriter
2438 __
2439 \family default
2440 and
2441 \family typewriter
2442 ___
2443 \family default
2444 are always kept updated with the for the last three results.
2445 This allows you to recall any previous result and further use it for new
2446 calculations.
2447 See Sec.\InsetSpace ~
2448
2449 \begin_inset LatexCommand \ref{sec:cache_output}
2450
2451 \end_inset
2452
2453 for more.
2454 \end_layout
2455
2456 \begin_layout Itemize
2457 Put a '
2458 \family typewriter
2459 ;
2460 \family default
2461 ' at the end of a line to supress the printing of output.
2462 This is useful when doing calculations which generate long output you are
2463 not interested in seeing.
2464 The
2465 \family typewriter
2466 _*
2467 \family default
2468 variables and the
2469 \family typewriter
2470 Out[]
2471 \family default
2472 list do get updated with the contents of the output, even if it is not
2473 printed.
2474 You can thus still access the generated results this way for further processing.
2475 \end_layout
2476
2477 \begin_layout Itemize
2478 A similar system exists for caching input.
2479 All input is stored in a global list called
2480 \family typewriter
2481 In
2482 \family default
2483 , so you can re-execute lines 22 through 28 plus line 34 by typing
2484 \family typewriter
2485 'exec In[22:29]+In[34]'
2486 \family default
2487 (using Python slicing notation).
2488 If you need to execute the same set of lines often, you can assign them
2489 to a macro with the
2490 \family typewriter
2491 %macro
2492 \family default
2493
2494 \family typewriter
2495 function.
2496
2497 \family default
2498 See sec.
2499
2500 \begin_inset LatexCommand \ref{sec:cache_input}
2501
2502 \end_inset
2503
2504 for more.
2505 \end_layout
2506
2507 \begin_layout Itemize
2508 Use your input history.
2509 The
2510 \family typewriter
2511 %hist
2512 \family default
2513 command can show you all previous input, without line numbers if desired
2514 (option
2515 \family typewriter
2516 -n
2517 \family default
2518 ) so you can directly copy and paste code either back in IPython or in a
2519 text editor.
2520 You can also save all your history by turning on logging via
2521 \family typewriter
2522 %logstart
2523 \family default
2524 ; these logs can later be either reloaded as IPython sessions or used as
2525 code for your programs.
2526 \end_layout
2527
2528 \begin_layout Itemize
2529 Define your own system aliases.
2530 Even though IPython gives you access to your system shell via the
2531 \family typewriter
2532 !
2533 \family default
2534 prefix, it is convenient to have aliases to the system commands you use
2535 most often.
2536 This allows you to work seamlessly from inside IPython with the same commands
2537 you are used to in your system shell.
2538 \newline
2539 IPython comes with some pre-defined
2540 aliases and a complete system for changing directories, both via a stack
2541 (see
2542 \family typewriter
2543 %pushd
2544 \family default
2545 ,
2546 \family typewriter
2547 %popd
2548 \family default
2549 and
2550 \family typewriter
2551 %dhist
2552 \family default
2553 ) and via direct
2554 \family typewriter
2555 %cd
2556 \family default
2557 .
2558 The latter keeps a history of visited directories and allows you to go
2559 to any previously visited one.
2560 \end_layout
2561
2562 \begin_layout Itemize
2563 Use Python to manipulate the results of system commands.
2564 The `
2565 \family typewriter
2566 !!
2567 \family default
2568 ' special syntax, and the
2569 \family typewriter
2570 %sc
2571 \family default
2572 and
2573 \family typewriter
2574 %sx
2575 \family default
2576 magic commands allow you to capture system output into Python variables.
2577 \end_layout
2578
2579 \begin_layout Itemize
2580 Expand python variables when calling the shell (either via
2581 \family typewriter
2582 `!'
2583 \family default
2584 and
2585 \family typewriter
2586 `!!'
2587 \family default
2588 or via aliases) by prepending a
2589 \family typewriter
2590 $
2591 \family default
2592 in front of them.
2593 You can also expand complete python expressions.
2594 See sec.\InsetSpace ~
2595
2596 \begin_inset LatexCommand \ref{sub:System-shell-access}
2597
2598 \end_inset
2599
2600 for more.
2601 \end_layout
2602
2603 \begin_layout Itemize
2604 Use profiles to maintain different configurations (modules to load, function
2605 definitions, option settings) for particular tasks.
2606 You can then have customized versions of IPython for specific purposes.
2607 See sec.\InsetSpace ~
2608
2609 \begin_inset LatexCommand \ref{sec:profiles}
2610
2611 \end_inset
2612
2613 for more.
2614 \end_layout
2615
2616 \begin_layout Itemize
2617 Embed IPython in your programs.
2618 A few lines of code are enough to load a complete IPython inside your own
2619 programs, giving you the ability to work with your data interactively after
2620 automatic processing has been completed.
2621 See sec.\InsetSpace ~
2622
2623 \begin_inset LatexCommand \ref{sec:embed}
2624
2625 \end_inset
2626
2627 for more.
2628 \end_layout
2629
2630 \begin_layout Itemize
2631 Use the Python profiler.
2632 When dealing with performance issues, the
2633 \family typewriter
2634 %run
2635 \family default
2636 command with a
2637 \family typewriter
2638 -p
2639 \family default
2640 option allows you to run complete programs under the control of the Python
2641 profiler.
2642 The
2643 \family typewriter
2644 %prun
2645 \family default
2646 command does a similar job for single Python expressions (like function
2647 calls).
2648 \end_layout
2649
2650 \begin_layout Itemize
2651 Use the IPython.demo.Demo class to load any Python script as an interactive
2652 demo.
2653 With a minimal amount of simple markup, you can control the execution of
2654 the script, stopping as needed.
2655 See sec.\InsetSpace ~
2656
2657 \begin_inset LatexCommand \ref{sec:interactive-demos}
2658
2659 \end_inset
2660
2661 for more.
2662 \end_layout
2663
2664 \begin_layout Itemize
2665 Run your doctests from within IPython for development and debugging.
2666 The special
2667 \family typewriter
2668 %doctest_mode
2669 \family default
2670 command toggles a mode where the prompt, output and exceptions display
2671 matches as closely as possible that of the default Python interpreter.
2672 In addition, this mode allows you to directly paste in code that contains
2673 leading `
2674 \family typewriter
2675 >>>
2676 \family default
2677 ' prompts, even if they have extra leading whitespace (as is common in doctest
2678 files).
2679 This combined with the `
2680 \family typewriter
2681 %history -t
2682 \family default
2683 n' call to see your translated history (with these extra prompts removed
2684 and no line numbers) allows for an easy doctest workflow, where you can
2685 go from doctest to interactive execution to pasting into valid Python code
2686 as needed.
2687 \end_layout
2688
2689 \begin_layout Subsection
2690 Source code handling tips
2691 \end_layout
2692
2693 \begin_layout Standard
2694 IPython is a line-oriented program, without full control of the terminal.
2695 Therefore, it doesn't support true multiline editing.
2696 However, it has a number of useful tools to help you in dealing effectively
2697 with more complex editing.
2698 \end_layout
2699
2700 \begin_layout Standard
2701 The
2702 \family typewriter
2703 %edit
2704 \family default
2705 command gives a reasonable approximation of multiline editing, by invoking
2706 your favorite editor on the spot.
2707 IPython will execute the code you type in there as if it were typed interactive
2708 ly.
2709 Type
2710 \family typewriter
2711 %edit?
2712 \family default
2713 for the full details on the edit command.
2714 \end_layout
2715
2716 \begin_layout Standard
2717 If you have typed various commands during a session, which you'd like to
2718 reuse, IPython provides you with a number of tools.
2719 Start by using
2720 \family typewriter
2721 %hist
2722 \family default
2723 to see your input history, so you can see the line numbers of all input.
2724 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
2725 and 28.
2726 All the commands below can operate on these with the syntax
2727 \end_layout
2728
2729 \begin_layout LyX-Code
2730 %command 10-20 24 28
2731 \end_layout
2732
2733 \begin_layout Standard
2734 where the command given can be:
2735 \end_layout
2736
2737 \begin_layout Itemize
2738
2739 \family typewriter
2740 %macro <macroname>
2741 \family default
2742 : this stores the lines into a variable which, when called at the prompt,
2743 re-executes the input.
2744 Macros can be edited later using
2745 \family typewriter
2746 `%edit macroname
2747 \family default
2748 ', and they can be stored persistently across sessions with `
2749 \family typewriter
2750 %store macroname
2751 \family default
2752 ' (the storage system is per-profile).
2753 The combination of quick macros, persistent storage and editing, allows
2754 you to easily refine quick-and-dirty interactive input into permanent utilities
2755 , always available both in IPython and as files for general reuse.
2756 \end_layout
2757
2758 \begin_layout Itemize
2759
2760 \family typewriter
2761 %edit
2762 \family default
2763 : this will open a text editor with those lines pre-loaded for further modificat
2764 ion.
2765 It will then execute the resulting file's contents as if you had typed
2766 it at the prompt.
2767 \end_layout
2768
2769 \begin_layout Itemize
2770
2771 \family typewriter
2772 %save <filename>
2773 \family default
2774 : this saves the lines directly to a named file on disk.
2775 \end_layout
2776
2777 \begin_layout Standard
2778 While
2779 \family typewriter
2780 %macro
2781 \family default
2782 saves input lines into memory for interactive re-execution, sometimes you'd
2783 like to save your input directly to a file.
2784 The
2785 \family typewriter
2786 %save
2787 \family default
2788 magic does this: its input sytnax is the same as
2789 \family typewriter
2790 %macro
2791 \family default
2792 , but it saves your input directly to a Python file.
2793 Note that the
2794 \family typewriter
2795 %logstart
2796 \family default
2797 command also saves input, but it logs
2798 \emph on
2799 all
2800 \emph default
2801 input to disk (though you can temporarily suspend it and reactivate it
2802 with
2803 \family typewriter
2804 %logoff/%logon
2805 \family default
2806 );
2807 \family typewriter
2808 %save
2809 \family default
2810 allows you to select which lines of input you need to save.
2811 \end_layout
2812
2813 \begin_layout Subsubsection*
2814 Lightweight 'version control'
2815 \end_layout
2816
2817 \begin_layout Standard
2818 When you call
2819 \family typewriter
2820 %edit
2821 \family default
2822 with no arguments, IPython opens an empty editor with a temporary file,
2823 and it returns the contents of your editing session as a string variable.
2824 Thanks to IPython's output caching mechanism, this is automatically stored:
2825 \end_layout
2826
2827 \begin_layout LyX-Code
2828 In [1]: %edit
2829 \end_layout
2830
2831 \begin_layout LyX-Code
2832 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
2833 \end_layout
2834
2835 \begin_layout LyX-Code
2836 Editing...
2837 done.
2838 Executing edited code...
2839 \end_layout
2840
2841 \begin_layout LyX-Code
2842 hello - this is a temporary file
2843 \end_layout
2844
2845 \begin_layout LyX-Code
2846 Out[1]: "print 'hello - this is a temporary file'
2847 \backslash
2848 n"
2849 \end_layout
2850
2851 \begin_layout Standard
2852 Now, if you call
2853 \family typewriter
2854 `%edit -p'
2855 \family default
2856 , IPython tries to open an editor with the same data as the last time you
2857 used
2858 \family typewriter
2859 %edit
2860 \family default
2861 .
2862 So if you haven't used
2863 \family typewriter
2864 %edit
2865 \family default
2866 in the meantime, this same contents will reopen; however, it will be done
2867 in a
2868 \emph on
2869 new file
2870 \emph default
2871 .
2872 This means that if you make changes and you later want to find an old version,
2873 you can always retrieve it by using its output number, via
2874 \family typewriter
2875 `%edit _NN'
2876 \family default
2877 , where
2878 \family typewriter
2879 NN
2880 \family default
2881 is the number of the output prompt.
2882 \end_layout
2883
2884 \begin_layout Standard
2885 Continuing with the example above, this should illustrate this idea:
2886 \end_layout
2887
2888 \begin_layout LyX-Code
2889 In [2]: edit -p
2890 \end_layout
2891
2892 \begin_layout LyX-Code
2893 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
2894 \end_layout
2895
2896 \begin_layout LyX-Code
2897 Editing...
2898 done.
2899 Executing edited code...
2900 \end_layout
2901
2902 \begin_layout LyX-Code
2903 hello - now I made some changes
2904 \end_layout
2905
2906 \begin_layout LyX-Code
2907 Out[2]: "print 'hello - now I made some changes'
2908 \backslash
2909 n"
2910 \end_layout
2911
2912 \begin_layout LyX-Code
2913 In [3]: edit _1
2914 \end_layout
2915
2916 \begin_layout LyX-Code
2917 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
2918 \end_layout
2919
2920 \begin_layout LyX-Code
2921 Editing...
2922 done.
2923 Executing edited code...
2924 \end_layout
2925
2926 \begin_layout LyX-Code
2927 hello - this is a temporary file
2928 \end_layout
2929
2930 \begin_layout LyX-Code
2931 IPython version control at work :)
2932 \end_layout
2933
2934 \begin_layout LyX-Code
2935 Out[3]: "print 'hello - this is a temporary file'
2936 \backslash
2937 nprint 'IPython version control at work :)'
2938 \backslash
2939 n"
2940 \end_layout
2941
2942 \begin_layout Standard
2943 This section was written after a contribution by Alexander Belchenko on
2944 the IPython user list.
2945 \end_layout
2946
2947 \begin_layout LyX-Code
2948
2949 \end_layout
2950
2951 \begin_layout Subsection
2952 Effective logging
2953 \end_layout
2954
2955 \begin_layout Standard
2956 A very useful suggestion sent in by Robert Kern follows:
2957 \end_layout
2958
2959 \begin_layout Standard
2960 I recently happened on a nifty way to keep tidy per-project log files.
2961 I made a profile for my project (which is called "parkfield").
2962 \end_layout
2963
2964 \begin_layout LyX-Code
2965 include ipythonrc
2966 \end_layout
2967
2968 \begin_layout LyX-Code
2969 # cancel earlier logfile invocation:
2970 \end_layout
2971
2972 \begin_layout LyX-Code
2973 logfile ''
2974 \end_layout
2975
2976 \begin_layout LyX-Code
2977 execute import time
2978 \end_layout
2979
2980 \begin_layout LyX-Code
2981 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2982 \end_layout
2983
2984 \begin_layout LyX-Code
2985 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2986 \end_layout
2987
2988 \begin_layout Standard
2989 I also added a shell alias for convenience:
2990 \end_layout
2991
2992 \begin_layout LyX-Code
2993 alias parkfield="ipython -pylab -profile parkfield"
2994 \end_layout
2995
2996 \begin_layout Standard
2997 Now I have a nice little directory with everything I ever type in, organized
2998 by project and date.
2999 \end_layout
3000
3001 \begin_layout Standard
3002
3003 \series bold
3004 Contribute your own:
3005 \series default
3006 If you have your own favorite tip on using IPython efficiently for a certain
3007 task (especially things which can't be done in the normal Python interpreter),
3008 don't hesitate to send it!
3009 \end_layout
3010
3011 \begin_layout Section
3012 Command-line use
3013 \end_layout
3014
3015 \begin_layout Standard
3016 You start IPython with the command:
3017 \end_layout
3018
3019 \begin_layout Standard
3020
3021 \family typewriter
3022 $ ipython [options] files
3023 \end_layout
3024
3025 \begin_layout Standard
3026 If invoked with no options, it executes all the files listed in sequence
3027 and drops you into the interpreter while still acknowledging any options
3028 you may have set in your ipythonrc file.
3029 This behavior is different from standard Python, which when called as
3030 \family typewriter
3031 python -i
3032 \family default
3033 will only execute one file and ignore your configuration setup.
3034 \end_layout
3035
3036 \begin_layout Standard
3037 Please note that some of the configuration options are not available at
3038 the command line, simply because they are not practical here.
3039 Look into your ipythonrc configuration file for details on those.
3040 This file typically installed in the
3041 \family typewriter
3042 $HOME/.ipython
3043 \family default
3044 directory.
3045 For Windows users,
3046 \family typewriter
3047 $HOME
3048 \family default
3049 resolves to
3050 \family typewriter
3051 C:
3052 \backslash
3053
3054 \backslash
3055 Documents and Settings
3056 \backslash
3057
3058 \backslash
3059 YourUserName
3060 \family default
3061 in most instances.
3062 In the rest of this text, we will refer to this directory as
3063 \family typewriter
3064 IPYTHONDIR
3065 \family default
3066 .
3067 \end_layout
3068
3069 \begin_layout Subsection
3070 \begin_inset LatexCommand \label{sec:threading-opts}
3071
3072 \end_inset
3073
3074 Special Threading Options
3075 \end_layout
3076
3077 \begin_layout Standard
3078 The following special options are ONLY valid at the beginning of the command
3079 line, and not later.
3080 This is because they control the initial- ization of ipython itself, before
3081 the normal option-handling mechanism is active.
3082 \end_layout
3083
3084 \begin_layout List
3085 \labelwidthstring 00.00.0000
3086
3087 \family typewriter
3088 \series bold
3089 -gthread,\InsetSpace ~
3090 -qthread,\InsetSpace ~
3091 -q4thread,\InsetSpace ~
3092 -wthread,\InsetSpace ~
3093 -pylab:
3094 \family default
3095 \series default
3096 Only
3097 \emph on
3098 one
3099 \emph default
3100 of these can be given, and it can only be given as the first option passed
3101 to IPython (it will have no effect in any other position).
3102 They provide threading support for the GTK, Qt (versions 3 and 4) and WXPython
3103 toolkits, and for the matplotlib library.
3104 \end_layout
3105
3106 \begin_layout List
3107 \labelwidthstring 00.00.0000
3108 \InsetSpace ~
3109 With any of the first four options, IPython starts running a separate thread
3110 for the graphical toolkit's operation, so that you can open and control
3111 graphical elements from within an IPython command line, without blocking.
3112 All four provide essentially the same functionality, respectively for GTK,
3113 Qt3, Qt4 and WXWidgets (via their Python interfaces).
3114 \end_layout
3115
3116 \begin_layout List
3117 \labelwidthstring 00.00.0000
3118 \InsetSpace ~
3119 Note that with
3120 \family typewriter
3121 -wthread
3122 \family default
3123 , you can additionally use the -wxversion option to request a specific version
3124 of wx to be used.
3125 This requires that you have the
3126 \family typewriter
3127 wxversion
3128 \family default
3129 Python module installed, which is part of recent wxPython distributions.
3130 \end_layout
3131
3132 \begin_layout List
3133 \labelwidthstring 00.00.0000
3134 \InsetSpace ~
3135 If
3136 \family typewriter
3137 -pylab
3138 \family default
3139 is given, IPython loads special support for the mat plotlib library (
3140 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
3141
3142 \end_inset
3143
3144 ), allowing interactive usage of any of its backends as defined in the user's
3145
3146 \family typewriter
3147 ~/.matplotlib/matplotlibrc
3148 \family default
3149 file.
3150 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
3151 of matplotlib backend requires it.
3152 It also modifies the
3153 \family typewriter
3154 %run
3155 \family default
3156 command to correctly execute (without blocking) any matplotlib-based script
3157 which calls
3158 \family typewriter
3159 show()
3160 \family default
3161 at the end.
3162
3163 \end_layout
3164
3165 \begin_layout List
3166 \labelwidthstring 00.00.0000
3167
3168 \family typewriter
3169 \series bold
3170 -tk
3171 \family default
3172 \series default
3173 The
3174 \family typewriter
3175 -g/q/q4/wthread
3176 \family default
3177 options, and
3178 \family typewriter
3179 -pylab
3180 \family default
3181 (if matplotlib is configured to use GTK, Qt3, Qt4 or WX), will normally
3182 block Tk graphical interfaces.
3183 This means that when either GTK, Qt or WX threading is active, any attempt
3184 to open a Tk GUI will result in a dead window, and possibly cause the Python
3185 interpreter to crash.
3186 An extra option,
3187 \family typewriter
3188 -tk
3189 \family default
3190 , is available to address this issue.
3191 It can
3192 \emph on
3193 only
3194 \emph default
3195 be given as a
3196 \emph on
3197 second
3198 \emph default
3199 option after any of the above (
3200 \family typewriter
3201 -gthread
3202 \family default
3203 ,
3204 \family typewriter
3205 -wthread
3206 \family default
3207 or
3208 \family typewriter
3209 -pylab
3210 \family default
3211 ).
3212 \end_layout
3213
3214 \begin_layout List
3215 \labelwidthstring 00.00.0000
3216 \InsetSpace ~
3217 If
3218 \family typewriter
3219 -tk
3220 \family default
3221 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
3222 This is however potentially unreliable, and you will have to test on your
3223 platform and Python configuration to determine whether it works for you.
3224 Debian users have reported success, apparently due to the fact that Debian
3225 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
3226 Under other Linux environments (such as Fedora Core 2/3), this option has
3227 caused random crashes and lockups of the Python interpreter.
3228 Under other operating systems (Mac OSX and Windows), you'll need to try
3229 it to find out, since currently no user reports are available.
3230 \end_layout
3231
3232 \begin_layout List
3233 \labelwidthstring 00.00.0000
3234 \InsetSpace ~
3235 There is unfortunately no way for IPython to determine at run time whether
3236
3237 \family typewriter
3238 -tk
3239 \family default
3240 will work reliably or not, so you will need to do some experiments before
3241 relying on it for regular work.
3242
3243 \end_layout
3244
3245 \begin_layout Subsection
3246 \begin_inset LatexCommand \label{sec:cmd-line-opts}
3247
3248 \end_inset
3249
3250 Regular Options
3251 \end_layout
3252
3253 \begin_layout Standard
3254 After the above threading options have been given, regular options can follow
3255 in any order.
3256 All options can be abbreviated to their shortest non-ambiguous form and
3257 are case-sensitive.
3258 One or two dashes can be used.
3259 Some options have an alternate short form, indicated after a
3260 \family typewriter
3261 |
3262 \family default
3263 .
3264 \end_layout
3265
3266 \begin_layout Standard
3267 Most options can also be set from your ipythonrc configuration file.
3268 See the provided example for more details on what the options do.
3269 Options given at the command line override the values set in the ipythonrc
3270 file.
3271 \end_layout
3272
3273 \begin_layout Standard
3274 All options with a
3275 \family typewriter
3276 [no]
3277 \family default
3278 prepended can be specified in negated form (
3279 \family typewriter
3280 -nooption
3281 \family default
3282 instead of
3283 \family typewriter
3284 -option
3285 \family default
3286 ) to turn the feature off.
3287 \end_layout
3288
3289 \begin_layout List
3290 \labelwidthstring 00.00.0000
3291
3292 \family typewriter
3293 \series bold
3294 -help
3295 \family default
3296 \series default
3297 : print a help message and exit.
3298 \end_layout
3299
3300 \begin_layout List
3301 \labelwidthstring 00.00.0000
3302
3303 \family typewriter
3304 \series bold
3305 -pylab:
3306 \family default
3307 \series default
3308 this can
3309 \emph on
3310 only
3311 \emph default
3312 be given as the
3313 \emph on
3314 first
3315 \emph default
3316 option passed to IPython (it will have no effect in any other position).
3317 It adds special support for the matplotlib library (
3318 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
3319
3320 \end_inset
3321
3322 ), allowing interactive usage of any of its backends as defined in the user's
3323
3324 \family typewriter
3325 .matplotlibrc
3326 \family default
3327 file.
3328 It automatically activates GTK or WX threading for IPyhton if the choice
3329 of matplotlib backend requires it.
3330 It also modifies the
3331 \family typewriter
3332 %run
3333 \family default
3334 command to correctly execute (without blocking) any matplotlib-based script
3335 which calls
3336 \family typewriter
3337 show()
3338 \family default
3339 at the end.
3340 See Sec.\InsetSpace ~
3341
3342 \begin_inset LatexCommand \ref{sec:matplotlib-support}
3343
3344 \end_inset
3345
3346 for more details.
3347 \end_layout
3348
3349 \begin_layout List
3350 \labelwidthstring 00.00.0000
3351
3352 \family typewriter
3353 \series bold
3354 -autocall <val>:
3355 \family default
3356 \series default
3357 Make IPython automatically call any callable object even if you didn't
3358 type explicit parentheses.
3359 For example, `str 43' becomes `str(43)' automatically.
3360 The value can be `0' to disable the feature, `1' for
3361 \emph on
3362 smart
3363 \emph default
3364 autocall, where it is not applied if there are no more arguments on the
3365 line, and `2' for
3366 \emph on
3367 full
3368 \emph default
3369 autocall, where all callable objects are automatically called (even if
3370 no arguments are present).
3371 The default is `1'.
3372 \end_layout
3373
3374 \begin_layout List
3375 \labelwidthstring 00.00.0000
3376
3377 \family typewriter
3378 \series bold
3379 -[no]autoindent:
3380 \family default
3381 \series default
3382 Turn automatic indentation on/off.
3383 \end_layout
3384
3385 \begin_layout List
3386 \labelwidthstring 00.00.0000
3387
3388 \family typewriter
3389 \series bold
3390 -[no]automagic
3391 \series default
3392 :
3393 \family default
3394 make magic commands automatic (without needing their first character to
3395 be
3396 \family typewriter
3397 %
3398 \family default
3399 ).
3400 Type
3401 \family typewriter
3402 %magic
3403 \family default
3404 at the IPython prompt for more information.
3405 \end_layout
3406
3407 \begin_layout List
3408 \labelwidthstring 00.00.0000
3409
3410 \family typewriter
3411 \series bold
3412 -[no]autoedit_syntax:
3413 \family default
3414 \series default
3415 When a syntax error occurs after editing a file, automatically open the
3416 file to the trouble causing line for convenient fixing.
3417
3418 \end_layout
3419
3420 \begin_layout List
3421 \labelwidthstring 00.00.0000
3422
3423 \family typewriter
3424 \series bold
3425 -[no]banner
3426 \series default
3427 :
3428 \family default
3429 Print the initial information banner (default on).
3430 \end_layout
3431
3432 \begin_layout List
3433 \labelwidthstring 00.00.0000
3434
3435 \family typewriter
3436 \series bold
3437 -c\InsetSpace ~
3438 <command>:
3439 \family default
3440 \series default
3441 execute the given command string, and set sys.argv to
3442 \family typewriter
3443 ['c']
3444 \family default
3445 .
3446 This is similar to the
3447 \family typewriter
3448 -c
3449 \family default
3450 option in the normal Python interpreter.
3451
3452 \end_layout
3453
3454 \begin_layout List
3455 \labelwidthstring 00.00.0000
3456
3457 \family typewriter
3458 \series bold
3459 -cache_size|cs\InsetSpace ~
3460 <n>
3461 \series default
3462 :
3463 \family default
3464 size of the output cache (maximum number of entries to hold in memory).
3465 The default is 1000, you can change it permanently in your config file.
3466 Setting it to 0 completely disables the caching system, and the minimum
3467 value accepted is 20 (if you provide a value less than 20, it is reset
3468 to 0 and a warning is issued) This limit is defined because otherwise you'll
3469 spend more time re-flushing a too small cache than working.
3470 \end_layout
3471
3472 \begin_layout List
3473 \labelwidthstring 00.00.0000
3474
3475 \family typewriter
3476 \series bold
3477 -classic|cl
3478 \series default
3479 :
3480 \family default
3481 Gives IPython a similar feel to the classic Python prompt.
3482 \end_layout
3483
3484 \begin_layout List
3485 \labelwidthstring 00.00.0000
3486
3487 \family typewriter
3488 \series bold
3489 -colors\InsetSpace ~
3490 <scheme>:
3491 \family default
3492 \series default
3493 Color scheme for prompts and exception reporting.
3494 Currently implemented: NoColor, Linux and LightBG.
3495 \end_layout
3496
3497 \begin_layout List
3498 \labelwidthstring 00.00.0000
3499
3500 \family typewriter
3501 \series bold
3502 -[no]color_info:
3503 \family default
3504 \series default
3505 IPython can display information about objects via a set of functions, and
3506 optionally can use colors for this, syntax highlighting source code and
3507 various other elements.
3508 However, because this information is passed through a pager (like 'less')
3509 and many pagers get confused with color codes, this option is off by default.
3510 You can test it and turn it on permanently in your ipythonrc file if it
3511 works for you.
3512 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
3513 that in RedHat 7.2 doesn't.
3514 \end_layout
3515
3516 \begin_layout List
3517 \labelwidthstring 00.00.0000
3518 \InsetSpace ~
3519 Test it and turn it on permanently if it works with your system.
3520 The magic function
3521 \family typewriter
3522 %color_info
3523 \family default
3524 allows you to toggle this interactively for testing.
3525 \end_layout
3526
3527 \begin_layout List
3528 \labelwidthstring 00.00.0000
3529
3530 \family typewriter
3531 \series bold
3532 -[no]debug
3533 \family default
3534 \series default
3535 : Show information about the loading process.
3536 Very useful to pin down problems with your configuration files or to get
3537 details about session restores.
3538 \end_layout
3539
3540 \begin_layout List
3541 \labelwidthstring 00.00.0000
3542
3543 \family typewriter
3544 \series bold
3545 -[no]deep_reload
3546 \series default
3547 :
3548 \family default
3549 IPython can use the
3550 \family typewriter
3551 deep_reload
3552 \family default
3553 module which reloads changes in modules recursively (it replaces the
3554 \family typewriter
3555 reload()
3556 \family default
3557 function, so you don't need to change anything to use it).
3558
3559 \family typewriter
3560 deep_reload()
3561 \family default
3562 forces a full reload of modules whose code may have changed, which the
3563 default
3564 \family typewriter
3565 reload()
3566 \family default
3567 function does not.
3568 \end_layout
3569
3570 \begin_layout List
3571 \labelwidthstring 00.00.0000
3572 \InsetSpace ~
3573 When deep_reload is off, IPython will use the normal
3574 \family typewriter
3575 reload()
3576 \family default
3577 , but deep_reload will still be available as
3578 \family typewriter
3579 dreload()
3580 \family default
3581 .
3582 This feature is off by default [which means that you have both normal
3583 \family typewriter
3584 reload()
3585 \family default
3586 and
3587 \family typewriter
3588 dreload()
3589 \family default
3590 ].
3591 \end_layout
3592
3593 \begin_layout List
3594 \labelwidthstring 00.00.0000
3595
3596 \family typewriter
3597 \series bold
3598 -editor\InsetSpace ~
3599 <name>
3600 \family default
3601 \series default
3602 : Which editor to use with the
3603 \family typewriter
3604 %edit
3605 \family default
3606 command.
3607 By default, IPython will honor your
3608 \family typewriter
3609 EDITOR
3610 \family default
3611 environment variable (if not set, vi is the Unix default and notepad the
3612 Windows one).
3613 Since this editor is invoked on the fly by IPython and is meant for editing
3614 small code snippets, you may want to use a small, lightweight editor here
3615 (in case your default
3616 \family typewriter
3617 EDITOR
3618 \family default
3619 is something like Emacs).
3620 \end_layout
3621
3622 \begin_layout List
3623 \labelwidthstring 00.00.0000
3624
3625 \family typewriter
3626 \series bold
3627 -ipythondir\InsetSpace ~
3628 <name>
3629 \series default
3630 :
3631 \family default
3632 name of your IPython configuration directory
3633 \family typewriter
3634 IPYTHONDIR
3635 \family default
3636 .
3637 This can also be specified through the environment variable
3638 \family typewriter
3639 IPYTHONDIR
3640 \family default
3641 .
3642 \end_layout
3643
3644 \begin_layout List
3645 \labelwidthstring 00.00.0000
3646
3647 \family typewriter
3648 \series bold
3649 -log|l
3650 \family default
3651 \series default
3652 : generate a log file of all input.
3653 The file is named
3654 \family typewriter
3655 ipython_log.py
3656 \family default
3657 in your current directory (which prevents logs from multiple IPython sessions
3658 from trampling each other).
3659 You can use this to later restore a session by loading your logfile as
3660 a file to be executed with option
3661 \family typewriter
3662 -logplay
3663 \family default
3664 (see below).
3665 \end_layout
3666
3667 \begin_layout List
3668 \labelwidthstring 00.00.0000
3669
3670 \family typewriter
3671 \series bold
3672 -logfile|lf\InsetSpace ~
3673 <name>
3674 \series default
3675 :
3676 \family default
3677 specify the name of your logfile.
3678 \end_layout
3679
3680 \begin_layout List
3681 \labelwidthstring 00.00.0000
3682
3683 \family typewriter
3684 \series bold
3685 -logplay|lp\InsetSpace ~
3686 <name>
3687 \series default
3688 :
3689 \family default
3690 you can replay a previous log.
3691 For restoring a session as close as possible to the state you left it in,
3692 use this option (don't just run the logfile).
3693 With
3694 \family typewriter
3695 -logplay
3696 \family default
3697 , IPython will try to reconstruct the previous working environment in full,
3698 not just execute the commands in the logfile.
3699 \end_layout
3700
3701 \begin_layout List
3702 \labelwidthstring 00.00.0000
3703 \InsetSpace ~
3704 When a session is restored, logging is automatically turned on again with
3705 the name of the logfile it was invoked with (it is read from the log header).
3706 So once you've turned logging on for a session, you can quit IPython and
3707 reload it as many times as you want and it will continue to log its history
3708 and restore from the beginning every time.
3709 \end_layout
3710
3711 \begin_layout List
3712 \labelwidthstring 00.00.0000
3713 \InsetSpace ~
3714 Caveats: there are limitations in this option.
3715 The history variables
3716 \family typewriter
3717 _i*
3718 \family default
3719 ,
3720 \family typewriter
3721 _*
3722 \family default
3723 and
3724 \family typewriter
3725 _dh
3726 \family default
3727 don't get restored properly.
3728 In the future we will try to implement full session saving by writing and
3729 retrieving a 'snapshot' of the memory state of IPython.
3730 But our first attempts failed because of inherent limitations of Python's
3731 Pickle module, so this may have to wait.
3732 \end_layout
3733
3734 \begin_layout List
3735 \labelwidthstring 00.00.0000
3736
3737 \family typewriter
3738 \series bold
3739 -[no]messages
3740 \series default
3741 :
3742 \family default
3743 Print messages which IPython collects about its startup process (default
3744 on).
3745 \end_layout
3746
3747 \begin_layout List
3748 \labelwidthstring 00.00.0000
3749
3750 \family typewriter
3751 \series bold
3752 -[no]pdb
3753 \family default
3754 \series default
3755 : Automatically call the pdb debugger after every uncaught exception.
3756 If you are used to debugging using pdb, this puts you automatically inside
3757 of it after any call (either in IPython or in code called by it) which
3758 triggers an exception which goes uncaught.
3759 \end_layout
3760
3761 \begin_layout List
3762 \labelwidthstring 00.00.0000
3763
3764 \family typewriter
3765 \series bold
3766 -[no]pprint
3767 \series default
3768 :
3769 \family default
3770 ipython can optionally use the pprint (pretty printer) module for displaying
3771 results.
3772 pprint tends to give a nicer display of nested data structures.
3773 If you like it, you can turn it on permanently in your config file (default
3774 off).
3775 \end_layout
3776
3777 \begin_layout List
3778 \labelwidthstring 00.00.0000
3779
3780 \family typewriter
3781 \series bold
3782 -profile|p <name>
3783 \series default
3784 :
3785 \family default
3786 assume that your config file is
3787 \family typewriter
3788 ipythonrc-<name>
3789 \family default
3790 (looks in current dir first, then in
3791 \family typewriter
3792 IPYTHONDIR
3793 \family default
3794 ).
3795 This is a quick way to keep and load multiple config files for different
3796 tasks, especially if you use the include option of config files.
3797 You can keep a basic
3798 \family typewriter
3799 IPYTHONDIR/ipythonrc
3800 \family default
3801 file and then have other 'profiles' which include this one and load extra
3802 things for particular tasks.
3803 For example:
3804 \end_layout
3805
3806 \begin_layout List
3807 \labelwidthstring 00.00.0000
3808
3809 \family typewriter
3810 \InsetSpace ~
3811
3812 \family default
3813 1.
3814
3815 \family typewriter
3816 $HOME/.ipython/ipythonrc
3817 \family default
3818 : load basic things you always want.
3819 \end_layout
3820
3821 \begin_layout List
3822 \labelwidthstring 00.00.0000
3823
3824 \family typewriter
3825 \InsetSpace ~
3826
3827 \family default
3828 2.
3829
3830 \family typewriter
3831 $HOME/.ipython/ipythonrc-math
3832 \family default
3833 : load (1) and basic math-related modules.
3834
3835 \end_layout
3836
3837 \begin_layout List
3838 \labelwidthstring 00.00.0000
3839
3840 \family typewriter
3841 \InsetSpace ~
3842
3843 \family default
3844 3.
3845
3846 \family typewriter
3847 $HOME/.ipython/ipythonrc-numeric
3848 \family default
3849 : load (1) and Numeric and plotting modules.
3850 \end_layout
3851
3852 \begin_layout List
3853 \labelwidthstring 00.00.0000
3854 \InsetSpace ~
3855 Since it is possible to create an endless loop by having circular file
3856 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3857 \end_layout
3858
3859 \begin_layout List
3860 \labelwidthstring 00.00.0000
3861
3862 \family typewriter
3863 \series bold
3864 -prompt_in1|pi1\InsetSpace ~
3865 <string>:
3866 \family default
3867 \series default
3868 Specify the string used for input prompts.
3869 Note that if you are using numbered prompts, the number is represented
3870 with a '
3871 \backslash
3872 #' in the string.
3873 Don't forget to quote strings with spaces embedded in them.
3874 Default: '
3875 \family typewriter
3876 In\InsetSpace ~
3877 [
3878 \backslash
3879 #]:
3880 \family default
3881 '.
3882 Sec.\InsetSpace ~
3883
3884 \begin_inset LatexCommand \ref{sec:prompts}
3885
3886 \end_inset
3887
3888 discusses in detail all the available escapes to customize your prompts.
3889 \end_layout
3890
3891 \begin_layout List
3892 \labelwidthstring 00.00.0000
3893
3894 \family typewriter
3895 \series bold
3896 -prompt_in2|pi2\InsetSpace ~
3897 <string>:
3898 \family default
3899 \series default
3900 Similar to the previous option, but used for the continuation prompts.
3901 The special sequence '
3902 \family typewriter
3903
3904 \backslash
3905 D
3906 \family default
3907 ' is similar to '
3908 \family typewriter
3909
3910 \backslash
3911 #
3912 \family default
3913 ', but with all digits replaced dots (so you can have your continuation
3914 prompt aligned with your input prompt).
3915 Default: '
3916 \family typewriter
3917 \InsetSpace ~
3918 \InsetSpace ~
3919 \InsetSpace ~
3920 .
3921 \backslash
3922 D.:
3923 \family default
3924 ' (note three spaces at the start for alignment with '
3925 \family typewriter
3926 In\InsetSpace ~
3927 [
3928 \backslash
3929 #]
3930 \family default
3931 ').
3932 \end_layout
3933
3934 \begin_layout List
3935 \labelwidthstring 00.00.0000
3936
3937 \family typewriter
3938 \series bold
3939 -prompt_out|po\InsetSpace ~
3940 <string>:
3941 \family default
3942 \series default
3943 String used for output prompts, also uses numbers like
3944 \family typewriter
3945 prompt_in1
3946 \family default
3947 .
3948 Default: '
3949 \family typewriter
3950 Out[
3951 \backslash
3952 #]:
3953 \family default
3954 '
3955 \end_layout
3956
3957 \begin_layout List
3958 \labelwidthstring 00.00.0000
3959
3960 \family typewriter
3961 \series bold
3962 -quick
3963 \family default
3964 \series default
3965 : start in bare bones mode (no config file loaded).
3966 \end_layout
3967
3968 \begin_layout List
3969 \labelwidthstring 00.00.0000
3970
3971 \family typewriter
3972 \series bold
3973 -rcfile\InsetSpace ~
3974 <name>
3975 \series default
3976 :
3977 \family default
3978 name of your IPython resource configuration file.
3979 Normally IPython loads ipythonrc (from current directory) or
3980 \family typewriter
3981 IPYTHONDIR/ipythonrc
3982 \family default
3983 .
3984 \end_layout
3985
3986 \begin_layout List
3987 \labelwidthstring 00.00.0000
3988 \InsetSpace ~
3989 If the loading of your config file fails, IPython starts with a bare bones
3990 configuration (no modules loaded at all).
3991 \end_layout
3992
3993 \begin_layout List
3994 \labelwidthstring 00.00.0000
3995
3996 \family typewriter
3997 \series bold
3998 -[no]readline
3999 \family default
4000 \series default
4001 : use the readline library, which is needed to support name completion and
4002 command history, among other things.
4003 It is enabled by default, but may cause problems for users of X/Emacs in
4004 Python comint or shell buffers.
4005 \end_layout
4006
4007 \begin_layout List
4008 \labelwidthstring 00.00.0000
4009 \InsetSpace ~
4010 Note that X/Emacs 'eterm' buffers (opened with
4011 \family typewriter
4012 M-x\InsetSpace ~
4013 term
4014 \family default
4015 ) support IPython's readline and syntax coloring fine, only 'emacs' (
4016 \family typewriter
4017 M-x\InsetSpace ~
4018 shell
4019 \family default
4020 and
4021 \family typewriter
4022 C-c\InsetSpace ~
4023 !
4024 \family default
4025 ) buffers do not.
4026 \end_layout
4027
4028 \begin_layout List
4029 \labelwidthstring 00.00.0000
4030
4031 \family typewriter
4032 \series bold
4033 -screen_length|sl\InsetSpace ~
4034 <n>
4035 \series default
4036 :
4037 \family default
4038 number of lines of your screen.
4039 This is used to control printing of very long strings.
4040 Strings longer than this number of lines will be sent through a pager instead
4041 of directly printed.
4042 \end_layout
4043
4044 \begin_layout List
4045 \labelwidthstring 00.00.0000
4046 \InsetSpace ~
4047 The default value for this is 0, which means IPython will auto-detect your
4048 screen size every time it needs to print certain potentially long strings
4049 (this doesn't change the behavior of the 'print' keyword, it's only triggered
4050 internally).
4051 If for some reason this isn't working well (it needs curses support), specify
4052 it yourself.
4053 Otherwise don't change the default.
4054 \end_layout
4055
4056 \begin_layout List
4057 \labelwidthstring 00.00.0000
4058
4059 \family typewriter
4060 \series bold
4061 -separate_in|si\InsetSpace ~
4062 <string>
4063 \series default
4064 :
4065 \family default
4066 separator before input prompts.
4067 Default: '
4068 \family typewriter
4069
4070 \backslash
4071 n
4072 \family default
4073 '
4074 \end_layout
4075
4076 \begin_layout List
4077 \labelwidthstring 00.00.0000
4078
4079 \family typewriter
4080 \series bold
4081 -separate_out|so\InsetSpace ~
4082 <string>
4083 \family default
4084 \series default
4085 : separator before output prompts.
4086 Default: nothing.
4087 \end_layout
4088
4089 \begin_layout List
4090 \labelwidthstring 00.00.0000
4091
4092 \family typewriter
4093 \series bold
4094 -separate_out2|so2\InsetSpace ~
4095 <string>
4096 \series default
4097 :
4098 \family default
4099 separator after output prompts.
4100 Default: nothing.
4101 \end_layout
4102
4103 \begin_layout List
4104 \labelwidthstring 00.00.0000
4105 \InsetSpace ~
4106 For these three options, use the value 0 to specify no separator.
4107 \end_layout
4108
4109 \begin_layout List
4110 \labelwidthstring 00.00.0000
4111
4112 \family typewriter
4113 \series bold
4114 -nosep
4115 \series default
4116 :
4117 \family default
4118 shorthand for
4119 \family typewriter
4120 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
4121 \family default
4122 .
4123 Simply removes all input/output separators.
4124 \end_layout
4125
4126 \begin_layout List
4127 \labelwidthstring 00.00.0000
4128
4129 \family typewriter
4130 \series bold
4131 -upgrade
4132 \family default
4133 \series default
4134 : allows you to upgrade your
4135 \family typewriter
4136 IPYTHONDIR
4137 \family default
4138 configuration when you install a new version of IPython.
4139 Since new versions may include new command line options or example files,
4140 this copies updated ipythonrc-type files.
4141 However, it backs up (with a
4142 \family typewriter
4143 .old
4144 \family default
4145 extension) all files which it overwrites so that you can merge back any
4146 customizations you might have in your personal files.
4147 \end_layout
4148
4149 \begin_layout List
4150 \labelwidthstring 00.00.0000
4151
4152 \family typewriter
4153 \series bold
4154 -Version
4155 \series default
4156 :
4157 \family default
4158 print version information and exit.
4159 \end_layout
4160
4161 \begin_layout List
4162 \labelwidthstring 00.00.0000
4163
4164 \family typewriter
4165 \series bold
4166 -wxversion\InsetSpace ~
4167 <string>:
4168 \family default
4169 \series default
4170 Select a specific version of wxPython (used in conjunction with
4171 \family typewriter
4172 -wthread
4173 \family default
4174 ).
4175 Requires the wxversion module, part of recent wxPython distributions
4176 \end_layout
4177
4178 \begin_layout List
4179 \labelwidthstring 00.00.0000
4180
4181 \family typewriter
4182 \series bold
4183 -xmode\InsetSpace ~
4184 <modename>
4185 \series default
4186 :
4187 \family default
4188 Mode for exception reporting.
4189 \end_layout
4190
4191 \begin_layout List
4192 \labelwidthstring 00.00.0000
4193 \InsetSpace ~
4194 Valid modes: Plain, Context and Verbose.
4195 \end_layout
4196
4197 \begin_layout List
4198 \labelwidthstring 00.00.0000
4199 \InsetSpace ~
4200 Plain: similar to python's normal traceback printing.
4201 \end_layout
4202
4203 \begin_layout List
4204 \labelwidthstring 00.00.0000
4205 \InsetSpace ~
4206 Context: prints 5 lines of context source code around each line in the
4207 traceback.
4208 \end_layout
4209
4210 \begin_layout List
4211 \labelwidthstring 00.00.0000
4212 \InsetSpace ~
4213 Verbose: similar to Context, but additionally prints the variables currently
4214 visible where the exception happened (shortening their strings if too long).
4215 This can potentially be very slow, if you happen to have a huge data structure
4216 whose string representation is complex to compute.
4217 Your computer may appear to freeze for a while with cpu usage at 100%.
4218 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
4219 it more than once).
4220 \end_layout
4221
4222 \begin_layout Section
4223 Interactive use
4224 \end_layout
4225
4226 \begin_layout Standard
4227
4228 \series bold
4229 Warning
4230 \series default
4231 : IPython relies on the existence of a global variable called
4232 \family typewriter
4233 __IP
4234 \family default
4235 which controls the shell itself.
4236 If you redefine
4237 \family typewriter
4238 __IP
4239 \family default
4240 to anything, bizarre behavior will quickly occur.
4241 \end_layout
4242
4243 \begin_layout Standard
4244 Other than the above warning, IPython is meant to work as a drop-in replacement
4245 for the standard interactive interpreter.
4246 As such, any code which is valid python should execute normally under IPython
4247 (cases where this is not true should be reported as bugs).
4248 It does, however, offer many features which are not available at a standard
4249 python prompt.
4250 What follows is a list of these.
4251 \end_layout
4252
4253 \begin_layout Subsection
4254 Caution for Windows users
4255 \end_layout
4256
4257 \begin_layout Standard
4258 Windows, unfortunately, uses the `
4259 \family typewriter
4260
4261 \backslash
4262
4263 \family default
4264 ' character as a path separator.
4265 This is a terrible choice, because `
4266 \family typewriter
4267
4268 \backslash
4269
4270 \family default
4271 ' also represents the escape character in most modern programming languages,
4272 including Python.
4273 For this reason, issuing many of the commands discussed below (especially
4274 magics which affect the filesystem) with `
4275 \family typewriter
4276
4277 \backslash
4278
4279 \family default
4280 ' in them will cause strange errors.
4281 \end_layout
4282
4283 \begin_layout Standard
4284 A partial solution is to use instead the `
4285 \family typewriter
4286 /
4287 \family default
4288 ' character as a path separator, which Windows recognizes in
4289 \emph on
4290 most
4291 \emph default
4292 situations.
4293 However, in Windows commands `
4294 \family typewriter
4295 /
4296 \family default
4297 ' flags options, so you can not use it for the root directory.
4298 This means that paths beginning at the root must be typed in a contrived
4299 manner like:
4300 \newline
4301
4302 \family typewriter
4303 %copy
4304 \backslash
4305 opt/foo/bar.txt
4306 \backslash
4307 tmp
4308 \end_layout
4309
4310 \begin_layout Standard
4311 There is no sensible thing IPython can do to truly work around this flaw
4312 in Windows
4313 \begin_inset Foot
4314 status collapsed
4315
4316 \begin_layout Standard
4317 If anyone comes up with a
4318 \emph on
4319 clean
4320 \emph default
4321 solution which works consistently and does not negatively impact other
4322 platforms at all, I'll gladly accept a patch.
4323 \end_layout
4324
4325 \end_inset
4326
4327 .
4328 \end_layout
4329
4330 \begin_layout Subsection
4331 \begin_inset LatexCommand \label{sec:magic}
4332
4333 \end_inset
4334
4335 Magic command system
4336 \end_layout
4337
4338 \begin_layout Standard
4339 IPython will treat any line whose first character is a
4340 \family typewriter
4341 %
4342 \family default
4343 as a special call to a 'magic' function.
4344 These allow you to control the behavior of IPython itself, plus a lot of
4345 system-type features.
4346 They are all prefixed with a
4347 \family typewriter
4348 %
4349 \family default
4350 character, but parameters are given without parentheses or quotes.
4351 \end_layout
4352
4353 \begin_layout Standard
4354 Example: typing
4355 \family typewriter
4356 '%cd mydir'
4357 \family default
4358 (without the quotes) changes you working directory to
4359 \family typewriter
4360 'mydir'
4361 \family default
4362 , if it exists.
4363 \end_layout
4364
4365 \begin_layout Standard
4366 If you have 'automagic' enabled (in your
4367 \family typewriter
4368 ipythonrc
4369 \family default
4370 file, via the command line option
4371 \family typewriter
4372 -automagic
4373 \family default
4374 or with the
4375 \family typewriter
4376 %automagic
4377 \family default
4378 function), you don't need to type in the
4379 \family typewriter
4380 %
4381 \family default
4382 explicitly.
4383 IPython will scan its internal list of magic functions and call one if
4384 it exists.
4385 With automagic on you can then just type '
4386 \family typewriter
4387 cd mydir
4388 \family default
4389 ' to go to directory '
4390 \family typewriter
4391 mydir
4392 \family default
4393 '.
4394 The automagic system has the lowest possible precedence in name searches,
4395 so defining an identifier with the same name as an existing magic function
4396 will shadow it for automagic use.
4397 You can still access the shadowed magic function by explicitly using the
4398
4399 \family typewriter
4400 %
4401 \family default
4402 character at the beginning of the line.
4403 \end_layout
4404
4405 \begin_layout Standard
4406 An example (with automagic on) should clarify all this:
4407 \end_layout
4408
4409 \begin_layout LyX-Code
4410 In [1]: cd ipython # %cd is called by automagic
4411 \end_layout
4412
4413 \begin_layout LyX-Code
4414 /home/fperez/ipython
4415 \end_layout
4416
4417 \begin_layout LyX-Code
4418 In [2]: cd=1 # now cd is just a variable
4419 \end_layout
4420
4421 \begin_layout LyX-Code
4422 In [3]: cd ..
4423 # and doesn't work as a function anymore
4424 \end_layout
4425
4426 \begin_layout LyX-Code
4427 ------------------------------------------------------------
4428 \end_layout
4429
4430 \begin_layout LyX-Code
4431 File "<console>", line 1
4432 \end_layout
4433
4434 \begin_layout LyX-Code
4435 cd ..
4436 \end_layout
4437
4438 \begin_layout LyX-Code
4439 ^
4440 \end_layout
4441
4442 \begin_layout LyX-Code
4443 SyntaxError: invalid syntax
4444 \end_layout
4445
4446 \begin_layout LyX-Code
4447
4448 \end_layout
4449
4450 \begin_layout LyX-Code
4451 In [4]: %cd ..
4452 # but %cd always works
4453 \end_layout
4454
4455 \begin_layout LyX-Code
4456 /home/fperez
4457 \end_layout
4458
4459 \begin_layout LyX-Code
4460 In [5]: del cd # if you remove the cd variable
4461 \end_layout
4462
4463 \begin_layout LyX-Code
4464 In [6]: cd ipython # automagic can work again
4465 \end_layout
4466
4467 \begin_layout LyX-Code
4468 /home/fperez/ipython
4469 \end_layout
4470
4471 \begin_layout Standard
4472 You can define your own magic functions to extend the system.
4473 The following example defines a new magic command,
4474 \family typewriter
4475 %impall
4476 \family default
4477 :
4478 \end_layout
4479
4480 \begin_layout LyX-Code
4481 import IPython.ipapi
4482 \end_layout
4483
4484 \begin_layout LyX-Code
4485 ip = IPython.ipapi.get()
4486 \end_layout
4487
4488 \begin_layout LyX-Code
4489
4490 \end_layout
4491
4492 \begin_layout LyX-Code
4493 def doimp(self, arg):
4494 \end_layout
4495
4496 \begin_layout LyX-Code
4497 ip = self.api
4498 \end_layout
4499
4500 \begin_layout LyX-Code
4501 ip.ex("import %s; reload(%s); from %s import *" % (
4502 \end_layout
4503
4504 \begin_layout LyX-Code
4505 arg,arg,arg)
4506 \end_layout
4507
4508 \begin_layout LyX-Code
4509 )
4510 \end_layout
4511
4512 \begin_layout LyX-Code
4513 ip.expose_magic('impall', doimp)
4514 \end_layout
4515
4516 \begin_layout Standard
4517 You can also define your own aliased names for magic functions.
4518 In your
4519 \family typewriter
4520 ipythonrc
4521 \family default
4522 file, placing a line like:
4523 \end_layout
4524
4525 \begin_layout Standard
4526
4527 \family typewriter
4528 execute __IP.magic_cl = __IP.magic_clear
4529 \end_layout
4530
4531 \begin_layout Standard
4532 will define
4533 \family typewriter
4534 %cl
4535 \family default
4536 as a new name for
4537 \family typewriter
4538 %clear
4539 \family default
4540 .
4541 \end_layout
4542
4543 \begin_layout Standard
4544 Type
4545 \family typewriter
4546 %magic
4547 \family default
4548 for more information, including a list of all available magic functions
4549 at any time and their docstrings.
4550 You can also type
4551 \family typewriter
4552 %magic_function_name?
4553 \family default
4554 (see sec.
4555
4556 \begin_inset LatexCommand \ref{sec:dyn-object-info}
4557
4558 \end_inset
4559
4560 for information on the
4561 \family typewriter
4562 '?'
4563 \family default
4564 system) to get information about any particular magic function you are
4565 interested in.
4566 \end_layout
4567
4568 \begin_layout Subsubsection
4569 Magic commands
4570 \end_layout
4571
4572 \begin_layout Standard
4573 The rest of this section is automatically generated for each release from
4574 the docstrings in the IPython code.
4575 Therefore the formatting is somewhat minimal, but this method has the advantage
4576 of having information always in sync with the code.
4577 \end_layout
4578
4579 \begin_layout Standard
4580 A list of all the magic commands available in IPython's
4581 \emph on
4582 default
4583 \emph default
4584 installation follows.
4585 This is similar to what you'll see by simply typing
4586 \family typewriter
4587 %magic
4588 \family default
4589 at the prompt, but that will also give you information about magic commands
4590 you may have added as part of your personal customizations.
4591 \end_layout
4592
4593 \begin_layout Standard
4594 \begin_inset Include \input{magic.tex}
4595 preview false
4596
4597 \end_inset
4598
4599
4600 \end_layout
4601
4602 \begin_layout Subsection
4603 Access to the standard Python help
4604 \end_layout
4605
4606 \begin_layout Standard
4607 As of Python 2.1, a help system is available with access to object docstrings
4608 and the Python manuals.
4609 Simply type
4610 \family typewriter
4611 'help'
4612 \family default
4613 (no quotes) to access it.
4614 You can also type
4615 \family typewriter
4616 help(object)
4617 \family default
4618 to obtain information about a given object, and
4619 \family typewriter
4620 help('keyword')
4621 \family default
4622 for information on a keyword.
4623 As noted in sec.
4624
4625 \begin_inset LatexCommand \ref{sec:help-access}
4626
4627 \end_inset
4628
4629 , you need to properly configure your environment variable
4630 \family typewriter
4631 PYTHONDOCS
4632 \family default
4633 for this feature to work correctly.
4634 \end_layout
4635
4636 \begin_layout Subsection
4637 \begin_inset LatexCommand \label{sec:dyn-object-info}
4638
4639 \end_inset
4640
4641 Dynamic object information
4642 \end_layout
4643
4644 \begin_layout Standard
4645 Typing
4646 \family typewriter
4647 ?word
4648 \family default
4649 or
4650 \family typewriter
4651 word?
4652 \family default
4653 prints detailed information about an object.
4654 If certain strings in the object are too long (docstrings, code, etc.) they
4655 get snipped in the center for brevity.
4656 This system gives access variable types and values, full source code for
4657 any object (if available), function prototypes and other useful information.
4658 \end_layout
4659
4660 \begin_layout Standard
4661 Typing
4662 \family typewriter
4663 ??word
4664 \family default
4665 or
4666 \family typewriter
4667 word??
4668 \family default
4669 gives access to the full information without snipping long strings.
4670 Long strings are sent to the screen through the
4671 \family typewriter
4672 less
4673 \family default
4674 pager if longer than the screen and printed otherwise.
4675 On systems lacking the
4676 \family typewriter
4677 less
4678 \family default
4679 command, IPython uses a very basic internal pager.
4680 \end_layout
4681
4682 \begin_layout Standard
4683 The following magic functions are particularly useful for gathering information
4684 about your working environment.
4685 You can get more details by typing
4686 \family typewriter
4687 %magic
4688 \family default
4689 or querying them individually (use
4690 \family typewriter
4691 %function_name?
4692 \family default
4693 with or without the
4694 \family typewriter
4695 %
4696 \family default
4697 ), this is just a summary:
4698 \end_layout
4699
4700 \begin_layout List
4701 \labelwidthstring 00.00.0000
4702
4703 \family typewriter
4704 \series bold
4705 %pdoc\InsetSpace ~
4706 <object>
4707 \family default
4708 \series default
4709 : Print (or run through a pager if too long) the docstring for an object.
4710 If the given object is a class, it will print both the class and the constructo
4711 r docstrings.
4712 \end_layout
4713
4714 \begin_layout List
4715 \labelwidthstring 00.00.0000
4716
4717 \family typewriter
4718 \series bold
4719 %pdef\InsetSpace ~
4720 <object>
4721 \family default
4722 \series default
4723 : Print the definition header for any callable object.
4724 If the object is a class, print the constructor information.
4725 \end_layout
4726
4727 \begin_layout List
4728 \labelwidthstring 00.00.0000
4729
4730 \family typewriter
4731 \series bold
4732 %psource\InsetSpace ~
4733 <object>
4734 \family default
4735 \series default
4736 : Print (or run through a pager if too long) the source code for an object.
4737 \end_layout
4738
4739 \begin_layout List
4740 \labelwidthstring 00.00.0000
4741
4742 \family typewriter
4743 \series bold
4744 %pfile\InsetSpace ~
4745 <object>
4746 \family default
4747 \series default
4748 : Show the entire source file where an object was defined via a pager, opening
4749 it at the line where the object definition begins.
4750 \end_layout
4751
4752 \begin_layout List
4753 \labelwidthstring 00.00.0000
4754
4755 \family typewriter
4756 \series bold
4757 %who/%whos
4758 \family default
4759 \series default
4760 : These functions give information about identifiers you have defined interactiv
4761 ely (not things you loaded or defined in your configuration files).
4762
4763 \family typewriter
4764 %who
4765 \family default
4766 just prints a list of identifiers and
4767 \family typewriter
4768 %whos
4769 \family default
4770 prints a table with some basic details about each identifier.
4771 \end_layout
4772
4773 \begin_layout Standard
4774 Note that the dynamic object information functions (
4775 \family typewriter
4776 ?/??, %pdoc, %pfile, %pdef, %psource
4777 \family default
4778 ) give you access to documentation even on things which are not really defined
4779 as separate identifiers.
4780 Try for example typing
4781 \family typewriter
4782 {}.get?
4783 \family default
4784 or after doing
4785 \family typewriter
4786 import os
4787 \family default
4788 , type
4789 \family typewriter
4790 os.path.abspath??
4791 \family default
4792 .
4793 \end_layout
4794
4795 \begin_layout Subsection
4796 \begin_inset LatexCommand \label{sec:readline}
4797
4798 \end_inset
4799
4800 Readline-based features
4801 \end_layout
4802
4803 \begin_layout Standard
4804 These features require the GNU readline library, so they won't work if your
4805 Python installation lacks readline support.
4806 We will first describe the default behavior IPython uses, and then how
4807 to change it to suit your preferences.
4808 \end_layout
4809
4810 \begin_layout Subsubsection
4811 Command line completion
4812 \end_layout
4813
4814 \begin_layout Standard
4815 At any time, hitting TAB will complete any available python commands or
4816 variable names, and show you a list of the possible completions if there's
4817 no unambiguous one.
4818 It will also complete filenames in the current directory if no python names
4819 match what you've typed so far.
4820 \end_layout
4821
4822 \begin_layout Subsubsection
4823 Search command history
4824 \end_layout
4825
4826 \begin_layout Standard
4827 IPython provides two ways for searching through previous input and thus
4828 reduce the need for repetitive typing:
4829 \end_layout
4830
4831 \begin_layout Enumerate
4832 Start typing, and then use
4833 \family typewriter
4834 Ctrl-p
4835 \family default
4836 (previous,up) and
4837 \family typewriter
4838 Ctrl-n
4839 \family default
4840 (next,down) to search through only the history items that match what you've
4841 typed so far.
4842 If you use
4843 \family typewriter
4844 Ctrl-p/Ctrl-n
4845 \family default
4846 at a blank prompt, they just behave like normal arrow keys.
4847 \end_layout
4848
4849 \begin_layout Enumerate
4850 Hit
4851 \family typewriter
4852 Ctrl-r
4853 \family default
4854 : opens a search prompt.
4855 Begin typing and the system searches your history for lines that contain
4856 what you've typed so far, completing as much as it can.
4857 \end_layout
4858
4859 \begin_layout Subsubsection
4860 Persistent command history across sessions
4861 \end_layout
4862
4863 \begin_layout Standard
4864 IPython will save your input history when it leaves and reload it next time
4865 you restart it.
4866 By default, the history file is named
4867 \family typewriter
4868 $IPYTHONDIR/history
4869 \family default
4870 , but if you've loaded a named profile, '
4871 \family typewriter
4872 -PROFILE_NAME
4873 \family default
4874 ' is appended to the name.
4875 This allows you to keep separate histories related to various tasks: commands
4876 related to numerical work will not be clobbered by a system shell history,
4877 for example.
4878 \end_layout
4879
4880 \begin_layout Subsubsection
4881 Autoindent
4882 \end_layout
4883
4884 \begin_layout Standard
4885 IPython can recognize lines ending in ':' and indent the next line, while
4886 also un-indenting automatically after 'raise' or 'return'.
4887
4888 \end_layout
4889
4890 \begin_layout Standard
4891 This feature uses the readline library, so it will honor your
4892 \family typewriter
4893 ~/.inputrc
4894 \family default
4895 configuration (or whatever file your
4896 \family typewriter
4897 INPUTRC
4898 \family default
4899 variable points to).
4900 Adding the following lines to your
4901 \family typewriter
4902 .inputrc
4903 \family default
4904 file can make indenting/unindenting more convenient (
4905 \family typewriter
4906 M-i
4907 \family default
4908 indents,
4909 \family typewriter
4910 M-u
4911 \family default
4912 unindents):
4913 \end_layout
4914
4915 \begin_layout Standard
4916
4917 \family typewriter
4918 $if Python
4919 \newline
4920 "
4921 \backslash
4922 M-i": "\InsetSpace ~
4923 \InsetSpace ~
4924 \InsetSpace ~
4925 \InsetSpace ~
4926 "
4927 \newline
4928 "
4929 \backslash
4930 M-u": "
4931 \backslash
4932 d
4933 \backslash
4934 d
4935 \backslash
4936 d
4937 \backslash
4938 d"
4939 \newline
4940 $endif
4941 \end_layout
4942
4943 \begin_layout Standard
4944 Note that there are 4 spaces between the quote marks after
4945 \family typewriter
4946 "M-i"
4947 \family default
4948 above.
4949 \end_layout
4950
4951 \begin_layout Standard
4952
4953 \series bold
4954 Warning:
4955 \series default
4956 this feature is ON by default, but it can cause problems with the pasting
4957 of multi-line indented code (the pasted code gets re-indented on each line).
4958 A magic function
4959 \family typewriter
4960 %autoindent
4961 \family default
4962 allows you to toggle it on/off at runtime.
4963 You can also disable it permanently on in your
4964 \family typewriter
4965 ipythonrc
4966 \family default
4967 file (set
4968 \family typewriter
4969 autoindent 0
4970 \family default
4971 ).
4972 \end_layout
4973
4974 \begin_layout Subsubsection
4975 Customizing readline behavior
4976 \end_layout
4977
4978 \begin_layout Standard
4979 All these features are based on the GNU readline library, which has an extremely
4980 customizable interface.
4981 Normally, readline is configured via a file which defines the behavior
4982 of the library; the details of the syntax for this can be found in the
4983 readline documentation available with your system or on the Internet.
4984 IPython doesn't read this file (if it exists) directly, but it does support
4985 passing to readline valid options via a simple interface.
4986 In brief, you can customize readline by setting the following options in
4987 your
4988 \family typewriter
4989 ipythonrc
4990 \family default
4991 configuration file (note that these options can
4992 \emph on
4993 not
4994 \emph default
4995 be specified at the command line):
4996 \end_layout
4997
4998 \begin_layout List
4999 \labelwidthstring 00.00.0000
5000
5001 \family typewriter
5002 \series bold
5003 readline_parse_and_bind:
5004 \family default
5005 \series default
5006 this option can appear as many times as you want, each time defining a
5007 string to be executed via a
5008 \family typewriter
5009 readline.parse_and_bind()
5010 \family default
5011 command.
5012 The syntax for valid commands of this kind can be found by reading the
5013 documentation for the GNU readline library, as these commands are of the
5014 kind which readline accepts in its configuration file.
5015 \end_layout
5016
5017 \begin_layout List
5018 \labelwidthstring 00.00.0000
5019
5020 \family typewriter
5021 \series bold
5022 readline_remove_delims:
5023 \family default
5024 \series default
5025 a string of characters to be removed from the default word-delimiters list
5026 used by readline, so that completions may be performed on strings which
5027 contain them.
5028 Do not change the default value unless you know what you're doing.
5029 \end_layout
5030
5031 \begin_layout List
5032 \labelwidthstring 00.00.0000
5033
5034 \family typewriter
5035 \series bold
5036 readline_omit__names
5037 \family default
5038 \series default
5039 : when tab-completion is enabled, hitting
5040 \family typewriter
5041 <tab>
5042 \family default
5043 after a '
5044 \family typewriter
5045 .
5046 \family default
5047 ' in a name will complete all attributes of an object, including all the
5048 special methods whose names include double underscores (like
5049 \family typewriter
5050 __getitem__
5051 \family default
5052 or
5053 \family typewriter
5054 __class__
5055 \family default
5056 ).
5057 If you'd rather not see these names by default, you can set this option
5058 to 1.
5059 Note that even when this option is set, you can still see those names by
5060 explicitly typing a
5061 \family typewriter
5062 _
5063 \family default
5064 after the period and hitting
5065 \family typewriter
5066 <tab>
5067 \family default
5068 : '
5069 \family typewriter
5070 name._<tab>
5071 \family default
5072 ' will always complete attribute names starting with '
5073 \family typewriter
5074 _
5075 \family default
5076 '.
5077 \end_layout
5078
5079 \begin_layout List
5080 \labelwidthstring 00.00.0000
5081 \InsetSpace ~
5082 This option is off by default so that new users see all attributes of any
5083 objects they are dealing with.
5084 \end_layout
5085
5086 \begin_layout Standard
5087 You will find the default values along with a corresponding detailed explanation
5088 in your
5089 \family typewriter
5090 ipythonrc
5091 \family default
5092 file.
5093 \end_layout
5094
5095 \begin_layout Subsection
5096 Session logging and restoring
5097 \end_layout
5098
5099 \begin_layout Standard
5100 You can log all input from a session either by starting IPython with the
5101 command line switches
5102 \family typewriter
5103 -log
5104 \family default
5105 or
5106 \family typewriter
5107 -logfile
5108 \family default
5109 (see sec.
5110
5111 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5112
5113 \end_inset
5114
5115 )or by activating the logging at any moment with the magic function
5116 \family typewriter
5117 %logstart
5118 \family default
5119 .
5120
5121 \end_layout
5122
5123 \begin_layout Standard
5124 Log files can later be reloaded with the
5125 \family typewriter
5126 -logplay
5127 \family default
5128 option and IPython will attempt to 'replay' the log by executing all the
5129 lines in it, thus restoring the state of a previous session.
5130 This feature is not quite perfect, but can still be useful in many cases.
5131 \end_layout
5132
5133 \begin_layout Standard
5134 The log files can also be used as a way to have a permanent record of any
5135 code you wrote while experimenting.
5136 Log files are regular text files which you can later open in your favorite
5137 text editor to extract code or to 'clean them up' before using them to
5138 replay a session.
5139 \end_layout
5140
5141 \begin_layout Standard
5142 The
5143 \family typewriter
5144 %logstart
5145 \family default
5146 function for activating logging in mid-session is used as follows:
5147 \end_layout
5148
5149 \begin_layout Standard
5150
5151 \family typewriter
5152 %logstart [log_name [log_mode]]
5153 \end_layout
5154
5155 \begin_layout Standard
5156 If no name is given, it defaults to a file named
5157 \family typewriter
5158 'log'
5159 \family default
5160 in your IPYTHONDIR directory, in
5161 \family typewriter
5162 'rotate'
5163 \family default
5164 mode (see below).
5165 \end_layout
5166
5167 \begin_layout Standard
5168 '
5169 \family typewriter
5170 %logstart name
5171 \family default
5172 ' saves to file
5173 \family typewriter
5174 'name'
5175 \family default
5176 in
5177 \family typewriter
5178 'backup'
5179 \family default
5180 mode.
5181 It saves your history up to that point and then continues logging.
5182 \end_layout
5183
5184 \begin_layout Standard
5185
5186 \family typewriter
5187 %logstart
5188 \family default
5189 takes a second optional parameter: logging mode.
5190 This can be one of (note that the modes are given unquoted):
5191 \end_layout
5192
5193 \begin_layout List
5194 \labelwidthstring 00.00.0000
5195
5196 \family typewriter
5197 over
5198 \family default
5199 : overwrite existing
5200 \family typewriter
5201 log_name
5202 \family default
5203 .
5204 \end_layout
5205
5206 \begin_layout List
5207 \labelwidthstring 00.00.0000
5208
5209 \family typewriter
5210 backup
5211 \family default
5212 : rename (if exists) to
5213 \family typewriter
5214 log_name~
5215 \family default
5216 and start
5217 \family typewriter
5218 log_name
5219 \family default
5220 .
5221 \end_layout
5222
5223 \begin_layout List
5224 \labelwidthstring 00.00.0000
5225
5226 \family typewriter
5227 append
5228 \family default
5229 : well, that says it.
5230 \end_layout
5231
5232 \begin_layout List
5233 \labelwidthstring 00.00.0000
5234
5235 \family typewriter
5236 rotate
5237 \family default
5238 : create rotating logs
5239 \family typewriter
5240 log_name
5241 \family default
5242 .
5243 \family typewriter
5244 1~
5245 \family default
5246 ,
5247 \family typewriter
5248 log_name.2~
5249 \family default
5250 , etc.
5251 \end_layout
5252
5253 \begin_layout Standard
5254 The
5255 \family typewriter
5256 %logoff
5257 \family default
5258 and
5259 \family typewriter
5260 %logon
5261 \family default
5262 functions allow you to temporarily stop and resume logging to a file which
5263 had previously been started with
5264 \family typewriter
5265 %logstart
5266 \family default
5267 .
5268 They will fail (with an explanation) if you try to use them before logging
5269 has been started.
5270 \end_layout
5271
5272 \begin_layout Subsection
5273 \begin_inset LatexCommand \label{sub:System-shell-access}
5274
5275 \end_inset
5276
5277 System shell access
5278 \end_layout
5279
5280 \begin_layout Standard
5281 Any input line beginning with a
5282 \family typewriter
5283 !
5284 \family default
5285 character is passed verbatim (minus the
5286 \family typewriter
5287 !
5288 \family default
5289 , of course) to the underlying operating system.
5290 For example, typing
5291 \family typewriter
5292 !ls
5293 \family default
5294 will run
5295 \family typewriter
5296 'ls'
5297 \family default
5298 in the current directory.
5299 \end_layout
5300
5301 \begin_layout Subsubsection
5302 Manual capture of command output
5303 \end_layout
5304
5305 \begin_layout Standard
5306 If the input line begins with
5307 \emph on
5308 two
5309 \emph default
5310 exclamation marks,
5311 \family typewriter
5312 !!
5313 \family default
5314 , the command is executed but its output is captured and returned as a python
5315 list, split on newlines.
5316 Any output sent by the subprocess to standard error is printed separately,
5317 so that the resulting list only captures standard output.
5318 The
5319 \family typewriter
5320 !!
5321 \family default
5322 syntax is a shorthand for the
5323 \family typewriter
5324 %sx
5325 \family default
5326 magic command.
5327 \end_layout
5328
5329 \begin_layout Standard
5330 Finally, the
5331 \family typewriter
5332 %sc
5333 \family default
5334 magic (short for `shell capture') is similar to
5335 \family typewriter
5336 %sx
5337 \family default
5338 , but allowing more fine-grained control of the capture details, and storing
5339 the result directly into a named variable.
5340 \end_layout
5341
5342 \begin_layout Standard
5343 See Sec.\InsetSpace ~
5344
5345 \begin_inset LatexCommand \ref{sec:magic}
5346
5347 \end_inset
5348
5349 for details on the magics
5350 \family typewriter
5351 %sc
5352 \family default
5353 and
5354 \family typewriter
5355 %sx
5356 \family default
5357 , or use IPython's own help (
5358 \family typewriter
5359 sc?
5360 \family default
5361 and
5362 \family typewriter
5363 sx?
5364 \family default
5365 ) for further details.
5366 \end_layout
5367
5368 \begin_layout Standard
5369 IPython also allows you to expand the value of python variables when making
5370 system calls.
5371 Any python variable or expression which you prepend with
5372 \family typewriter
5373 $
5374 \family default
5375 will get expanded before the system call is made.
5376
5377 \end_layout
5378
5379 \begin_layout Standard
5380
5381 \family typewriter
5382 In [1]: pyvar='Hello world'
5383 \newline
5384 In [2]: !echo "A python variable: $pyvar"
5385 \newline
5386 A python
5387 variable: Hello world
5388 \end_layout
5389
5390 \begin_layout Standard
5391 If you want the shell to actually see a literal
5392 \family typewriter
5393 $
5394 \family default
5395 , you need to type it twice:
5396 \end_layout
5397
5398 \begin_layout Standard
5399
5400 \family typewriter
5401 In [3]: !echo "A system variable: $$HOME"
5402 \newline
5403 A system variable: /home/fperez
5404 \end_layout
5405
5406 \begin_layout Standard
5407 You can pass arbitrary expressions, though you'll need to delimit them with
5408
5409 \family typewriter
5410 {}
5411 \family default
5412 if there is ambiguity as to the extent of the expression:
5413 \end_layout
5414
5415 \begin_layout Standard
5416
5417 \family typewriter
5418 In [5]: x=10
5419 \newline
5420 In [6]: y=20
5421 \newline
5422 In [13]: !echo $x+y
5423 \newline
5424 10+y
5425 \newline
5426 In [7]: !echo ${x+y}
5427 \newline
5428 30
5429
5430 \end_layout
5431
5432 \begin_layout Standard
5433 Even object attributes can be expanded:
5434 \end_layout
5435
5436 \begin_layout Standard
5437
5438 \family typewriter
5439 In [12]: !echo $sys.argv
5440 \newline
5441 [/home/fperez/usr/bin/ipython]
5442 \end_layout
5443
5444 \begin_layout Subsection
5445 System command aliases
5446 \end_layout
5447
5448 \begin_layout Standard
5449 The
5450 \family typewriter
5451 %alias
5452 \family default
5453 magic function and the
5454 \family typewriter
5455 alias
5456 \family default
5457 option in the
5458 \family typewriter
5459 ipythonrc
5460 \family default
5461 configuration file allow you to define magic functions which are in fact
5462 system shell commands.
5463 These aliases can have parameters.
5464
5465 \end_layout
5466
5467 \begin_layout Standard
5468 '
5469 \family typewriter
5470 %alias alias_name cmd
5471 \family default
5472 ' defines '
5473 \family typewriter
5474 alias_name
5475 \family default
5476 ' as an alias for '
5477 \family typewriter
5478 cmd
5479 \family default
5480 '
5481 \end_layout
5482
5483 \begin_layout Standard
5484 Then, typing '
5485 \family typewriter
5486 %alias_name params
5487 \family default
5488 ' will execute the system command '
5489 \family typewriter
5490 cmd params
5491 \family default
5492 ' (from your underlying operating system).
5493
5494 \end_layout
5495
5496 \begin_layout Standard
5497 You can also define aliases with parameters using
5498 \family typewriter
5499 %s
5500 \family default
5501 specifiers (one per parameter).
5502 The following example defines the
5503 \family typewriter
5504 %parts
5505 \family default
5506 function as an alias to the command '
5507 \family typewriter
5508 echo first %s second %s
5509 \family default
5510 ' where each
5511 \family typewriter
5512 %s
5513 \family default
5514 will be replaced by a positional parameter to the call to
5515 \family typewriter
5516 %parts:
5517 \end_layout
5518
5519 \begin_layout Standard
5520
5521 \family typewriter
5522 In [1]: alias parts echo first %s second %s
5523 \newline
5524 In [2]: %parts A B
5525 \newline
5526 first A second
5527 B
5528 \newline
5529 In [3]: %parts A
5530 \newline
5531 Incorrect number of arguments: 2 expected.
5532
5533 \newline
5534 parts is an alias to: 'echo first %s second %s'
5535 \end_layout
5536
5537 \begin_layout Standard
5538 If called with no parameters,
5539 \family typewriter
5540 %alias
5541 \family default
5542 prints the table of currently defined aliases.
5543 \end_layout
5544
5545 \begin_layout Standard
5546 The
5547 \family typewriter
5548 %rehash/rehashx
5549 \family default
5550 magics allow you to load your entire
5551 \family typewriter
5552 $PATH
5553 \family default
5554 as ipython aliases.
5555 See their respective docstrings (or sec.\InsetSpace ~
5556
5557 \begin_inset LatexCommand \ref{sec:magic}
5558
5559 \end_inset
5560
5561 for further details).
5562 \end_layout
5563
5564 \begin_layout Subsection
5565 \begin_inset LatexCommand \label{sec:dreload}
5566
5567 \end_inset
5568
5569 Recursive reload
5570 \end_layout
5571
5572 \begin_layout Standard
5573 The
5574 \family typewriter
5575 dreload
5576 \family default
5577 function does a recursive reload of a module: changes made to the module
5578 since you imported will actually be available without having to exit.
5579 \end_layout
5580
5581 \begin_layout Subsection
5582 Verbose and colored exception traceback printouts
5583 \end_layout
5584
5585 \begin_layout Standard
5586 IPython provides the option to see very detailed exception tracebacks, which
5587 can be especially useful when debugging large programs.
5588 You can run any Python file with the
5589 \family typewriter
5590 %run
5591 \family default
5592 function to benefit from these detailed tracebacks.
5593 Furthermore, both normal and verbose tracebacks can be colored (if your
5594 terminal supports it) which makes them much easier to parse visually.
5595 \end_layout
5596
5597 \begin_layout Standard
5598 See the magic
5599 \family typewriter
5600 xmode
5601 \family default
5602 and
5603 \family typewriter
5604 colors
5605 \family default
5606 functions for details (just type
5607 \family typewriter
5608 %magic
5609 \family default
5610 ).
5611 \end_layout
5612
5613 \begin_layout Standard
5614 These features are basically a terminal version of Ka-Ping Yee's
5615 \family typewriter
5616 cgitb
5617 \family default
5618 module, now part of the standard Python library.
5619 \end_layout
5620
5621 \begin_layout Subsection
5622 \begin_inset LatexCommand \label{sec:cache_input}
5623
5624 \end_inset
5625
5626 Input caching system
5627 \end_layout
5628
5629 \begin_layout Standard
5630 IPython offers numbered prompts (In/Out) with input and output caching.
5631 All input is saved and can be retrieved as variables (besides the usual
5632 arrow key recall).
5633 \end_layout
5634
5635 \begin_layout Standard
5636 The following GLOBAL variables always exist (so don't overwrite them!):
5637
5638 \family typewriter
5639 _i
5640 \family default
5641 : stores previous input.
5642
5643 \family typewriter
5644 _ii
5645 \family default
5646 : next previous.
5647
5648 \family typewriter
5649 _iii
5650 \family default
5651 : next-next previous.
5652
5653 \family typewriter
5654 _ih
5655 \family default
5656 : a list of all input
5657 \family typewriter
5658 _ih[n]
5659 \family default
5660 is the input from line
5661 \family typewriter
5662 n
5663 \family default
5664 and this list is aliased to the global variable
5665 \family typewriter
5666 In
5667 \family default
5668 .
5669 If you overwrite
5670 \family typewriter
5671 In
5672 \family default
5673 with a variable of your own, you can remake the assignment to the internal
5674 list with a simple
5675 \family typewriter
5676 'In=_ih'
5677 \family default
5678 .
5679 \end_layout
5680
5681 \begin_layout Standard
5682 Additionally, global variables named
5683 \family typewriter
5684 _i<n>
5685 \family default
5686 are dynamically created (
5687 \family typewriter
5688 <n>
5689 \family default
5690 being the prompt counter), such that
5691 \newline
5692
5693 \family typewriter
5694 _i<n> == _ih[<n>] == In[<n>].
5695 \end_layout
5696
5697 \begin_layout Standard
5698 For example, what you typed at prompt 14 is available as
5699 \family typewriter
5700 _i14,
5701 \family default
5702
5703 \family typewriter
5704 _ih[14]
5705 \family default
5706 and
5707 \family typewriter
5708 In[14]
5709 \family default
5710 .
5711 \end_layout
5712
5713 \begin_layout Standard
5714 This allows you to easily cut and paste multi line interactive prompts by
5715 printing them out: they print like a clean string, without prompt characters.
5716 You can also manipulate them like regular variables (they are strings),
5717 modify or exec them (typing
5718 \family typewriter
5719 'exec _i9'
5720 \family default
5721 will re-execute the contents of input prompt 9, '
5722 \family typewriter
5723 exec In[9:14]+In[18]
5724 \family default
5725 ' will re-execute lines 9 through 13 and line 18).
5726 \end_layout
5727
5728 \begin_layout Standard
5729 You can also re-execute multiple lines of input easily by using the magic
5730
5731 \family typewriter
5732 %macro
5733 \family default
5734 function (which automates the process and allows re-execution without having
5735 to type '
5736 \family typewriter
5737 exec
5738 \family default
5739 ' every time).
5740 The macro system also allows you to re-execute previous lines which include
5741 magic function calls (which require special processing).
5742 Type
5743 \family typewriter
5744 %macro?
5745 \family default
5746 or see sec.
5747
5748 \begin_inset LatexCommand \ref{sec:magic}
5749
5750 \end_inset
5751
5752 for more details on the macro system.
5753 \end_layout
5754
5755 \begin_layout Standard
5756 A history function
5757 \family typewriter
5758 %hist
5759 \family default
5760 allows you to see any part of your input history by printing a range of
5761 the
5762 \family typewriter
5763 _i
5764 \family default
5765 variables.
5766 \end_layout
5767
5768 \begin_layout Subsection
5769 \begin_inset LatexCommand \label{sec:cache_output}
5770
5771 \end_inset
5772
5773 Output caching system
5774 \end_layout
5775
5776 \begin_layout Standard
5777 For output that is returned from actions, a system similar to the input
5778 cache exists but using
5779 \family typewriter
5780 _
5781 \family default
5782 instead of
5783 \family typewriter
5784 _i
5785 \family default
5786 .
5787 Only actions that produce a result (NOT assignments, for example) are cached.
5788 If you are familiar with Mathematica, IPython's
5789 \family typewriter
5790 _
5791 \family default
5792 variables behave exactly like Mathematica's
5793 \family typewriter
5794 %
5795 \family default
5796 variables.
5797 \end_layout
5798
5799 \begin_layout Standard
5800 The following GLOBAL variables always exist (so don't overwrite them!):
5801
5802 \end_layout
5803
5804 \begin_layout List
5805 \labelwidthstring 00.00.0000
5806
5807 \family typewriter
5808 \series bold
5809 _
5810 \family default
5811 \series default
5812 (a
5813 \emph on
5814 single
5815 \emph default
5816 underscore) : stores previous output, like Python's default interpreter.
5817 \end_layout
5818
5819 \begin_layout List
5820 \labelwidthstring 00.00.0000
5821
5822 \family typewriter
5823 \series bold
5824 __
5825 \family default
5826 \series default
5827 (two underscores): next previous.
5828 \end_layout
5829
5830 \begin_layout List
5831 \labelwidthstring 00.00.0000
5832
5833 \family typewriter
5834 \series bold
5835 ___
5836 \family default
5837 \series default
5838 (three underscores): next-next previous.
5839 \end_layout
5840
5841 \begin_layout Standard
5842 Additionally, global variables named
5843 \family typewriter
5844 _<n>
5845 \family default
5846 are dynamically created (
5847 \family typewriter
5848 <n>
5849 \family default
5850 being the prompt counter), such that the result of output
5851 \family typewriter
5852 <n>
5853 \family default
5854 is always available as
5855 \family typewriter
5856 _<n>
5857 \family default
5858 (don't use the angle brackets, just the number, e.g.
5859
5860 \family typewriter
5861 _21
5862 \family default
5863 ).
5864 \end_layout
5865
5866 \begin_layout Standard
5867 These global variables are all stored in a global dictionary (not a list,
5868 since it only has entries for lines which returned a result) available
5869 under the names
5870 \family typewriter
5871 _oh
5872 \family default
5873 and
5874 \family typewriter
5875 Out
5876 \family default
5877 (similar to
5878 \family typewriter
5879 _ih
5880 \family default
5881 and
5882 \family typewriter
5883 In
5884 \family default
5885 ).
5886 So the output from line 12 can be obtained as
5887 \family typewriter
5888 _12
5889 \family default
5890 ,
5891 \family typewriter
5892 Out[12]
5893 \family default
5894 or
5895 \family typewriter
5896 _oh[12]
5897 \family default
5898 .
5899 If you accidentally overwrite the
5900 \family typewriter
5901 Out
5902 \family default
5903 variable you can recover it by typing
5904 \family typewriter
5905 'Out=_oh
5906 \family default
5907 ' at the prompt.
5908 \end_layout
5909
5910 \begin_layout Standard
5911 This system obviously can potentially put heavy memory demands on your system,
5912 since it prevents Python's garbage collector from removing any previously
5913 computed results.
5914 You can control how many results are kept in memory with the option (at
5915 the command line or in your
5916 \family typewriter
5917 ipythonrc
5918 \family default
5919 file)
5920 \family typewriter
5921 cache_size
5922 \family default
5923 .
5924 If you set it to 0, the whole system is completely disabled and the prompts
5925 revert to the classic
5926 \family typewriter
5927 '>>>'
5928 \family default
5929 of normal Python.
5930 \end_layout
5931
5932 \begin_layout Subsection
5933 Directory history
5934 \end_layout
5935
5936 \begin_layout Standard
5937 Your history of visited directories is kept in the global list
5938 \family typewriter
5939 _dh
5940 \family default
5941 , and the magic
5942 \family typewriter
5943 %cd
5944 \family default
5945 command can be used to go to any entry in that list.
5946 The
5947 \family typewriter
5948 %dhist
5949 \family default
5950 command allows you to view this history.
5951 \end_layout
5952
5953 \begin_layout Subsection
5954 Automatic parentheses and quotes
5955 \end_layout
5956
5957 \begin_layout Standard
5958 These features were adapted from Nathan Gray's LazyPython.
5959 They are meant to allow less typing for common situations.
5960 \end_layout
5961
5962 \begin_layout Subsubsection
5963 Automatic parentheses
5964 \end_layout
5965
5966 \begin_layout Standard
5967 Callable objects (i.e.
5968 functions, methods, etc) can be invoked like this (notice the commas between
5969 the arguments):
5970 \end_layout
5971
5972 \begin_layout Standard
5973
5974 \family typewriter
5975 >>> callable_ob arg1, arg2, arg3
5976 \end_layout
5977
5978 \begin_layout Standard
5979 and the input will be translated to this:
5980 \end_layout
5981
5982 \begin_layout Standard
5983
5984 \family typewriter
5985 --> callable_ob(arg1, arg2, arg3)
5986 \end_layout
5987
5988 \begin_layout Standard
5989 You can force automatic parentheses by using '/' as the first character
5990 of a line.
5991 For example:
5992 \end_layout
5993
5994 \begin_layout Standard
5995
5996 \family typewriter
5997 >>> /globals # becomes 'globals()'
5998 \end_layout
5999
6000 \begin_layout Standard
6001 Note that the '/' MUST be the first character on the line! This won't work:
6002
6003 \end_layout
6004
6005 \begin_layout Standard
6006
6007 \family typewriter
6008 >>> print /globals # syntax error
6009 \end_layout
6010
6011 \begin_layout Standard
6012 In most cases the automatic algorithm should work, so you should rarely
6013 need to explicitly invoke /.
6014 One notable exception is if you are trying to call a function with a list
6015 of tuples as arguments (the parenthesis will confuse IPython):
6016 \end_layout
6017
6018 \begin_layout Standard
6019
6020 \family typewriter
6021 In [1]: zip (1,2,3),(4,5,6) # won't work
6022 \end_layout
6023
6024 \begin_layout Standard
6025 but this will work:
6026 \end_layout
6027
6028 \begin_layout Standard
6029
6030 \family typewriter
6031 In [2]: /zip (1,2,3),(4,5,6)
6032 \newline
6033 ------> zip ((1,2,3),(4,5,6))
6034 \newline
6035 Out[2]= [(1, 4),
6036 (2, 5), (3, 6)]
6037 \end_layout
6038
6039 \begin_layout Standard
6040 IPython tells you that it has altered your command line by displaying the
6041 new command line preceded by
6042 \family typewriter
6043 -->
6044 \family default
6045 .
6046 e.g.:
6047 \end_layout
6048
6049 \begin_layout Standard
6050
6051 \family typewriter
6052 In [18]: callable list
6053 \newline
6054 -------> callable (list)
6055 \end_layout
6056
6057 \begin_layout Subsubsection
6058 Automatic quoting
6059 \end_layout
6060
6061 \begin_layout Standard
6062 You can force automatic quoting of a function's arguments by using
6063 \family typewriter
6064 `,'
6065 \family default
6066 or
6067 \family typewriter
6068 `;'
6069 \family default
6070 as the first character of a line.
6071 For example:
6072 \end_layout
6073
6074 \begin_layout Standard
6075
6076 \family typewriter
6077 >>> ,my_function /home/me # becomes my_function("/home/me")
6078 \end_layout
6079
6080 \begin_layout Standard
6081 If you use
6082 \family typewriter
6083 `;'
6084 \family default
6085 instead, the whole argument is quoted as a single string (while
6086 \family typewriter
6087 `,'
6088 \family default
6089 splits on whitespace):
6090 \end_layout
6091
6092 \begin_layout Standard
6093
6094 \family typewriter
6095 >>> ,my_function a b c # becomes my_function("a","b","c")
6096 \end_layout
6097
6098 \begin_layout Standard
6099
6100 \family typewriter
6101 >>> ;my_function a b c # becomes my_function("a b c")
6102 \end_layout
6103
6104 \begin_layout Standard
6105 Note that the `
6106 \family typewriter
6107 ,
6108 \family default
6109 ' or `
6110 \family typewriter
6111 ;
6112 \family default
6113 ' MUST be the first character on the line! This won't work:
6114 \end_layout
6115
6116 \begin_layout Standard
6117
6118 \family typewriter
6119 >>> x = ,my_function /home/me # syntax error
6120 \end_layout
6121
6122 \begin_layout Section
6123 \begin_inset LatexCommand \label{sec:customization}
6124
6125 \end_inset
6126
6127 Customization
6128 \end_layout
6129
6130 \begin_layout Standard
6131 As we've already mentioned, IPython reads a configuration file which can
6132 be specified at the command line (
6133 \family typewriter
6134 -rcfile
6135 \family default
6136 ) or which by default is assumed to be called
6137 \family typewriter
6138 ipythonrc
6139 \family default
6140 .
6141 Such a file is looked for in the current directory where IPython is started
6142 and then in your
6143 \family typewriter
6144 IPYTHONDIR
6145 \family default
6146 , which allows you to have local configuration files for specific projects.
6147 In this section we will call these types of configuration files simply
6148 rcfiles (short for resource configuration file).
6149 \end_layout
6150
6151 \begin_layout Standard
6152 The syntax of an rcfile is one of key-value pairs separated by whitespace,
6153 one per line.
6154 Lines beginning with a
6155 \family typewriter
6156 #
6157 \family default
6158 are ignored as comments, but comments can
6159 \series bold
6160 not
6161 \series default
6162 be put on lines with data (the parser is fairly primitive).
6163 Note that these are not python files, and this is deliberate, because it
6164 allows us to do some things which would be quite tricky to implement if
6165 they were normal python files.
6166 \end_layout
6167
6168 \begin_layout Standard
6169 First, an rcfile can contain permanent default values for almost all command
6170 line options (except things like
6171 \family typewriter
6172 -help
6173 \family default
6174 or
6175 \family typewriter
6176 -Version
6177 \family default
6178 ).
6179 Sec\InsetSpace ~
6180
6181 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
6182
6183 \end_inset
6184
6185 contains a description of all command-line options.
6186 However, values you explicitly specify at the command line override the
6187 values defined in the rcfile.
6188 \end_layout
6189
6190 \begin_layout Standard
6191 Besides command line option values, the rcfile can specify values for certain
6192 extra special options which are not available at the command line.
6193 These options are briefly described below.
6194
6195 \end_layout
6196
6197 \begin_layout Standard
6198 Each of these options may appear as many times as you need it in the file.
6199 \end_layout
6200
6201 \begin_layout List
6202 \labelwidthstring 00.00.0000
6203
6204 \family typewriter
6205 \series bold
6206 include\InsetSpace ~
6207 <file1>\InsetSpace ~
6208 <file2>\InsetSpace ~
6209 ...
6210 \family default
6211 \series default
6212 : you can name
6213 \emph on
6214 other
6215 \emph default
6216 rcfiles you want to recursively load up to 15 levels (don't use the
6217 \family typewriter
6218 <>
6219 \family default
6220 brackets in your names!).
6221 This feature allows you to define a 'base' rcfile with general options
6222 and special-purpose files which can be loaded only when needed with particular
6223 configuration options.
6224 To make this more convenient, IPython accepts the
6225 \family typewriter
6226 -profile <name>
6227 \family default
6228 option (abbreviates to
6229 \family typewriter
6230 -p <name
6231 \family default
6232 >)
6233 \family typewriter
6234 which
6235 \family default
6236 tells it to look for an rcfile named
6237 \family typewriter
6238 ipythonrc-<name>
6239 \family default
6240 .
6241
6242 \end_layout
6243
6244 \begin_layout List
6245 \labelwidthstring 00.00.0000
6246
6247 \family typewriter
6248 \series bold
6249 import_mod\InsetSpace ~
6250 <mod1>\InsetSpace ~
6251 <mod2>\InsetSpace ~
6252 ...
6253 \family default
6254 \series default
6255 : import modules with '
6256 \family typewriter
6257 import
6258 \family default
6259
6260 \family typewriter
6261 <mod1>,<mod2>,...
6262 \family default
6263 '
6264 \end_layout
6265
6266 \begin_layout List
6267 \labelwidthstring 00.00.0000
6268
6269 \family typewriter
6270 \series bold
6271 import_some\InsetSpace ~
6272 <mod>\InsetSpace ~
6273 <f1>\InsetSpace ~
6274 <f2>\InsetSpace ~
6275 ...
6276 \family default
6277 \series default
6278 : import functions with '
6279 \family typewriter
6280 from <mod> import
6281 \family default
6282
6283 \family typewriter
6284 <f1>,<f2>,...
6285 \family default
6286 '
6287 \end_layout
6288
6289 \begin_layout List
6290 \labelwidthstring 00.00.0000
6291
6292 \family typewriter
6293 \series bold
6294 import_all\InsetSpace ~
6295 <mod1>\InsetSpace ~
6296 <mod2>\InsetSpace ~
6297 ...
6298 \family default
6299 \series default
6300 : for each module listed import functions with '
6301 \family typewriter
6302 from <mod> import *
6303 \family default
6304 '
6305 \end_layout
6306
6307 \begin_layout List
6308 \labelwidthstring 00.00.0000
6309
6310 \family typewriter
6311 \series bold
6312 execute\InsetSpace ~
6313 <python\InsetSpace ~
6314 code>
6315 \family default
6316 \series default
6317 : give any single-line python code to be executed.
6318 \end_layout
6319
6320 \begin_layout List
6321 \labelwidthstring 00.00.0000
6322
6323 \family typewriter
6324 \series bold
6325 execfile\InsetSpace ~
6326 <filename>
6327 \family default
6328 \series default
6329 : execute the python file given with an '
6330 \family typewriter
6331 execfile(filename)
6332 \family default
6333 ' command.
6334 Username expansion is performed on the given names.
6335 So if you need any amount of extra fancy customization that won't fit in
6336 any of the above 'canned' options, you can just put it in a separate python
6337 file and execute it.
6338 \end_layout
6339
6340 \begin_layout List
6341 \labelwidthstring 00.00.0000
6342
6343 \family typewriter
6344 \series bold
6345 alias\InsetSpace ~
6346 <alias_def>
6347 \family default
6348 \series default
6349 : this is equivalent to calling '
6350 \family typewriter
6351 %alias\InsetSpace ~
6352 <alias_def>
6353 \family default
6354 ' at the IPython command line.
6355 This way, from within IPython you can do common system tasks without having
6356 to exit it or use the
6357 \family typewriter
6358 !
6359 \family default
6360 escape.
6361 IPython isn't meant to be a shell replacement, but it is often very useful
6362 to be able to do things with files while testing code.
6363 This gives you the flexibility to have within IPython any aliases you may
6364 be used to under your normal system shell.
6365 \end_layout
6366
6367 \begin_layout Subsection
6368 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
6369
6370 \end_inset
6371
6372 Sample
6373 \family typewriter
6374 ipythonrc
6375 \family default
6376 file
6377 \end_layout
6378
6379 \begin_layout Standard
6380 The default rcfile, called
6381 \family typewriter
6382 ipythonrc
6383 \family default
6384 and supplied in your
6385 \family typewriter
6386 IPYTHONDIR
6387 \family default
6388 directory contains lots of comments on all of these options.
6389 We reproduce it here for reference:
6390 \end_layout
6391
6392 \begin_layout Standard
6393 \begin_inset ERT
6394 status open
6395
6396 \begin_layout Standard
6397
6398
6399 \backslash
6400 codelist{../IPython/UserConfig/ipythonrc}
6401 \end_layout
6402
6403 \end_inset
6404
6405
6406 \end_layout
6407
6408 \begin_layout Subsection
6409 \begin_inset LatexCommand \label{sec:prompts}
6410
6411 \end_inset
6412
6413 Fine-tuning your prompt
6414 \end_layout
6415
6416 \begin_layout Standard
6417 IPython's prompts can be customized using a syntax similar to that of the
6418
6419 \family typewriter
6420 bash
6421 \family default
6422 shell.
6423 Many of
6424 \family typewriter
6425 bash
6426 \family default
6427 's escapes are supported, as well as a few additional ones.
6428 We list them below:
6429 \end_layout
6430
6431 \begin_layout Description
6432
6433 \backslash
6434 # the prompt/history count number.
6435 This escape is automatically wrapped in the coloring codes for the currently
6436 active color scheme.
6437 \end_layout
6438
6439 \begin_layout Description
6440
6441 \backslash
6442 N the 'naked' prompt/history count number: this is just the number itself,
6443 without any coloring applied to it.
6444 This lets you produce numbered prompts with your own colors.
6445 \end_layout
6446
6447 \begin_layout Description
6448
6449 \backslash
6450 D the prompt/history count, with the actual digits replaced by dots.
6451 Used mainly in continuation prompts (prompt_in2)
6452 \end_layout
6453
6454 \begin_layout Description
6455
6456 \backslash
6457 w the current working directory
6458 \end_layout
6459
6460 \begin_layout Description
6461
6462 \backslash
6463 W the basename of current working directory
6464 \end_layout
6465
6466 \begin_layout Description
6467
6468 \backslash
6469 X
6470 \emph on
6471 n
6472 \emph default
6473 where
6474 \begin_inset Formula $n=0\ldots5.$
6475 \end_inset
6476
6477 The current working directory, with
6478 \family typewriter
6479 $HOME
6480 \family default
6481 replaced by
6482 \family typewriter
6483 ~
6484 \family default
6485 , and filtered out to contain only
6486 \begin_inset Formula $n$
6487 \end_inset
6488
6489 path elements
6490 \end_layout
6491
6492 \begin_layout Description
6493
6494 \backslash
6495 Y
6496 \emph on
6497 n
6498 \emph default
6499 Similar to
6500 \backslash
6501 X
6502 \emph on
6503 n
6504 \emph default
6505 , but with the
6506 \begin_inset Formula $n+1$
6507 \end_inset
6508
6509 element included if it is
6510 \family typewriter
6511 ~
6512 \family default
6513 (this is similar to the behavior of the %c
6514 \emph on
6515 n
6516 \emph default
6517 escapes in
6518 \family typewriter
6519 tcsh
6520 \family default
6521 )
6522 \end_layout
6523
6524 \begin_layout Description
6525
6526 \backslash
6527 u the username of the current user
6528 \end_layout
6529
6530 \begin_layout Description
6531
6532 \backslash
6533 $ if the effective UID is 0, a #, otherwise a $
6534 \end_layout
6535
6536 \begin_layout Description
6537
6538 \backslash
6539 h the hostname up to the first `.'
6540 \end_layout
6541
6542 \begin_layout Description
6543
6544 \backslash
6545 H the hostname
6546 \end_layout
6547
6548 \begin_layout Description
6549
6550 \backslash
6551 n a newline
6552 \end_layout
6553
6554 \begin_layout Description
6555
6556 \backslash
6557 r a carriage return
6558 \end_layout
6559
6560 \begin_layout Description
6561
6562 \backslash
6563 v IPython version string
6564 \end_layout
6565
6566 \begin_layout Standard
6567 In addition to these, ANSI color escapes can be insterted into the prompts,
6568 as
6569 \family typewriter
6570
6571 \backslash
6572 C_
6573 \emph on
6574 ColorName
6575 \family default
6576 \emph default
6577 .
6578 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
6579 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
6580 Normal, Purple, Red, White, Yellow.
6581 \end_layout
6582
6583 \begin_layout Standard
6584 Finally, IPython supports the evaluation of arbitrary expressions in your
6585 prompt string.
6586 The prompt strings are evaluated through the syntax of PEP 215, but basically
6587 you can use
6588 \family typewriter
6589 $x.y
6590 \family default
6591 to expand the value of
6592 \family typewriter
6593 x.y
6594 \family default
6595 , and for more complicated expressions you can use braces:
6596 \family typewriter
6597 ${foo()+x}
6598 \family default
6599 will call function
6600 \family typewriter
6601 foo
6602 \family default
6603 and add to it the value of
6604 \family typewriter
6605 x
6606 \family default
6607 , before putting the result into your prompt.
6608 For example, using
6609 \newline
6610
6611 \family typewriter
6612 prompt_in1 '${commands.getoutput("uptime")}
6613 \backslash
6614 nIn [
6615 \backslash
6616 #]: '
6617 \newline
6618
6619 \family default
6620 will print the result of the uptime command on each prompt (assuming the
6621
6622 \family typewriter
6623 commands
6624 \family default
6625 module has been imported in your
6626 \family typewriter
6627 ipythonrc
6628 \family default
6629 file).
6630 \end_layout
6631
6632 \begin_layout Subsubsection
6633 Prompt examples
6634 \end_layout
6635
6636 \begin_layout Standard
6637 The following options in an ipythonrc file will give you IPython's default
6638 prompts:
6639 \end_layout
6640
6641 \begin_layout Standard
6642
6643 \family typewriter
6644 prompt_in1 'In [
6645 \backslash
6646 #]:'
6647 \newline
6648 prompt_in2 '\InsetSpace ~
6649 \InsetSpace ~
6650 \InsetSpace ~
6651 .
6652 \backslash
6653 D.:'
6654 \newline
6655 prompt_out 'Out[
6656 \backslash
6657 #]:'
6658 \end_layout
6659
6660 \begin_layout Standard
6661 which look like this:
6662 \end_layout
6663
6664 \begin_layout Standard
6665
6666 \family typewriter
6667 In [1]: 1+2
6668 \newline
6669 Out[1]: 3
6670 \end_layout
6671
6672 \begin_layout Standard
6673
6674 \family typewriter
6675 In [2]: for i in (1,2,3):
6676 \newline
6677
6678 \begin_inset ERT
6679 status collapsed
6680
6681 \begin_layout Standard
6682
6683
6684 \backslash
6685 hspace*{0mm}
6686 \end_layout
6687
6688 \end_inset
6689
6690 \InsetSpace ~
6691 \InsetSpace ~
6692 \InsetSpace ~
6693 ...: \InsetSpace ~
6694 \InsetSpace ~
6695 \InsetSpace ~
6696 \InsetSpace ~
6697 print i,
6698 \newline
6699
6700 \begin_inset ERT
6701 status collapsed
6702
6703 \begin_layout Standard
6704
6705
6706 \backslash
6707 hspace*{0mm}
6708 \end_layout
6709
6710 \end_inset
6711
6712 \InsetSpace ~
6713 \InsetSpace ~
6714 \InsetSpace ~
6715 ...:
6716 \newline
6717 1 2 3
6718 \end_layout
6719
6720 \begin_layout Standard
6721 These will give you a very colorful prompt with path information:
6722 \end_layout
6723
6724 \begin_layout Standard
6725
6726 \family typewriter
6727 #prompt_in1 '
6728 \backslash
6729 C_Red
6730 \backslash
6731 u
6732 \backslash
6733 C_Blue[
6734 \backslash
6735 C_Cyan
6736 \backslash
6737 Y1
6738 \backslash
6739 C_Blue]
6740 \backslash
6741 C_LightGreen
6742 \backslash
6743 #>'
6744 \newline
6745 prompt_in2 ' ..
6746 \backslash
6747 D>'
6748 \newline
6749 prompt_out '<
6750 \backslash
6751 #>'
6752 \end_layout
6753
6754 \begin_layout Standard
6755 which look like this:
6756 \end_layout
6757
6758 \begin_layout Standard
6759
6760 \family typewriter
6761 \color red
6762 fperez
6763 \color blue
6764 [
6765 \color cyan
6766 ~/ipython
6767 \color blue
6768 ]
6769 \color green
6770 1>
6771 \color none
6772 1+2
6773 \newline
6774
6775 \begin_inset ERT
6776 status collapsed
6777
6778 \begin_layout Standard
6779
6780
6781 \backslash
6782 hspace*{0mm}
6783 \end_layout
6784
6785 \end_inset
6786
6787 \InsetSpace ~
6788 \InsetSpace ~
6789 \InsetSpace ~
6790 \InsetSpace ~
6791 \InsetSpace ~
6792 \InsetSpace ~
6793 \InsetSpace ~
6794 \InsetSpace ~
6795 \InsetSpace ~
6796 \InsetSpace ~
6797 \InsetSpace ~
6798 \InsetSpace ~
6799 \InsetSpace ~
6800 \InsetSpace ~
6801 \InsetSpace ~
6802 \InsetSpace ~
6803
6804 \color red
6805 <1>
6806 \color none
6807 3
6808 \newline
6809
6810 \color red
6811 fperez
6812 \color blue
6813 [
6814 \color cyan
6815 ~/ipython
6816 \color blue
6817 ]
6818 \color green
6819 2>
6820 \color none
6821 for i in (1,2,3):
6822 \newline
6823
6824 \begin_inset ERT
6825 status collapsed
6826
6827 \begin_layout Standard
6828
6829
6830 \backslash
6831 hspace*{0mm}
6832 \end_layout
6833
6834 \end_inset
6835
6836 \InsetSpace ~
6837 \InsetSpace ~
6838 \InsetSpace ~
6839 \InsetSpace ~
6840 \InsetSpace ~
6841 \InsetSpace ~
6842 \InsetSpace ~
6843 \InsetSpace ~
6844 \InsetSpace ~
6845 \InsetSpace ~
6846 \InsetSpace ~
6847 \InsetSpace ~
6848 \InsetSpace ~
6849 \InsetSpace ~
6850 \InsetSpace ~
6851
6852 \color green
6853 ...>
6854 \color none
6855 \InsetSpace ~
6856 \InsetSpace ~
6857 \InsetSpace ~
6858 \InsetSpace ~
6859 print i,
6860 \newline
6861
6862 \begin_inset ERT
6863 status collapsed
6864
6865 \begin_layout Standard
6866
6867
6868 \backslash
6869 hspace*{0mm}
6870 \end_layout
6871
6872 \end_inset
6873
6874 \InsetSpace ~
6875 \InsetSpace ~
6876 \InsetSpace ~
6877 \InsetSpace ~
6878 \InsetSpace ~
6879 \InsetSpace ~
6880 \InsetSpace ~
6881 \InsetSpace ~
6882 \InsetSpace ~
6883 \InsetSpace ~
6884 \InsetSpace ~
6885 \InsetSpace ~
6886 \InsetSpace ~
6887 \InsetSpace ~
6888 \InsetSpace ~
6889
6890 \color green
6891 ...>
6892 \color none
6893
6894 \newline
6895 1 2 3
6896 \end_layout
6897
6898 \begin_layout Standard
6899 The following shows the usage of dynamic expression evaluation:
6900 \end_layout
6901
6902 \begin_layout Subsection
6903 \begin_inset LatexCommand \label{sec:profiles}
6904
6905 \end_inset
6906
6907 IPython profiles
6908 \end_layout
6909
6910 \begin_layout Standard
6911 As we already mentioned, IPython supports the
6912 \family typewriter
6913 -profile
6914 \family default
6915 command-line option (see sec.
6916
6917 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
6918
6919 \end_inset
6920
6921 ).
6922 A profile is nothing more than a particular configuration file like your
6923 basic
6924 \family typewriter
6925 ipythonrc
6926 \family default
6927 one, but with particular customizations for a specific purpose.
6928 When you start IPython with '
6929 \family typewriter
6930 ipython -profile <name>
6931 \family default
6932 ', it assumes that in your
6933 \family typewriter
6934 IPYTHONDIR
6935 \family default
6936 there is a file called
6937 \family typewriter
6938 ipythonrc-<name>
6939 \family default
6940 , and loads it instead of the normal
6941 \family typewriter
6942 ipythonrc
6943 \family default
6944 .
6945 \end_layout
6946
6947 \begin_layout Standard
6948 This system allows you to maintain multiple configurations which load modules,
6949 set options, define functions, etc.
6950 suitable for different tasks and activate them in a very simple manner.
6951 In order to avoid having to repeat all of your basic options (common things
6952 that don't change such as your color preferences, for example), any profile
6953 can include another configuration file.
6954 The most common way to use profiles is then to have each one include your
6955 basic
6956 \family typewriter
6957 ipythonrc
6958 \family default
6959 file as a starting point, and then add further customizations.
6960 \end_layout
6961
6962 \begin_layout Standard
6963 In sections
6964 \begin_inset LatexCommand \ref{sec:syntax-extensions}
6965
6966 \end_inset
6967
6968 and
6969 \begin_inset LatexCommand \ref{sec:Gnuplot}
6970
6971 \end_inset
6972
6973 we discuss some particular profiles which come as part of the standard
6974 IPython distribution.
6975 You may also look in your
6976 \family typewriter
6977 IPYTHONDIR
6978 \family default
6979 directory, any file whose name begins with
6980 \family typewriter
6981 ipythonrc-
6982 \family default
6983 is a profile.
6984 You can use those as examples for further customizations to suit your own
6985 needs.
6986 \end_layout
6987
6988 \begin_layout Section
6989 \begin_inset OptArg
6990 status open
6991
6992 \begin_layout Standard
6993 IPython as default...
6994 \end_layout
6995
6996 \end_inset
6997
6998 IPython as your default Python environment
6999 \end_layout
7000
7001 \begin_layout Standard
7002 Python honors the environment variable
7003 \family typewriter
7004 PYTHONSTARTUP
7005 \family default
7006 and will execute at startup the file referenced by this variable.
7007 If you put at the end of this file the following two lines of code:
7008 \end_layout
7009
7010 \begin_layout Standard
7011
7012 \family typewriter
7013 import IPython
7014 \newline
7015 IPython.Shell.IPShell().mainloop(sys_exit=1)
7016 \end_layout
7017
7018 \begin_layout Standard
7019 then IPython will be your working environment anytime you start Python.
7020 The
7021 \family typewriter
7022 sys_exit=1
7023 \family default
7024 is needed to have IPython issue a call to
7025 \family typewriter
7026 sys.exit()
7027 \family default
7028 when it finishes, otherwise you'll be back at the normal Python '
7029 \family typewriter
7030 >>>
7031 \family default
7032 ' prompt
7033 \begin_inset Foot
7034 status collapsed
7035
7036 \begin_layout Standard
7037 Based on an idea by Holger Krekel.
7038 \end_layout
7039
7040 \end_inset
7041
7042 .
7043 \end_layout
7044
7045 \begin_layout Standard
7046 This is probably useful to developers who manage multiple Python versions
7047 and don't want to have correspondingly multiple IPython versions.
7048 Note that in this mode, there is no way to pass IPython any command-line
7049 options, as those are trapped first by Python itself.
7050 \end_layout
7051
7052 \begin_layout Section
7053 \begin_inset LatexCommand \label{sec:embed}
7054
7055 \end_inset
7056
7057 Embedding IPython
7058 \end_layout
7059
7060 \begin_layout Standard
7061 It is possible to start an IPython instance
7062 \emph on
7063 inside
7064 \emph default
7065 your own Python programs.
7066 This allows you to evaluate dynamically the state of your code, operate
7067 with your variables, analyze them, etc.
7068 Note however that any changes you make to values while in the shell do
7069
7070 \emph on
7071 not
7072 \emph default
7073 propagate back to the running code, so it is safe to modify your values
7074 because you won't break your code in bizarre ways by doing so.
7075 \end_layout
7076
7077 \begin_layout Standard
7078 This feature allows you to easily have a fully functional python environment
7079 for doing object introspection anywhere in your code with a simple function
7080 call.
7081 In some cases a simple print statement is enough, but if you need to do
7082 more detailed analysis of a code fragment this feature can be very valuable.
7083 \end_layout
7084
7085 \begin_layout Standard
7086 It can also be useful in scientific computing situations where it is common
7087 to need to do some automatic, computationally intensive part and then stop
7088 to look at data, plots, etc
7089 \begin_inset Foot
7090 status collapsed
7091
7092 \begin_layout Standard
7093 This functionality was inspired by IDL's combination of the
7094 \family typewriter
7095 stop
7096 \family default
7097 keyword and the
7098 \family typewriter
7099 .continue
7100 \family default
7101 executive command, which I have found very useful in the past, and by a
7102 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
7103 06/01 concerning similar uses of pyrepl.
7104 \end_layout
7105
7106 \end_inset
7107
7108 .
7109 Opening an IPython instance will give you full access to your data and
7110 functions, and you can resume program execution once you are done with
7111 the interactive part (perhaps to stop again later, as many times as needed).
7112 \end_layout
7113
7114 \begin_layout Standard
7115 The following code snippet is the bare minimum you need to include in your
7116 Python programs for this to work (detailed examples follow later):
7117 \end_layout
7118
7119 \begin_layout LyX-Code
7120 from IPython.Shell import IPShellEmbed
7121 \end_layout
7122
7123 \begin_layout LyX-Code
7124 ipshell = IPShellEmbed()
7125 \end_layout
7126
7127 \begin_layout LyX-Code
7128 ipshell() # this call anywhere in your program will start IPython
7129 \end_layout
7130
7131 \begin_layout Standard
7132 You can run embedded instances even in code which is itself being run at
7133 the IPython interactive prompt with '
7134 \family typewriter
7135 %run\InsetSpace ~
7136 <filename>
7137 \family default
7138 '.
7139 Since it's easy to get lost as to where you are (in your top-level IPython
7140 or in your embedded one), it's a good idea in such cases to set the in/out
7141 prompts to something different for the embedded instances.
7142 The code examples below illustrate this.
7143 \end_layout
7144
7145 \begin_layout Standard
7146 You can also have multiple IPython instances in your program and open them
7147 separately, for example with different options for data presentation.
7148 If you close and open the same instance multiple times, its prompt counters
7149 simply continue from each execution to the next.
7150 \end_layout
7151
7152 \begin_layout Standard
7153 Please look at the docstrings in the
7154 \family typewriter
7155 Shell.py
7156 \family default
7157 module for more details on the use of this system.
7158 \end_layout
7159
7160 \begin_layout Standard
7161 The following sample file illustrating how to use the embedding functionality
7162 is provided in the examples directory as
7163 \family typewriter
7164 example-embed.py
7165 \family default
7166 .
7167 It should be fairly self-explanatory:
7168 \end_layout
7169
7170 \begin_layout Standard
7171 \begin_inset ERT
7172 status open
7173
7174 \begin_layout Standard
7175
7176
7177 \backslash
7178 codelist{examples/example-embed.py}
7179 \end_layout
7180
7181 \end_inset
7182
7183
7184 \end_layout
7185
7186 \begin_layout Standard
7187 Once you understand how the system functions, you can use the following
7188 code fragments in your programs which are ready for cut and paste:
7189 \end_layout
7190
7191 \begin_layout Standard
7192 \begin_inset ERT
7193 status open
7194
7195 \begin_layout Standard
7196
7197
7198 \backslash
7199 codelist{examples/example-embed-short.py}
7200 \end_layout
7201
7202 \end_inset
7203
7204
7205 \end_layout
7206
7207 \begin_layout Section
7208 \begin_inset LatexCommand \label{sec:using-pdb}
7209
7210 \end_inset
7211
7212 Using the Python debugger (
7213 \family typewriter
7214 pdb
7215 \family default
7216 )
7217 \end_layout
7218
7219 \begin_layout Subsection
7220 Running entire programs via
7221 \family typewriter
7222 pdb
7223 \end_layout
7224
7225 \begin_layout Standard
7226
7227 \family typewriter
7228 pdb
7229 \family default
7230 , the Python debugger, is a powerful interactive debugger which allows you
7231 to step through code, set breakpoints, watch variables, etc.
7232 IPython makes it very easy to start any script under the control of
7233 \family typewriter
7234 pdb
7235 \family default
7236 , regardless of whether you have wrapped it into a
7237 \family typewriter
7238 `main()'
7239 \family default
7240 function or not.
7241 For this, simply type
7242 \family typewriter
7243 `%run -d myscript'
7244 \family default
7245 at an IPython prompt.
7246 See the
7247 \family typewriter
7248 %run
7249 \family default
7250 command's documentation (via
7251 \family typewriter
7252 `%run?'
7253 \family default
7254 or in Sec.\InsetSpace ~
7255
7256 \begin_inset LatexCommand \ref{sec:magic}
7257
7258 \end_inset
7259
7260 ) for more details, including how to control where
7261 \family typewriter
7262 pdb
7263 \family default
7264 will stop execution first.
7265 \end_layout
7266
7267 \begin_layout Standard
7268 For more information on the use of the
7269 \family typewriter
7270 pdb
7271 \family default
7272 debugger, read the included
7273 \family typewriter
7274 pdb.doc
7275 \family default
7276 file (part of the standard Python distribution).
7277 On a stock Linux system it is located at
7278 \family typewriter
7279 /usr/lib/python2.3/pdb.doc
7280 \family default
7281 , but the easiest way to read it is by using the
7282 \family typewriter
7283 help()
7284 \family default
7285 function of the
7286 \family typewriter
7287 pdb
7288 \family default
7289 module as follows (in an IPython prompt):
7290 \end_layout
7291
7292 \begin_layout Standard
7293
7294 \family typewriter
7295 In [1]: import pdb
7296 \newline
7297 In [2]: pdb.help()
7298 \end_layout
7299
7300 \begin_layout Standard
7301 This will load the
7302 \family typewriter
7303 pdb.doc
7304 \family default
7305 document in a file viewer for you automatically.
7306 \end_layout
7307
7308 \begin_layout Subsection
7309 Automatic invocation of
7310 \family typewriter
7311 pdb
7312 \family default
7313 on exceptions
7314 \end_layout
7315
7316 \begin_layout Standard
7317 IPython, if started with the
7318 \family typewriter
7319 -pdb
7320 \family default
7321 option (or if the option is set in your rc file) can call the Python
7322 \family typewriter
7323 pdb
7324 \family default
7325 debugger every time your code triggers an uncaught exception
7326 \begin_inset Foot
7327 status collapsed
7328
7329 \begin_layout Standard
7330 Many thanks to Christopher Hart for the request which prompted adding this
7331 feature to IPython.
7332 \end_layout
7333
7334 \end_inset
7335
7336 .
7337 This feature can also be toggled at any time with the
7338 \family typewriter
7339 %pdb
7340 \family default
7341 magic command.
7342 This can be extremely useful in order to find the origin of subtle bugs,
7343 because
7344 \family typewriter
7345 pdb
7346 \family default
7347 opens up at the point in your code which triggered the exception, and while
7348 your program is at this point `dead', all the data is still available and
7349 you can walk up and down the stack frame and understand the origin of the
7350 problem.
7351 \end_layout
7352
7353 \begin_layout Standard
7354 Furthermore, you can use these debugging facilities both with the embedded
7355 IPython mode and without IPython at all.
7356 For an embedded shell (see sec.
7357
7358 \begin_inset LatexCommand \ref{sec:embed}
7359
7360 \end_inset
7361
7362 ), simply call the constructor with
7363 \family typewriter
7364 `-pdb'
7365 \family default
7366 in the argument string and automatically
7367 \family typewriter
7368 pdb
7369 \family default
7370 will be called if an uncaught exception is triggered by your code.
7371
7372 \end_layout
7373
7374 \begin_layout Standard
7375 For stand-alone use of the feature in your programs which do not use IPython
7376 at all, put the following lines toward the top of your `main' routine:
7377 \end_layout
7378
7379 \begin_layout Standard
7380 \align left
7381
7382 \family typewriter
7383 import sys,IPython.ultraTB
7384 \newline
7385 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbos
7386 e', color_scheme=`Linux', call_pdb=1)
7387 \end_layout
7388
7389 \begin_layout Standard
7390 The
7391 \family typewriter
7392 mode
7393 \family default
7394 keyword can be either
7395 \family typewriter
7396 `Verbose'
7397 \family default
7398 or
7399 \family typewriter
7400 `Plain'
7401 \family default
7402 , giving either very detailed or normal tracebacks respectively.
7403 The
7404 \family typewriter
7405 color_scheme
7406 \family default
7407 keyword can be one of
7408 \family typewriter
7409 `NoColor'
7410 \family default
7411 ,
7412 \family typewriter
7413 `Linux'
7414 \family default
7415 (default) or
7416 \family typewriter
7417 `LightBG'
7418 \family default
7419 .
7420 These are the same options which can be set in IPython with
7421 \family typewriter
7422 -colors
7423 \family default
7424 and
7425 \family typewriter
7426 -xmode
7427 \family default
7428 .
7429 \end_layout
7430
7431 \begin_layout Standard
7432 This will give any of your programs detailed, colored tracebacks with automatic
7433 invocation of
7434 \family typewriter
7435 pdb
7436 \family default
7437 .
7438 \end_layout
7439
7440 \begin_layout Section
7441 \begin_inset LatexCommand \label{sec:syntax-extensions}
7442
7443 \end_inset
7444
7445 Extensions for syntax processing
7446 \end_layout
7447
7448 \begin_layout Standard
7449 This isn't for the faint of heart, because the potential for breaking things
7450 is quite high.
7451 But it can be a very powerful and useful feature.
7452 In a nutshell, you can redefine the way IPython processes the user input
7453 line to accept new, special extensions to the syntax without needing to
7454 change any of IPython's own code.
7455 \end_layout
7456
7457 \begin_layout Standard
7458 In the
7459 \family typewriter
7460 IPython/Extensions
7461 \family default
7462 directory you will find some examples supplied, which we will briefly describe
7463 now.
7464 These can be used `as is' (and both provide very useful functionality),
7465 or you can use them as a starting point for writing your own extensions.
7466 \end_layout
7467
7468 \begin_layout Subsection
7469 Pasting of code starting with
7470 \family typewriter
7471 `>>>
7472 \family default
7473 ' or
7474 \family typewriter
7475 `...
7476
7477 \family default
7478 '
7479 \end_layout
7480
7481 \begin_layout Standard
7482 In the python tutorial it is common to find code examples which have been
7483 taken from real python sessions.
7484 The problem with those is that all the lines begin with either
7485 \family typewriter
7486 `>>>
7487 \family default
7488 ' or
7489 \family typewriter
7490 `...
7491
7492 \family default
7493 ', which makes it impossible to paste them all at once.
7494 One must instead do a line by line manual copying, carefully removing the
7495 leading extraneous characters.
7496 \end_layout
7497
7498 \begin_layout Standard
7499 This extension identifies those starting characters and removes them from
7500 the input automatically, so that one can paste multi-line examples directly
7501 into IPython, saving a lot of time.
7502 Please look at the file
7503 \family typewriter
7504 InterpreterPasteInput.py
7505 \family default
7506 in the
7507 \family typewriter
7508 IPython/Extensions
7509 \family default
7510 directory for details on how this is done.
7511 \end_layout
7512
7513 \begin_layout Standard
7514 IPython comes with a special profile enabling this feature, called
7515 \family typewriter
7516 tutorial
7517 \family default
7518 \emph on
7519 .
7520
7521 \emph default
7522 Simply start IPython via
7523 \family typewriter
7524 `ipython\InsetSpace ~
7525 -p\InsetSpace ~
7526 tutorial'
7527 \family default
7528 and the feature will be available.
7529 In a normal IPython session you can activate the feature by importing the
7530 corresponding module with:
7531 \newline
7532
7533 \family typewriter
7534 In [1]: import IPython.Extensions.InterpreterPasteInput
7535 \end_layout
7536
7537 \begin_layout Standard
7538 The following is a 'screenshot' of how things work when this extension is
7539 on, copying an example from the standard tutorial:
7540 \end_layout
7541
7542 \begin_layout Standard
7543
7544 \family typewriter
7545 IPython profile: tutorial
7546 \newline
7547 \InsetSpace ~
7548
7549 \newline
7550 *** Pasting of code with ">>>" or "..." has been enabled.
7551 \newline
7552 \InsetSpace ~
7553
7554 \newline
7555 In
7556 [1]: >>> def fib2(n): # return Fibonacci series up to n
7557 \newline
7558
7559 \begin_inset ERT
7560 status collapsed
7561
7562 \begin_layout Standard
7563
7564
7565 \backslash
7566 hspace*{0mm}
7567 \end_layout
7568
7569 \end_inset
7570
7571 \InsetSpace ~
7572 \InsetSpace ~
7573 ...: ...\InsetSpace ~
7574 \InsetSpace ~
7575 \InsetSpace ~
7576 \InsetSpace ~
7577 """Return a list containing the Fibonacci series up to n."""
7578 \newline
7579
7580 \begin_inset ERT
7581 status collapsed
7582
7583 \begin_layout Standard
7584
7585
7586 \backslash
7587 hspace*{0mm}
7588 \end_layout
7589
7590 \end_inset
7591
7592 \InsetSpace ~
7593 \InsetSpace ~
7594 ...: ...\InsetSpace ~
7595 \InsetSpace ~
7596 \InsetSpace ~
7597 \InsetSpace ~
7598 result = []
7599 \newline
7600
7601 \begin_inset ERT
7602 status collapsed
7603
7604 \begin_layout Standard
7605
7606
7607 \backslash
7608 hspace*{0mm}
7609 \end_layout
7610
7611 \end_inset
7612
7613 \InsetSpace ~
7614 \InsetSpace ~
7615 ...: ...\InsetSpace ~
7616 \InsetSpace ~
7617 \InsetSpace ~
7618 \InsetSpace ~
7619 a, b = 0, 1
7620 \newline
7621
7622 \begin_inset ERT
7623 status collapsed
7624
7625 \begin_layout Standard
7626
7627
7628 \backslash
7629 hspace*{0mm}
7630 \end_layout
7631
7632 \end_inset
7633
7634 \InsetSpace ~
7635 \InsetSpace ~
7636 ...: ...\InsetSpace ~
7637 \InsetSpace ~
7638 \InsetSpace ~
7639 \InsetSpace ~
7640 while b < n:
7641 \newline
7642
7643 \begin_inset ERT
7644 status collapsed
7645
7646 \begin_layout Standard
7647
7648
7649 \backslash
7650 hspace*{0mm}
7651 \end_layout
7652
7653 \end_inset
7654
7655 \InsetSpace ~
7656 \InsetSpace ~
7657 ...: ...\InsetSpace ~
7658 \InsetSpace ~
7659 \InsetSpace ~
7660 \InsetSpace ~
7661 \InsetSpace ~
7662 \InsetSpace ~
7663 \InsetSpace ~
7664 \InsetSpace ~
7665 result.append(b)\InsetSpace ~
7666 \InsetSpace ~
7667 \InsetSpace ~
7668 # see below
7669 \newline
7670
7671 \begin_inset ERT
7672 status collapsed
7673
7674 \begin_layout Standard
7675
7676
7677 \backslash
7678 hspace*{0mm}
7679 \end_layout
7680
7681 \end_inset
7682
7683 \InsetSpace ~
7684 \InsetSpace ~
7685 ...: ...\InsetSpace ~
7686 \InsetSpace ~
7687 \InsetSpace ~
7688 \InsetSpace ~
7689 \InsetSpace ~
7690 \InsetSpace ~
7691 \InsetSpace ~
7692 \InsetSpace ~
7693 a, b = b, a+b
7694 \newline
7695
7696 \begin_inset ERT
7697 status collapsed
7698
7699 \begin_layout Standard
7700
7701
7702 \backslash
7703 hspace*{0mm}
7704 \end_layout
7705
7706 \end_inset
7707
7708 \InsetSpace ~
7709 \InsetSpace ~
7710 ...: ...\InsetSpace ~
7711 \InsetSpace ~
7712 \InsetSpace ~
7713 \InsetSpace ~
7714 return result
7715 \newline
7716
7717 \begin_inset ERT
7718 status collapsed
7719
7720 \begin_layout Standard
7721
7722
7723 \backslash
7724 hspace*{0mm}
7725 \end_layout
7726
7727 \end_inset
7728
7729 \InsetSpace ~
7730 \InsetSpace ~
7731 ...:
7732 \newline
7733 \InsetSpace ~
7734
7735 \newline
7736 In [2]: fib2(10)
7737 \newline
7738 Out[2]: [1, 1, 2, 3, 5, 8]
7739 \end_layout
7740
7741 \begin_layout Standard
7742 Note that as currently written, this extension does
7743 \emph on
7744 not
7745 \emph default
7746 recognize IPython's prompts for pasting.
7747 Those are more complicated, since the user can change them very easily,
7748 they involve numbers and can vary in length.
7749 One could however extract all the relevant information from the IPython
7750 instance and build an appropriate regular expression.
7751 This is left as an exercise for the reader.
7752 \end_layout
7753
7754 \begin_layout Subsection
7755 Input of physical quantities with units
7756 \end_layout
7757
7758 \begin_layout Standard
7759 The module
7760 \family typewriter
7761 PhysicalQInput
7762 \family default
7763 allows a simplified form of input for physical quantities with units.
7764 This file is meant to be used in conjunction with the
7765 \family typewriter
7766 PhysicalQInteractive
7767 \family default
7768 module (in the same directory) and
7769 \family typewriter
7770 Physics.PhysicalQuantities
7771 \family default
7772 from Konrad Hinsen's ScientificPython (
7773 \begin_inset LatexCommand \htmlurl{http://dirac.cnrs-orleans.fr/ScientificPython/}
7774
7775 \end_inset
7776
7777 ).
7778 \end_layout
7779
7780 \begin_layout Standard
7781 The
7782 \family typewriter
7783 Physics.PhysicalQuantities
7784 \family default
7785 module defines
7786 \family typewriter
7787 PhysicalQuantity
7788 \family default
7789 objects, but these must be declared as instances of a class.
7790 For example, to define
7791 \family typewriter
7792 v
7793 \family default
7794 as a velocity of 3\InsetSpace ~
7795 m/s, normally you would write:
7796 \family typewriter
7797
7798 \newline
7799 In [1]: v = PhysicalQuantity(3,'m/s')
7800 \end_layout
7801
7802 \begin_layout Standard
7803 Using the
7804 \family typewriter
7805 PhysicalQ_Input
7806 \family default
7807 extension this can be input instead as:
7808 \family typewriter
7809
7810 \newline
7811 In [1]: v = 3 m/s
7812 \family default
7813
7814 \newline
7815 which is much more convenient for interactive use (even though it is blatantly
7816 invalid Python syntax).
7817 \end_layout
7818
7819 \begin_layout Standard
7820 The
7821 \family typewriter
7822 physics
7823 \family default
7824 profile supplied with IPython (enabled via
7825 \family typewriter
7826 'ipython -p physics'
7827 \family default
7828 ) uses these extensions, which you can also activate with:
7829 \end_layout
7830
7831 \begin_layout Standard
7832
7833 \family typewriter
7834 from math import * # math MUST be imported BEFORE PhysicalQInteractive
7835 \newline
7836 from
7837 IPython.Extensions.PhysicalQInteractive import *
7838 \newline
7839 import IPython.Extensions.PhysicalQ
7840 Input
7841 \end_layout
7842
7843 \begin_layout Section
7844 \begin_inset LatexCommand \label{sec:IPython-as-shell}
7845
7846 \end_inset
7847
7848 IPython as a system shell
7849 \end_layout
7850
7851 \begin_layout Standard
7852 IPython ships with a special profile called
7853 \family typewriter
7854 pysh
7855 \family default
7856 , which you can activate at the command line as
7857 \family typewriter
7858 `ipython -p pysh'
7859 \family default
7860 .
7861 This loads
7862 \family typewriter
7863 InterpreterExec
7864 \family default
7865 , along with some additional facilities and a prompt customized for filesystem
7866 navigation.
7867 \end_layout
7868
7869 \begin_layout Standard
7870 Note that this does
7871 \emph on
7872 not
7873 \emph default
7874 make IPython a full-fledged system shell.
7875 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
7876 you'll suspend pysh itself, not the process you just started.
7877
7878 \end_layout
7879
7880 \begin_layout Standard
7881 What the shell profile allows you to do is to use the convenient and powerful
7882 syntax of Python to do quick scripting at the command line.
7883 Below we describe some of its features.
7884 \end_layout
7885
7886 \begin_layout Subsection
7887 Aliases
7888 \end_layout
7889
7890 \begin_layout Standard
7891 All of your
7892 \family typewriter
7893 $PATH
7894 \family default
7895 has been loaded as IPython aliases, so you should be able to type any normal
7896 system command and have it executed.
7897 See
7898 \family typewriter
7899 %alias?
7900 \family default
7901 and
7902 \family typewriter
7903 %unalias?
7904 \family default
7905 for details on the alias facilities.
7906 See also
7907 \family typewriter
7908 %rehash?
7909 \family default
7910 and
7911 \family typewriter
7912 %rehashx?
7913 \family default
7914 for details on the mechanism used to load
7915 \family typewriter
7916 $PATH
7917 \family default
7918 .
7919 \end_layout
7920
7921 \begin_layout Subsection
7922 Special syntax
7923 \end_layout
7924
7925 \begin_layout Standard
7926 Any lines which begin with
7927 \family typewriter
7928 `~'
7929 \family default
7930 ,
7931 \family typewriter
7932 `/'
7933 \family default
7934 and
7935 \family typewriter
7936 `.'
7937 \family default
7938 will be executed as shell commands instead of as Python code.
7939 The special escapes below are also recognized.
7940
7941 \family typewriter
7942 !cmd
7943 \family default
7944 is valid in single or multi-line input, all others are only valid in single-lin
7945 e input:
7946 \end_layout
7947
7948 \begin_layout Description
7949
7950 \family typewriter
7951 !cmd
7952 \family default
7953 pass `cmd' directly to the shell
7954 \end_layout
7955
7956 \begin_layout Description
7957
7958 \family typewriter
7959 !!cmd
7960 \family default
7961 execute `cmd' and return output as a list (split on `
7962 \backslash
7963 n')
7964 \end_layout
7965
7966 \begin_layout Description
7967
7968 \family typewriter
7969 $var=cmd
7970 \family default
7971 capture output of cmd into var, as a string
7972 \end_layout
7973
7974 \begin_layout Description
7975
7976 \family typewriter
7977 $$var=cmd
7978 \family default
7979 capture output of cmd into var, as a list (split on `
7980 \backslash
7981 n')
7982 \end_layout
7983
7984 \begin_layout Standard
7985 The
7986 \family typewriter
7987 $
7988 \family default
7989 /
7990 \family typewriter
7991 $$
7992 \family default
7993 syntaxes make Python variables from system output, which you can later
7994 use for further scripting.
7995 The converse is also possible: when executing an alias or calling to the
7996 system via
7997 \family typewriter
7998 !
7999 \family default
8000 /
8001 \family typewriter
8002 !!
8003 \family default
8004 , you can expand any python variable or expression by prepending it with
8005
8006 \family typewriter
8007 $
8008 \family default
8009 .
8010 Full details of the allowed syntax can be found in Python's PEP 215.
8011 \end_layout
8012
8013 \begin_layout Standard
8014 A few brief examples will illustrate these (note that the indentation below
8015 may be incorrectly displayed):
8016 \end_layout
8017
8018 \begin_layout Standard
8019
8020 \family typewriter
8021 fperez[~/test]|3> !ls *s.py
8022 \newline
8023 scopes.py strings.py
8024 \end_layout
8025
8026 \begin_layout Standard
8027 ls is an internal alias, so there's no need to use
8028 \family typewriter
8029 !
8030 \family default
8031 :
8032 \end_layout
8033
8034 \begin_layout Standard
8035
8036 \family typewriter
8037 fperez[~/test]|4> ls *s.py
8038 \newline
8039 scopes.py* strings.py
8040 \end_layout
8041
8042 \begin_layout Standard
8043 !!ls will return the output into a Python variable:
8044 \end_layout
8045
8046 \begin_layout Standard
8047
8048 \family typewriter
8049 fperez[~/test]|5> !!ls *s.py
8050 \newline
8051
8052 \begin_inset ERT
8053 status collapsed
8054
8055 \begin_layout Standard
8056
8057
8058 \backslash
8059 hspace*{0mm}
8060 \end_layout
8061
8062 \end_inset
8063
8064 \InsetSpace ~
8065 \InsetSpace ~
8066 \InsetSpace ~
8067 \InsetSpace ~
8068 \InsetSpace ~
8069 \InsetSpace ~
8070 \InsetSpace ~
8071 \InsetSpace ~
8072 \InsetSpace ~
8073 \InsetSpace ~
8074 \InsetSpace ~
8075 \InsetSpace ~
8076 \InsetSpace ~
8077 \InsetSpace ~
8078 <5> ['scopes.py', 'strings.py']
8079 \newline
8080 fperez[~/test]|6> print _5
8081 \newline
8082 ['scopes.py', 'strings.py
8083 ']
8084 \end_layout
8085
8086 \begin_layout Standard
8087
8088 \family typewriter
8089 $
8090 \family default
8091 and
8092 \family typewriter
8093 $$
8094 \family default
8095 allow direct capture to named variables:
8096 \end_layout
8097
8098 \begin_layout Standard
8099
8100 \family typewriter
8101 fperez[~/test]|7> $astr = ls *s.py
8102 \newline
8103 fperez[~/test]|8> astr
8104 \newline
8105
8106 \begin_inset ERT
8107 status collapsed
8108
8109 \begin_layout Standard
8110
8111
8112 \backslash
8113 hspace*{0mm}
8114 \end_layout
8115
8116 \end_inset
8117
8118 \InsetSpace ~
8119 \InsetSpace ~
8120 \InsetSpace ~
8121 \InsetSpace ~
8122 \InsetSpace ~
8123 \InsetSpace ~
8124 \InsetSpace ~
8125 \InsetSpace ~
8126 \InsetSpace ~
8127 \InsetSpace ~
8128 \InsetSpace ~
8129 \InsetSpace ~
8130 \InsetSpace ~
8131 \InsetSpace ~
8132 <8> 'scopes.py
8133 \backslash
8134 nstrings.py'
8135 \end_layout
8136
8137 \begin_layout Standard
8138
8139 \family typewriter
8140 fperez[~/test]|9> $$alist = ls *s.py
8141 \newline
8142 fperez[~/test]|10> alist
8143 \newline
8144
8145 \begin_inset ERT
8146 status collapsed
8147
8148 \begin_layout Standard
8149
8150
8151 \backslash
8152 hspace*{0mm}
8153 \end_layout
8154
8155 \end_inset
8156
8157 \InsetSpace ~
8158 \InsetSpace ~
8159 \InsetSpace ~
8160 \InsetSpace ~
8161 \InsetSpace ~
8162 \InsetSpace ~
8163 \InsetSpace ~
8164 \InsetSpace ~
8165 \InsetSpace ~
8166 \InsetSpace ~
8167 \InsetSpace ~
8168 \InsetSpace ~
8169 \InsetSpace ~
8170 \InsetSpace ~
8171 <10> ['scopes.py', 'strings.py']
8172 \end_layout
8173
8174 \begin_layout Standard
8175 alist is now a normal python list you can loop over.
8176 Using
8177 \family typewriter
8178 $
8179 \family default
8180 will expand back the python values when alias calls are made:
8181 \end_layout
8182
8183 \begin_layout Standard
8184
8185 \family typewriter
8186 fperez[~/test]|11> for f in alist:
8187 \newline
8188
8189 \begin_inset ERT
8190 status collapsed
8191
8192 \begin_layout Standard
8193
8194
8195 \backslash
8196 hspace*{0mm}
8197 \end_layout
8198
8199 \end_inset
8200
8201 \InsetSpace ~
8202 \InsetSpace ~
8203 \InsetSpace ~
8204 \InsetSpace ~
8205 \InsetSpace ~
8206 \InsetSpace ~
8207 \InsetSpace ~
8208 \InsetSpace ~
8209 \InsetSpace ~
8210 \InsetSpace ~
8211 \InsetSpace ~
8212 \InsetSpace ~
8213 \InsetSpace ~
8214 \InsetSpace ~
8215 |..> \InsetSpace ~
8216 \InsetSpace ~
8217 \InsetSpace ~
8218 \InsetSpace ~
8219 print 'file',f,
8220 \newline
8221
8222 \begin_inset ERT
8223 status collapsed
8224
8225 \begin_layout Standard
8226
8227
8228 \backslash
8229 hspace*{0mm}
8230 \end_layout
8231
8232 \end_inset
8233
8234 \InsetSpace ~
8235 \InsetSpace ~
8236 \InsetSpace ~
8237 \InsetSpace ~
8238 \InsetSpace ~
8239 \InsetSpace ~
8240 \InsetSpace ~
8241 \InsetSpace ~
8242 \InsetSpace ~
8243 \InsetSpace ~
8244 \InsetSpace ~
8245 \InsetSpace ~
8246 \InsetSpace ~
8247 \InsetSpace ~
8248 |..> \InsetSpace ~
8249 \InsetSpace ~
8250 \InsetSpace ~
8251 \InsetSpace ~
8252 wc -l $f
8253 \newline
8254
8255 \begin_inset ERT
8256 status collapsed
8257
8258 \begin_layout Standard
8259
8260
8261 \backslash
8262 hspace*{0mm}
8263 \end_layout
8264
8265 \end_inset
8266
8267 \InsetSpace ~
8268 \InsetSpace ~
8269 \InsetSpace ~
8270 \InsetSpace ~
8271 \InsetSpace ~
8272 \InsetSpace ~
8273 \InsetSpace ~
8274 \InsetSpace ~
8275 \InsetSpace ~
8276 \InsetSpace ~
8277 \InsetSpace ~
8278 \InsetSpace ~
8279 \InsetSpace ~
8280 \InsetSpace ~
8281 |..>
8282 \newline
8283 file scopes.py 13 scopes.py
8284 \newline
8285 file strings.py 4 strings.py
8286 \end_layout
8287
8288 \begin_layout Standard
8289 Note that you may need to protect your variables with braces if you want
8290 to append strings to their names.
8291 To copy all files in alist to
8292 \family typewriter
8293 .bak
8294 \family default
8295 extensions, you must use:
8296 \end_layout
8297
8298 \begin_layout Standard
8299
8300 \family typewriter
8301 fperez[~/test]|12> for f in alist:
8302 \newline
8303
8304 \begin_inset ERT
8305 status collapsed
8306
8307 \begin_layout Standard
8308
8309
8310 \backslash
8311 hspace*{0mm}
8312 \end_layout
8313
8314 \end_inset
8315
8316 \InsetSpace ~
8317 \InsetSpace ~
8318 \InsetSpace ~
8319 \InsetSpace ~
8320 \InsetSpace ~
8321 \InsetSpace ~
8322 \InsetSpace ~
8323 \InsetSpace ~
8324 \InsetSpace ~
8325 \InsetSpace ~
8326 \InsetSpace ~
8327 \InsetSpace ~
8328 \InsetSpace ~
8329 \InsetSpace ~
8330 |..> \InsetSpace ~
8331 \InsetSpace ~
8332 \InsetSpace ~
8333 \InsetSpace ~
8334 cp $f ${f}.bak
8335 \end_layout
8336
8337 \begin_layout Standard
8338 If you try using
8339 \family typewriter
8340 $f.bak
8341 \family default
8342 , you'll get an AttributeError exception saying that your string object
8343 doesn't have a
8344 \family typewriter
8345 .bak
8346 \family default
8347 attribute.
8348 This is because the
8349 \family typewriter
8350 $
8351 \family default
8352 expansion mechanism allows you to expand full Python expressions:
8353 \end_layout
8354
8355 \begin_layout Standard
8356
8357 \family typewriter
8358 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
8359 \newline
8360 sys.platform is: linux2
8361 \end_layout
8362
8363 \begin_layout Standard
8364 IPython's input history handling is still active, which allows you to rerun
8365 a single block of multi-line input by simply using exec:
8366 \newline
8367
8368 \family typewriter
8369 fperez[~/test]|14> $$alist = ls *.eps
8370 \newline
8371 fperez[~/test]|15> exec _i11
8372 \newline
8373 file image2.eps
8374 921 image2.eps
8375 \newline
8376 file image.eps 921 image.eps
8377 \end_layout
8378
8379 \begin_layout Standard
8380 While these are new special-case syntaxes, they are designed to allow very
8381 efficient use of the shell with minimal typing.
8382 At an interactive shell prompt, conciseness of expression wins over readability.
8383 \end_layout
8384
8385 \begin_layout Subsection
8386 Useful functions and modules
8387 \end_layout
8388
8389 \begin_layout Standard
8390 The os, sys and shutil modules from the Python standard library are automaticall
8391 y loaded.
8392 Some additional functions, useful for shell usage, are listed below.
8393 You can request more help about them with `
8394 \family typewriter
8395 ?
8396 \family default
8397 '.
8398 \end_layout
8399
8400 \begin_layout Description
8401
8402 \family typewriter
8403 shell
8404 \family default
8405 - execute a command in the underlying system shell
8406 \end_layout
8407
8408 \begin_layout Description
8409
8410 \family typewriter
8411 system
8412 \family default
8413 - like
8414 \family typewriter
8415 shell()
8416 \family default
8417 , but return the exit status of the command
8418 \end_layout
8419
8420 \begin_layout Description
8421
8422 \family typewriter
8423 sout
8424 \family default
8425 - capture the output of a command as a string
8426 \end_layout
8427
8428 \begin_layout Description
8429
8430 \family typewriter
8431 lout
8432 \family default
8433 - capture the output of a command as a list (split on `
8434 \backslash
8435 n')
8436 \end_layout
8437
8438 \begin_layout Description
8439
8440 \family typewriter
8441 getoutputerror
8442 \family default
8443 - capture (output,error) of a shell commandss
8444 \end_layout
8445
8446 \begin_layout Standard
8447
8448 \family typewriter
8449 sout
8450 \family default
8451 /
8452 \family typewriter
8453 lout
8454 \family default
8455 are the functional equivalents of
8456 \family typewriter
8457 $
8458 \family default
8459 /
8460 \family typewriter
8461 $$
8462 \family default
8463 .
8464 They are provided to allow you to capture system output in the middle of
8465 true python code, function definitions, etc (where
8466 \family typewriter
8467 $
8468 \family default
8469 and
8470 \family typewriter
8471 $$
8472 \family default
8473 are invalid).
8474 \end_layout
8475
8476 \begin_layout Subsection
8477 Directory management
8478 \end_layout
8479
8480 \begin_layout Standard
8481 Since each command passed by pysh to the underlying system is executed in
8482 a subshell which exits immediately, you can NOT use !cd to navigate the
8483 filesystem.
8484 \end_layout
8485
8486 \begin_layout Standard
8487 Pysh provides its own builtin
8488 \family typewriter
8489 `%cd
8490 \family default
8491 ' magic command to move in the filesystem (the
8492 \family typewriter
8493 %
8494 \family default
8495 is not required with automagic on).
8496 It also maintains a list of visited directories (use
8497 \family typewriter
8498 %dhist
8499 \family default
8500 to see it) and allows direct switching to any of them.
8501 Type
8502 \family typewriter
8503 `cd?
8504 \family default
8505 ' for more details.
8506 \end_layout
8507
8508 \begin_layout Standard
8509
8510 \family typewriter
8511 %pushd
8512 \family default
8513 ,
8514 \family typewriter
8515 %popd
8516 \family default
8517 and
8518 \family typewriter
8519 %dirs
8520 \family default
8521 are provided for directory stack handling.
8522 \end_layout
8523
8524 \begin_layout Subsection
8525 Prompt customization
8526 \end_layout
8527
8528 \begin_layout Standard
8529 The supplied
8530 \family typewriter
8531 ipythonrc-pysh
8532 \family default
8533 profile comes with an example of a very colored and detailed prompt, mainly
8534 to serve as an illustration.
8535 The valid escape sequences, besides color names, are:
8536 \end_layout
8537
8538 \begin_layout Description
8539
8540 \backslash
8541 # - Prompt number, wrapped in the color escapes for the input prompt (determined
8542 by the current color scheme).
8543 \end_layout
8544
8545 \begin_layout Description
8546
8547 \backslash
8548 N - Just the prompt counter number,
8549 \emph on
8550 without
8551 \emph default
8552 any coloring wrappers.
8553 You can thus customize the actual prompt colors manually.
8554 \end_layout
8555
8556 \begin_layout Description
8557
8558 \backslash
8559 D - Dots, as many as there are digits in
8560 \backslash
8561 # (so they align).
8562 \end_layout
8563
8564 \begin_layout Description
8565
8566 \backslash
8567 w - Current working directory (cwd).
8568 \end_layout
8569
8570 \begin_layout Description
8571
8572 \backslash
8573 W - Basename of current working directory.
8574 \end_layout
8575
8576 \begin_layout Description
8577
8578 \backslash
8579 X
8580 \emph on
8581 N
8582 \emph default
8583 - Where
8584 \emph on
8585 N
8586 \emph default
8587 =0..5.
8588 N terms of the cwd, with $HOME written as ~.
8589 \end_layout
8590
8591 \begin_layout Description
8592
8593 \backslash
8594 Y
8595 \emph on
8596 N
8597 \emph default
8598 - Where
8599 \emph on
8600 N
8601 \emph default
8602 =0..5.
8603 Like X
8604 \emph on
8605 N
8606 \emph default
8607 , but if ~ is term
8608 \emph on
8609 N
8610 \emph default
8611 +1 it's also shown.
8612 \end_layout
8613
8614 \begin_layout Description
8615
8616 \backslash
8617 u - Username.
8618 \end_layout
8619
8620 \begin_layout Description
8621
8622 \backslash
8623 H - Full hostname.
8624 \end_layout
8625
8626 \begin_layout Description
8627
8628 \backslash
8629 h - Hostname up to first '.'
8630 \end_layout
8631
8632 \begin_layout Description
8633
8634 \backslash
8635 $ - Root symbol ($ or #).
8636
8637 \end_layout
8638
8639 \begin_layout Description
8640
8641 \backslash
8642 t - Current time, in H:M:S format.
8643 \end_layout
8644
8645 \begin_layout Description
8646
8647 \backslash
8648 v - IPython release version.
8649
8650 \end_layout
8651
8652 \begin_layout Description
8653
8654 \backslash
8655 n - Newline.
8656
8657 \end_layout
8658
8659 \begin_layout Description
8660
8661 \backslash
8662 r - Carriage return.
8663
8664 \end_layout
8665
8666 \begin_layout Description
8667
8668 \backslash
8669
8670 \backslash
8671 - An explicitly escaped '
8672 \backslash
8673 '.
8674 \end_layout
8675
8676 \begin_layout Standard
8677 You can configure your prompt colors using any ANSI color escape.
8678 Each color escape sets the color for any subsequent text, until another
8679 escape comes in and changes things.
8680 The valid color escapes are:
8681 \end_layout
8682
8683 \begin_layout Description
8684
8685 \backslash
8686 C_Black
8687 \end_layout
8688
8689 \begin_layout Description
8690
8691 \backslash
8692 C_Blue
8693 \end_layout
8694
8695 \begin_layout Description
8696
8697 \backslash
8698 C_Brown
8699 \end_layout
8700
8701 \begin_layout Description
8702
8703 \backslash
8704 C_Cyan
8705 \end_layout
8706
8707 \begin_layout Description
8708
8709 \backslash
8710 C_DarkGray
8711 \end_layout
8712
8713 \begin_layout Description
8714
8715 \backslash
8716 C_Green
8717 \end_layout
8718
8719 \begin_layout Description
8720
8721 \backslash
8722 C_LightBlue
8723 \end_layout
8724
8725 \begin_layout Description
8726
8727 \backslash
8728 C_LightCyan
8729 \end_layout
8730
8731 \begin_layout Description
8732
8733 \backslash
8734 C_LightGray
8735 \end_layout
8736
8737 \begin_layout Description
8738
8739 \backslash
8740 C_LightGreen
8741 \end_layout
8742
8743 \begin_layout Description
8744
8745 \backslash
8746 C_LightPurple
8747 \end_layout
8748
8749 \begin_layout Description
8750
8751 \backslash
8752 C_LightRed
8753 \end_layout
8754
8755 \begin_layout Description
8756
8757 \backslash
8758 C_Purple
8759 \end_layout
8760
8761 \begin_layout Description
8762
8763 \backslash
8764 C_Red
8765 \end_layout
8766
8767 \begin_layout Description
8768
8769 \backslash
8770 C_White
8771 \end_layout
8772
8773 \begin_layout Description
8774
8775 \backslash
8776 C_Yellow
8777 \end_layout
8778
8779 \begin_layout Description
8780
8781 \backslash
8782 C_Normal Stop coloring, defaults to your terminal settings.
8783 \end_layout
8784
8785 \begin_layout Section
8786 \begin_inset LatexCommand \label{sec:Threading-support}
8787
8788 \end_inset
8789
8790 Threading support
8791 \end_layout
8792
8793 \begin_layout Standard
8794
8795 \series bold
8796 WARNING:
8797 \series default
8798 The threading support is still somewhat experimental, and it has only seen
8799 reasonable testing under Linux.
8800 Threaded code is particularly tricky to debug, and it tends to show extremely
8801 platform-dependent behavior.
8802 Since I only have access to Linux machines, I will have to rely on user's
8803 experiences and assistance for this area of IPython to improve under other
8804 platforms.
8805 \end_layout
8806
8807 \begin_layout Standard
8808 IPython, via the
8809 \family typewriter
8810 -gthread
8811 \family default
8812 ,
8813 \family typewriter
8814 -qthread
8815 \family default
8816 ,
8817 \family typewriter
8818 -q4thread
8819 \family default
8820 and
8821 \family typewriter
8822 -wthread
8823 \family default
8824 options (described in Sec.\InsetSpace ~
8825
8826 \begin_inset LatexCommand \ref{sec:threading-opts}
8827
8828 \end_inset
8829
8830 ), can run in multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython
8831 applications respectively.
8832 These GUI toolkits need to control the python main loop of execution, so
8833 under a normal Python interpreter, starting a pyGTK, Qt3, Qt4 or WXPython
8834 application will immediately freeze the shell.
8835
8836 \end_layout
8837
8838 \begin_layout Standard
8839 IPython, with one of these options (you can only use one at a time), separates
8840 the graphical loop and IPython's code execution run into different threads.
8841 This allows you to test interactively (with
8842 \family typewriter
8843 %run
8844 \family default
8845 , for example) your GUI code without blocking.
8846 \end_layout
8847
8848 \begin_layout Standard
8849 A nice mini-tutorial on using IPython along with the Qt Designer application
8850 is available at the SciPy wiki:
8851 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer}
8852
8853 \end_inset
8854
8855 .
8856 \end_layout
8857
8858 \begin_layout Subsection
8859 Tk issues
8860 \end_layout
8861
8862 \begin_layout Standard
8863 As indicated in Sec.\InsetSpace ~
8864
8865 \begin_inset LatexCommand \ref{sec:threading-opts}
8866
8867 \end_inset
8868
8869 , a special
8870 \family typewriter
8871 -tk
8872 \family default
8873 option is provided to try and allow Tk graphical applications to coexist
8874 interactively with WX, Qt or GTK ones.
8875 Whether this works at all, however, is very platform and configuration
8876 dependent.
8877 Please experiment with simple test cases before committing to using this
8878 combination of Tk and GTK/Qt/WX threading in a production environment.
8879 \end_layout
8880
8881 \begin_layout Subsection
8882 I/O pitfalls
8883 \end_layout
8884
8885 \begin_layout Standard
8886 Be mindful that the Python interpreter switches between threads every
8887 \begin_inset Formula $N$
8888 \end_inset
8889
8890 bytecodes, where the default value as of Python\InsetSpace ~
8891 2.3 is
8892 \begin_inset Formula $N=100.$
8893 \end_inset
8894
8895 This value can be read by using the
8896 \family typewriter
8897 sys.getcheckinterval()
8898 \family default
8899 function, and it can be reset via
8900 \family typewriter
8901 sys.setcheckinterval(
8902 \emph on
8903 N
8904 \emph default
8905 )
8906 \family default
8907 .
8908 This switching of threads can cause subtly confusing effects if one of
8909 your threads is doing file I/O.
8910 In text mode, most systems only flush file buffers when they encounter
8911 a
8912 \family typewriter
8913 `
8914 \backslash
8915 n'
8916 \family default
8917 .
8918 An instruction as simple as
8919 \family typewriter
8920
8921 \newline
8922 \InsetSpace ~
8923 \InsetSpace ~
8924 print >> filehandle,
8925 \begin_inset Quotes eld
8926 \end_inset
8927
8928 hello world
8929 \begin_inset Quotes erd
8930 \end_inset
8931
8932
8933 \family default
8934
8935 \newline
8936 actually consists of several bytecodes, so it is possible that the newline
8937 does not reach your file before the next thread switch.
8938 Similarly, if you are writing to a file in binary mode, the file won't
8939 be flushed until the buffer fills, and your other thread may see apparently
8940 truncated files.
8941
8942 \end_layout
8943
8944 \begin_layout Standard
8945 For this reason, if you are using IPython's thread support and have (for
8946 example) a GUI application which will read data generated by files written
8947 to from the IPython thread, the safest approach is to open all of your
8948 files in unbuffered mode (the third argument to the
8949 \family typewriter
8950 file/open
8951 \family default
8952 function is the buffering value):
8953 \newline
8954
8955 \family typewriter
8956 \InsetSpace ~
8957 \InsetSpace ~
8958 filehandle = open(filename,mode,0)
8959 \end_layout
8960
8961 \begin_layout Standard
8962 This is obviously a brute force way of avoiding race conditions with the
8963 file buffering.
8964 If you want to do it cleanly, and you have a resource which is being shared
8965 by the interactive IPython loop and your GUI thread, you should really
8966 handle it with thread locking and syncrhonization properties.
8967 The Python documentation discusses these.
8968 \end_layout
8969
8970 \begin_layout Section
8971 \begin_inset LatexCommand \label{sec:interactive-demos}
8972
8973 \end_inset
8974
8975 Interactive demos with IPython
8976 \end_layout
8977
8978 \begin_layout Standard
8979 IPython ships with a basic system for running scripts interactively in sections,
8980 useful when presenting code to audiences.
8981 A few tags embedded in comments (so that the script remains valid Python
8982 code) divide a file into separate blocks, and the demo can be run one block
8983 at a time, with IPython printing (with syntax highlighting) the block before
8984 executing it, and returning to the interactive prompt after each block.
8985 The interactive namespace is updated after each block is run with the contents
8986 of the demo's namespace.
8987 \end_layout
8988
8989 \begin_layout Standard
8990 This allows you to show a piece of code, run it and then execute interactively
8991 commands based on the variables just created.
8992 Once you want to continue, you simply execute the next block of the demo.
8993 The following listing shows the markup necessary for dividing a script
8994 into sections for execution as a demo.
8995 \end_layout
8996
8997 \begin_layout Standard
8998 \begin_inset ERT
8999 status open
9000
9001 \begin_layout Standard
9002
9003
9004 \backslash
9005 codelist{examples/example-demo.py}
9006 \end_layout
9007
9008 \end_inset
9009
9010
9011 \end_layout
9012
9013 \begin_layout Standard
9014 In order to run a file as a demo, you must first make a
9015 \family typewriter
9016 Demo
9017 \family default
9018 object out of it.
9019 If the file is named
9020 \family typewriter
9021 myscript.py
9022 \family default
9023 , the following code will make a demo:
9024 \end_layout
9025
9026 \begin_layout LyX-Code
9027 from IPython.demo import Demo
9028 \end_layout
9029
9030 \begin_layout LyX-Code
9031 mydemo = Demo('myscript.py')
9032 \end_layout
9033
9034 \begin_layout Standard
9035 This creates the
9036 \family typewriter
9037 mydemo
9038 \family default
9039 object, whose blocks you run one at a time by simply calling the object
9040 with no arguments.
9041 If you have autocall active in IPython (the default), all you need to do
9042 is type
9043 \end_layout
9044
9045 \begin_layout LyX-Code
9046 mydemo
9047 \end_layout
9048
9049 \begin_layout Standard
9050 and IPython will call it, executing each block.
9051 Demo objects can be restarted, you can move forward or back skipping blocks,
9052 re-execute the last block, etc.
9053 Simply use the Tab key on a demo object to see its methods, and call
9054 \family typewriter
9055 `?'
9056 \family default
9057 on them to see their docstrings for more usage details.
9058 In addition, the
9059 \family typewriter
9060 demo
9061 \family default
9062 module itself contains a comprehensive docstring, which you can access
9063 via
9064 \end_layout
9065
9066 \begin_layout LyX-Code
9067 from IPython import demo
9068 \end_layout
9069
9070 \begin_layout LyX-Code
9071 demo?
9072 \end_layout
9073
9074 \begin_layout Standard
9075
9076 \series bold
9077 Limitations:
9078 \series default
9079 It is important to note that these demos are limited to fairly simple uses.
9080 In particular, you can
9081 \emph on
9082 not
9083 \emph default
9084 put division marks in indented code (loops, if statements, function definitions
9085 , etc.) Supporting something like this would basically require tracking the
9086 internal execution state of the Python interpreter, so only top-level divisions
9087 are allowed.
9088 If you want to be able to open an IPython instance at an arbitrary point
9089 in a program, you can use IPython's embedding facilities, described in
9090 detail in Sec\SpecialChar \@.
9091 \InsetSpace ~
9092
9093 \begin_inset LatexCommand \ref{sec:embed}
9094
9095 \end_inset
9096
9097 .
9098 \end_layout
9099
9100 \begin_layout Section
9101 \begin_inset LatexCommand \label{sec:matplotlib-support}
9102
9103 \end_inset
9104
9105 Plotting with
9106 \family typewriter
9107 matplotlib
9108 \family default
9109
9110 \end_layout
9111
9112 \begin_layout Standard
9113 The matplotlib library (
9114 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
9115
9116 \end_inset
9117
9118 ) provides high quality 2D plotting for Python.
9119 Matplotlib can produce plots on screen using a variety of GUI toolkits,
9120 including Tk, GTK and WXPython.
9121 It also provides a number of commands useful for scientific computing,
9122 all with a syntax compatible with that of the popular Matlab program.
9123 \end_layout
9124
9125 \begin_layout Standard
9126 IPython accepts the special option
9127 \family typewriter
9128 -pylab
9129 \family default
9130 (Sec.\InsetSpace ~
9131
9132 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
9133
9134 \end_inset
9135
9136 ).
9137 This configures it to support matplotlib, honoring the settings in the
9138
9139 \family typewriter
9140 .matplotlibrc
9141 \family default
9142 file.
9143 IPython will detect the user's choice of matplotlib GUI backend, and automatica
9144 lly select the proper threading model to prevent blocking.
9145 It also sets matplotlib in interactive mode and modifies
9146 \family typewriter
9147 %run
9148 \family default
9149 slightly, so that any matplotlib-based script can be executed using
9150 \family typewriter
9151 %run
9152 \family default
9153 and the final
9154 \family typewriter
9155 show()
9156 \family default
9157 command does not block the interactive shell.
9158 \end_layout
9159
9160 \begin_layout Standard
9161 The
9162 \family typewriter
9163 -pylab
9164 \family default
9165 option must be given first in order for IPython to configure its threading
9166 mode.
9167 However, you can still issue other options afterwards.
9168 This allows you to have a matplotlib-based environment customized with
9169 additional modules using the standard IPython profile mechanism (Sec.\InsetSpace ~
9170
9171 \begin_inset LatexCommand \ref{sec:profiles}
9172
9173 \end_inset
9174
9175 ): ``
9176 \family typewriter
9177 ipython -pylab -p myprofile
9178 \family default
9179 '' will load the profile defined in
9180 \family typewriter
9181 ipythonrc-myprofile
9182 \family default
9183 after configuring matplotlib.
9184 \end_layout
9185
9186 \begin_layout Section
9187 \begin_inset LatexCommand \label{sec:Gnuplot}
9188
9189 \end_inset
9190
9191 Plotting with
9192 \family typewriter
9193 Gnuplot
9194 \end_layout
9195
9196 \begin_layout Standard
9197 Through the magic extension system described in sec.
9198
9199 \begin_inset LatexCommand \ref{sec:magic}
9200
9201 \end_inset
9202
9203 , IPython incorporates a mechanism for conveniently interfacing with the
9204 Gnuplot system (
9205 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
9206
9207 \end_inset
9208
9209 ).
9210 Gnuplot is a very complete 2D and 3D plotting package available for many
9211 operating systems and commonly included in modern Linux distributions.
9212
9213 \end_layout
9214
9215 \begin_layout Standard
9216 Besides having Gnuplot installed, this functionality requires the
9217 \family typewriter
9218 Gnuplot.py
9219 \family default
9220 module for interfacing python with Gnuplot.
9221 It can be downloaded from:
9222 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
9223
9224 \end_inset
9225
9226 .
9227 \end_layout
9228
9229 \begin_layout Subsection
9230 Proper Gnuplot configuration
9231 \end_layout
9232
9233 \begin_layout Standard
9234 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
9235 However, as of
9236 \family typewriter
9237 Gnuplot.py
9238 \family default
9239 version 1.7, a new option was added to communicate between Python and Gnuplot
9240 via FIFOs (pipes).
9241 This mechanism, while fast, also breaks the mouse system.
9242 You must therefore set the variable
9243 \family typewriter
9244 prefer_fifo_data
9245 \family default
9246 to
9247 \family typewriter
9248 0
9249 \family default
9250 in file
9251 \family typewriter
9252 gp_unix.py
9253 \family default
9254 if you wish to keep the interactive mouse and keyboard features working
9255 properly (
9256 \family typewriter
9257 prefer_inline_data
9258 \family default
9259 also must be
9260 \family typewriter
9261 0
9262 \family default
9263 , but this is the default so unless you've changed it manually you should
9264 be fine).
9265 \end_layout
9266
9267 \begin_layout Standard
9268 'Out of the box', Gnuplot is configured with a rather poor set of size,
9269 color and linewidth choices which make the graphs fairly hard to read on
9270 modern high-resolution displays (although they work fine on old 640x480
9271 ones).
9272 Below is a section of my
9273 \family typewriter
9274 .Xdefaults
9275 \family default
9276 file which I use for having a more convenient Gnuplot setup.
9277 Remember to load it by running
9278 \family typewriter
9279 `xrdb .Xdefaults`
9280 \family default
9281 :
9282 \end_layout
9283
9284 \begin_layout Standard
9285
9286 \family typewriter
9287 !******************************************************************
9288 \newline
9289 ! gnuplot
9290 options
9291 \newline
9292 ! modify this for a convenient window size
9293 \newline
9294 gnuplot*geometry: 780x580
9295 \end_layout
9296
9297 \begin_layout Standard
9298
9299 \family typewriter
9300 ! on-screen font (not for PostScript)
9301 \newline
9302 gnuplot*font: -misc-fixed-bold-r-normal--15
9303 -120-100-100-c-90-iso8859-1
9304 \end_layout
9305
9306 \begin_layout Standard
9307
9308 \family typewriter
9309 ! color options
9310 \newline
9311 gnuplot*background: black
9312 \newline
9313 gnuplot*textColor: white
9314 \newline
9315 gnuplot*borderCo
9316 lor: white
9317 \newline
9318 gnuplot*axisColor: white
9319 \newline
9320 gnuplot*line1Color: red
9321 \newline
9322 gnuplot*line2Color:
9323 green
9324 \newline
9325 gnuplot*line3Color: blue
9326 \newline
9327 gnuplot*line4Color: magenta
9328 \newline
9329 gnuplot*line5Color:
9330 cyan
9331 \newline
9332 gnuplot*line6Color: sienna
9333 \newline
9334 gnuplot*line7Color: orange
9335 \newline
9336 gnuplot*line8Color:
9337 coral
9338 \end_layout
9339
9340 \begin_layout Standard
9341
9342 \family typewriter
9343 ! multiplicative factor for point styles
9344 \newline
9345 gnuplot*pointsize: 2
9346 \end_layout
9347
9348 \begin_layout Standard
9349
9350 \family typewriter
9351 ! line width options (in pixels)
9352 \newline
9353 gnuplot*borderWidth: 2
9354 \newline
9355 gnuplot*axisWidth:
9356 2
9357 \newline
9358 gnuplot*line1Width: 2
9359 \newline
9360 gnuplot*line2Width: 2
9361 \newline
9362 gnuplot*line3Width: 2
9363 \newline
9364 gnuplot*line4Wi
9365 dth: 2
9366 \newline
9367 gnuplot*line5Width: 2
9368 \newline
9369 gnuplot*line6Width: 2
9370 \newline
9371 gnuplot*line7Width: 2
9372 \newline
9373 gnuplot*lin
9374 e8Width: 2
9375 \end_layout
9376
9377 \begin_layout Subsection
9378 The
9379 \family typewriter
9380 IPython.GnuplotRuntime
9381 \family default
9382 module
9383 \end_layout
9384
9385 \begin_layout Standard
9386 IPython includes a module called
9387 \family typewriter
9388 Gnuplot2.py
9389 \family default
9390 which extends and improves the default
9391 \family typewriter
9392 Gnuplot
9393 \family default
9394 .
9395 \family typewriter
9396 py
9397 \family default
9398 (which it still relies upon).
9399 For example, the new
9400 \family typewriter
9401 plot
9402 \family default
9403 function adds several improvements to the original making it more convenient
9404 for interactive use, and
9405 \family typewriter
9406 hardcopy
9407 \family default
9408 fixes a bug in the original which under some circumstances blocks the creation
9409 of PostScript output.
9410 \end_layout
9411
9412 \begin_layout Standard
9413 For scripting use,
9414 \family typewriter
9415 GnuplotRuntime.py
9416 \family default
9417 is provided, which wraps
9418 \family typewriter
9419 Gnuplot2.py
9420 \family default
9421 and creates a series of global aliases.
9422 These make it easy to control Gnuplot plotting jobs through the Python
9423 language.
9424 \end_layout
9425
9426 \begin_layout Standard
9427 Below is some example code which illustrates how to configure Gnuplot inside
9428 your own programs but have it available for further interactive use through
9429 an embedded IPython instance.
9430 Simply run this file at a system prompt.
9431 This file is provided as
9432 \family typewriter
9433 example-gnuplot.py
9434 \family default
9435 in the examples directory:
9436 \end_layout
9437
9438 \begin_layout Standard
9439 \begin_inset ERT
9440 status open
9441
9442 \begin_layout Standard
9443
9444
9445 \backslash
9446 codelist{examples/example-gnuplot.py}
9447 \end_layout
9448
9449 \end_inset
9450
9451
9452 \end_layout
9453
9454 \begin_layout Subsection
9455 The
9456 \family typewriter
9457 numeric
9458 \family default
9459 profile: a scientific computing environment
9460 \end_layout
9461
9462 \begin_layout Standard
9463 The
9464 \family typewriter
9465 numeric
9466 \family default
9467 IPython profile, which you can activate with
9468 \family typewriter
9469 `ipython -p numeric
9470 \family default
9471 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
9472 other useful things for numerical computing), contained in the
9473 \family typewriter
9474 IPython.GnuplotInteractive
9475 \family default
9476 module.
9477 This will create the globals
9478 \family typewriter
9479 Gnuplot
9480 \family default
9481 (an alias to the improved Gnuplot2 module),
9482 \family typewriter
9483 gp
9484 \family default
9485 (a Gnuplot active instance), the new magic commands
9486 \family typewriter
9487 %gpc
9488 \family default
9489 and
9490 \family typewriter
9491 %gp_set_instance
9492 \family default
9493 and several other convenient globals.
9494 Type
9495 \family typewriter
9496 gphelp()
9497 \family default
9498 for further details.
9499 \end_layout
9500
9501 \begin_layout Standard
9502 This should turn IPython into a convenient environment for numerical computing,
9503 with all the functions in the NumPy library and the Gnuplot facilities
9504 for plotting.
9505 Further improvements can be obtained by loading the SciPy libraries for
9506 scientific computing, available at
9507 \begin_inset LatexCommand \htmlurl{http://scipy.org}
9508
9509 \end_inset
9510
9511 .
9512 \end_layout
9513
9514 \begin_layout Standard
9515 If you are in the middle of a working session with numerical objects and
9516 need to plot them but you didn't start the
9517 \family typewriter
9518 numeric
9519 \family default
9520 profile, you can load these extensions at any time by typing
9521 \newline
9522
9523 \family typewriter
9524 from IPython.GnuplotInteractive import *
9525 \newline
9526
9527 \family default
9528 at the IPython prompt.
9529 This will allow you to keep your objects intact and start using Gnuplot
9530 to view them.
9531 \end_layout
9532
9533 \begin_layout Section
9534 Reporting bugs
9535 \end_layout
9536
9537 \begin_layout Subsection*
9538 Automatic crash reports
9539 \end_layout
9540
9541 \begin_layout Standard
9542 Ideally, IPython itself shouldn't crash.
9543 It will catch exceptions produced by you, but bugs in its internals will
9544 still crash it.
9545 \end_layout
9546
9547 \begin_layout Standard
9548 In such a situation, IPython will leave a file named
9549 \family typewriter
9550 IPython_crash_report.txt
9551 \family default
9552 in your IPYTHONDIR directory (that way if crashes happen several times
9553 it won't litter many directories, the post-mortem file is always located
9554 in the same place and new occurrences just overwrite the previous one).
9555 If you can mail this file to the developers (see sec.
9556
9557 \begin_inset LatexCommand \ref{sec:credits}
9558
9559 \end_inset
9560
9561 for names and addresses), it will help us
9562 \emph on
9563 a lot
9564 \emph default
9565 in understanding the cause of the problem and fixing it sooner.
9566 \end_layout
9567
9568 \begin_layout Subsection*
9569 The bug tracker
9570 \end_layout
9571
9572 \begin_layout Standard
9573 IPython also has an online bug-tracker, located at
9574 \begin_inset LatexCommand \htmlurl{http://projects.scipy.org/ipython/ipython/report/1}
9575
9576 \end_inset
9577
9578 .
9579 In addition to mailing the developers, it would be a good idea to file
9580 a bug report here.
9581 This will ensure that the issue is properly followed to conclusion.
9582 To report new bugs you will have to register first.
9583 \end_layout
9584
9585 \begin_layout Standard
9586 You can also use this bug tracker to file feature requests.
9587 \end_layout
9588
9589 \begin_layout Section
9590 Brief history
9591 \end_layout
9592
9593 \begin_layout Subsection
9594 Origins
9595 \end_layout
9596
9597 \begin_layout Standard
9598 The current IPython system grew out of the following three projects:
9599 \end_layout
9600
9601 \begin_layout List
9602 \labelwidthstring 00.00.0000
9603 ipython by Fernando P
9604 \begin_inset ERT
9605 status collapsed
9606
9607 \begin_layout Standard
9608
9609
9610 \backslash
9611 '{e}
9612 \end_layout
9613
9614 \end_inset
9615
9616 rez.
9617 I was working on adding Mathematica-type prompts and a flexible configuration
9618 system (something better than
9619 \family typewriter
9620 $PYTHONSTARTUP
9621 \family default
9622 ) to the standard Python interactive interpreter.
9623 \end_layout
9624
9625 \begin_layout List
9626 \labelwidthstring 00.00.0000
9627 IPP by Janko Hauser.
9628 Very well organized, great usability.
9629 Had an old help system.
9630 IPP was used as the `container' code into which I added the functionality
9631 from ipython and LazyPython.
9632 \end_layout
9633
9634 \begin_layout List
9635 \labelwidthstring 00.00.0000
9636 LazyPython by Nathan Gray.
9637 Simple but
9638 \emph on
9639 very
9640 \emph default
9641 powerful.
9642 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
9643 were all taken from here.
9644 \end_layout
9645
9646 \begin_layout Standard
9647 When I found out (see sec.
9648
9649 \begin_inset LatexCommand \ref{figgins}
9650
9651 \end_inset
9652
9653 ) about IPP and LazyPython I tried to join all three into a unified system.
9654 I thought this could provide a very nice working environment, both for
9655 regular programming and scientific computing: shell-like features, IDL/Matlab
9656 numerics, Mathematica-type prompt history and great object introspection
9657 and help facilities.
9658 I think it worked reasonably well, though it was a lot more work than I
9659 had initially planned.
9660 \end_layout
9661
9662 \begin_layout Subsection
9663 Current status
9664 \end_layout
9665
9666 \begin_layout Standard
9667 The above listed features work, and quite well for the most part.
9668 But until a major internal restructuring is done (see below), only bug
9669 fixing will be done, no other features will be added (unless very minor
9670 and well localized in the cleaner parts of the code).
9671 \end_layout
9672
9673 \begin_layout Standard
9674 IPython consists of some 18000 lines of pure python code, of which roughly
9675 two thirds is reasonably clean.
9676 The rest is, messy code which needs a massive restructuring before any
9677 further major work is done.
9678 Even the messy code is fairly well documented though, and most of the problems
9679 in the (non-existent) class design are well pointed to by a PyChecker run.
9680 So the rewriting work isn't that bad, it will just be time-consuming.
9681 \end_layout
9682
9683 \begin_layout Subsection
9684 Future
9685 \end_layout
9686
9687 \begin_layout Standard
9688 See the separate
9689 \family typewriter
9690 new_design
9691 \family default
9692 document for details.
9693 Ultimately, I would like to see IPython become part of the standard Python
9694 distribution as a `big brother with batteries' to the standard Python interacti
9695 ve interpreter.
9696 But that will never happen with the current state of the code, so all contribut
9697 ions are welcome.
9698 \end_layout
9699
9700 \begin_layout Section
9701 License
9702 \end_layout
9703
9704 \begin_layout Standard
9705 IPython is released under the terms of the BSD license, whose general form
9706 can be found at:
9707 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
9708
9709 \end_inset
9710
9711 .
9712 The full text of the IPython license is reproduced below:
9713 \end_layout
9714
9715 \begin_layout Quote
9716
9717 \family typewriter
9718 \size small
9719 IPython is released under a BSD-type license.
9720 \end_layout
9721
9722 \begin_layout Quote
9723
9724 \family typewriter
9725 \size small
9726 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
9727 \end_layout
9728
9729 \begin_layout Quote
9730
9731 \family typewriter
9732 \size small
9733 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
9734 \newline
9735 Nathaniel Gray <n8gray@ca
9736 ltech.edu>.
9737 \end_layout
9738
9739 \begin_layout Quote
9740
9741 \family typewriter
9742 \size small
9743 All rights reserved.
9744 \end_layout
9745
9746 \begin_layout Quote
9747
9748 \family typewriter
9749 \size small
9750 Redistribution and use in source and binary forms, with or without modification,
9751 are permitted provided that the following conditions are met:
9752 \end_layout
9753
9754 \begin_layout Quote
9755
9756 \family typewriter
9757 \size small
9758 a.
9759 Redistributions of source code must retain the above copyright notice,
9760 this list of conditions and the following disclaimer.
9761 \end_layout
9762
9763 \begin_layout Quote
9764
9765 \family typewriter
9766 \size small
9767 b.
9768 Redistributions in binary form must reproduce the above copyright notice,
9769 this list of conditions and the following disclaimer in the documentation
9770 and/or other materials provided with the distribution.
9771 \end_layout
9772
9773 \begin_layout Quote
9774
9775 \family typewriter
9776 \size small
9777 c.
9778 Neither the name of the copyright holders nor the names of any contributors
9779 to this software may be used to endorse or promote products derived from
9780 this software without specific prior written permission.
9781 \end_layout
9782
9783 \begin_layout Quote
9784
9785 \family typewriter
9786 \size small
9787 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
9788 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
9789 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
9790 PURPOSE ARE DISCLAIMED.
9791 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
9792 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
9793 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
9794 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
9795 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9796 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9797 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9798
9799 \end_layout
9800
9801 \begin_layout Standard
9802 Individual authors are the holders of the copyright for their code and are
9803 listed in each file.
9804 \end_layout
9805
9806 \begin_layout Standard
9807 Some files (
9808 \family typewriter
9809 DPyGetOpt.py
9810 \family default
9811 , for example) may be licensed under different conditions.
9812 Ultimately each file indicates clearly the conditions under which its author/au
9813 thors have decided to publish the code.
9814 \end_layout
9815
9816 \begin_layout Standard
9817 Versions of IPython up to and including 0.6.3 were released under the GNU
9818 Lesser General Public License (LGPL), available at
9819 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
9820
9821 \end_inset
9822
9823 .
9824 \end_layout
9825
9826 \begin_layout Section
9827 \begin_inset LatexCommand \label{sec:credits}
9828
9829 \end_inset
9830
9831 Credits
9832 \end_layout
9833
9834 \begin_layout Standard
9835 IPython is mainly developed by Fernando P
9836 \begin_inset ERT
9837 status collapsed
9838
9839 \begin_layout Standard
9840
9841
9842 \backslash
9843 '{e}
9844 \end_layout
9845
9846 \end_inset
9847
9848 rez
9849 \family typewriter
9850 <Fernando.Perez@colorado.edu>
9851 \family default
9852 , but the project was born from mixing in Fernando's code with the IPP project
9853 by Janko Hauser
9854 \family typewriter
9855 <jhauser-AT-zscout.de>
9856 \family default
9857 and LazyPython by Nathan Gray
9858 \family typewriter
9859 <n8gray-AT-caltech.edu>
9860 \family default
9861 .
9862 For all IPython-related requests, please contact Fernando.
9863
9864 \end_layout
9865
9866 \begin_layout Standard
9867 As of early 2006, the following developers have joined the core team:
9868 \end_layout
9869
9870 \begin_layout List
9871 \labelwidthstring 00.00.0000
9872 Robert\InsetSpace ~
9873 Kern
9874 \family typewriter
9875 <rkern-AT-enthought.com>
9876 \family default
9877 : co-mentored the 2005 Google Summer of Code project to develop python interacti
9878 ve notebooks (XML documents) and graphical interface.
9879 This project was awarded to the students Tzanko Matev
9880 \family typewriter
9881 <tsanko-AT-gmail.com>
9882 \family default
9883 and Toni Alatalo
9884 \family typewriter
9885 <antont-AT-an.org>
9886 \end_layout
9887
9888 \begin_layout List
9889 \labelwidthstring 00.00.0000
9890 Brian\InsetSpace ~
9891 Granger
9892 \family typewriter
9893 <bgranger-AT-scu.edu>
9894 \family default
9895 : extending IPython to allow support for interactive parallel computing.
9896 \end_layout
9897
9898 \begin_layout List
9899 \labelwidthstring 00.00.0000
9900 Ville\InsetSpace ~
9901 Vainio
9902 \family typewriter
9903 <vivainio-AT-gmail.com>
9904 \family default
9905 : Ville is the new maintainer for the main trunk of IPython after version
9906 0.7.1.
9907 \end_layout
9908
9909 \begin_layout Standard
9910 User or development help should be requested via the IPython mailing lists:
9911 \end_layout
9912
9913 \begin_layout Description
9914 User\InsetSpace ~
9915 list:
9916 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
9917
9918 \end_inset
9919
9920
9921 \end_layout
9922
9923 \begin_layout Description
9924 Developer's\InsetSpace ~
9925 list:
9926 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
9927
9928 \end_inset
9929
9930
9931 \end_layout
9932
9933 \begin_layout Standard
9934 The IPython project is also very grateful to
9935 \begin_inset Foot
9936 status collapsed
9937
9938 \begin_layout Standard
9939 I've mangled email addresses to reduce spam, since the IPython manuals can
9940 be accessed online.
9941 \end_layout
9942
9943 \end_inset
9944
9945 :
9946 \end_layout
9947
9948 \begin_layout Standard
9949 Bill Bumgarner
9950 \family typewriter
9951 <bbum-AT-friday.com>
9952 \family default
9953 : for providing the DPyGetOpt module which gives very powerful and convenient
9954 handling of command-line options (light years ahead of what Python 2.1.1's
9955 getopt module does).
9956 \end_layout
9957
9958 \begin_layout Standard
9959 Ka-Ping Yee
9960 \family typewriter
9961 <ping-AT-lfw.org>
9962 \family default
9963 : for providing the Itpl module for convenient and powerful string interpolation
9964 with a much nicer syntax than formatting through the '%' operator.
9965 \end_layout
9966
9967 \begin_layout Standard
9968 Arnd Baecker
9969 \family typewriter
9970 <baecker-AT-physik.tu-dresden.de>
9971 \family default
9972 : for his many very useful suggestions and comments, and lots of help with
9973 testing and documentation checking.
9974 Many of IPython's newer features are a result of discussions with him (bugs
9975 are still my fault, not his).
9976 \end_layout
9977
9978 \begin_layout Standard
9979 Obviously Guido van\InsetSpace ~
9980 Rossum and the whole Python development team, that goes
9981 without saying.
9982 \end_layout
9983
9984 \begin_layout Standard
9985 IPython's website is generously hosted at
9986 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
9987
9988 \end_inset
9989
9990 by Enthought (
9991 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
9992
9993 \end_inset
9994
9995 ).
9996 I am very grateful to them and all of the SciPy team for their contribution.
9997 \end_layout
9998
9999 \begin_layout Standard
10000 \begin_inset LatexCommand \label{figgins}
10001
10002 \end_inset
10003
10004 Fernando would also like to thank Stephen Figgins
10005 \family typewriter
10006 <fig-AT-monitor.net>
10007 \family default
10008 , an O'Reilly Python editor.
10009 His Oct/11/2001 article about IPP and LazyPython, was what got this project
10010 started.
10011 You can read it at:
10012 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
10013
10014 \end_inset
10015
10016 .
10017 \end_layout
10018
10019 \begin_layout Standard
10020 And last but not least, all the kind IPython users who have emailed new
10021 code, bug reports, fixes, comments and ideas.
10022 A brief list follows, please let me know if I have ommitted your name by
10023 accident:
10024 \end_layout
10025
10026 \begin_layout List
10027 \labelwidthstring 00.00.0000
10028 Jack\InsetSpace ~
10029 Moffit
10030 \family typewriter
10031 <jack-AT-xiph.org>
10032 \family default
10033 Bug fixes, including the infamous color problem.
10034 This bug alone caused many lost hours and frustration, many thanks to him
10035 for the fix.
10036 I've always been a fan of Ogg & friends, now I have one more reason to
10037 like these folks.
10038 \newline
10039 Jack is also contributing with Debian packaging and many
10040 other things.
10041 \end_layout
10042
10043 \begin_layout List
10044 \labelwidthstring 00.00.0000
10045 Alexander\InsetSpace ~
10046 Schmolck
10047 \family typewriter
10048 <a.schmolck-AT-gmx.net>
10049 \family default
10050 Emacs work, bug reports, bug fixes, ideas, lots more.
10051 The ipython.el mode for (X)Emacs is Alex's code, providing full support
10052 for IPython under (X)Emacs.
10053 \end_layout
10054
10055 \begin_layout List
10056 \labelwidthstring 00.00.0000
10057 Andrea\InsetSpace ~
10058 Riciputi
10059 \family typewriter
10060 <andrea.riciputi-AT-libero.it>
10061 \family default
10062 Mac OSX information, Fink package management.
10063 \end_layout
10064
10065 \begin_layout List
10066 \labelwidthstring 00.00.0000
10067 Gary\InsetSpace ~
10068 Bishop
10069 \family typewriter
10070 <gb-AT-cs.unc.edu>
10071 \family default
10072 Bug reports, and patches to work around the exception handling idiosyncracies
10073 of WxPython.
10074 Readline and color support for Windows.
10075 \end_layout
10076
10077 \begin_layout List
10078 \labelwidthstring 00.00.0000
10079 Jeffrey\InsetSpace ~
10080 Collins
10081 \family typewriter
10082 <Jeff.Collins-AT-vexcel.com>
10083 \family default
10084 Bug reports.
10085 Much improved readline support, including fixes for Python 2.3.
10086 \end_layout
10087
10088 \begin_layout List
10089 \labelwidthstring 00.00.0000
10090 Dryice\InsetSpace ~
10091 Liu
10092 \family typewriter
10093 <dryice-AT-liu.com.cn>
10094 \family default
10095 FreeBSD port.
10096 \end_layout
10097
10098 \begin_layout List
10099 \labelwidthstring 00.00.0000
10100 Mike\InsetSpace ~
10101 Heeter
10102 \family typewriter
10103 <korora-AT-SDF.LONESTAR.ORG>
10104 \end_layout
10105
10106 \begin_layout List
10107 \labelwidthstring 00.00.0000
10108 Christopher\InsetSpace ~
10109 Hart
10110 \family typewriter
10111 <hart-AT-caltech.edu>
10112 \family default
10113 PDB integration.
10114 \end_layout
10115
10116 \begin_layout List
10117 \labelwidthstring 00.00.0000
10118 Milan\InsetSpace ~
10119 Zamazal
10120 \family typewriter
10121 <pdm-AT-zamazal.org>
10122 \family default
10123 Emacs info.
10124 \end_layout
10125
10126 \begin_layout List
10127 \labelwidthstring 00.00.0000
10128 Philip\InsetSpace ~
10129 Hisley
10130 \family typewriter
10131 <compsys-AT-starpower.net>
10132 \end_layout
10133
10134 \begin_layout List
10135 \labelwidthstring 00.00.0000
10136 Holger\InsetSpace ~
10137 Krekel
10138 \family typewriter
10139 <pyth-AT-devel.trillke.net>
10140 \family default
10141 Tab completion, lots more.
10142 \end_layout
10143
10144 \begin_layout List
10145 \labelwidthstring 00.00.0000
10146 Robin\InsetSpace ~
10147 Siebler
10148 \family typewriter
10149 <robinsiebler-AT-starband.net>
10150 \end_layout
10151
10152 \begin_layout List
10153 \labelwidthstring 00.00.0000
10154 Ralf\InsetSpace ~
10155 Ahlbrink
10156 \family typewriter
10157 <ralf_ahlbrink-AT-web.de>
10158 \end_layout
10159
10160 \begin_layout List
10161 \labelwidthstring 00.00.0000
10162 Thorsten\InsetSpace ~
10163 Kampe
10164 \family typewriter
10165 <thorsten-AT-thorstenkampe.de>
10166 \end_layout
10167
10168 \begin_layout List
10169 \labelwidthstring 00.00.0000
10170 Fredrik\InsetSpace ~
10171 Kant
10172 \family typewriter
10173 <fredrik.kant-AT-front.com>
10174 \family default
10175 Windows setup.
10176 \end_layout
10177
10178 \begin_layout List
10179 \labelwidthstring 00.00.0000
10180 Syver\InsetSpace ~
10181 Enstad
10182 \family typewriter
10183 <syver-en-AT-online.no>
10184 \family default
10185 Windows setup.
10186 \end_layout
10187
10188 \begin_layout List
10189 \labelwidthstring 00.00.0000
10190 Richard
10191 \family typewriter
10192 <rxe-AT-renre-europe.com>
10193 \family default
10194 Global embedding.
10195 \end_layout
10196
10197 \begin_layout List
10198 \labelwidthstring 00.00.0000
10199 Hayden\InsetSpace ~
10200 Callow
10201 \family typewriter
10202 <h.callow-AT-elec.canterbury.ac.nz>
10203 \family default
10204 Gnuplot.py 1.6 compatibility.
10205 \end_layout
10206
10207 \begin_layout List
10208 \labelwidthstring 00.00.0000
10209 Leonardo\InsetSpace ~
10210 Santagada
10211 \family typewriter
10212 <retype-AT-terra.com.br>
10213 \family default
10214 Fixes for Windows installation.
10215 \end_layout
10216
10217 \begin_layout List
10218 \labelwidthstring 00.00.0000
10219 Christopher\InsetSpace ~
10220 Armstrong
10221 \family typewriter
10222 <radix-AT-twistedmatrix.com>
10223 \family default
10224 Bugfixes.
10225 \end_layout
10226
10227 \begin_layout List
10228 \labelwidthstring 00.00.0000
10229 Francois\InsetSpace ~
10230 Pinard
10231 \family typewriter
10232 <pinard-AT-iro.umontreal.ca>
10233 \family default
10234 Code and documentation fixes.
10235 \end_layout
10236
10237 \begin_layout List
10238 \labelwidthstring 00.00.0000
10239 Cory\InsetSpace ~
10240 Dodt
10241 \family typewriter
10242 <cdodt-AT-fcoe.k12.ca.us>
10243 \family default
10244 Bug reports and Windows ideas.
10245 Patches for Windows installer.
10246 \end_layout
10247
10248 \begin_layout List
10249 \labelwidthstring 00.00.0000
10250 Olivier\InsetSpace ~
10251 Aubert
10252 \family typewriter
10253 <oaubert-AT-bat710.univ-lyon1.fr>
10254 \family default
10255 New magics.
10256 \end_layout
10257
10258 \begin_layout List
10259 \labelwidthstring 00.00.0000
10260 King\InsetSpace ~
10261 C.\InsetSpace ~
10262 Shu
10263 \family typewriter
10264 <kingshu-AT-myrealbox.com>
10265 \family default
10266 Autoindent patch.
10267 \end_layout
10268
10269 \begin_layout List
10270 \labelwidthstring 00.00.0000
10271 Chris\InsetSpace ~
10272 Drexler
10273 \family typewriter
10274 <chris-AT-ac-drexler.de>
10275 \family default
10276 Readline packages for Win32/CygWin.
10277 \end_layout
10278
10279 \begin_layout List
10280 \labelwidthstring 00.00.0000
10281 Gustavo\InsetSpace ~
10282 Cordova\InsetSpace ~
10283 Avila
10284 \family typewriter
10285 <gcordova-AT-sismex.com>
10286 \family default
10287 EvalDict code for nice, lightweight string interpolation.
10288 \end_layout
10289
10290 \begin_layout List
10291 \labelwidthstring 00.00.0000
10292 Kasper\InsetSpace ~
10293 Souren
10294 \family typewriter
10295 <Kasper.Souren-AT-ircam.fr>
10296 \family default
10297 Bug reports, ideas.
10298 \end_layout
10299
10300 \begin_layout List
10301 \labelwidthstring 00.00.0000
10302 Gever\InsetSpace ~
10303 Tulley
10304 \family typewriter
10305 <gever-AT-helium.com>
10306 \family default
10307 Code contributions.
10308 \end_layout
10309
10310 \begin_layout List
10311 \labelwidthstring 00.00.0000
10312 Ralf\InsetSpace ~
10313 Schmitt
10314 \family typewriter
10315 <ralf-AT-brainbot.com>
10316 \family default
10317 Bug reports & fixes.
10318 \end_layout
10319
10320 \begin_layout List
10321 \labelwidthstring 00.00.0000
10322 Oliver\InsetSpace ~
10323 Sander
10324 \family typewriter
10325 <osander-AT-gmx.de>
10326 \family default
10327 Bug reports.
10328 \end_layout
10329
10330 \begin_layout List
10331 \labelwidthstring 00.00.0000
10332 Rod\InsetSpace ~
10333 Holland
10334 \family typewriter
10335 <rhh-AT-structurelabs.com>
10336 \family default
10337 Bug reports and fixes to logging module.
10338 \end_layout
10339
10340 \begin_layout List
10341 \labelwidthstring 00.00.0000
10342 Daniel\InsetSpace ~
10343 'Dang'\InsetSpace ~
10344 Griffith
10345 \family typewriter
10346 <pythondev-dang-AT-lazytwinacres.net>
10347 \family default
10348 Fixes, enhancement suggestions for system shell use.
10349 \end_layout
10350
10351 \begin_layout List
10352 \labelwidthstring 00.00.0000
10353 Viktor\InsetSpace ~
10354 Ransmayr
10355 \family typewriter
10356 <viktor.ransmayr-AT-t-online.de>
10357 \family default
10358 Tests and reports on Windows installation issues.
10359 Contributed a true Windows binary installer.
10360 \end_layout
10361
10362 \begin_layout List
10363 \labelwidthstring 00.00.0000
10364 Mike\InsetSpace ~
10365 Salib
10366 \family typewriter
10367 <msalib-AT-mit.edu>
10368 \family default
10369 Help fixing a subtle bug related to traceback printing.
10370 \end_layout
10371
10372 \begin_layout List
10373 \labelwidthstring 00.00.0000
10374 W.J.\InsetSpace ~
10375 van\InsetSpace ~
10376 der\InsetSpace ~
10377 Laan
10378 \family typewriter
10379 <gnufnork-AT-hetdigitalegat.nl>
10380 \family default
10381 Bash-like prompt specials.
10382 \end_layout
10383
10384 \begin_layout List
10385 \labelwidthstring 00.00.0000
10386 Antoon\InsetSpace ~
10387 Pardon
10388 \family typewriter
10389 <Antoon.Pardon-AT-rece.vub.ac.be>
10390 \family default
10391 Critical fix for the multithreaded IPython.
10392 \end_layout
10393
10394 \begin_layout List
10395 \labelwidthstring 00.00.0000
10396 John\InsetSpace ~
10397 Hunter
10398 \family typewriter
10399 <jdhunter-AT-nitace.bsd.uchicago.edu>
10400 \family default
10401 Matplotlib author, helped with all the development of support for matplotlib
10402 in IPyhton, including making necessary changes to matplotlib itself.
10403 \end_layout
10404
10405 \begin_layout List
10406 \labelwidthstring 00.00.0000
10407 Matthew\InsetSpace ~
10408 Arnison
10409 \family typewriter
10410 <maffew-AT-cat.org.au>
10411 \family default
10412 Bug reports, `
10413 \family typewriter
10414 %run -d
10415 \family default
10416 ' idea.
10417 \end_layout
10418
10419 \begin_layout List
10420 \labelwidthstring 00.00.0000
10421 Prabhu\InsetSpace ~
10422 Ramachandran
10423 \family typewriter
10424 <prabhu_r-AT-users.sourceforge.net>
10425 \family default
10426 Help with (X)Emacs support, threading patches, ideas...
10427 \end_layout
10428
10429 \begin_layout List
10430 \labelwidthstring 00.00.0000
10431 Norbert\InsetSpace ~
10432 Tretkowski
10433 \family typewriter
10434 <tretkowski-AT-inittab.de>
10435 \family default
10436 help with Debian packaging and distribution.
10437 \end_layout
10438
10439 \begin_layout List
10440 \labelwidthstring 00.00.0000
10441 George\InsetSpace ~
10442 Sakkis <
10443 \family typewriter
10444 gsakkis-AT-eden.rutgers.edu>
10445 \family default
10446 New matcher for tab-completing named arguments of user-defined functions.
10447 \end_layout
10448
10449 \begin_layout List
10450 \labelwidthstring 00.00.0000
10451 J�rgen\InsetSpace ~
10452 Stenarson
10453 \family typewriter
10454 <jorgen.stenarson-AT-bostream.nu>
10455 \family default
10456 Wildcard support implementation for searching namespaces.
10457 \end_layout
10458
10459 \begin_layout List
10460 \labelwidthstring 00.00.0000
10461 Vivian\InsetSpace ~
10462 De\InsetSpace ~
10463 Smedt
10464 \family typewriter
10465 <vivian-AT-vdesmedt.com>
10466 \family default
10467 Debugger enhancements, so that when pdb is activated from within IPython,
10468 coloring, tab completion and other features continue to work seamlessly.
10469 \end_layout
10470
10471 \begin_layout List
10472 \labelwidthstring 00.00.0000
10473 Scott\InsetSpace ~
10474 Tsai
10475 \family typewriter
10476 <scottt958-AT-yahoo.com.tw>
10477 \family default
10478 Support for automatic editor invocation on syntax errors (see
10479 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
10480
10481 \end_inset
10482
10483 ).
10484 \end_layout
10485
10486 \begin_layout List
10487 \labelwidthstring 00.00.0000
10488 Alexander\InsetSpace ~
10489 Belchenko
10490 \family typewriter
10491 <bialix-AT-ukr.net>
10492 \family default
10493 Improvements for win32 paging system.
10494 \end_layout
10495
10496 \begin_layout List
10497 \labelwidthstring 00.00.0000
10498 Will\InsetSpace ~
10499 Maier
10500 \family typewriter
10501 <willmaier-AT-ml1.net>
10502 \family default
10503 Official OpenBSD port.
10504 \end_layout
10505
10506 \end_body
10507 \end_document
@@ -1,2 +0,0 b''
1 #!/bin/sh
2 ipython --magic_docstrings > magic.tex No newline at end of file
@@ -1,28 +0,0 b''
1 #!/usr/bin/env ipython
2 """ Must be launched via ipython not normal python
3
4 Run by:
5
6 ipython update_manual.py
7 """
8
9 import sys,IPython,re
10
11 fil=open("magic.tex","w")
12 oldout=sys.stdout
13 sys.stdout=fil
14 _ip.magic("magic -latex")
15 sys.stdout=oldout
16 fil.close()
17
18 fil=open("manual_base.lyx")
19 txt=fil.read()
20 fil.close()
21
22 manualtext=re.sub("__version__",IPython.__version__,txt)
23 fil=open("manual.lyx","w")
24 fil.write(manualtext)
25 fil.close()
26 print "Manual (magic.tex, manual.lyx) succesfully updated, exiting..."
27 import os
28 os.abort()
@@ -1,72 +0,0 b''
1 #!/usr/bin/env python
2 """Backup directories using rsync. Quick and dirty.
3
4 backup.py config_file final_actions
5 """
6
7 #----------------------------------------------------------------------------
8 # configure in this section
9
10 # all dirs relative to current dir.
11
12 # output directory for backups
13 outdir = ''
14
15 # list directories to backup as a dict with 1 or 0 values for
16 # recursive (or not) descent:
17 to_backup = {}
18
19 # list exclude patterns here (space-separated):
20 # if the pattern ends with a / then it will only match a directory, not a
21 # file, link or device.
22 # see man rsync for more details on the exclude patterns
23 exc_pats = '#*# *~ *.pyc *.pyo *.o '
24
25 # global options for rsync
26 rsync_opts='-v -t -a --delete --delete-excluded'
27
28 #----------------------------------------------------------------------------
29 # real code begins
30 import os,string,re,sys
31 from IPython.genutils import *
32 from IPython.Itpl import itpl
33
34 # config file can redefine final actions
35 def final():
36 pass
37
38 # load config from cmd line config file or default bkprc.py
39 try:
40 execfile(sys.argv[1])
41 except:
42 try:
43 execfile('bkprc.py')
44 except IOError:
45 print 'You need to provide a config file: bkp.py rcfile'
46 sys.exit()
47
48 # make output dir if needed
49 outdir = os.path.expanduser(outdir)
50 try:
51 os.makedirs(outdir)
52 except OSError: # raised if dir already exists -> no need to make it
53 pass
54
55 # build rsync command and call:
56 exclude = re.sub(r'([^\s].*?)(\s|$)',r'--exclude "\1"\2',exc_pats)
57 rsync = itpl('rsync $rsync_opts $exclude')
58
59 # the same can also be done with lists (keep it for reference):
60 #exclude = string.join(['--exclude "'+p+'"' for p in qw(exc_pats)])
61
62 # rsync takes -r as a flag, not 0/1 so translate:
63 rec_flag = {0:'',1:'-r'}
64
65 # loop over user specified directories calling rsync
66 for bakdir,rec in to_backup.items():
67 bakdir = os.path.expanduser(bakdir)
68 xsys(itpl('$rsync $rec_flag[rec] $bakdir $outdir'),
69 debug=0,verbose=1,header='\n### ')
70
71 # final actions?
72 final()
@@ -1,22 +0,0 b''
1 #!/bin/sh
2
3 # Simple backup script for ipython, to keep around a static copy of the whole
4 # project at the current version point. We do this by exporting from SVN.
5
6 # Config here
7 IPYTHONSVN=$HOME/ipython/svn/ipython/trunk
8 BACKUPDIR=$HOME/ipython/backup
9
10 ####
11 # Code begins
12 IPVERSION=`ipython -Version`
13 IPX=ipython-$IPVERSION
14 ARCHIVE=$BACKUPDIR/$IPX.tgz
15
16 svn export $IPYTHONSVN $IPX
17
18 tar czf $ARCHIVE $IPX
19
20 rm -rf $IPX
21
22 echo "Backup left in: $ARCHIVE"
@@ -1,22 +0,0 b''
1 # config file for a quick'n dirty backup script that uses rsync
2
3 # output directory for backups
4 outdir = '~/tmp'
5
6 # list directories to backup as a dict with 1 or 0 values for
7 # recursive (or not) descent:
8 to_backup = {'~/ipython/ipython':1}
9
10 # exclude patterns. anything ending in / is considered a directory
11 exc_pats = '#*# *~ *.o *.pyc *.pyo MANIFEST *.pdf *.flc build/ dist/ ' \
12 ' doc/manual/ doc/manual.lyx ChangeLog.* magic.tex *.1.gz '
13
14 # final actions after doing the backup
15 def final():
16 dbg = 0
17 version = bq('ipython -V')
18 out_tgz = outdir+'/ipython-'+version+'.tgz'
19 xsys(itpl('cd $outdir; pwd;tar -czf $out_tgz ipython'),debug=dbg,verbose=1)
20 #xsys(itpl('cp $out_tgz /mnt/card/fperez/ipython'),debug=dbg,verbose=1)
21 xsys(itpl('mv $out_tgz ~/ipython/backup'),debug=dbg,verbose=1)
22 xsys(itpl('rm -rf ${outdir}/ipython'),debug=dbg,verbose=1)
@@ -1,78 +0,0 b''
1 #!/usr/bin/env python
2 """Simple svn commit wrapper which emails a given list of people.
3
4 Usage:
5
6 ipsvnc [args]
7
8 This is equivalent to doing
9
10 svn commit [args]
11
12 If the commit operation is successful (the script asks for confirmation), a
13 hardwired list of maintainers is informed of the commit.
14
15 This is a poor-man's substitute for a proper svn post-commit hook with an
16 ipython-svn email list, which we're waiting to get soon. It should be removed
17 once that facility is in place.
18
19 This only works on a unix box which can send mail by itself."""
20
21 import os
22 import commands
23 import sys
24 import time
25
26 # Package maintainers to be alerted
27 maintainers = ['fperez@colorado.edu', 'rkern@ucsd.edu', 'antont@an.org',
28 'tsanko@gmail.com']
29
30 #maintainers = ['fperez@colorado.edu'] # dbg
31
32 # Assemble command line back, before passing it to svn
33 svnargs = []
34 for arg in sys.argv[1:]:
35 if ' ' in arg:
36 svnargs.append('"%s"' % arg)
37 else:
38 svnargs.append(arg)
39 svnargs = ' '.join(svnargs)
40
41 #print 'SVN args: <%s>' % svnargs; sys.exit() # dbg
42
43 # perform commit
44 print 'Performing SVN commit, this may take some time...'
45 os.system('svn commit %s' % svnargs)
46 svntime = time.asctime()
47 print 'Getting SVN log and version info...'
48 svnstatus = commands.getoutput('svn log -r HEAD')
49 svnversion = commands.getoutput('svnversion .').split(':')[-1]
50
51 # Confirm with user (trying to get the status from the svn commit blocks
52 # silently, I don't care to debug it)
53 ans = raw_input('If commit was succesful, proceed '
54 'with email notification? [Y/n] ')
55 if ans.lower().startswith('n'):
56 print "Exiting now..."
57 sys.exit(1)
58 else:
59 print "OK. Emailing maintainers..."
60
61 # Send emails
62 subject = "[IPython SVN] New commit performed by %s" % os.getlogin()
63 body = """\
64 Commit performed at: %s
65
66 SVN arguments used: %s
67
68 SVN Version: %s
69
70 This version probably points to this changeset:
71 http://projects.scipy.org/ipython/ipython/changeset/%s
72
73 Current SVN status after last commit:
74 %s""" % (svntime,svnargs,svnversion,svnversion,svnstatus)
75
76 for maint in maintainers:
77 print "Emailing",maint
78 os.system('echo "%s" | mail -s "%s" %s' % (body, subject,maint))
This diff has been collapsed as it changes many lines, (1049 lines changed) Show them Hide them
@@ -1,1049 +0,0 b''
1 #!/usr/bin/env perl
2 #
3 #*****************************************************************************
4 #
5 # lyxport - script for exporting lyx docs to HTML, PostScript and PDF
6 #
7 # Inspired on the lyx2html script by Steffen Evers (tron@cs.tu-berlin.de)
8 # (many thanks to him).
9 #
10 # Copyright (C) 2001 Fernando Pérez (Fernando.Perez@colorado.edu)
11 #
12 #*****************************************************************************
13 #
14 # This program is free software; you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 2 of the License, or
17 # (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # If you do not have a copy of the GNU General Public License, write
25 # to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
26 # MA 02139, USA.
27 #
28 # If the author of this software was too lazy to include the full GPL
29 # text along with the code, you can find it at:
30 #
31 # http://www.gnu.org/copyleft/gpl.html
32 #
33 #*****************************************************************************
34
35 =pod
36
37 =head1 NAME
38
39 B<lyxport> - Export a LyX or LaTeX file to HTML, PostScript and PDF.
40
41 =head1 SYNOPSIS
42
43 B<lyxport> [options] F<file>
44
45 Perl script which takes a LyX or LaTeX file as its only argument and produces
46 HTML, PostScript and PDF versions of the document. The name is short for "lyx
47 export".
48
49 You can call B<lyxport> with a filename with or without extension: F<file>,
50 F<file.lyx> and F<file.tex> will all work. B<lyxport> will update the LaTeX
51 file if there is a corresponding LyX file with a newer timestamp.
52
53 Use B<lyxport --help> for more information, and B<lyxport --man> for a full
54 man page.
55
56 =cut
57
58 #*****************************************************************************
59 # modify here the command names to suit your local conditions
60 my %cmd= (
61 lyx => "/usr/bin/lyx",
62 latex => "latex",
63 latex2html => "latex2html",
64 dvips => "dvips",
65 pdflatex => "pdflatex",
66 epstopdf => "epstopdf"
67 );
68
69 #************ DO NOT CHANGE ANYTHING BELOW THIS ULESS YOU *REALLY* KNOW
70 #************ WHAT YOU ARE DOING.
71
72 #*****************************************************************************
73 # modules and globals
74 use strict;
75 use File::Copy;
76 use File::Basename;
77 my (%opt); # command line options
78 my $version = "0.3.2"; # keep this up to date with the docs (at end)!
79
80 #*****************************************************************************
81 # "main" (simple minded way to keep variable scoping under control)
82 main();
83
84 sub main {
85 my ($runs, # number of latex runs
86 $file_in, # input filename as given at cmd line
87 $file_base, # base (no extension) name of file to work on
88 $lyx_time, # timestamps of lyx/tex files
89 $tex_time,
90 $l2h_file, # tex file cleaned up for latex2html
91 $targets_built,
92 $targets_failed,
93 $status, # status string for diagnostics printing
94 @latex_from_lyx # LaTeX files was created from LyX file
95 );
96
97 #------------------------------------------------------------------------
98 # code begins
99
100 cmdline_process(\%opt,\$file_in);
101
102 # set defaults and filenames needed throughout
103 $runs=$opt{runs};
104 set_cmd_defaults(\%cmd);
105 $file_base=check_file_exists($file_in);
106 # various filenames (with extensions)
107 my @exts=qw(lyx tex aux dvi log ps pdf out toc);
108 my ($lyx,$tex,$aux,$dvi,$log,$ps,$pdf,$out,$toc) = map { "$file_base.$_" } @exts;
109
110 # first, if tex file is older than lyx file, update
111 @latex_from_lyx=update_tex($lyx,$tex);
112
113 if ($opt{clean}) {
114 lyxport_info("Cleanup of old auxiliary files requested");
115 safe_system("rm -rf $file_base");
116 unlink ($aux,$log,$out,$toc);
117 }
118
119 # run latex for both html (needs .aux file) and ps (needs .dvi)
120 if ($opt{html} or $opt{ps}) {
121 run_latex("$cmd{latex} -interaction=nonstopmode",$tex,\$runs);
122 }
123 # now make targets
124 if ($opt{html}) {
125 make_html($tex,$file_base,$opt{opts_l2h},\$status,
126 \$targets_built,\$targets_failed);
127 }
128 if ($opt{ps}) {
129 make_ps($dvi,$ps,$file_base,\$status,\$targets_built,\$targets_failed);
130 }
131 if ($opt{pdf}) {
132 make_pdf($tex,$pdf,\$runs,$file_base,
133 \$status,\$targets_built,\$targets_failed);
134 }
135
136 #cleanup before exiting and print some diagnostics info
137 unless ($opt{debug}) {
138 unlink ($dvi,$log,$out);
139 }
140 # extra cleanup
141 if ($opt{tidy}) {
142 print "tidy up $opt{tidy},$aux,$log,$out,$toc,@latex_from_lyx\n";
143 tidy_up($opt{tidy},$aux,$log,$out,$toc,@latex_from_lyx);
144 }
145 final_diagnostics($file_in,$status,$targets_built,$targets_failed);
146 exit(0);
147 } # end of main()
148
149 #*****************************************************************************
150 # subroutines
151
152 #-----------------------------------------------------------------------------
153 sub make_html {
154 my($tex,$html_dir,$opts_l2h,$stat_ref,$built_ref,$failed_ref)=@_;
155 my($success);
156
157 lyxport_info("Making HTML");
158 run_latex2html($tex,$opts_l2h);
159 $success=check_targets("${html_dir}/${html_dir}.html",'HTML',
160 $built_ref,$failed_ref);
161 if ($success) {$$stat_ref .= "Target HTML built in directory $html_dir\n" }
162 } # end of make_html()
163
164 #-----------------------------------------------------------------------------
165 sub make_ps {
166 my($dvi,$ps,$html_dir,$stat_ref,$built_ref,$failed_ref)=@_;
167 my($success);
168
169 lyxport_info("Making PostScript");
170 safe_system("$cmd{dvips} $dvi -o $ps");
171 $success=check_targets($ps,'PostScript',$built_ref,$failed_ref);
172 if ($success and not $opt{leave}) {
173 move2html_dir('PostScript',$ps,$html_dir,$stat_ref,$built_ref);
174 }
175 } # end of make_ps()
176
177 #-----------------------------------------------------------------------------
178 sub make_pdf {
179 my($tex,$pdf,$runs_ref,$html_dir,$stat_ref,$built_ref,$failed_ref)=@_;
180 my($success);
181
182 lyxport_info("Making PDF");
183 run_pdflatex($tex,$pdf,$runs_ref);
184 $success=check_targets($pdf,'PDF',$built_ref,$failed_ref);
185 if ($success and not $opt{leave}) {
186 move2html_dir('PDF',$pdf,$html_dir,$stat_ref,$built_ref);
187 }
188 } # end of make_pdf()
189
190 #-----------------------------------------------------------------------------
191 # move a given target to the html dir, only if it exists. leaves diagnostics
192 # info in a status string
193 sub move2html_dir {
194 my($name,$file,$dir,$stat_ref,$html_status_ref)=@_;
195
196 if ($$html_status_ref =~ /HTML/) {
197 safe_system("mv $file $dir");
198 $$stat_ref .= "Target $name moved to directory $dir\n";
199 } else {
200 $$stat_ref .= "Target $name left in current directory\n";
201 }
202 } # end of move2html_dir()
203
204 #-----------------------------------------------------------------------------
205 # make sure that the tex file is up to date vs the lyx original before starting
206 # returns a list of the included .tex files which were generated (besides the main one)
207 sub update_tex {
208 my($lyx,$tex)=@_;
209 my($lyx_time,$tex_time);
210 my(@lyx_out,@made_tex,$lc);
211
212 @made_tex=();
213 unless (-e $lyx) {
214 print "LyX file not found. Working off the LaTeX file alone.\n\n";
215 return;
216 }
217 $lyx_time=(stat($lyx))[9];
218 $tex_time=(stat($tex))[9];
219 if ($lyx_time>$tex_time or not(-e $tex)) {
220 lyxport_info("LaTeX file outdated or not existent, regenerating it...");
221 unlink $tex;
222 @lyx_out=`$cmd{lyx} -dbg latex --export latex $lyx 2>&1 `;
223 # try again without -dbg option: LyX has a bug here! Note that this will
224 # disable the ability to remove extra .tex files generated from \include
225 # statements. But at least it will work, until they fix the bug in LyX.
226 unless (-e $tex) {
227 @lyx_out=`$cmd{lyx} --export latex $lyx 2>&1 `;
228 }
229 # end of ugly workaround
230 unless (-e $tex) {die "Aborting: couldn't create LaTeX file with LyX.\n\n"};
231 push (@made_tex,$tex);
232 # find whether lyx made auxiliary (included) .tex files and report
233 foreach $lc (0..$#lyx_out-1) {
234 $_=$lyx_out[$lc];
235 if (/^incfile:.*\.lyx/) {
236 $lyx_out[$lc+1] =~ /^writefile:(.*)$/;
237 push (@made_tex,basename($1));
238 }
239 }
240 if (@made_tex) {
241 lyxport_info("Made LaTeX included files: @made_tex");
242 }
243 lyxport_info("Done with LaTeX generation. Moving on.");
244 }
245 return @made_tex;
246 } # end of update_tex()
247
248 #-----------------------------------------------------------------------------
249 # run latex on a file as many times as needed
250 # if the given # of runs is > 0, that many are done; otherwise latex is run
251 # as many times as needed until cross-references work.
252 # can be used to run either normal latex or pdflatex
253 sub run_latex {
254 my($latex_cmd,$file,$runs_ref)=@_;
255
256 # pre-determined # of runs
257 if ($$runs_ref > 0) {
258 foreach (1..$$runs_ref) {
259 lyxport_info("$latex_cmd run # $$runs_ref");
260 safe_system("$latex_cmd $file");
261 }
262 }
263 # or make as many runs as needed to get things right (not very robust...)
264 else {
265 $$runs_ref=0;
266 while (1) {
267 $$runs_ref++;
268 lyxport_info("$latex_cmd run # $$runs_ref");
269 $_ = `$latex_cmd $file`;
270 print;
271 last unless (/Rerun to get cross-references right/m or
272 /^No file .*\.toc.$/m);
273 }
274 }
275 } # end of run_latex()
276
277 #-----------------------------------------------------------------------------
278 # cleanup the tex code so that latex2html doesn't get too confused
279 # this is essentially a Perl version (made with s2p) of Steffan Effer's
280 # original improvetex sed script, part of his lyx2html script collection
281 sub improve_tex4html {
282 my ($texfile,$newfile)=@_;
283 my ($len1,$pflag);
284 my $printit=1;
285 local *OLD,*NEW;
286
287 open(OLD,"< $texfile") || die "Can't read from file $texfile: $!\n";
288 open(NEW,"> $newfile") || die "Can't write to file $newfile: $!\n";
289 select(NEW) || die "Can't make $newfile default filehandle: $!\n";
290
291 # code generated by s2p follows. Emacs can't reindent it properly!
292 # this code is ugly (once in Perl, original sed was ok). Clean it up...
293 $pflag=$\; # save print flag
294 $\="\n";
295 LINE:
296 while (<OLD>) {
297 chomp;
298 # remove pagerefs over two lines (senseless in HTML)
299 if (/on *$\|on *page *$/) {
300 $_ .= "\n";
301 $len1 = length;
302 $_ .= <OLD>;
303 chop if $len1 < length;
304 s/on *\n*page *\n*\\pageref{[^}]*}/\n/g;
305 }
306 # remove regular pagerefs (senseless in HTML)
307 s/on *page *\\pageref{[^}]*}//g;
308 # comment out redefintion of url tag (confuses latex2html)
309 if (/^\\IfFileExists{url.sty}/) {
310 s/^/%/;
311 print;
312 $_ = <OLD>;
313 s/^/%/;
314 }
315 # remove empty pages
316 if (/^\\thispagestyle{empty}~\\newpage$/) {
317 $printit = 0;
318 next LINE;
319 }
320 if (/^\\thispagestyle{empty}~$/) {
321 $printit = 0;
322 next LINE;
323 }
324 # remove custom latex commands for fancyheaders
325 s/\\fancyhead[^{]*{[^{}]*([^{}]*{[^{}]*})*[^{}]*}*//g;
326 s/\\thispagestyle{[^{}]*}//g;
327 # change documentclass from scrbook to book
328 s/^(\\documentclass[^{}]*{)scrbook}/$1book}/;
329 # comment out unsupported packages
330 s/^(\\usepackage\[T1\]{fontenc})/%$1/;
331 s/^(\\usepackage{a4wide})/%$1/;
332 s/^(\\usepackage{fancyhdr})/%$1/;
333 s/^(\\usepackage{ae)/%$1/;
334 s/^(\\pagestyle{fancy})/%$1/;
335 # the geometry package doesn't make sense in html
336 s/^(\\usepackage{geometry})/%$1/;
337 s/^(\\geometry)/%$1/;
338 # comment out ident/skip block command (produces error message; why?)
339 s/^(\\setlength\\parskip{.*})/%$1/;
340 s/^(\\setlength\\parindent{.*})/%$1/;
341 } continue {
342 if ($printit) { print }
343 else { $printit++ }
344 }
345 close(OLD);
346 close(NEW);
347 select(STDOUT);
348 $\=$pflag; # restore defaults
349 } # end of improve_tex4html()
350
351 #-----------------------------------------------------------------------------
352 sub run_latex2html {
353 my ($tex,$latex2html_opts)=@_;
354 my ($l2h_file,$symlink_exists,$htmldir);
355
356 ($htmldir=$tex) =~ s/\.tex$//;
357 $l2h_file="${tex}_#tmp_2html#";
358 improve_tex4html($tex,$l2h_file);
359 # add index support
360 my $xtraargs = "";
361 my $idx = "$htmldir.idx";
362 if(-e $idx ) {
363 $xtraargs .= "-index $idx";
364 }
365 safe_system("$cmd{latex2html} $xtraargs $latex2html_opts $l2h_file");
366 unless ($opt{debug}) {
367 unlink($l2h_file,"$htmldir/labels.pl");
368 }
369
370 # latex2html always leaves 2 copies of the file (one as file.html, one as
371 # index.html). In systems that support symlinks, remove one and replace it
372 # with a link:
373 $symlink_exists = eval { symlink("",""); 1 };
374 if ($symlink_exists) {
375 unlink("$htmldir/index.html");
376 symlink("$htmldir.html","$htmldir/index.html");
377 }
378 } # end of run_latex2html()
379
380 #-----------------------------------------------------------------------------
381 # remove calls to eps figures if they have an accompanying tiff, jpg or png
382 sub improve_tex_figs {
383 my ($tex,$textmp)=@_;
384 local (*TEX,*TMP);
385
386 # begin changes to tex file
387 my ($printit,$figname,$fignoneps,$figbase,$figext,$fignew,@figlist,@tmpfiles);
388 open(TEX,"< $tex") || die "Can't read from LaTeX file $tex: $!\n";
389 open(TMP,"> $textmp") || die "Can't write to temp file $textmp: $!\n";
390 $printit=1;
391 while (<TEX>) {
392 if (/includegraphics{([^\}]*)/) {
393 $figname=$1;
394 # remove .eps from fig name and make a .pdf version if necessary
395 if ($figname =~ /\.eps$/i) {
396 ($figbase = $figname) =~ s/\.eps$//i;
397 # now we need to find if there's any non-eps figure for this file:
398 # pdflatex can handle jpegs, tiffs, etc. So we only need to build
399 # an associated pdf if there is no other figure file for pdflatex
400 # to work with
401 @figlist=grep {/\.jpe?g$|\.tiff?$|\.png$|\.pdf$/i} <$figbase.*>;
402 if (@figlist > 1) {
403 lyxport_info("Problem! More than one figure file found: @figlist");
404 die "I don't know what to do here. Sorry, aborting...\n\n";
405 } elsif (@figlist==1) {
406 # problem: pdftex only recognizes jpg (not jpeg, not JPG, etc)
407 # and tif (not tiff, not TIF, etc). It also gets confused by files
408 # called a.b.c.jpg (it thinks .b.c.jpg is the extension). argh!!!
409 ($fignoneps)=(@figlist);
410 # so first, extract the 3 or 4 letter extension and lowercase it
411 $fignoneps =~ /.*\.(....??)$/;
412 ($figext = $1) =~ tr/[A-Z]/[a-z]/;
413 # and remove any periods from the base of the name (replace by _)
414 $figbase =~ s/\./_/g;
415 $fignew="$figbase.$figext";
416 if ($fignoneps =~ /\.JPE?G$|\.TIFF?$|\.PNG$|\.PDF$/) {
417 lyxport_info("pdflatex only recognizes the following extensions:\n".
418 "pdf, png, jpg, tif. (all lowercase, no variations like jpeg or tiff).\n".
419 "lyxport will make a copy of $fignoneps to $fignew so that pdflatex is happy");
420 copy($fignoneps,$fignew);
421 push(@tmpfiles,$fignew);
422 }
423 s/$figname/$fignew/; # in $_, for printing to temp file
424 } else {
425 s/$figname/$figbase.pdf/;
426 lyxport_info("Making PDF figure <$figbase.pdf> from <$figname>");
427 safe_system("$cmd{epstopdf} $figname");
428 }
429
430 }
431 }
432 } continue {
433 if ($printit) { print TMP $_}
434 else { $printit++ }
435 }
436 close(TEX);
437 close(TMP);
438 return @tmpfiles;
439 } # end of improve_tex_figs()
440
441 #-----------------------------------------------------------------------------
442 # Make the pdf directly from the latex file
443 # Notes: for this to work ok, the following must have been done:
444 # 1. ~/.dvipsrc file must contain the lines
445 # p+ psfonts.cmz
446 # p+ psfonts.amz
447 # 2. The latex preamble of the lyx file must have
448 # \usepackage{ae,aecompl}
449 # This is so that T1 encoded fonts come out looking good in the final pdf.
450 sub run_pdflatex {
451 my ($tex,$pdf,$runs_ref)=@_;
452 my ($texbase,$tmpbase,$textmp,@tmpfiles,@extensions,$printit);
453 local *TEX,*TMP;
454
455 # first fix references to eps figures (make sure that pdf versions exist!!!)
456 # make all changes in a temp tex file
457 ($texbase=$tex) =~ s/\.tex$//;
458 $tmpbase = "${texbase}_#tmp_pdf#";
459 @extensions=qw(tex aux out toc log);
460 ($textmp,@tmpfiles)= map { "${tmpbase}.$_" } @extensions;
461
462 push(@tmpfiles,improve_tex_figs($tex,$textmp));
463 # now run the actual pdflatex converter
464 run_latex("$cmd{pdflatex} -interaction=nonstopmode",$textmp,$runs_ref);
465 rename( "${tmpbase}.pdf",$pdf);
466 unless ($opt{debug}) { unlink ($textmp,@tmpfiles,"texput.log"); }
467 } # end of run_pdflatex()
468
469 #-----------------------------------------------------------------------------
470 # general utility routines (not related to latex/html/pdf) follow
471
472 #-------------------------------------------------------------------------
473 sub cmdline_process{
474 my($opt_ref,$file_ref)=@_;
475
476 # modules
477 no strict "vars"; # avoid some unpleasant warnings while checking options
478
479 use Getopt::Long;
480 # allow bundling of single letter options (-a -b == -ab)
481 Getopt::Long::Configure ("bundling");
482 use Pod::Usage;
483
484 # note: the second name for each option (after |) is an alias for user
485 # convenience only. Internally, the only created hash entries use the *first*
486 # name as a key (i.e. $opt{h} doesn't exist, $opt{html} is set with -h or --html)
487 my(@option_list) = qw(html|h ps|p pdf|f leave
488 runs|r=i opts_l2h|o=s clean|c tidy|t+
489 cld|l debug|d help man|m version|v);
490
491 # debug mode overrides all post-run cleanup options
492 if ($opt{debug}) { $opt{t}=0 }
493
494 # default: a negative # of runs means auto-detect
495 $$opt_ref{runs}= -99;
496 # dash options first
497 GetOptions($opt_ref,@option_list) || pod2usage(-verbose => 0);
498
499 # execute all possible "die" modes first
500 cmdline_debug(%$opt_ref) if ($$opt_ref{cld});
501 pod2usage(-verbose => 1) if ($$opt_ref{help});
502 pod2usage(-verbose => 2) if ($$opt_ref{man});
503 die "\nlyxport: version $version\n\n" if ($$opt_ref{version});
504
505 ## Now get filename (only ONE)
506 pod2usage(-verbose => 0, -message =>
507 "\nERROR: lyxport works with exactly ONE file at a time.\n")
508 if (@ARGV != 1);
509 ($$file_ref)=@ARGV;
510
511 # choose whether to make all targets or just the explicitly specified ones
512 unless ($$opt_ref{html} or $$opt_ref{ps} or $$opt_ref{pdf}) {
513 $$opt_ref{html}=$$opt_ref{ps}=$$opt_ref{pdf}=1;
514 }
515 } # end of cmdline_process()
516
517 #-----------------------------------------------------------------------------
518 # quick and dirty hash printing by key/value pairs
519 sub print_hash {
520 my($key_msg,$val_msg,%hash)=@_;
521 my($op,$val);
522
523 while ( ($op,$val)=each(%hash) ) {print "$key_msg $op $val_msg $val\n" }
524 } # end of print_hash()
525
526 #-----------------------------------------------------------------------------
527 sub cmdline_debug{
528 my(%opt)=@_;
529
530 print "\nlyxport command line debug mode\n";
531 print "-------------------------------\n\n";
532 print "This is a dump of your command line options, as key-value pairs:\n\n";
533 print_hash("","->",%opt);
534 print "\nExiting...\n\n";
535 exit;
536 } # end of cmdline_debug()
537
538 #-----------------------------------------------------------------------------
539 # execute a system call but die with some info if return value is non-zero
540 sub safe_system {
541 my $error;
542
543 $error=system(@_)/256;
544 if ($error) {
545 print "\nERROR: Command\n @_\nfailed.\n";
546 }
547 return $error;
548 } # end of safe_system()
549
550 #-----------------------------------------------------------------------------
551 # check that the command names specified at the top exist in the system,
552 # otherwise choose bare defaults and hope for the best.
553 sub set_cmd_defaults {
554 my ($cmd)=@_;
555 my ($prog,$cmd_name);
556
557 print "\n";
558 while (($prog,$cmd_name)=each(%cmd)) {
559 print "Checking for program <$prog>, as <$cmd_name>... \n";
560 if (system("which $cmd_name")/256) {
561 $$cmd{$prog}=$prog;
562 print "Not found. Reverting to default name $prog.\n";
563 } else { print "OK, found it.\n" }
564 }
565 print "\nDone configuring command names\n\n";
566 } # end of set_cmd_defaults()
567
568 #-----------------------------------------------------------------------------
569 # make sure there's either a .lyx or a .tex file to work with
570 # returns a stripped name (without .lyx or .tex extension) of the file
571 sub check_file_exists {
572 my($file_in)=@_;
573 my($base_file);
574
575 $_=$file_in;
576 if (/\.lyx$/) { s/\.lyx$// }
577 elsif (/\.tex$/) { s/\.tex$// }
578 $base_file=$_;
579 unless (-e "${base_file}.lyx" or -e "${base_file}.tex") {
580 die "I can't find a LyX or LaTeX file to work with!\nAborting...\n\n";
581 }
582 return $base_file;
583 } # end of check_file_exists()
584
585 #-----------------------------------------------------------------------------
586 sub check_targets{
587 my($file,$tag,$built,$failed)=@_;
588 my($success)=0;
589
590 $tag .= ' ';
591 if (-s $file) { $$built .= $tag; $success=1; }
592 else { $$failed .= $tag }
593 return $success;
594 } # end of check_targets()
595
596 #-----------------------------------------------------------------------------
597 # do extra cleaning of aux, toc, log files generated during running
598 sub tidy_up {
599 my($tidy,$aux,$log,$out,$toc,@latex_from_lyx)=@_;
600
601 lyxport_info("Cleanup of leftover auxiliary files");
602 print "Removing files: $aux, $log, $out, $toc\n";
603 unlink ($aux,$log,$out,$toc);
604 if ($tidy>1 and @latex_from_lyx) {
605 lyxport_info("Extra cleanup: removing LaTeX file(s) @latex_from_lyx");
606 unlink(@latex_from_lyx);
607 foreach (@latex_from_lyx) {
608 s/\.tex$/\.aux/;
609 if (-e) {
610 print "Removing aux file $_\n";
611 unlink($_);
612 }
613 }
614 }
615 } # end of tidy_up()
616
617 #-----------------------------------------------------------------------------
618 sub lyxport_info {
619 my ($target)=@_;
620
621 print "\n",'*'x75,"\n";
622 print "<lyxport> $target\n\n";
623 } # end of lyxport_info()
624
625 #-----------------------------------------------------------------------------
626 sub final_diagnostics{
627 my($file_in,$status,$targets_built,$targets_failed)=@_;
628
629 lyxport_info("All done!");
630 print "Input file: $file_in\n\n";
631 print "Targets built : $targets_built\n\n";
632 if ($targets_failed) {
633 print "PROBLEM!\nTargets failed: $targets_failed\n\n";
634 }
635 print "Diagnostics of build process:\n\n$status\nBye!\n\n";
636 } # end of final_diagnostics()
637
638
639 #************************ end of code for <lyxport> *******************
640
641 __END__
642
643 =pod
644
645 =head1 DESCRIPTION
646
647 =head2 Purpose
648
649 LyX ( http://www.lyx.org ) is a wonderful document processor, which can produce
650 from a single source multiple versions for different purposes: a PostScript
651 file for printing on a Unix-type system, a PDF file for distribution across
652 multiple operating systems, or an HTML file for Internet display. It
653 accomplishes this by exporting its own file format to a LaTeX file and then
654 running various converters on this resulting file.
655
656 However, it turns out that this process isn't exactly foolproof, as these
657 converters have all sorts of little quirks which can produce anything from
658 surprises in the way the final result looks like to outright failure of the
659 export process. The purpose of B<lyxport> is to serve as a "smart wrapper"
660 around those export facilities which LyX normally uses, trying to massage the
661 LaTeX file that everything starts from in the hopes of having better success
662 in producing HTML and PDF (PostScript usually poses no problems).
663
664 B<lyxport> also allows you to keep around only the LyX file, and possibly any
665 ancillary figure files. B<lyxport> takes care of generating (and removing
666 afterwards if instructed to do so) any intermediate files necessary for the
667 export process.
668
669 For example, in order to make PDF from a LaTeX file, any included eps figures
670 need to be converted to pdf format. But LyX likes to have the figures in eps
671 format for on-screen display, which is a great feature to have. B<lyxport>
672 allows you to keep your LyX file as usual (with references to .eps figures)
673 and will make .pdf versions of any included figure on the fly as needed. You
674 can even ask it to remove those pdf files after it finishes, if you really
675 want to maintain a minimum of files around (though it will have to remake them
676 again if you ever need to update your pdf exported document).
677
678 =head2 Command line use
679
680 If you simply type B<lyxport> F<file>, it will try to make PostScript, HTML,
681 and PDF versions of your file, putting them all in a single directory named
682 F<file> (without a .lyx or .tex extension if your file had one). But it has
683 L<command line options|OPTIONS AND ARGUMENTS> for making only the
684 formats you want, and fairly detailed control over its behavior.
685
686 =head2 If you don't have LyX
687
688 Despite its name, if you are a regular LaTeX user and don't even have LyX
689 installed in your system, B<lyxport> can still be useful to you. In fact,
690 B<lyxport> only uses LyX once in each run: if there is no F<file.tex> or if
691 F<file.lyx> file is newer than F<file.tex>, B<lyxport> updates F<file.tex>
692 from F<file.lyx>. But if there is no F<file.lyx> at all it will simply use
693 F<file.tex> and proceed with all its functionality intact.
694
695 =cut
696 ###########################################################################
697 =pod
698
699 =head1 OPTIONS AND ARGUMENTS
700
701 Single letter options (preceded by a single dash B<->) can be bundled: B<-pf>
702 is equivalent to B<-p -f>. Long options (preceded by two dashes B<-->) can be
703 abbreviated to as few letters as needed to clear ambiguity.
704
705 =over
706
707 =item B<-r --runs> I<NUM>
708
709 Set number of latex runs by hand (otherwise auto-determined).
710
711 =item B<-o --opts_l2h> I<'string'>
712
713 String with options to be passed to B<latex2html>. This string should be
714 protected by single quotes to allow double quotes inside of it.
715
716 For example, if you want to pass to B<latex2html> the option B<-info "my
717 info"> you can do so with B<lyxport -o ' -info "my info" '> (the extra spaces
718 around the quote marks are not needed, they are here only for the sake of
719 clarity).
720
721 B<latex2html> has I<many> command-line options. For a project you are working
722 constantly on, it may be more convenient to permanently set some of those
723 options via a file called F<.latex2html-init> which B<latex2html> always
724 reads at startup. See the B<latex2html> man page or the excellent online
725 documentation kept at http://www-texdev.mpce.mq.edu.au/l2h/docs/manual for
726 full details.
727
728 =item B<-h --html>
729
730 Export to HTML.
731
732 =item B<-p --ps>
733
734 Export to PostScript.
735
736 =item B<-f --pdf>
737
738 Export to PDF. See below the section L<PDF GENERATION> for details on how to
739 obtain nice-looking PDF from your LaTeX sources.
740
741 If none of the three above options is specified, the default behavior is to
742 export I<all> three formats. If any is given, then only those formats
743 explicitly specified will be produced (e.g. B<-h -f> makes HTML and PDF only,
744 but not PostScript).
745
746 =item B<--leave>
747
748 By default lyxport moves the resulting PostScript and PDF files into the
749 directory containing the HTML results (if it was created). This option tells
750 it to leave them in the current directory.
751
752 =item B<-c --clean>
753
754 Do a clean start export, removing first any html directory, .aux, .log
755 and .toc files which may have been left from previous runs.
756
757 =item B<-t --tidy>
758
759 B<lyxport> will tidy up I<after> itself, removing .aux, .log and .toc files left
760 in the current directory. Use this only for "final" publication of documents, as
761 those files are otherwise useful to shorten the time of runs.
762
763 This option is incremental: you can call it twice (you can bundle it as
764 B<-tt>). If called twice, B<lyxport> will remove also the LaTeX file
765 associated with your LyX file, but I<only if> B<lyxport> I<itself created it
766 in the same run>. This behavior is meant to be a safety net, so that
767 B<lyxport> doesn't accidentally remove LaTeX files which you may have manually
768 modified in some way.
769
770 So if this option is called twice, you can start with a LyX file named F<file.lyx>
771 and end up only with your original file plus a single directory named F<file> which
772 will contain F<file.html>, F<file.ps> and F<file.pdf> (plus some ancillary stuff for
773 the html version). This mode of operation is obviously provided for the neatness
774 freaks amongst us.
775
776 =item B<-d --debug>
777
778 Debugging mode: B<lyxport> will leave I<all> temporary files it creates lying
779 around. If a particular target refuses to build, you can then try to run the
780 respective commands on the temporary files manually, and possibly diagnose the
781 source of the problem.
782
783 This option will override any calls made to option B<--tidy>.
784
785 =item B<-l --cld>
786
787 Special command-line debugging mode: only prints (in a rather primitive form)
788 the names and values of all command-line options which were set. Useful for
789 finding problems with complicated option strings being passed to
790 B<latex2html>.
791
792 =item B<--help>
793
794 Print this help and quit.
795
796 =item B<-m --man>
797
798 Print a complete man page. B<lyxport> is documented using embedded pod
799 strings, so you can see its full documentation using the command B<perldoc
800 lyxport>.
801
802 You can also convert this documentation to other formats using the
803 I<pod2_anything> family of converters (L<pod2html>, L<pod2latex>, L<pod2man>
804 and L<pod2text>). See their respective man pages for details.
805
806 Note that if you installed B<lyxport> properly, you should already have a man
807 page available, plus html and plain text versions of the documents. These are
808 by default installed to a directory named F</usr/local/doc/lyxport-XXX>, where
809 F<XXX> is the version number. At installation time, you may manually change
810 the F</usr/local> prefix. Consult your local documents or ask your system
811 administrator for details on the specifics of your configuration.
812
813 =item B<-v --version>
814
815 Print version information and quit.
816
817 =item B<filename>
818
819 The given filename may have a .lyx or .tex extension (or none at
820 all). I<lyxport> will update the tex file from the lyx file if necessary.
821
822 B<lyxport> accepts only I<one> filename at a time.
823
824 =back
825
826 =cut
827 ###########################################################################
828 =pod
829
830 =head1 INTEGRATION WITH LyX
831
832 If you find that B<lyxport> is more succesful in exporting your files than
833 LyX's default calls to B<latex2html> and B<pdflatex>, you can modify LyX to
834 use B<lyxport> as its conversion routine. For LyX versions 1.1.6 and above, go
835 to C<< Edit->Preferences->Converters->Converters >> and specify B<lyxport> as your
836 converter for C<< LaTeX->HTML >> and C<< LaTeX->PDF >>. LyX's convention
837 is to call B<$$i> the current file.
838
839 For example, if you want to setup B<lyxport> to be your PDF export filter
840 under LyX, in the C<Converters> dialog, in the C<< LaTeX->PDF(pdflatex) >>
841 option, set:
842
843 lyxport --pdf $$i
844
845 This way you'll be able to export to pdf directly from within LyX, even if
846 your figures are in eps format.
847
848 LyX's C<Converters> dialog is a bit confusing: after making changes, you must
849 first press the C<Modify> button for your changes to actually be recorded, and
850 then C<Save>.
851
852 You can similarly set up B<lyxport> to be your LaTeX to HTML converter.
853
854 For LyX versions earlier than 1.1.6 (which didn't have the new Preferences
855 dialog) these same options can be configured via your LyX defaults file. See
856 the LyX documentation for details.
857
858 =cut
859 ###########################################################################
860 =pod
861
862 =head1 PDF GENERATION
863
864 =head2 Fonts
865
866 Normally PDF documents made on Unix-type systems from LaTeX sources produce
867 horrible looking fonts when viewed with Adobe's own Acrobat Reader. I don't
868 know the many intricacies of the problem (you can search for the details on
869 your own). I'll simply list here the trick that has helped I<me> solve the
870 font problem. Try it, your mileage may vary.
871
872 =over
873
874 =item 1
875
876 In your home directory, make (or modify it if it already exists) a file
877 named F<.dvipsrc> which must contain the lines:
878
879 p+ psfonts.cmz
880 p+ psfonts.amz
881
882 =item 2
883
884 Make sure that the LaTeX preamble of your LyX file (or the part before
885 C<\begin{document}> if you are using straight LaTeX files) contains:
886
887 \usepackage[T1]{fontenc}
888 \usepackage{ae,aecompl}
889
890 This will guarantee that T1 encoded fonts come out looking good in the final PDF.
891
892 =back
893
894 =head2 Figures
895
896 B<pdflatex> (if I understand correctly) only accepts filenames with a single
897 B<.> in them, and only uses graphic files with extensions pdf, png, jpg and
898 tif (all lowercase). B<lyxport> will do its best to analyze your latex file
899 and try to change references to figures to accommodate B<pdflatex>, by
900 creating temporary copies of your image files if necessary.
901
902 Ideally, you should be able to have for example a figure called F<fig.1.JPG>
903 along with a F<fig.1.eps> (for B<lyx> to preview it), and B<lyxport> would
904 export a pdf document without leaving any more files after itself, even though
905 it temporarily had to create F<fig_1.jpg> to make B<pdflatex> happy. As I
906 said, ideally... If things don't quite work, try the B<--debug> option. If you
907 find a fix for the problem, mail it to me: fperez@pizero.colorado.edu
908
909 =head2 Links
910
911 In order for URLs and similar elements to produce proper active links in the
912 PDF document, you need to include in your LaTeX preamble the line
913
914 \usepackage{hyperref}
915
916 =cut
917 ###########################################################################
918 =pod
919
920 =head1 REQUIRES
921
922 B<lyxport> relies on some programs listed below, for the reasons indicated:
923
924 =over
925
926 =item B<lyx>
927
928 To make LaTeX files from LyX files. Tested with lyx version 1.1.6fix1, should
929 work with earlier versions (perhaps with minor changes to the way LyX is called).
930
931 =item B<latex>
932
933 To produce PostScript and for latex2html to work properly (cross-references).
934
935 =item B<dvips>
936
937 For making PostScript output.
938
939 =item B<latex2html>
940
941 For generating HTML from latex sources.
942
943 =item B<pdflatex>
944
945 For making PDF output from a latex file with proper cross-referencing and
946 internal document links.
947
948 =item B<epstopdf>
949
950 A Perl script to automatically generate pdf versions of eps figures included
951 in lyx files. It is more robust in its handling of various eps quirks than a
952 straight call to B<ps2pdf>.
953
954 =item B<perl>
955
956 Well, it's a Perl script after all, isn't it?
957
958 =back
959
960 However, partial use of B<lyxport> is still possible without some of these
961 components. If for example you don't have B<latex2html> in your system, you
962 can still use B<lyxport> to produce PostScript and PDF. Various combinations
963 are possible.
964
965 =head2 Portability
966
967 There are calls in B<lyxport> to some Unix commands like B<rm -rf>. For this
968 reason it is not totally portable. These calls are however reasonably few and
969 could be eliminated if there is enough demand by replacing them with
970 equivalent Perl code. It's just more work...
971
972 =cut
973 ###########################################################################
974 =pod
975
976 =head1 TO DO
977
978 =over
979
980 =item *
981
982 Build rpm for more convenient installation.
983
984 =item *
985
986 Clean up the C<improve_tex4html()> code for readability.
987
988 =back
989
990 =cut
991 ###########################################################################
992 =pod
993
994 =head1 VERSION
995
996 This is B<lyxport> version 0.3.1
997
998 =cut
999 ###########################################################################
1000 =pod
1001
1002 =head1 AUTHOR
1003
1004 Fernando Pérez E<lt>fperez@pizero.colorado.eduE<gt>.
1005
1006 Please email me with comments, suggestions, bugfixes, etc.
1007
1008 The most current version of B<lyxport> should always be available at
1009 http://www-hep.colorado.edu/~fperez/lyxport
1010
1011 =cut
1012 ###########################################################################
1013 =pod
1014
1015 =head1 ACKNOWLEDGEMENTS
1016
1017 Inspired on the B<lyx2html> script by Steffen Evers
1018 E<lt>tron@cs.tu-berlin.deE<gt>. Some of the code is a blatant ripoff of
1019 Steffen's code, using B<s2p> to get Perl versions of his original B<sed>
1020 scripts.
1021
1022 =cut
1023 ###########################################################################
1024 =pod
1025
1026
1027 =head1 COPYRIGHT AND DISCLAIMER
1028
1029 This program is Copyright 2001 by Fernando Pérez.
1030
1031 This program is free software; you can redistribute it and/or modify it under
1032 the terms of the GNU General Public License as published by the Free Software
1033 Foundation; either version 2 of the License, or (at your option) any later
1034 version.
1035
1036 This program is distributed in the hope that it will be useful,
1037 but WITHOUT ANY WARRANTY; without even the implied warranty of
1038 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1039 GNU General Public License for more details.
1040
1041 If you do not have a copy of the GNU General Public License write to
1042 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
1043 MA 02139, USA.
1044
1045 If the author of this software was too lazy to include the full GPL text along
1046 with the code, you can find it at: http://www.gnu.org/copyleft/gpl.html
1047
1048 =cut
1049 #************************** end of file <lyxport> **********************
General Comments 0
You need to be logged in to leave comments. Login now