Show More
@@ -1,72 +1,74 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | One of Python's nicest features is its interactive interpreter. This allows |
|
6 | 6 | very fast testing of ideas without the overhead of creating test files as is |
|
7 | 7 | typical in most programming languages. However, the interpreter supplied with |
|
8 | 8 | the standard Python distribution is fairly primitive (and IDLE isn't really |
|
9 | 9 | much better). |
|
10 | 10 | |
|
11 | 11 | IPython tries to: |
|
12 | 12 | |
|
13 | 13 | i - provide an efficient environment for interactive work in Python |
|
14 | 14 | programming. It tries to address what we see as shortcomings of the standard |
|
15 | 15 | Python prompt, and adds many features to make interactive work much more |
|
16 | 16 | efficient. |
|
17 | 17 | |
|
18 | 18 | ii - offer a flexible framework so that it can be used as the base |
|
19 | 19 | environment for other projects and problems where Python can be the |
|
20 | 20 | underlying language. Specifically scientific environments like Mathematica, |
|
21 | 21 | IDL and Mathcad inspired its design, but similar ideas can be useful in many |
|
22 | 22 | fields. Python is a fabulous language for implementing this kind of system |
|
23 | 23 | (due to its dynamic and introspective features), and with suitable libraries |
|
24 | 24 | entire systems could be built leveraging Python's power. |
|
25 | 25 | |
|
26 | 26 | iii - serve as an embeddable, ready to go interpreter for your own programs. |
|
27 | 27 | |
|
28 | 28 | IPython requires Python 2.3 or newer. |
|
29 | 29 | |
|
30 |
$Id: __init__.py 239 |
|
|
30 | $Id: __init__.py 2398 2007-05-26 10:20:14Z vivainio $""" | |
|
31 | 31 | |
|
32 | 32 | #***************************************************************************** |
|
33 | 33 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
34 | 34 | # |
|
35 | 35 | # Distributed under the terms of the BSD License. The full license is in |
|
36 | 36 | # the file COPYING, distributed as part of this software. |
|
37 | 37 | #***************************************************************************** |
|
38 | 38 | |
|
39 | 39 | # Enforce proper version requirements |
|
40 | 40 | import sys |
|
41 | 41 | |
|
42 | 42 | if sys.version[0:3] < '2.3': |
|
43 | 43 | raise ImportError('Python Version 2.3 or above is required for IPython.') |
|
44 | 44 | |
|
45 | 45 | # Make it easy to import extensions - they are always directly on pythonpath. |
|
46 | 46 | # Therefore, non-IPython modules can be added to Extensions directory |
|
47 | 47 | import os |
|
48 | 48 | sys.path.append(os.path.dirname(__file__) + "/Extensions") |
|
49 | 49 | |
|
50 | 50 | # Define what gets imported with a 'from IPython import *' |
|
51 | __all__ = ['deep_reload','genutils','ipstruct','ultraTB','DPyGetOpt', | |
|
51 | __all__ = ['ipapi','generics','deep_reload','genutils','ipstruct','ultraTB','DPyGetOpt', | |
|
52 | 52 | 'Itpl','hooks','ConfigLoader','OutputTrap','Release','Shell', |
|
53 | 53 | 'platutils','platutils_win32','platutils_posix','platutils_dummy', |
|
54 |
|
|
|
54 | 'rlineimpl', 'strdispatch'] | |
|
55 | 55 | |
|
56 | 56 | # Load __all__ in IPython namespace so that a simple 'import IPython' gives |
|
57 | 57 | # access to them via IPython.<name> |
|
58 | 58 | glob,loc = globals(),locals() |
|
59 | 59 | for name in __all__: |
|
60 | 60 | __import__(name,glob,loc,[]) |
|
61 | 61 | |
|
62 | import Shell | |
|
63 | ||
|
62 | 64 | # Release data |
|
63 | 65 | from IPython import Release # do it explicitly so pydoc can see it - pydoc bug |
|
64 | 66 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ |
|
65 | 67 | ( Release.authors['Fernando'] + Release.authors['Janko'] + \ |
|
66 | 68 | Release.authors['Nathan'] ) |
|
67 | 69 | __license__ = Release.license |
|
68 | 70 | __version__ = Release.version |
|
69 | 71 | __revision__ = Release.revision |
|
70 | 72 | |
|
71 | 73 | # Namespace cleanup |
|
72 | 74 | del name,glob,loc |
@@ -1,28 +1,28 b'' | |||
|
1 | 1 | from IPython.ipapi import TryNext |
|
2 | 2 | from IPython.external.simplegeneric import generic |
|
3 | 3 | |
|
4 |
|
|
|
4 | ''' 'Generic' functions for extending IPython | |
|
5 | 5 | |
|
6 | 6 | See http://cheeseshop.python.org/pypi/simplegeneric |
|
7 | 7 | |
|
8 | 8 | Here's an example from genutils.py: |
|
9 | 9 | |
|
10 | 10 | def print_lsstring(arg): |
|
11 | 11 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
12 | 12 | print "LSString (.p, .n, .l, .s available). Value:" |
|
13 | 13 |
|
|
14 | 14 |
|
|
15 | 15 |
|
|
16 | 16 |
|
|
17 | 17 |
|
|
18 | 18 |
|
|
19 | 19 |
|
|
20 | """ | |
|
20 | ''' | |
|
21 | 21 | |
|
22 | 22 | @generic |
|
23 | 23 | def result_display(result): |
|
24 | 24 | """ print the result of computation """ |
|
25 | 25 | raise TryNext |
|
26 | 26 | |
|
27 | 27 | result_display = generic(result_display) |
|
28 | 28 |
@@ -1,1783 +1,1781 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | General purpose utilities. |
|
4 | 4 | |
|
5 | 5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
6 | 6 | these things are also convenient when working at the command line. |
|
7 | 7 | |
|
8 |
$Id: genutils.py 239 |
|
|
8 | $Id: genutils.py 2398 2007-05-26 10:20:14Z vivainio $""" | |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
19 | 19 | __license__ = Release.license |
|
20 | 20 | |
|
21 | 21 | #**************************************************************************** |
|
22 | 22 | # required modules from the Python standard library |
|
23 | 23 | import __main__ |
|
24 | 24 | import commands |
|
25 | 25 | import os |
|
26 | 26 | import re |
|
27 | 27 | import shlex |
|
28 | 28 | import shutil |
|
29 | 29 | import sys |
|
30 | 30 | import tempfile |
|
31 | 31 | import time |
|
32 | 32 | import types |
|
33 | 33 | import warnings |
|
34 | 34 | |
|
35 | 35 | # Other IPython utilities |
|
36 | 36 | import IPython |
|
37 | 37 | from IPython.Itpl import Itpl,itpl,printpl |
|
38 | 38 | from IPython import DPyGetOpt |
|
39 | 39 | from IPython.generics import result_display |
|
40 | 40 | from path import path |
|
41 | 41 | if os.name == "nt": |
|
42 | 42 | from IPython.winconsole import get_console_size |
|
43 | 43 | |
|
44 | 44 | #**************************************************************************** |
|
45 | 45 | # Exceptions |
|
46 | 46 | class Error(Exception): |
|
47 | 47 | """Base class for exceptions in this module.""" |
|
48 | 48 | pass |
|
49 | 49 | |
|
50 | 50 | #---------------------------------------------------------------------------- |
|
51 | 51 | class IOStream: |
|
52 | 52 | def __init__(self,stream,fallback): |
|
53 | 53 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
54 | 54 | stream = fallback |
|
55 | 55 | self.stream = stream |
|
56 | 56 | self._swrite = stream.write |
|
57 | 57 | self.flush = stream.flush |
|
58 | 58 | |
|
59 | 59 | def write(self,data): |
|
60 | 60 | try: |
|
61 | 61 | self._swrite(data) |
|
62 | 62 | except: |
|
63 | 63 | try: |
|
64 | 64 | # print handles some unicode issues which may trip a plain |
|
65 | 65 | # write() call. Attempt to emulate write() by using a |
|
66 | 66 | # trailing comma |
|
67 | 67 | print >> self.stream, data, |
|
68 | 68 | except: |
|
69 | 69 | # if we get here, something is seriously broken. |
|
70 | 70 | print >> sys.stderr, \ |
|
71 | 71 | 'ERROR - failed to write data to stream:', self.stream |
|
72 | 72 | |
|
73 | 73 | def close(self): |
|
74 | 74 | pass |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | class IOTerm: |
|
78 | 78 | """ Term holds the file or file-like objects for handling I/O operations. |
|
79 | 79 | |
|
80 | 80 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
81 | 81 | Windows they can can replaced to allow editing the strings before they are |
|
82 | 82 | displayed.""" |
|
83 | 83 | |
|
84 | 84 | # In the future, having IPython channel all its I/O operations through |
|
85 | 85 | # this class will make it easier to embed it into other environments which |
|
86 | 86 | # are not a normal terminal (such as a GUI-based shell) |
|
87 | 87 | def __init__(self,cin=None,cout=None,cerr=None): |
|
88 | 88 | self.cin = IOStream(cin,sys.stdin) |
|
89 | 89 | self.cout = IOStream(cout,sys.stdout) |
|
90 | 90 | self.cerr = IOStream(cerr,sys.stderr) |
|
91 | 91 | |
|
92 | 92 | # Global variable to be used for all I/O |
|
93 | 93 | Term = IOTerm() |
|
94 | 94 | |
|
95 | 95 | import IPython.rlineimpl as readline |
|
96 | 96 | # Remake Term to use the readline i/o facilities |
|
97 | 97 | if sys.platform == 'win32' and readline.have_readline: |
|
98 | 98 | |
|
99 | 99 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
100 | 100 | |
|
101 | 101 | |
|
102 | 102 | #**************************************************************************** |
|
103 | 103 | # Generic warning/error printer, used by everything else |
|
104 | 104 | def warn(msg,level=2,exit_val=1): |
|
105 | 105 | """Standard warning printer. Gives formatting consistency. |
|
106 | 106 | |
|
107 | 107 | Output is sent to Term.cerr (sys.stderr by default). |
|
108 | 108 | |
|
109 | 109 | Options: |
|
110 | 110 | |
|
111 | 111 | -level(2): allows finer control: |
|
112 | 112 | 0 -> Do nothing, dummy function. |
|
113 | 113 | 1 -> Print message. |
|
114 | 114 | 2 -> Print 'WARNING:' + message. (Default level). |
|
115 | 115 | 3 -> Print 'ERROR:' + message. |
|
116 | 116 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
117 | 117 | |
|
118 | 118 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
119 | 119 | warning. Ignored for all other levels.""" |
|
120 | 120 | |
|
121 | 121 | if level>0: |
|
122 | 122 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
123 | 123 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
124 | 124 | if level == 4: |
|
125 | 125 | print >> Term.cerr,'Exiting.\n' |
|
126 | 126 | sys.exit(exit_val) |
|
127 | 127 | |
|
128 | 128 | def info(msg): |
|
129 | 129 | """Equivalent to warn(msg,level=1).""" |
|
130 | 130 | |
|
131 | 131 | warn(msg,level=1) |
|
132 | 132 | |
|
133 | 133 | def error(msg): |
|
134 | 134 | """Equivalent to warn(msg,level=3).""" |
|
135 | 135 | |
|
136 | 136 | warn(msg,level=3) |
|
137 | 137 | |
|
138 | 138 | def fatal(msg,exit_val=1): |
|
139 | 139 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
140 | 140 | |
|
141 | 141 | warn(msg,exit_val=exit_val,level=4) |
|
142 | 142 | |
|
143 | 143 | #--------------------------------------------------------------------------- |
|
144 | 144 | # Debugging routines |
|
145 | 145 | # |
|
146 | 146 | def debugx(expr,pre_msg=''): |
|
147 | 147 | """Print the value of an expression from the caller's frame. |
|
148 | 148 | |
|
149 | 149 | Takes an expression, evaluates it in the caller's frame and prints both |
|
150 | 150 | the given expression and the resulting value (as well as a debug mark |
|
151 | 151 | indicating the name of the calling function. The input must be of a form |
|
152 | 152 | suitable for eval(). |
|
153 | 153 | |
|
154 | 154 | An optional message can be passed, which will be prepended to the printed |
|
155 | 155 | expr->value pair.""" |
|
156 | 156 | |
|
157 | 157 | cf = sys._getframe(1) |
|
158 | 158 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
159 | 159 | eval(expr,cf.f_globals,cf.f_locals)) |
|
160 | 160 | |
|
161 | 161 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
162 | 162 | #def debugx(expr,pre_msg=''): pass |
|
163 | 163 | |
|
164 | 164 | #---------------------------------------------------------------------------- |
|
165 | 165 | StringTypes = types.StringTypes |
|
166 | 166 | |
|
167 | 167 | # Basic timing functionality |
|
168 | 168 | |
|
169 | 169 | # If possible (Unix), use the resource module instead of time.clock() |
|
170 | 170 | try: |
|
171 | 171 | import resource |
|
172 | 172 | def clocku(): |
|
173 | 173 | """clocku() -> floating point number |
|
174 | 174 | |
|
175 | 175 | Return the *USER* CPU time in seconds since the start of the process. |
|
176 | 176 | This is done via a call to resource.getrusage, so it avoids the |
|
177 | 177 | wraparound problems in time.clock().""" |
|
178 | 178 | |
|
179 | 179 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
180 | 180 | |
|
181 | 181 | def clocks(): |
|
182 | 182 | """clocks() -> floating point number |
|
183 | 183 | |
|
184 | 184 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
185 | 185 | This is done via a call to resource.getrusage, so it avoids the |
|
186 | 186 | wraparound problems in time.clock().""" |
|
187 | 187 | |
|
188 | 188 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
189 | 189 | |
|
190 | 190 | def clock(): |
|
191 | 191 | """clock() -> floating point number |
|
192 | 192 | |
|
193 | 193 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
194 | 194 | the process. This is done via a call to resource.getrusage, so it |
|
195 | 195 | avoids the wraparound problems in time.clock().""" |
|
196 | 196 | |
|
197 | 197 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
198 | 198 | return u+s |
|
199 | 199 | |
|
200 | 200 | def clock2(): |
|
201 | 201 | """clock2() -> (t_user,t_system) |
|
202 | 202 | |
|
203 | 203 | Similar to clock(), but return a tuple of user/system times.""" |
|
204 | 204 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
205 | 205 | |
|
206 | 206 | except ImportError: |
|
207 | 207 | # There is no distinction of user/system time under windows, so we just use |
|
208 | 208 | # time.clock() for everything... |
|
209 | 209 | clocku = clocks = clock = time.clock |
|
210 | 210 | def clock2(): |
|
211 | 211 | """Under windows, system CPU time can't be measured. |
|
212 | 212 | |
|
213 | 213 | This just returns clock() and zero.""" |
|
214 | 214 | return time.clock(),0.0 |
|
215 | 215 | |
|
216 | 216 | def timings_out(reps,func,*args,**kw): |
|
217 | 217 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
218 | 218 | |
|
219 | 219 | Execute a function reps times, return a tuple with the elapsed total |
|
220 | 220 | CPU time in seconds, the time per call and the function's output. |
|
221 | 221 | |
|
222 | 222 | Under Unix, the return value is the sum of user+system time consumed by |
|
223 | 223 | the process, computed via the resource module. This prevents problems |
|
224 | 224 | related to the wraparound effect which the time.clock() function has. |
|
225 | 225 | |
|
226 | 226 | Under Windows the return value is in wall clock seconds. See the |
|
227 | 227 | documentation for the time module for more details.""" |
|
228 | 228 | |
|
229 | 229 | reps = int(reps) |
|
230 | 230 | assert reps >=1, 'reps must be >= 1' |
|
231 | 231 | if reps==1: |
|
232 | 232 | start = clock() |
|
233 | 233 | out = func(*args,**kw) |
|
234 | 234 | tot_time = clock()-start |
|
235 | 235 | else: |
|
236 | 236 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
237 | 237 | start = clock() |
|
238 | 238 | for dummy in rng: func(*args,**kw) |
|
239 | 239 | out = func(*args,**kw) # one last time |
|
240 | 240 | tot_time = clock()-start |
|
241 | 241 | av_time = tot_time / reps |
|
242 | 242 | return tot_time,av_time,out |
|
243 | 243 | |
|
244 | 244 | def timings(reps,func,*args,**kw): |
|
245 | 245 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
246 | 246 | |
|
247 | 247 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
248 | 248 | time in seconds and the time per call. These are just the first two values |
|
249 | 249 | in timings_out().""" |
|
250 | 250 | |
|
251 | 251 | return timings_out(reps,func,*args,**kw)[0:2] |
|
252 | 252 | |
|
253 | 253 | def timing(func,*args,**kw): |
|
254 | 254 | """timing(func,*args,**kw) -> t_total |
|
255 | 255 | |
|
256 | 256 | Execute a function once, return the elapsed total CPU time in |
|
257 | 257 | seconds. This is just the first value in timings_out().""" |
|
258 | 258 | |
|
259 | 259 | return timings_out(1,func,*args,**kw)[0] |
|
260 | 260 | |
|
261 | 261 | #**************************************************************************** |
|
262 | 262 | # file and system |
|
263 | 263 | |
|
264 | 264 | def arg_split(s,posix=False): |
|
265 | 265 | """Split a command line's arguments in a shell-like manner. |
|
266 | 266 | |
|
267 | 267 | This is a modified version of the standard library's shlex.split() |
|
268 | 268 | function, but with a default of posix=False for splitting, so that quotes |
|
269 | 269 | in inputs are respected.""" |
|
270 | 270 | |
|
271 | 271 | # XXX - there may be unicode-related problems here!!! I'm not sure that |
|
272 | 272 | # shlex is truly unicode-safe, so it might be necessary to do |
|
273 | 273 | # |
|
274 | 274 | # s = s.encode(sys.stdin.encoding) |
|
275 | 275 | # |
|
276 | 276 | # first, to ensure that shlex gets a normal string. Input from anyone who |
|
277 | 277 | # knows more about unicode and shlex than I would be good to have here... |
|
278 | 278 | lex = shlex.shlex(s, posix=posix) |
|
279 | 279 | lex.whitespace_split = True |
|
280 | 280 | return list(lex) |
|
281 | 281 | |
|
282 | 282 | def system(cmd,verbose=0,debug=0,header=''): |
|
283 | 283 | """Execute a system command, return its exit status. |
|
284 | 284 | |
|
285 | 285 | Options: |
|
286 | 286 | |
|
287 | 287 | - verbose (0): print the command to be executed. |
|
288 | 288 | |
|
289 | 289 | - debug (0): only print, do not actually execute. |
|
290 | 290 | |
|
291 | 291 | - header (''): Header to print on screen prior to the executed command (it |
|
292 | 292 | is only prepended to the command, no newlines are added). |
|
293 | 293 | |
|
294 | 294 | Note: a stateful version of this function is available through the |
|
295 | 295 | SystemExec class.""" |
|
296 | 296 | |
|
297 | 297 | stat = 0 |
|
298 | 298 | if verbose or debug: print header+cmd |
|
299 | 299 | sys.stdout.flush() |
|
300 | 300 | if not debug: stat = os.system(cmd) |
|
301 | 301 | return stat |
|
302 | 302 | |
|
303 | 303 | # This function is used by ipython in a lot of places to make system calls. |
|
304 | 304 | # We need it to be slightly different under win32, due to the vagaries of |
|
305 | 305 | # 'network shares'. A win32 override is below. |
|
306 | 306 | |
|
307 | 307 | def shell(cmd,verbose=0,debug=0,header=''): |
|
308 | 308 | """Execute a command in the system shell, always return None. |
|
309 | 309 | |
|
310 | 310 | Options: |
|
311 | 311 | |
|
312 | 312 | - verbose (0): print the command to be executed. |
|
313 | 313 | |
|
314 | 314 | - debug (0): only print, do not actually execute. |
|
315 | 315 | |
|
316 | 316 | - header (''): Header to print on screen prior to the executed command (it |
|
317 | 317 | is only prepended to the command, no newlines are added). |
|
318 | 318 | |
|
319 | 319 | Note: this is similar to genutils.system(), but it returns None so it can |
|
320 | 320 | be conveniently used in interactive loops without getting the return value |
|
321 | 321 | (typically 0) printed many times.""" |
|
322 | 322 | |
|
323 | 323 | stat = 0 |
|
324 | 324 | if verbose or debug: print header+cmd |
|
325 | 325 | # flush stdout so we don't mangle python's buffering |
|
326 | 326 | sys.stdout.flush() |
|
327 | 327 | if not debug: |
|
328 | 328 | os.system(cmd) |
|
329 | 329 | |
|
330 | 330 | # override shell() for win32 to deal with network shares |
|
331 | 331 | if os.name in ('nt','dos'): |
|
332 | 332 | |
|
333 | 333 | shell_ori = shell |
|
334 | 334 | |
|
335 | 335 | def shell(cmd,verbose=0,debug=0,header=''): |
|
336 | 336 | if os.getcwd().startswith(r"\\"): |
|
337 | 337 | path = os.getcwd() |
|
338 | 338 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
339 | 339 | # as cmd.exe cannot handle UNC addresses) |
|
340 | 340 | os.chdir("c:") |
|
341 | 341 | # issue pushd to the UNC-share and then run the command |
|
342 | 342 | try: |
|
343 | 343 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
344 | 344 | finally: |
|
345 | 345 | os.chdir(path) |
|
346 | 346 | else: |
|
347 | 347 | shell_ori(cmd,verbose,debug,header) |
|
348 | 348 | |
|
349 | 349 | shell.__doc__ = shell_ori.__doc__ |
|
350 | 350 | |
|
351 | 351 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
352 | 352 | """Dummy substitute for perl's backquotes. |
|
353 | 353 | |
|
354 | 354 | Executes a command and returns the output. |
|
355 | 355 | |
|
356 | 356 | Accepts the same arguments as system(), plus: |
|
357 | 357 | |
|
358 | 358 | - split(0): if true, the output is returned as a list split on newlines. |
|
359 | 359 | |
|
360 | 360 | Note: a stateful version of this function is available through the |
|
361 | 361 | SystemExec class. |
|
362 | 362 | |
|
363 | 363 | This is pretty much deprecated and rarely used, |
|
364 | 364 | genutils.getoutputerror may be what you need. |
|
365 | 365 | |
|
366 | 366 | """ |
|
367 | 367 | |
|
368 | 368 | if verbose or debug: print header+cmd |
|
369 | 369 | if not debug: |
|
370 | 370 | output = os.popen(cmd).read() |
|
371 | 371 | # stipping last \n is here for backwards compat. |
|
372 | 372 | if output.endswith('\n'): |
|
373 | 373 | output = output[:-1] |
|
374 | 374 | if split: |
|
375 | 375 | return output.split('\n') |
|
376 | 376 | else: |
|
377 | 377 | return output |
|
378 | 378 | |
|
379 | 379 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
380 | 380 | """Return (standard output,standard error) of executing cmd in a shell. |
|
381 | 381 | |
|
382 | 382 | Accepts the same arguments as system(), plus: |
|
383 | 383 | |
|
384 | 384 | - split(0): if true, each of stdout/err is returned as a list split on |
|
385 | 385 | newlines. |
|
386 | 386 | |
|
387 | 387 | Note: a stateful version of this function is available through the |
|
388 | 388 | SystemExec class.""" |
|
389 | 389 | |
|
390 | 390 | if verbose or debug: print header+cmd |
|
391 | 391 | if not cmd: |
|
392 | 392 | if split: |
|
393 | 393 | return [],[] |
|
394 | 394 | else: |
|
395 | 395 | return '','' |
|
396 | 396 | if not debug: |
|
397 | 397 | pin,pout,perr = os.popen3(cmd) |
|
398 | 398 | tout = pout.read().rstrip() |
|
399 | 399 | terr = perr.read().rstrip() |
|
400 | 400 | pin.close() |
|
401 | 401 | pout.close() |
|
402 | 402 | perr.close() |
|
403 | 403 | if split: |
|
404 | 404 | return tout.split('\n'),terr.split('\n') |
|
405 | 405 | else: |
|
406 | 406 | return tout,terr |
|
407 | 407 | |
|
408 | 408 | # for compatibility with older naming conventions |
|
409 | 409 | xsys = system |
|
410 | 410 | bq = getoutput |
|
411 | 411 | |
|
412 | 412 | class SystemExec: |
|
413 | 413 | """Access the system and getoutput functions through a stateful interface. |
|
414 | 414 | |
|
415 | 415 | Note: here we refer to the system and getoutput functions from this |
|
416 | 416 | library, not the ones from the standard python library. |
|
417 | 417 | |
|
418 | 418 | This class offers the system and getoutput functions as methods, but the |
|
419 | 419 | verbose, debug and header parameters can be set for the instance (at |
|
420 | 420 | creation time or later) so that they don't need to be specified on each |
|
421 | 421 | call. |
|
422 | 422 | |
|
423 | 423 | For efficiency reasons, there's no way to override the parameters on a |
|
424 | 424 | per-call basis other than by setting instance attributes. If you need |
|
425 | 425 | local overrides, it's best to directly call system() or getoutput(). |
|
426 | 426 | |
|
427 | 427 | The following names are provided as alternate options: |
|
428 | 428 | - xsys: alias to system |
|
429 | 429 | - bq: alias to getoutput |
|
430 | 430 | |
|
431 | 431 | An instance can then be created as: |
|
432 | 432 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
433 | 433 | |
|
434 | 434 | And used as: |
|
435 | 435 | >>> sysexec.xsys('pwd') |
|
436 | 436 | >>> dirlist = sysexec.bq('ls -l') |
|
437 | 437 | """ |
|
438 | 438 | |
|
439 | 439 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
440 | 440 | """Specify the instance's values for verbose, debug and header.""" |
|
441 | 441 | setattr_list(self,'verbose debug header split') |
|
442 | 442 | |
|
443 | 443 | def system(self,cmd): |
|
444 | 444 | """Stateful interface to system(), with the same keyword parameters.""" |
|
445 | 445 | |
|
446 | 446 | system(cmd,self.verbose,self.debug,self.header) |
|
447 | 447 | |
|
448 | 448 | def shell(self,cmd): |
|
449 | 449 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
450 | 450 | |
|
451 | 451 | shell(cmd,self.verbose,self.debug,self.header) |
|
452 | 452 | |
|
453 | 453 | xsys = system # alias |
|
454 | 454 | |
|
455 | 455 | def getoutput(self,cmd): |
|
456 | 456 | """Stateful interface to getoutput().""" |
|
457 | 457 | |
|
458 | 458 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
459 | 459 | |
|
460 | 460 | def getoutputerror(self,cmd): |
|
461 | 461 | """Stateful interface to getoutputerror().""" |
|
462 | 462 | |
|
463 | 463 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
464 | 464 | |
|
465 | 465 | bq = getoutput # alias |
|
466 | 466 | |
|
467 | 467 | #----------------------------------------------------------------------------- |
|
468 | 468 | def mutex_opts(dict,ex_op): |
|
469 | 469 | """Check for presence of mutually exclusive keys in a dict. |
|
470 | 470 | |
|
471 | 471 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
472 | 472 | for op1,op2 in ex_op: |
|
473 | 473 | if op1 in dict and op2 in dict: |
|
474 | 474 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
475 | 475 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
476 | 476 | |
|
477 | 477 | #----------------------------------------------------------------------------- |
|
478 | 478 | def get_py_filename(name): |
|
479 | 479 | """Return a valid python filename in the current directory. |
|
480 | 480 | |
|
481 | 481 | If the given name is not a file, it adds '.py' and searches again. |
|
482 | 482 | Raises IOError with an informative message if the file isn't found.""" |
|
483 | 483 | |
|
484 | 484 | name = os.path.expanduser(name) |
|
485 | 485 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
486 | 486 | name += '.py' |
|
487 | 487 | if os.path.isfile(name): |
|
488 | 488 | return name |
|
489 | 489 | else: |
|
490 | 490 | raise IOError,'File `%s` not found.' % name |
|
491 | 491 | |
|
492 | 492 | #----------------------------------------------------------------------------- |
|
493 | 493 | def filefind(fname,alt_dirs = None): |
|
494 | 494 | """Return the given filename either in the current directory, if it |
|
495 | 495 | exists, or in a specified list of directories. |
|
496 | 496 | |
|
497 | 497 | ~ expansion is done on all file and directory names. |
|
498 | 498 | |
|
499 | 499 | Upon an unsuccessful search, raise an IOError exception.""" |
|
500 | 500 | |
|
501 | 501 | if alt_dirs is None: |
|
502 | 502 | try: |
|
503 | 503 | alt_dirs = get_home_dir() |
|
504 | 504 | except HomeDirError: |
|
505 | 505 | alt_dirs = os.getcwd() |
|
506 | 506 | search = [fname] + list_strings(alt_dirs) |
|
507 | 507 | search = map(os.path.expanduser,search) |
|
508 | 508 | #print 'search list for',fname,'list:',search # dbg |
|
509 | 509 | fname = search[0] |
|
510 | 510 | if os.path.isfile(fname): |
|
511 | 511 | return fname |
|
512 | 512 | for direc in search[1:]: |
|
513 | 513 | testname = os.path.join(direc,fname) |
|
514 | 514 | #print 'testname',testname # dbg |
|
515 | 515 | if os.path.isfile(testname): |
|
516 | 516 | return testname |
|
517 | 517 | raise IOError,'File' + `fname` + \ |
|
518 | 518 | ' not found in current or supplied directories:' + `alt_dirs` |
|
519 | 519 | |
|
520 | 520 | #---------------------------------------------------------------------------- |
|
521 | 521 | def file_read(filename): |
|
522 | 522 | """Read a file and close it. Returns the file source.""" |
|
523 | 523 | fobj = open(filename,'r'); |
|
524 | 524 | source = fobj.read(); |
|
525 | 525 | fobj.close() |
|
526 | 526 | return source |
|
527 | 527 | |
|
528 | 528 | def file_readlines(filename): |
|
529 | 529 | """Read a file and close it. Returns the file source using readlines().""" |
|
530 | 530 | fobj = open(filename,'r'); |
|
531 | 531 | lines = fobj.readlines(); |
|
532 | 532 | fobj.close() |
|
533 | 533 | return lines |
|
534 | 534 | |
|
535 | 535 | #---------------------------------------------------------------------------- |
|
536 | 536 | def target_outdated(target,deps): |
|
537 | 537 | """Determine whether a target is out of date. |
|
538 | 538 | |
|
539 | 539 | target_outdated(target,deps) -> 1/0 |
|
540 | 540 | |
|
541 | 541 | deps: list of filenames which MUST exist. |
|
542 | 542 | target: single filename which may or may not exist. |
|
543 | 543 | |
|
544 | 544 | If target doesn't exist or is older than any file listed in deps, return |
|
545 | 545 | true, otherwise return false. |
|
546 | 546 | """ |
|
547 | 547 | try: |
|
548 | 548 | target_time = os.path.getmtime(target) |
|
549 | 549 | except os.error: |
|
550 | 550 | return 1 |
|
551 | 551 | for dep in deps: |
|
552 | 552 | dep_time = os.path.getmtime(dep) |
|
553 | 553 | if dep_time > target_time: |
|
554 | 554 | #print "For target",target,"Dep failed:",dep # dbg |
|
555 | 555 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
556 | 556 | return 1 |
|
557 | 557 | return 0 |
|
558 | 558 | |
|
559 | 559 | #----------------------------------------------------------------------------- |
|
560 | 560 | def target_update(target,deps,cmd): |
|
561 | 561 | """Update a target with a given command given a list of dependencies. |
|
562 | 562 | |
|
563 | 563 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
564 | 564 | |
|
565 | 565 | This is just a wrapper around target_outdated() which calls the given |
|
566 | 566 | command if target is outdated.""" |
|
567 | 567 | |
|
568 | 568 | if target_outdated(target,deps): |
|
569 | 569 | xsys(cmd) |
|
570 | 570 | |
|
571 | 571 | #---------------------------------------------------------------------------- |
|
572 | 572 | def unquote_ends(istr): |
|
573 | 573 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
574 | 574 | |
|
575 | 575 | if not istr: |
|
576 | 576 | return istr |
|
577 | 577 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
578 | 578 | (istr[0]=='"' and istr[-1]=='"'): |
|
579 | 579 | return istr[1:-1] |
|
580 | 580 | else: |
|
581 | 581 | return istr |
|
582 | 582 | |
|
583 | 583 | #---------------------------------------------------------------------------- |
|
584 | 584 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
585 | 585 | """ Process command-line options and arguments. |
|
586 | 586 | |
|
587 | 587 | Arguments: |
|
588 | 588 | |
|
589 | 589 | - argv: list of arguments, typically sys.argv. |
|
590 | 590 | |
|
591 | 591 | - names: list of option names. See DPyGetOpt docs for details on options |
|
592 | 592 | syntax. |
|
593 | 593 | |
|
594 | 594 | - defaults: dict of default values. |
|
595 | 595 | |
|
596 | 596 | - usage: optional usage notice to print if a wrong argument is passed. |
|
597 | 597 | |
|
598 | 598 | Return a dict of options and a list of free arguments.""" |
|
599 | 599 | |
|
600 | 600 | getopt = DPyGetOpt.DPyGetOpt() |
|
601 | 601 | getopt.setIgnoreCase(0) |
|
602 | 602 | getopt.parseConfiguration(names) |
|
603 | 603 | |
|
604 | 604 | try: |
|
605 | 605 | getopt.processArguments(argv) |
|
606 | 606 | except: |
|
607 | 607 | print usage |
|
608 | 608 | warn(`sys.exc_value`,level=4) |
|
609 | 609 | |
|
610 | 610 | defaults.update(getopt.optionValues) |
|
611 | 611 | args = getopt.freeValues |
|
612 | 612 | |
|
613 | 613 | return defaults,args |
|
614 | 614 | |
|
615 | 615 | #---------------------------------------------------------------------------- |
|
616 | 616 | def optstr2types(ostr): |
|
617 | 617 | """Convert a string of option names to a dict of type mappings. |
|
618 | 618 | |
|
619 | 619 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
620 | 620 | |
|
621 | 621 | This is used to get the types of all the options in a string formatted |
|
622 | 622 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
623 | 623 | which are strings (they need no further conversion). This function's main |
|
624 | 624 | use is to get a typemap for use with read_dict(). |
|
625 | 625 | """ |
|
626 | 626 | |
|
627 | 627 | typeconv = {None:'',int:'',float:''} |
|
628 | 628 | typemap = {'s':None,'i':int,'f':float} |
|
629 | 629 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
630 | 630 | |
|
631 | 631 | for w in ostr.split(): |
|
632 | 632 | oname,alias,otype = opt_re.match(w).groups() |
|
633 | 633 | if otype == '' or alias == '!': # simple switches are integers too |
|
634 | 634 | otype = 'i' |
|
635 | 635 | typeconv[typemap[otype]] += oname + ' ' |
|
636 | 636 | return typeconv |
|
637 | 637 | |
|
638 | 638 | #---------------------------------------------------------------------------- |
|
639 | 639 | def read_dict(filename,type_conv=None,**opt): |
|
640 | 640 | |
|
641 | 641 | """Read a dictionary of key=value pairs from an input file, optionally |
|
642 | 642 | performing conversions on the resulting values. |
|
643 | 643 | |
|
644 | 644 | read_dict(filename,type_conv,**opt) -> dict |
|
645 | 645 | |
|
646 | 646 | Only one value per line is accepted, the format should be |
|
647 | 647 | # optional comments are ignored |
|
648 | 648 | key value\n |
|
649 | 649 | |
|
650 | 650 | Args: |
|
651 | 651 | |
|
652 | 652 | - type_conv: A dictionary specifying which keys need to be converted to |
|
653 | 653 | which types. By default all keys are read as strings. This dictionary |
|
654 | 654 | should have as its keys valid conversion functions for strings |
|
655 | 655 | (int,long,float,complex, or your own). The value for each key |
|
656 | 656 | (converter) should be a whitespace separated string containing the names |
|
657 | 657 | of all the entries in the file to be converted using that function. For |
|
658 | 658 | keys to be left alone, use None as the conversion function (only needed |
|
659 | 659 | with purge=1, see below). |
|
660 | 660 | |
|
661 | 661 | - opt: dictionary with extra options as below (default in parens) |
|
662 | 662 | |
|
663 | 663 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
664 | 664 | of the dictionary to be returned. If purge is going to be used, the |
|
665 | 665 | set of keys to be left as strings also has to be explicitly specified |
|
666 | 666 | using the (non-existent) conversion function None. |
|
667 | 667 | |
|
668 | 668 | fs(None): field separator. This is the key/value separator to be used |
|
669 | 669 | when parsing the file. The None default means any whitespace [behavior |
|
670 | 670 | of string.split()]. |
|
671 | 671 | |
|
672 | 672 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
673 | 673 | |
|
674 | 674 | warn(1): warning level if requested keys are not found in file. |
|
675 | 675 | - 0: silently ignore. |
|
676 | 676 | - 1: inform but proceed. |
|
677 | 677 | - 2: raise KeyError exception. |
|
678 | 678 | |
|
679 | 679 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
680 | 680 | |
|
681 | 681 | unique([]): list of keys (or space separated string) which can't be |
|
682 | 682 | repeated. If one such key is found in the file, each new instance |
|
683 | 683 | overwrites the previous one. For keys not listed here, the behavior is |
|
684 | 684 | to make a list of all appearances. |
|
685 | 685 | |
|
686 | 686 | Example: |
|
687 | 687 | If the input file test.ini has: |
|
688 | 688 | i 3 |
|
689 | 689 | x 4.5 |
|
690 | 690 | y 5.5 |
|
691 | 691 | s hi ho |
|
692 | 692 | Then: |
|
693 | 693 | |
|
694 | 694 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
695 | 695 | >>> read_dict('test.ini') |
|
696 | 696 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
697 | 697 | >>> read_dict('test.ini',type_conv) |
|
698 | 698 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
699 | 699 | >>> read_dict('test.ini',type_conv,purge=1) |
|
700 | 700 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
701 | 701 | """ |
|
702 | 702 | |
|
703 | 703 | # starting config |
|
704 | 704 | opt.setdefault('purge',0) |
|
705 | 705 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
706 | 706 | opt.setdefault('strip',0) |
|
707 | 707 | opt.setdefault('warn',1) |
|
708 | 708 | opt.setdefault('no_empty',0) |
|
709 | 709 | opt.setdefault('unique','') |
|
710 | 710 | if type(opt['unique']) in StringTypes: |
|
711 | 711 | unique_keys = qw(opt['unique']) |
|
712 | 712 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
713 | 713 | unique_keys = opt['unique'] |
|
714 | 714 | else: |
|
715 | 715 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
716 | 716 | |
|
717 | 717 | dict = {} |
|
718 | 718 | # first read in table of values as strings |
|
719 | 719 | file = open(filename,'r') |
|
720 | 720 | for line in file.readlines(): |
|
721 | 721 | line = line.strip() |
|
722 | 722 | if len(line) and line[0]=='#': continue |
|
723 | 723 | if len(line)>0: |
|
724 | 724 | lsplit = line.split(opt['fs'],1) |
|
725 | 725 | try: |
|
726 | 726 | key,val = lsplit |
|
727 | 727 | except ValueError: |
|
728 | 728 | key,val = lsplit[0],'' |
|
729 | 729 | key = key.strip() |
|
730 | 730 | if opt['strip']: val = val.strip() |
|
731 | 731 | if val == "''" or val == '""': val = '' |
|
732 | 732 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
733 | 733 | continue |
|
734 | 734 | # if a key is found more than once in the file, build a list |
|
735 | 735 | # unless it's in the 'unique' list. In that case, last found in file |
|
736 | 736 | # takes precedence. User beware. |
|
737 | 737 | try: |
|
738 | 738 | if dict[key] and key in unique_keys: |
|
739 | 739 | dict[key] = val |
|
740 | 740 | elif type(dict[key]) is types.ListType: |
|
741 | 741 | dict[key].append(val) |
|
742 | 742 | else: |
|
743 | 743 | dict[key] = [dict[key],val] |
|
744 | 744 | except KeyError: |
|
745 | 745 | dict[key] = val |
|
746 | 746 | # purge if requested |
|
747 | 747 | if opt['purge']: |
|
748 | 748 | accepted_keys = qwflat(type_conv.values()) |
|
749 | 749 | for key in dict.keys(): |
|
750 | 750 | if key in accepted_keys: continue |
|
751 | 751 | del(dict[key]) |
|
752 | 752 | # now convert if requested |
|
753 | 753 | if type_conv==None: return dict |
|
754 | 754 | conversions = type_conv.keys() |
|
755 | 755 | try: conversions.remove(None) |
|
756 | 756 | except: pass |
|
757 | 757 | for convert in conversions: |
|
758 | 758 | for val in qw(type_conv[convert]): |
|
759 | 759 | try: |
|
760 | 760 | dict[val] = convert(dict[val]) |
|
761 | 761 | except KeyError,e: |
|
762 | 762 | if opt['warn'] == 0: |
|
763 | 763 | pass |
|
764 | 764 | elif opt['warn'] == 1: |
|
765 | 765 | print >>sys.stderr, 'Warning: key',val,\ |
|
766 | 766 | 'not found in file',filename |
|
767 | 767 | elif opt['warn'] == 2: |
|
768 | 768 | raise KeyError,e |
|
769 | 769 | else: |
|
770 | 770 | raise ValueError,'Warning level must be 0,1 or 2' |
|
771 | 771 | |
|
772 | 772 | return dict |
|
773 | 773 | |
|
774 | 774 | #---------------------------------------------------------------------------- |
|
775 | 775 | def flag_calls(func): |
|
776 | 776 | """Wrap a function to detect and flag when it gets called. |
|
777 | 777 | |
|
778 | 778 | This is a decorator which takes a function and wraps it in a function with |
|
779 | 779 | a 'called' attribute. wrapper.called is initialized to False. |
|
780 | 780 | |
|
781 | 781 | The wrapper.called attribute is set to False right before each call to the |
|
782 | 782 | wrapped function, so if the call fails it remains False. After the call |
|
783 | 783 | completes, wrapper.called is set to True and the output is returned. |
|
784 | 784 | |
|
785 | 785 | Testing for truth in wrapper.called allows you to determine if a call to |
|
786 | 786 | func() was attempted and succeeded.""" |
|
787 | 787 | |
|
788 | 788 | def wrapper(*args,**kw): |
|
789 | 789 | wrapper.called = False |
|
790 | 790 | out = func(*args,**kw) |
|
791 | 791 | wrapper.called = True |
|
792 | 792 | return out |
|
793 | 793 | |
|
794 | 794 | wrapper.called = False |
|
795 | 795 | wrapper.__doc__ = func.__doc__ |
|
796 | 796 | return wrapper |
|
797 | 797 | |
|
798 | 798 | #---------------------------------------------------------------------------- |
|
799 | 799 | class HomeDirError(Error): |
|
800 | 800 | pass |
|
801 | 801 | |
|
802 | 802 | def get_home_dir(): |
|
803 | 803 | """Return the closest possible equivalent to a 'home' directory. |
|
804 | 804 | |
|
805 | 805 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
806 | 806 | |
|
807 | 807 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
808 | 808 | raised for all other OSes. """ |
|
809 | 809 | |
|
810 | 810 | isdir = os.path.isdir |
|
811 | 811 | env = os.environ |
|
812 | 812 | |
|
813 | 813 | # first, check py2exe distribution root directory for _ipython. |
|
814 | 814 | # This overrides all. Normally does not exist. |
|
815 | 815 | if '\\library.zip\\' in IPython.__file__.lower(): |
|
816 | 816 | root, rest = IPython.__file__.lower().split('library.zip') |
|
817 | 817 | if os.path.isdir(root + '_ipython'): |
|
818 | 818 | return root |
|
819 | 819 | |
|
820 | 820 | try: |
|
821 | 821 | homedir = env['HOME'] |
|
822 | 822 | if not isdir(homedir): |
|
823 | 823 | # in case a user stuck some string which does NOT resolve to a |
|
824 | 824 | # valid path, it's as good as if we hadn't foud it |
|
825 | 825 | raise KeyError |
|
826 | 826 | return homedir |
|
827 | 827 | except KeyError: |
|
828 | 828 | if os.name == 'posix': |
|
829 | 829 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
830 | 830 | elif os.name == 'nt': |
|
831 | 831 | # For some strange reason, win9x returns 'nt' for os.name. |
|
832 | 832 | try: |
|
833 | 833 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
834 | 834 | if not isdir(homedir): |
|
835 | 835 | homedir = os.path.join(env['USERPROFILE']) |
|
836 | 836 | if not isdir(homedir): |
|
837 | 837 | raise HomeDirError |
|
838 | 838 | return homedir |
|
839 | 839 | except: |
|
840 | 840 | try: |
|
841 | 841 | # Use the registry to get the 'My Documents' folder. |
|
842 | 842 | import _winreg as wreg |
|
843 | 843 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
844 | 844 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
845 | 845 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
846 | 846 | key.Close() |
|
847 | 847 | if not isdir(homedir): |
|
848 | 848 | e = ('Invalid "Personal" folder registry key ' |
|
849 | 849 | 'typically "My Documents".\n' |
|
850 | 850 | 'Value: %s\n' |
|
851 | 851 | 'This is not a valid directory on your system.' % |
|
852 | 852 | homedir) |
|
853 | 853 | raise HomeDirError(e) |
|
854 | 854 | return homedir |
|
855 | 855 | except HomeDirError: |
|
856 | 856 | raise |
|
857 | 857 | except: |
|
858 | 858 | return 'C:\\' |
|
859 | 859 | elif os.name == 'dos': |
|
860 | 860 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
861 | 861 | return 'C:\\' |
|
862 | 862 | else: |
|
863 | 863 | raise HomeDirError,'support for your operating system not implemented.' |
|
864 | 864 | |
|
865 | 865 | #**************************************************************************** |
|
866 | 866 | # strings and text |
|
867 | 867 | |
|
868 | 868 | class LSString(str): |
|
869 | 869 | """String derivative with a special access attributes. |
|
870 | 870 | |
|
871 | 871 | These are normal strings, but with the special attributes: |
|
872 | 872 | |
|
873 | 873 | .l (or .list) : value as list (split on newlines). |
|
874 | 874 | .n (or .nlstr): original value (the string itself). |
|
875 | 875 | .s (or .spstr): value as whitespace-separated string. |
|
876 | 876 | .p (or .paths): list of path objects |
|
877 | 877 | |
|
878 | 878 | Any values which require transformations are computed only once and |
|
879 | 879 | cached. |
|
880 | 880 | |
|
881 | 881 | Such strings are very useful to efficiently interact with the shell, which |
|
882 | 882 | typically only understands whitespace-separated options for commands.""" |
|
883 | 883 | |
|
884 | 884 | def get_list(self): |
|
885 | 885 | try: |
|
886 | 886 | return self.__list |
|
887 | 887 | except AttributeError: |
|
888 | 888 | self.__list = self.split('\n') |
|
889 | 889 | return self.__list |
|
890 | 890 | |
|
891 | 891 | l = list = property(get_list) |
|
892 | 892 | |
|
893 | 893 | def get_spstr(self): |
|
894 | 894 | try: |
|
895 | 895 | return self.__spstr |
|
896 | 896 | except AttributeError: |
|
897 | 897 | self.__spstr = self.replace('\n',' ') |
|
898 | 898 | return self.__spstr |
|
899 | 899 | |
|
900 | 900 | s = spstr = property(get_spstr) |
|
901 | 901 | |
|
902 | 902 | def get_nlstr(self): |
|
903 | 903 | return self |
|
904 | 904 | |
|
905 | 905 | n = nlstr = property(get_nlstr) |
|
906 | 906 | |
|
907 | 907 | def get_paths(self): |
|
908 | 908 | try: |
|
909 | 909 | return self.__paths |
|
910 | 910 | except AttributeError: |
|
911 | 911 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
912 | 912 | return self.__paths |
|
913 | 913 | |
|
914 | 914 | p = paths = property(get_paths) |
|
915 | 915 | |
|
916 | ||
|
917 | ||
|
918 | 916 | def print_lsstring(arg): |
|
919 | 917 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
920 | 918 | print "LSString (.p, .n, .l, .s available). Value:" |
|
921 | 919 | print arg |
|
922 | 920 | |
|
923 | 921 | print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
924 | 922 | |
|
925 | 923 | #---------------------------------------------------------------------------- |
|
926 | 924 | class SList(list): |
|
927 | 925 | """List derivative with a special access attributes. |
|
928 | 926 | |
|
929 | 927 | These are normal lists, but with the special attributes: |
|
930 | 928 | |
|
931 | 929 | .l (or .list) : value as list (the list itself). |
|
932 | 930 | .n (or .nlstr): value as a string, joined on newlines. |
|
933 | 931 | .s (or .spstr): value as a string, joined on spaces. |
|
934 | 932 | .p (or .paths): list of path objects |
|
935 | 933 | |
|
936 | 934 | Any values which require transformations are computed only once and |
|
937 | 935 | cached.""" |
|
938 | 936 | |
|
939 | 937 | def get_list(self): |
|
940 | 938 | return self |
|
941 | 939 | |
|
942 | 940 | l = list = property(get_list) |
|
943 | 941 | |
|
944 | 942 | def get_spstr(self): |
|
945 | 943 | try: |
|
946 | 944 | return self.__spstr |
|
947 | 945 | except AttributeError: |
|
948 | 946 | self.__spstr = ' '.join(self) |
|
949 | 947 | return self.__spstr |
|
950 | 948 | |
|
951 | 949 | s = spstr = property(get_spstr) |
|
952 | 950 | |
|
953 | 951 | def get_nlstr(self): |
|
954 | 952 | try: |
|
955 | 953 | return self.__nlstr |
|
956 | 954 | except AttributeError: |
|
957 | 955 | self.__nlstr = '\n'.join(self) |
|
958 | 956 | return self.__nlstr |
|
959 | 957 | |
|
960 | 958 | n = nlstr = property(get_nlstr) |
|
961 | 959 | |
|
962 | 960 | def get_paths(self): |
|
963 | 961 | try: |
|
964 | 962 | return self.__paths |
|
965 | 963 | except AttributeError: |
|
966 | 964 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
967 | 965 | return self.__paths |
|
968 | 966 | |
|
969 | 967 | p = paths = property(get_paths) |
|
970 | 968 | |
|
971 | 969 | #---------------------------------------------------------------------------- |
|
972 | 970 | def esc_quotes(strng): |
|
973 | 971 | """Return the input string with single and double quotes escaped out""" |
|
974 | 972 | |
|
975 | 973 | return strng.replace('"','\\"').replace("'","\\'") |
|
976 | 974 | |
|
977 | 975 | #---------------------------------------------------------------------------- |
|
978 | 976 | def make_quoted_expr(s): |
|
979 | 977 | """Return string s in appropriate quotes, using raw string if possible. |
|
980 | 978 | |
|
981 | 979 | Effectively this turns string: cd \ao\ao\ |
|
982 | 980 | to: r"cd \ao\ao\_"[:-1] |
|
983 | 981 | |
|
984 | 982 | Note the use of raw string and padding at the end to allow trailing backslash. |
|
985 | 983 | |
|
986 | 984 | """ |
|
987 | 985 | |
|
988 | 986 | tail = '' |
|
989 | 987 | tailpadding = '' |
|
990 | 988 | raw = '' |
|
991 | 989 | if "\\" in s: |
|
992 | 990 | raw = 'r' |
|
993 | 991 | if s.endswith('\\'): |
|
994 | 992 | tail = '[:-1]' |
|
995 | 993 | tailpadding = '_' |
|
996 | 994 | if '"' not in s: |
|
997 | 995 | quote = '"' |
|
998 | 996 | elif "'" not in s: |
|
999 | 997 | quote = "'" |
|
1000 | 998 | elif '"""' not in s and not s.endswith('"'): |
|
1001 | 999 | quote = '"""' |
|
1002 | 1000 | elif "'''" not in s and not s.endswith("'"): |
|
1003 | 1001 | quote = "'''" |
|
1004 | 1002 | else: |
|
1005 | 1003 | # give up, backslash-escaped string will do |
|
1006 | 1004 | return '"%s"' % esc_quotes(s) |
|
1007 | 1005 | res = itpl("$raw$quote$s$tailpadding$quote$tail") |
|
1008 | 1006 | return res |
|
1009 | 1007 | |
|
1010 | 1008 | |
|
1011 | 1009 | #---------------------------------------------------------------------------- |
|
1012 | 1010 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
1013 | 1011 | """Take multiple lines of input. |
|
1014 | 1012 | |
|
1015 | 1013 | A list with each line of input as a separate element is returned when a |
|
1016 | 1014 | termination string is entered (defaults to a single '.'). Input can also |
|
1017 | 1015 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
1018 | 1016 | |
|
1019 | 1017 | Lines of input which end in \\ are joined into single entries (and a |
|
1020 | 1018 | secondary continuation prompt is issued as long as the user terminates |
|
1021 | 1019 | lines with \\). This allows entering very long strings which are still |
|
1022 | 1020 | meant to be treated as single entities. |
|
1023 | 1021 | """ |
|
1024 | 1022 | |
|
1025 | 1023 | try: |
|
1026 | 1024 | if header: |
|
1027 | 1025 | header += '\n' |
|
1028 | 1026 | lines = [raw_input(header + ps1)] |
|
1029 | 1027 | except EOFError: |
|
1030 | 1028 | return [] |
|
1031 | 1029 | terminate = [terminate_str] |
|
1032 | 1030 | try: |
|
1033 | 1031 | while lines[-1:] != terminate: |
|
1034 | 1032 | new_line = raw_input(ps1) |
|
1035 | 1033 | while new_line.endswith('\\'): |
|
1036 | 1034 | new_line = new_line[:-1] + raw_input(ps2) |
|
1037 | 1035 | lines.append(new_line) |
|
1038 | 1036 | |
|
1039 | 1037 | return lines[:-1] # don't return the termination command |
|
1040 | 1038 | except EOFError: |
|
1041 | 1039 | |
|
1042 | 1040 | return lines |
|
1043 | 1041 | |
|
1044 | 1042 | #---------------------------------------------------------------------------- |
|
1045 | 1043 | def raw_input_ext(prompt='', ps2='... '): |
|
1046 | 1044 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
1047 | 1045 | |
|
1048 | 1046 | line = raw_input(prompt) |
|
1049 | 1047 | while line.endswith('\\'): |
|
1050 | 1048 | line = line[:-1] + raw_input(ps2) |
|
1051 | 1049 | return line |
|
1052 | 1050 | |
|
1053 | 1051 | #---------------------------------------------------------------------------- |
|
1054 | 1052 | def ask_yes_no(prompt,default=None): |
|
1055 | 1053 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
1056 | 1054 | |
|
1057 | 1055 | If default is given (one of 'y','n'), it is used if the user input is |
|
1058 | 1056 | empty. Otherwise the question is repeated until an answer is given. |
|
1059 | 1057 | |
|
1060 | 1058 | An EOF is treated as the default answer. If there is no default, an |
|
1061 | 1059 | exception is raised to prevent infinite loops. |
|
1062 | 1060 | |
|
1063 | 1061 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1064 | 1062 | |
|
1065 | 1063 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1066 | 1064 | ans = None |
|
1067 | 1065 | while ans not in answers.keys(): |
|
1068 | 1066 | try: |
|
1069 | 1067 | ans = raw_input(prompt+' ').lower() |
|
1070 | 1068 | if not ans: # response was an empty string |
|
1071 | 1069 | ans = default |
|
1072 | 1070 | except KeyboardInterrupt: |
|
1073 | 1071 | pass |
|
1074 | 1072 | except EOFError: |
|
1075 | 1073 | if default in answers.keys(): |
|
1076 | 1074 | ans = default |
|
1077 | 1075 | |
|
1078 | 1076 | else: |
|
1079 | 1077 | raise |
|
1080 | 1078 | |
|
1081 | 1079 | return answers[ans] |
|
1082 | 1080 | |
|
1083 | 1081 | #---------------------------------------------------------------------------- |
|
1084 | 1082 | def marquee(txt='',width=78,mark='*'): |
|
1085 | 1083 | """Return the input string centered in a 'marquee'.""" |
|
1086 | 1084 | if not txt: |
|
1087 | 1085 | return (mark*width)[:width] |
|
1088 | 1086 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1089 | 1087 | if nmark < 0: nmark =0 |
|
1090 | 1088 | marks = mark*nmark |
|
1091 | 1089 | return '%s %s %s' % (marks,txt,marks) |
|
1092 | 1090 | |
|
1093 | 1091 | #---------------------------------------------------------------------------- |
|
1094 | 1092 | class EvalDict: |
|
1095 | 1093 | """ |
|
1096 | 1094 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1097 | 1095 | |
|
1098 | 1096 | Usage: |
|
1099 | 1097 | >>>number = 19 |
|
1100 | 1098 | >>>text = "python" |
|
1101 | 1099 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1102 | 1100 | """ |
|
1103 | 1101 | |
|
1104 | 1102 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1105 | 1103 | # modified (shorter) version of: |
|
1106 | 1104 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1107 | 1105 | # Skip Montanaro (skip@pobox.com). |
|
1108 | 1106 | |
|
1109 | 1107 | def __getitem__(self, name): |
|
1110 | 1108 | frame = sys._getframe(1) |
|
1111 | 1109 | return eval(name, frame.f_globals, frame.f_locals) |
|
1112 | 1110 | |
|
1113 | 1111 | EvalString = EvalDict # for backwards compatibility |
|
1114 | 1112 | #---------------------------------------------------------------------------- |
|
1115 | 1113 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1116 | 1114 | """Similar to Perl's qw() operator, but with some more options. |
|
1117 | 1115 | |
|
1118 | 1116 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1119 | 1117 | |
|
1120 | 1118 | words can also be a list itself, and with flat=1, the output will be |
|
1121 | 1119 | recursively flattened. Examples: |
|
1122 | 1120 | |
|
1123 | 1121 | >>> qw('1 2') |
|
1124 | 1122 | ['1', '2'] |
|
1125 | 1123 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1126 | 1124 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1127 | 1125 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1128 | 1126 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1129 | 1127 | |
|
1130 | 1128 | if type(words) in StringTypes: |
|
1131 | 1129 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1132 | 1130 | if word and not word.isspace() ] |
|
1133 | 1131 | if flat: |
|
1134 | 1132 | return flatten(map(qw,words,[1]*len(words))) |
|
1135 | 1133 | return map(qw,words) |
|
1136 | 1134 | |
|
1137 | 1135 | #---------------------------------------------------------------------------- |
|
1138 | 1136 | def qwflat(words,sep=None,maxsplit=-1): |
|
1139 | 1137 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1140 | 1138 | return qw(words,1,sep,maxsplit) |
|
1141 | 1139 | |
|
1142 | 1140 | #---------------------------------------------------------------------------- |
|
1143 | 1141 | def qw_lol(indata): |
|
1144 | 1142 | """qw_lol('a b') -> [['a','b']], |
|
1145 | 1143 | otherwise it's just a call to qw(). |
|
1146 | 1144 | |
|
1147 | 1145 | We need this to make sure the modules_some keys *always* end up as a |
|
1148 | 1146 | list of lists.""" |
|
1149 | 1147 | |
|
1150 | 1148 | if type(indata) in StringTypes: |
|
1151 | 1149 | return [qw(indata)] |
|
1152 | 1150 | else: |
|
1153 | 1151 | return qw(indata) |
|
1154 | 1152 | |
|
1155 | 1153 | #----------------------------------------------------------------------------- |
|
1156 | 1154 | def list_strings(arg): |
|
1157 | 1155 | """Always return a list of strings, given a string or list of strings |
|
1158 | 1156 | as input.""" |
|
1159 | 1157 | |
|
1160 | 1158 | if type(arg) in StringTypes: return [arg] |
|
1161 | 1159 | else: return arg |
|
1162 | 1160 | |
|
1163 | 1161 | #---------------------------------------------------------------------------- |
|
1164 | 1162 | def grep(pat,list,case=1): |
|
1165 | 1163 | """Simple minded grep-like function. |
|
1166 | 1164 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1167 | 1165 | |
|
1168 | 1166 | It only does simple string matching, with no support for regexps. Use the |
|
1169 | 1167 | option case=0 for case-insensitive matching.""" |
|
1170 | 1168 | |
|
1171 | 1169 | # This is pretty crude. At least it should implement copying only references |
|
1172 | 1170 | # to the original data in case it's big. Now it copies the data for output. |
|
1173 | 1171 | out=[] |
|
1174 | 1172 | if case: |
|
1175 | 1173 | for term in list: |
|
1176 | 1174 | if term.find(pat)>-1: out.append(term) |
|
1177 | 1175 | else: |
|
1178 | 1176 | lpat=pat.lower() |
|
1179 | 1177 | for term in list: |
|
1180 | 1178 | if term.lower().find(lpat)>-1: out.append(term) |
|
1181 | 1179 | |
|
1182 | 1180 | if len(out): return out |
|
1183 | 1181 | else: return None |
|
1184 | 1182 | |
|
1185 | 1183 | #---------------------------------------------------------------------------- |
|
1186 | 1184 | def dgrep(pat,*opts): |
|
1187 | 1185 | """Return grep() on dir()+dir(__builtins__). |
|
1188 | 1186 | |
|
1189 | 1187 | A very common use of grep() when working interactively.""" |
|
1190 | 1188 | |
|
1191 | 1189 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1192 | 1190 | |
|
1193 | 1191 | #---------------------------------------------------------------------------- |
|
1194 | 1192 | def idgrep(pat): |
|
1195 | 1193 | """Case-insensitive dgrep()""" |
|
1196 | 1194 | |
|
1197 | 1195 | return dgrep(pat,0) |
|
1198 | 1196 | |
|
1199 | 1197 | #---------------------------------------------------------------------------- |
|
1200 | 1198 | def igrep(pat,list): |
|
1201 | 1199 | """Synonym for case-insensitive grep.""" |
|
1202 | 1200 | |
|
1203 | 1201 | return grep(pat,list,case=0) |
|
1204 | 1202 | |
|
1205 | 1203 | #---------------------------------------------------------------------------- |
|
1206 | 1204 | def indent(str,nspaces=4,ntabs=0): |
|
1207 | 1205 | """Indent a string a given number of spaces or tabstops. |
|
1208 | 1206 | |
|
1209 | 1207 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1210 | 1208 | """ |
|
1211 | 1209 | if str is None: |
|
1212 | 1210 | return |
|
1213 | 1211 | ind = '\t'*ntabs+' '*nspaces |
|
1214 | 1212 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1215 | 1213 | if outstr.endswith(os.linesep+ind): |
|
1216 | 1214 | return outstr[:-len(ind)] |
|
1217 | 1215 | else: |
|
1218 | 1216 | return outstr |
|
1219 | 1217 | |
|
1220 | 1218 | #----------------------------------------------------------------------------- |
|
1221 | 1219 | def native_line_ends(filename,backup=1): |
|
1222 | 1220 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1223 | 1221 | |
|
1224 | 1222 | If the optional backup argument is given as false, no backup of the |
|
1225 | 1223 | original file is left. """ |
|
1226 | 1224 | |
|
1227 | 1225 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1228 | 1226 | |
|
1229 | 1227 | bak_filename = filename + backup_suffixes[os.name] |
|
1230 | 1228 | |
|
1231 | 1229 | original = open(filename).read() |
|
1232 | 1230 | shutil.copy2(filename,bak_filename) |
|
1233 | 1231 | try: |
|
1234 | 1232 | new = open(filename,'wb') |
|
1235 | 1233 | new.write(os.linesep.join(original.splitlines())) |
|
1236 | 1234 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1237 | 1235 | new.close() |
|
1238 | 1236 | except: |
|
1239 | 1237 | os.rename(bak_filename,filename) |
|
1240 | 1238 | if not backup: |
|
1241 | 1239 | try: |
|
1242 | 1240 | os.remove(bak_filename) |
|
1243 | 1241 | except: |
|
1244 | 1242 | pass |
|
1245 | 1243 | |
|
1246 | 1244 | #---------------------------------------------------------------------------- |
|
1247 | 1245 | def get_pager_cmd(pager_cmd = None): |
|
1248 | 1246 | """Return a pager command. |
|
1249 | 1247 | |
|
1250 | 1248 | Makes some attempts at finding an OS-correct one.""" |
|
1251 | 1249 | |
|
1252 | 1250 | if os.name == 'posix': |
|
1253 | 1251 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1254 | 1252 | elif os.name in ['nt','dos']: |
|
1255 | 1253 | default_pager_cmd = 'type' |
|
1256 | 1254 | |
|
1257 | 1255 | if pager_cmd is None: |
|
1258 | 1256 | try: |
|
1259 | 1257 | pager_cmd = os.environ['PAGER'] |
|
1260 | 1258 | except: |
|
1261 | 1259 | pager_cmd = default_pager_cmd |
|
1262 | 1260 | return pager_cmd |
|
1263 | 1261 | |
|
1264 | 1262 | #----------------------------------------------------------------------------- |
|
1265 | 1263 | def get_pager_start(pager,start): |
|
1266 | 1264 | """Return the string for paging files with an offset. |
|
1267 | 1265 | |
|
1268 | 1266 | This is the '+N' argument which less and more (under Unix) accept. |
|
1269 | 1267 | """ |
|
1270 | 1268 | |
|
1271 | 1269 | if pager in ['less','more']: |
|
1272 | 1270 | if start: |
|
1273 | 1271 | start_string = '+' + str(start) |
|
1274 | 1272 | else: |
|
1275 | 1273 | start_string = '' |
|
1276 | 1274 | else: |
|
1277 | 1275 | start_string = '' |
|
1278 | 1276 | return start_string |
|
1279 | 1277 | |
|
1280 | 1278 | #---------------------------------------------------------------------------- |
|
1281 | 1279 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() |
|
1282 | 1280 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
1283 | 1281 | import msvcrt |
|
1284 | 1282 | def page_more(): |
|
1285 | 1283 | """ Smart pausing between pages |
|
1286 | 1284 | |
|
1287 | 1285 | @return: True if need print more lines, False if quit |
|
1288 | 1286 | """ |
|
1289 | 1287 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1290 | 1288 | ans = msvcrt.getch() |
|
1291 | 1289 | if ans in ("q", "Q"): |
|
1292 | 1290 | result = False |
|
1293 | 1291 | else: |
|
1294 | 1292 | result = True |
|
1295 | 1293 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1296 | 1294 | return result |
|
1297 | 1295 | else: |
|
1298 | 1296 | def page_more(): |
|
1299 | 1297 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1300 | 1298 | if ans.lower().startswith('q'): |
|
1301 | 1299 | return False |
|
1302 | 1300 | else: |
|
1303 | 1301 | return True |
|
1304 | 1302 | |
|
1305 | 1303 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1306 | 1304 | |
|
1307 | 1305 | def page_dumb(strng,start=0,screen_lines=25): |
|
1308 | 1306 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1309 | 1307 | |
|
1310 | 1308 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1311 | 1309 | mode.""" |
|
1312 | 1310 | |
|
1313 | 1311 | out_ln = strng.splitlines()[start:] |
|
1314 | 1312 | screens = chop(out_ln,screen_lines-1) |
|
1315 | 1313 | if len(screens) == 1: |
|
1316 | 1314 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1317 | 1315 | else: |
|
1318 | 1316 | last_escape = "" |
|
1319 | 1317 | for scr in screens[0:-1]: |
|
1320 | 1318 | hunk = os.linesep.join(scr) |
|
1321 | 1319 | print >>Term.cout, last_escape + hunk |
|
1322 | 1320 | if not page_more(): |
|
1323 | 1321 | return |
|
1324 | 1322 | esc_list = esc_re.findall(hunk) |
|
1325 | 1323 | if len(esc_list) > 0: |
|
1326 | 1324 | last_escape = esc_list[-1] |
|
1327 | 1325 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1328 | 1326 | |
|
1329 | 1327 | #---------------------------------------------------------------------------- |
|
1330 | 1328 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1331 | 1329 | """Print a string, piping through a pager after a certain length. |
|
1332 | 1330 | |
|
1333 | 1331 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1334 | 1332 | terminal screen (total lines minus lines you need to reserve to show other |
|
1335 | 1333 | information). |
|
1336 | 1334 | |
|
1337 | 1335 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1338 | 1336 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1339 | 1337 | printing, paging after that. That is, if you want auto-detection but need |
|
1340 | 1338 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1341 | 1339 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1342 | 1340 | |
|
1343 | 1341 | If a string won't fit in the allowed lines, it is sent through the |
|
1344 | 1342 | specified pager command. If none given, look for PAGER in the environment, |
|
1345 | 1343 | and ultimately default to less. |
|
1346 | 1344 | |
|
1347 | 1345 | If no system pager works, the string is sent through a 'dumb pager' |
|
1348 | 1346 | written in python, very simplistic. |
|
1349 | 1347 | """ |
|
1350 | 1348 | |
|
1351 | 1349 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1352 | 1350 | TERM = os.environ.get('TERM','dumb') |
|
1353 | 1351 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1354 | 1352 | print strng |
|
1355 | 1353 | return |
|
1356 | 1354 | # chop off the topmost part of the string we don't want to see |
|
1357 | 1355 | str_lines = strng.split(os.linesep)[start:] |
|
1358 | 1356 | str_toprint = os.linesep.join(str_lines) |
|
1359 | 1357 | num_newlines = len(str_lines) |
|
1360 | 1358 | len_str = len(str_toprint) |
|
1361 | 1359 | |
|
1362 | 1360 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1363 | 1361 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1364 | 1362 | # terminals. If someone later feels like refining it, it's not hard. |
|
1365 | 1363 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1366 | 1364 | |
|
1367 | 1365 | if os.name == "nt": |
|
1368 | 1366 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1369 | 1367 | else: |
|
1370 | 1368 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1371 | 1369 | |
|
1372 | 1370 | # auto-determine screen size |
|
1373 | 1371 | if screen_lines <= 0: |
|
1374 | 1372 | if TERM=='xterm': |
|
1375 | 1373 | try: |
|
1376 | 1374 | import curses |
|
1377 | 1375 | if hasattr(curses,'initscr'): |
|
1378 | 1376 | use_curses = 1 |
|
1379 | 1377 | else: |
|
1380 | 1378 | use_curses = 0 |
|
1381 | 1379 | except ImportError: |
|
1382 | 1380 | use_curses = 0 |
|
1383 | 1381 | else: |
|
1384 | 1382 | # curses causes problems on many terminals other than xterm. |
|
1385 | 1383 | use_curses = 0 |
|
1386 | 1384 | if use_curses: |
|
1387 | 1385 | scr = curses.initscr() |
|
1388 | 1386 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1389 | 1387 | curses.endwin() |
|
1390 | 1388 | screen_lines += screen_lines_real |
|
1391 | 1389 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1392 | 1390 | #screen_cols,'columns.' # dbg |
|
1393 | 1391 | else: |
|
1394 | 1392 | screen_lines += screen_lines_def |
|
1395 | 1393 | |
|
1396 | 1394 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1397 | 1395 | if numlines <= screen_lines : |
|
1398 | 1396 | #print '*** normal print' # dbg |
|
1399 | 1397 | print >>Term.cout, str_toprint |
|
1400 | 1398 | else: |
|
1401 | 1399 | # Try to open pager and default to internal one if that fails. |
|
1402 | 1400 | # All failure modes are tagged as 'retval=1', to match the return |
|
1403 | 1401 | # value of a failed system command. If any intermediate attempt |
|
1404 | 1402 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1405 | 1403 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1406 | 1404 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1407 | 1405 | if os.name == 'nt': |
|
1408 | 1406 | if pager_cmd.startswith('type'): |
|
1409 | 1407 | # The default WinXP 'type' command is failing on complex strings. |
|
1410 | 1408 | retval = 1 |
|
1411 | 1409 | else: |
|
1412 | 1410 | tmpname = tempfile.mktemp('.txt') |
|
1413 | 1411 | tmpfile = file(tmpname,'wt') |
|
1414 | 1412 | tmpfile.write(strng) |
|
1415 | 1413 | tmpfile.close() |
|
1416 | 1414 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1417 | 1415 | if os.system(cmd): |
|
1418 | 1416 | retval = 1 |
|
1419 | 1417 | else: |
|
1420 | 1418 | retval = None |
|
1421 | 1419 | os.remove(tmpname) |
|
1422 | 1420 | else: |
|
1423 | 1421 | try: |
|
1424 | 1422 | retval = None |
|
1425 | 1423 | # if I use popen4, things hang. No idea why. |
|
1426 | 1424 | #pager,shell_out = os.popen4(pager_cmd) |
|
1427 | 1425 | pager = os.popen(pager_cmd,'w') |
|
1428 | 1426 | pager.write(strng) |
|
1429 | 1427 | pager.close() |
|
1430 | 1428 | retval = pager.close() # success returns None |
|
1431 | 1429 | except IOError,msg: # broken pipe when user quits |
|
1432 | 1430 | if msg.args == (32,'Broken pipe'): |
|
1433 | 1431 | retval = None |
|
1434 | 1432 | else: |
|
1435 | 1433 | retval = 1 |
|
1436 | 1434 | except OSError: |
|
1437 | 1435 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1438 | 1436 | retval = 1 |
|
1439 | 1437 | if retval is not None: |
|
1440 | 1438 | page_dumb(strng,screen_lines=screen_lines) |
|
1441 | 1439 | |
|
1442 | 1440 | #---------------------------------------------------------------------------- |
|
1443 | 1441 | def page_file(fname,start = 0, pager_cmd = None): |
|
1444 | 1442 | """Page a file, using an optional pager command and starting line. |
|
1445 | 1443 | """ |
|
1446 | 1444 | |
|
1447 | 1445 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1448 | 1446 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1449 | 1447 | |
|
1450 | 1448 | try: |
|
1451 | 1449 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1452 | 1450 | raise EnvironmentError |
|
1453 | 1451 | xsys(pager_cmd + ' ' + fname) |
|
1454 | 1452 | except: |
|
1455 | 1453 | try: |
|
1456 | 1454 | if start > 0: |
|
1457 | 1455 | start -= 1 |
|
1458 | 1456 | page(open(fname).read(),start) |
|
1459 | 1457 | except: |
|
1460 | 1458 | print 'Unable to show file',`fname` |
|
1461 | 1459 | |
|
1462 | 1460 | #---------------------------------------------------------------------------- |
|
1463 | 1461 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1464 | 1462 | """Print a string snipping the midsection to fit in width. |
|
1465 | 1463 | |
|
1466 | 1464 | print_full: mode control: |
|
1467 | 1465 | - 0: only snip long strings |
|
1468 | 1466 | - 1: send to page() directly. |
|
1469 | 1467 | - 2: snip long strings and ask for full length viewing with page() |
|
1470 | 1468 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1471 | 1469 | |
|
1472 | 1470 | if print_full == 1: |
|
1473 | 1471 | page(header+str) |
|
1474 | 1472 | return 0 |
|
1475 | 1473 | |
|
1476 | 1474 | print header, |
|
1477 | 1475 | if len(str) < width: |
|
1478 | 1476 | print str |
|
1479 | 1477 | snip = 0 |
|
1480 | 1478 | else: |
|
1481 | 1479 | whalf = int((width -5)/2) |
|
1482 | 1480 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1483 | 1481 | snip = 1 |
|
1484 | 1482 | if snip and print_full == 2: |
|
1485 | 1483 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1486 | 1484 | page(str) |
|
1487 | 1485 | return snip |
|
1488 | 1486 | |
|
1489 | 1487 | #**************************************************************************** |
|
1490 | 1488 | # lists, dicts and structures |
|
1491 | 1489 | |
|
1492 | 1490 | def belong(candidates,checklist): |
|
1493 | 1491 | """Check whether a list of items appear in a given list of options. |
|
1494 | 1492 | |
|
1495 | 1493 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1496 | 1494 | |
|
1497 | 1495 | return [x in checklist for x in candidates] |
|
1498 | 1496 | |
|
1499 | 1497 | #---------------------------------------------------------------------------- |
|
1500 | 1498 | def uniq_stable(elems): |
|
1501 | 1499 | """uniq_stable(elems) -> list |
|
1502 | 1500 | |
|
1503 | 1501 | Return from an iterable, a list of all the unique elements in the input, |
|
1504 | 1502 | but maintaining the order in which they first appear. |
|
1505 | 1503 | |
|
1506 | 1504 | A naive solution to this problem which just makes a dictionary with the |
|
1507 | 1505 | elements as keys fails to respect the stability condition, since |
|
1508 | 1506 | dictionaries are unsorted by nature. |
|
1509 | 1507 | |
|
1510 | 1508 | Note: All elements in the input must be valid dictionary keys for this |
|
1511 | 1509 | routine to work, as it internally uses a dictionary for efficiency |
|
1512 | 1510 | reasons.""" |
|
1513 | 1511 | |
|
1514 | 1512 | unique = [] |
|
1515 | 1513 | unique_dict = {} |
|
1516 | 1514 | for nn in elems: |
|
1517 | 1515 | if nn not in unique_dict: |
|
1518 | 1516 | unique.append(nn) |
|
1519 | 1517 | unique_dict[nn] = None |
|
1520 | 1518 | return unique |
|
1521 | 1519 | |
|
1522 | 1520 | #---------------------------------------------------------------------------- |
|
1523 | 1521 | class NLprinter: |
|
1524 | 1522 | """Print an arbitrarily nested list, indicating index numbers. |
|
1525 | 1523 | |
|
1526 | 1524 | An instance of this class called nlprint is available and callable as a |
|
1527 | 1525 | function. |
|
1528 | 1526 | |
|
1529 | 1527 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1530 | 1528 | and using 'sep' to separate the index from the value. """ |
|
1531 | 1529 | |
|
1532 | 1530 | def __init__(self): |
|
1533 | 1531 | self.depth = 0 |
|
1534 | 1532 | |
|
1535 | 1533 | def __call__(self,lst,pos='',**kw): |
|
1536 | 1534 | """Prints the nested list numbering levels.""" |
|
1537 | 1535 | kw.setdefault('indent',' ') |
|
1538 | 1536 | kw.setdefault('sep',': ') |
|
1539 | 1537 | kw.setdefault('start',0) |
|
1540 | 1538 | kw.setdefault('stop',len(lst)) |
|
1541 | 1539 | # we need to remove start and stop from kw so they don't propagate |
|
1542 | 1540 | # into a recursive call for a nested list. |
|
1543 | 1541 | start = kw['start']; del kw['start'] |
|
1544 | 1542 | stop = kw['stop']; del kw['stop'] |
|
1545 | 1543 | if self.depth == 0 and 'header' in kw.keys(): |
|
1546 | 1544 | print kw['header'] |
|
1547 | 1545 | |
|
1548 | 1546 | for idx in range(start,stop): |
|
1549 | 1547 | elem = lst[idx] |
|
1550 | 1548 | if type(elem)==type([]): |
|
1551 | 1549 | self.depth += 1 |
|
1552 | 1550 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1553 | 1551 | self.depth -= 1 |
|
1554 | 1552 | else: |
|
1555 | 1553 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1556 | 1554 | |
|
1557 | 1555 | nlprint = NLprinter() |
|
1558 | 1556 | #---------------------------------------------------------------------------- |
|
1559 | 1557 | def all_belong(candidates,checklist): |
|
1560 | 1558 | """Check whether a list of items ALL appear in a given list of options. |
|
1561 | 1559 | |
|
1562 | 1560 | Returns a single 1 or 0 value.""" |
|
1563 | 1561 | |
|
1564 | 1562 | return 1-(0 in [x in checklist for x in candidates]) |
|
1565 | 1563 | |
|
1566 | 1564 | #---------------------------------------------------------------------------- |
|
1567 | 1565 | def sort_compare(lst1,lst2,inplace = 1): |
|
1568 | 1566 | """Sort and compare two lists. |
|
1569 | 1567 | |
|
1570 | 1568 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1571 | 1569 | to avoid that (at the cost of temporary copy creation).""" |
|
1572 | 1570 | if not inplace: |
|
1573 | 1571 | lst1 = lst1[:] |
|
1574 | 1572 | lst2 = lst2[:] |
|
1575 | 1573 | lst1.sort(); lst2.sort() |
|
1576 | 1574 | return lst1 == lst2 |
|
1577 | 1575 | |
|
1578 | 1576 | #---------------------------------------------------------------------------- |
|
1579 | 1577 | def mkdict(**kwargs): |
|
1580 | 1578 | """Return a dict from a keyword list. |
|
1581 | 1579 | |
|
1582 | 1580 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1583 | 1581 | # the standard way |
|
1584 | 1582 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1585 | 1583 | # a cleaner way |
|
1586 | 1584 | >>>data = dict(red=1, green=2, blue=3) |
|
1587 | 1585 | |
|
1588 | 1586 | If you need more than this, look at the Struct() class.""" |
|
1589 | 1587 | |
|
1590 | 1588 | return kwargs |
|
1591 | 1589 | |
|
1592 | 1590 | #---------------------------------------------------------------------------- |
|
1593 | 1591 | def list2dict(lst): |
|
1594 | 1592 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1595 | 1593 | |
|
1596 | 1594 | dic = {} |
|
1597 | 1595 | for k,v in lst: dic[k] = v |
|
1598 | 1596 | return dic |
|
1599 | 1597 | |
|
1600 | 1598 | #---------------------------------------------------------------------------- |
|
1601 | 1599 | def list2dict2(lst,default=''): |
|
1602 | 1600 | """Takes a list and turns it into a dict. |
|
1603 | 1601 | Much slower than list2dict, but more versatile. This version can take |
|
1604 | 1602 | lists with sublists of arbitrary length (including sclars).""" |
|
1605 | 1603 | |
|
1606 | 1604 | dic = {} |
|
1607 | 1605 | for elem in lst: |
|
1608 | 1606 | if type(elem) in (types.ListType,types.TupleType): |
|
1609 | 1607 | size = len(elem) |
|
1610 | 1608 | if size == 0: |
|
1611 | 1609 | pass |
|
1612 | 1610 | elif size == 1: |
|
1613 | 1611 | dic[elem] = default |
|
1614 | 1612 | else: |
|
1615 | 1613 | k,v = elem[0], elem[1:] |
|
1616 | 1614 | if len(v) == 1: v = v[0] |
|
1617 | 1615 | dic[k] = v |
|
1618 | 1616 | else: |
|
1619 | 1617 | dic[elem] = default |
|
1620 | 1618 | return dic |
|
1621 | 1619 | |
|
1622 | 1620 | #---------------------------------------------------------------------------- |
|
1623 | 1621 | def flatten(seq): |
|
1624 | 1622 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1625 | 1623 | |
|
1626 | 1624 | return [x for subseq in seq for x in subseq] |
|
1627 | 1625 | |
|
1628 | 1626 | #---------------------------------------------------------------------------- |
|
1629 | 1627 | def get_slice(seq,start=0,stop=None,step=1): |
|
1630 | 1628 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1631 | 1629 | if stop == None: |
|
1632 | 1630 | stop = len(seq) |
|
1633 | 1631 | item = lambda i: seq[i] |
|
1634 | 1632 | return map(item,xrange(start,stop,step)) |
|
1635 | 1633 | |
|
1636 | 1634 | #---------------------------------------------------------------------------- |
|
1637 | 1635 | def chop(seq,size): |
|
1638 | 1636 | """Chop a sequence into chunks of the given size.""" |
|
1639 | 1637 | chunk = lambda i: seq[i:i+size] |
|
1640 | 1638 | return map(chunk,xrange(0,len(seq),size)) |
|
1641 | 1639 | |
|
1642 | 1640 | #---------------------------------------------------------------------------- |
|
1643 | 1641 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1644 | 1642 | # from its old 'with' name. |
|
1645 | 1643 | def with_obj(object, **args): |
|
1646 | 1644 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1647 | 1645 | |
|
1648 | 1646 | Example: |
|
1649 | 1647 | with_obj(jim, |
|
1650 | 1648 | born = 1960, |
|
1651 | 1649 | haircolour = 'Brown', |
|
1652 | 1650 | eyecolour = 'Green') |
|
1653 | 1651 | |
|
1654 | 1652 | Credit: Greg Ewing, in |
|
1655 | 1653 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1656 | 1654 | |
|
1657 | 1655 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1658 | 1656 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1659 | 1657 | |
|
1660 | 1658 | object.__dict__.update(args) |
|
1661 | 1659 | |
|
1662 | 1660 | #---------------------------------------------------------------------------- |
|
1663 | 1661 | def setattr_list(obj,alist,nspace = None): |
|
1664 | 1662 | """Set a list of attributes for an object taken from a namespace. |
|
1665 | 1663 | |
|
1666 | 1664 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1667 | 1665 | alist with their values taken from nspace, which must be a dict (something |
|
1668 | 1666 | like locals() will often do) If nspace isn't given, locals() of the |
|
1669 | 1667 | *caller* is used, so in most cases you can omit it. |
|
1670 | 1668 | |
|
1671 | 1669 | Note that alist can be given as a string, which will be automatically |
|
1672 | 1670 | split into a list on whitespace. If given as a list, it must be a list of |
|
1673 | 1671 | *strings* (the variable names themselves), not of variables.""" |
|
1674 | 1672 | |
|
1675 | 1673 | # this grabs the local variables from the *previous* call frame -- that is |
|
1676 | 1674 | # the locals from the function that called setattr_list(). |
|
1677 | 1675 | # - snipped from weave.inline() |
|
1678 | 1676 | if nspace is None: |
|
1679 | 1677 | call_frame = sys._getframe().f_back |
|
1680 | 1678 | nspace = call_frame.f_locals |
|
1681 | 1679 | |
|
1682 | 1680 | if type(alist) in StringTypes: |
|
1683 | 1681 | alist = alist.split() |
|
1684 | 1682 | for attr in alist: |
|
1685 | 1683 | val = eval(attr,nspace) |
|
1686 | 1684 | setattr(obj,attr,val) |
|
1687 | 1685 | |
|
1688 | 1686 | #---------------------------------------------------------------------------- |
|
1689 | 1687 | def getattr_list(obj,alist,*args): |
|
1690 | 1688 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1691 | 1689 | |
|
1692 | 1690 | Get a list of named attributes for an object. When a default argument is |
|
1693 | 1691 | given, it is returned when the attribute doesn't exist; without it, an |
|
1694 | 1692 | exception is raised in that case. |
|
1695 | 1693 | |
|
1696 | 1694 | Note that alist can be given as a string, which will be automatically |
|
1697 | 1695 | split into a list on whitespace. If given as a list, it must be a list of |
|
1698 | 1696 | *strings* (the variable names themselves), not of variables.""" |
|
1699 | 1697 | |
|
1700 | 1698 | if type(alist) in StringTypes: |
|
1701 | 1699 | alist = alist.split() |
|
1702 | 1700 | if args: |
|
1703 | 1701 | if len(args)==1: |
|
1704 | 1702 | default = args[0] |
|
1705 | 1703 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1706 | 1704 | else: |
|
1707 | 1705 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1708 | 1706 | else: |
|
1709 | 1707 | return map(lambda attr: getattr(obj,attr),alist) |
|
1710 | 1708 | |
|
1711 | 1709 | #---------------------------------------------------------------------------- |
|
1712 | 1710 | def map_method(method,object_list,*argseq,**kw): |
|
1713 | 1711 | """map_method(method,object_list,*args,**kw) -> list |
|
1714 | 1712 | |
|
1715 | 1713 | Return a list of the results of applying the methods to the items of the |
|
1716 | 1714 | argument sequence(s). If more than one sequence is given, the method is |
|
1717 | 1715 | called with an argument list consisting of the corresponding item of each |
|
1718 | 1716 | sequence. All sequences must be of the same length. |
|
1719 | 1717 | |
|
1720 | 1718 | Keyword arguments are passed verbatim to all objects called. |
|
1721 | 1719 | |
|
1722 | 1720 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1723 | 1721 | |
|
1724 | 1722 | out_list = [] |
|
1725 | 1723 | idx = 0 |
|
1726 | 1724 | for object in object_list: |
|
1727 | 1725 | try: |
|
1728 | 1726 | handler = getattr(object, method) |
|
1729 | 1727 | except AttributeError: |
|
1730 | 1728 | out_list.append(None) |
|
1731 | 1729 | else: |
|
1732 | 1730 | if argseq: |
|
1733 | 1731 | args = map(lambda lst:lst[idx],argseq) |
|
1734 | 1732 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1735 | 1733 | out_list.append(handler(args,**kw)) |
|
1736 | 1734 | else: |
|
1737 | 1735 | out_list.append(handler(**kw)) |
|
1738 | 1736 | idx += 1 |
|
1739 | 1737 | return out_list |
|
1740 | 1738 | |
|
1741 | 1739 | #---------------------------------------------------------------------------- |
|
1742 | 1740 | def import_fail_info(mod_name,fns=None): |
|
1743 | 1741 | """Inform load failure for a module.""" |
|
1744 | 1742 | |
|
1745 | 1743 | if fns == None: |
|
1746 | 1744 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
1747 | 1745 | else: |
|
1748 | 1746 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
1749 | 1747 | |
|
1750 | 1748 | #---------------------------------------------------------------------------- |
|
1751 | 1749 | # Proposed popitem() extension, written as a method |
|
1752 | 1750 | |
|
1753 | 1751 | |
|
1754 | 1752 | class NotGiven: pass |
|
1755 | 1753 | |
|
1756 | 1754 | def popkey(dct,key,default=NotGiven): |
|
1757 | 1755 | """Return dct[key] and delete dct[key]. |
|
1758 | 1756 | |
|
1759 | 1757 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1760 | 1758 | KeyError. """ |
|
1761 | 1759 | |
|
1762 | 1760 | try: |
|
1763 | 1761 | val = dct[key] |
|
1764 | 1762 | except KeyError: |
|
1765 | 1763 | if default is NotGiven: |
|
1766 | 1764 | raise |
|
1767 | 1765 | else: |
|
1768 | 1766 | return default |
|
1769 | 1767 | else: |
|
1770 | 1768 | del dct[key] |
|
1771 | 1769 | return val |
|
1772 | 1770 | |
|
1773 | 1771 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
1774 | 1772 | def newFunc(*args, **kwargs): |
|
1775 | 1773 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
1776 | 1774 | ( func.__name__, suggest), |
|
1777 | 1775 | category=DeprecationWarning, |
|
1778 | 1776 | stacklevel = 2) |
|
1779 | 1777 | return func(*args, **kwargs) |
|
1780 | 1778 | return newFunc |
|
1781 | 1779 | |
|
1782 | 1780 | #*************************** end of file <genutils.py> ********************** |
|
1783 | 1781 |
@@ -1,434 +1,434 b'' | |||
|
1 | 1 | ''' IPython customization API |
|
2 | 2 | |
|
3 | 3 | Your one-stop module for configuring & extending ipython |
|
4 | 4 | |
|
5 | 5 | The API will probably break when ipython 1.0 is released, but so |
|
6 | 6 | will the other configuration method (rc files). |
|
7 | 7 | |
|
8 | 8 | All names prefixed by underscores are for internal use, not part |
|
9 | 9 | of the public api. |
|
10 | 10 | |
|
11 | 11 | Below is an example that you can just put to a module and import from ipython. |
|
12 | 12 | |
|
13 | 13 | A good practice is to install the config script below as e.g. |
|
14 | 14 | |
|
15 | 15 | ~/.ipython/my_private_conf.py |
|
16 | 16 | |
|
17 | 17 | And do |
|
18 | 18 | |
|
19 | 19 | import_mod my_private_conf |
|
20 | 20 | |
|
21 | 21 | in ~/.ipython/ipythonrc |
|
22 | 22 | |
|
23 | 23 | That way the module is imported at startup and you can have all your |
|
24 | 24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
25 | 25 | stuff) in there. |
|
26 | 26 | |
|
27 | 27 | ----------------------------------------------- |
|
28 | 28 | import IPython.ipapi |
|
29 | 29 | ip = IPython.ipapi.get() |
|
30 | 30 | |
|
31 | 31 | def ankka_f(self, arg): |
|
32 | 32 | print "Ankka",self,"says uppercase:",arg.upper() |
|
33 | 33 | |
|
34 | 34 | ip.expose_magic("ankka",ankka_f) |
|
35 | 35 | |
|
36 | 36 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
37 | 37 | ip.magic('alias helloworld echo "Hello world"') |
|
38 | 38 | ip.system('pwd') |
|
39 | 39 | |
|
40 | 40 | ip.ex('import re') |
|
41 | 41 | ip.ex(""" |
|
42 | 42 | def funcci(a,b): |
|
43 | 43 | print a+b |
|
44 | 44 | print funcci(3,4) |
|
45 | 45 | """) |
|
46 | 46 | ip.ex("funcci(348,9)") |
|
47 | 47 | |
|
48 | 48 | def jed_editor(self,filename, linenum=None): |
|
49 | 49 | print "Calling my own editor, jed ... via hook!" |
|
50 | 50 | import os |
|
51 | 51 | if linenum is None: linenum = 0 |
|
52 | 52 | os.system('jed +%d %s' % (linenum, filename)) |
|
53 | 53 | print "exiting jed" |
|
54 | 54 | |
|
55 | 55 | ip.set_hook('editor',jed_editor) |
|
56 | 56 | |
|
57 | 57 | o = ip.options |
|
58 | 58 | o.autocall = 2 # FULL autocall mode |
|
59 | 59 | |
|
60 | 60 | print "done!" |
|
61 | 61 | ''' |
|
62 | 62 | |
|
63 | 63 | # stdlib imports |
|
64 | 64 | import __builtin__ |
|
65 | 65 | import sys |
|
66 | 66 | |
|
67 | 67 | # our own |
|
68 | from IPython.genutils import warn,error | |
|
68 | #from IPython.genutils import warn,error | |
|
69 | 69 | |
|
70 | 70 | class TryNext(Exception): |
|
71 | 71 | """Try next hook exception. |
|
72 | 72 | |
|
73 | 73 | Raise this in your hook function to indicate that the next hook handler |
|
74 | 74 | should be used to handle the operation. If you pass arguments to the |
|
75 | 75 | constructor those arguments will be used by the next hook instead of the |
|
76 | 76 | original ones. |
|
77 | 77 | """ |
|
78 | 78 | |
|
79 | 79 | def __init__(self, *args, **kwargs): |
|
80 | 80 | self.args = args |
|
81 | 81 | self.kwargs = kwargs |
|
82 | 82 | |
|
83 | 83 | class IPyAutocall: |
|
84 | 84 | """ Instances of this class are always autocalled |
|
85 | 85 | |
|
86 | 86 | This happens regardless of 'autocall' variable state. Use this to |
|
87 | 87 | develop macro-like mechanisms. |
|
88 | 88 | """ |
|
89 | 89 | |
|
90 | 90 | def set_ip(self,ip): |
|
91 | 91 | """ Will be used to set _ip point to current ipython instance b/f call |
|
92 | 92 | |
|
93 | 93 | Override this method if you don't want this to happen. |
|
94 | 94 | |
|
95 | 95 | """ |
|
96 | 96 | self._ip = ip |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | # contains the most recently instantiated IPApi |
|
100 | 100 | |
|
101 | 101 | class IPythonNotRunning: |
|
102 | 102 | """Dummy do-nothing class. |
|
103 | 103 | |
|
104 | 104 | Instances of this class return a dummy attribute on all accesses, which |
|
105 | 105 | can be called and warns. This makes it easier to write scripts which use |
|
106 | 106 | the ipapi.get() object for informational purposes to operate both with and |
|
107 | 107 | without ipython. Obviously code which uses the ipython object for |
|
108 | 108 | computations will not work, but this allows a wider range of code to |
|
109 | 109 | transparently work whether ipython is being used or not.""" |
|
110 | 110 | |
|
111 | 111 | def __init__(self,warn=True): |
|
112 | 112 | if warn: |
|
113 | 113 | self.dummy = self._dummy_warn |
|
114 | 114 | else: |
|
115 | 115 | self.dummy = self._dummy_silent |
|
116 | 116 | |
|
117 | 117 | def __str__(self): |
|
118 | 118 | return "<IPythonNotRunning>" |
|
119 | 119 | |
|
120 | 120 | __repr__ = __str__ |
|
121 | 121 | |
|
122 | 122 | def __getattr__(self,name): |
|
123 | 123 | return self.dummy |
|
124 | 124 | |
|
125 | 125 | def _dummy_warn(self,*args,**kw): |
|
126 | 126 | """Dummy function, which doesn't do anything but warn.""" |
|
127 | 127 | |
|
128 |
|
|
|
128 | print ("IPython is not running, this is a dummy no-op function") | |
|
129 | 129 | |
|
130 | 130 | def _dummy_silent(self,*args,**kw): |
|
131 | 131 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
132 | 132 | pass |
|
133 | 133 | |
|
134 | 134 | _recent = None |
|
135 | 135 | |
|
136 | 136 | |
|
137 | 137 | def get(allow_dummy=False,dummy_warn=True): |
|
138 | 138 | """Get an IPApi object. |
|
139 | 139 | |
|
140 | 140 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
141 | 141 | instead of None if not running under IPython. |
|
142 | 142 | |
|
143 | 143 | If dummy_warn is false, the dummy instance will be completely silent. |
|
144 | 144 | |
|
145 | 145 | Running this should be the first thing you do when writing extensions that |
|
146 | 146 | can be imported as normal modules. You can then direct all the |
|
147 | 147 | configuration operations against the returned object. |
|
148 | 148 | """ |
|
149 | 149 | global _recent |
|
150 | 150 | if allow_dummy and not _recent: |
|
151 | 151 | _recent = IPythonNotRunning(dummy_warn) |
|
152 | 152 | return _recent |
|
153 | 153 | |
|
154 | 154 | class IPApi: |
|
155 | 155 | """ The actual API class for configuring IPython |
|
156 | 156 | |
|
157 | 157 | You should do all of the IPython configuration by getting an IPApi object |
|
158 | 158 | with IPython.ipapi.get() and using the attributes and methods of the |
|
159 | 159 | returned object.""" |
|
160 | 160 | |
|
161 | 161 | def __init__(self,ip): |
|
162 | 162 | |
|
163 | 163 | # All attributes exposed here are considered to be the public API of |
|
164 | 164 | # IPython. As needs dictate, some of these may be wrapped as |
|
165 | 165 | # properties. |
|
166 | 166 | |
|
167 | 167 | self.magic = ip.ipmagic |
|
168 | 168 | |
|
169 | 169 | self.system = ip.system |
|
170 | 170 | |
|
171 | 171 | self.set_hook = ip.set_hook |
|
172 | 172 | |
|
173 | 173 | self.set_custom_exc = ip.set_custom_exc |
|
174 | 174 | |
|
175 | 175 | self.user_ns = ip.user_ns |
|
176 | 176 | |
|
177 | 177 | self.set_crash_handler = ip.set_crash_handler |
|
178 | 178 | |
|
179 | 179 | # Session-specific data store, which can be used to store |
|
180 | 180 | # data that should persist through the ipython session. |
|
181 | 181 | self.meta = ip.meta |
|
182 | 182 | |
|
183 | 183 | # The ipython instance provided |
|
184 | 184 | self.IP = ip |
|
185 | 185 | |
|
186 | 186 | global _recent |
|
187 | 187 | _recent = self |
|
188 | 188 | |
|
189 | 189 | # Use a property for some things which are added to the instance very |
|
190 | 190 | # late. I don't have time right now to disentangle the initialization |
|
191 | 191 | # order issues, so a property lets us delay item extraction while |
|
192 | 192 | # providing a normal attribute API. |
|
193 | 193 | def get_db(self): |
|
194 | 194 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
195 | 195 | return self.IP.db |
|
196 | 196 | |
|
197 | 197 | db = property(get_db,None,None,get_db.__doc__) |
|
198 | 198 | |
|
199 | 199 | def get_options(self): |
|
200 | 200 | """All configurable variables.""" |
|
201 | 201 | |
|
202 | 202 | # catch typos by disabling new attribute creation. If new attr creation |
|
203 | 203 | # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True) |
|
204 | 204 | # for the received rc struct. |
|
205 | 205 | |
|
206 | 206 | self.IP.rc.allow_new_attr(False) |
|
207 | 207 | return self.IP.rc |
|
208 | 208 | |
|
209 | 209 | options = property(get_options,None,None,get_options.__doc__) |
|
210 | 210 | |
|
211 | 211 | def expose_magic(self,magicname, func): |
|
212 | 212 | ''' Expose own function as magic function for ipython |
|
213 | 213 | |
|
214 | 214 | def foo_impl(self,parameter_s=''): |
|
215 | 215 | """My very own magic!. (Use docstrings, IPython reads them).""" |
|
216 | 216 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' |
|
217 | 217 | print 'The self object is:',self |
|
218 | 218 | |
|
219 | 219 | ipapi.expose_magic("foo",foo_impl) |
|
220 | 220 | ''' |
|
221 | 221 | |
|
222 | 222 | import new |
|
223 | 223 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
224 | 224 | setattr(self.IP, "magic_" + magicname, im) |
|
225 | 225 | |
|
226 | 226 | def ex(self,cmd): |
|
227 | 227 | """ Execute a normal python statement in user namespace """ |
|
228 | 228 | exec cmd in self.user_ns |
|
229 | 229 | |
|
230 | 230 | def ev(self,expr): |
|
231 | 231 | """ Evaluate python expression expr in user namespace |
|
232 | 232 | |
|
233 | 233 | Returns the result of evaluation""" |
|
234 | 234 | return eval(expr,self.user_ns) |
|
235 | 235 | |
|
236 | 236 | def runlines(self,lines): |
|
237 | 237 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
238 | 238 | |
|
239 | 239 | This allows %magic and !shell escape notations. |
|
240 | 240 | |
|
241 | 241 | Takes either all lines in one string or list of lines. |
|
242 | 242 | """ |
|
243 | 243 | if isinstance(lines,basestring): |
|
244 | 244 | self.IP.runlines(lines) |
|
245 | 245 | else: |
|
246 | 246 | self.IP.runlines('\n'.join(lines)) |
|
247 | 247 | |
|
248 | 248 | def to_user_ns(self,vars): |
|
249 | 249 | """Inject a group of variables into the IPython user namespace. |
|
250 | 250 | |
|
251 | 251 | Inputs: |
|
252 | 252 | |
|
253 | 253 | - vars: string with variable names separated by whitespace |
|
254 | 254 | |
|
255 | 255 | This utility routine is meant to ease interactive debugging work, |
|
256 | 256 | where you want to easily propagate some internal variable in your code |
|
257 | 257 | up to the interactive namespace for further exploration. |
|
258 | 258 | |
|
259 | 259 | When you run code via %run, globals in your script become visible at |
|
260 | 260 | the interactive prompt, but this doesn't happen for locals inside your |
|
261 | 261 | own functions and methods. Yet when debugging, it is common to want |
|
262 | 262 | to explore some internal variables further at the interactive propmt. |
|
263 | 263 | |
|
264 | 264 | Examples: |
|
265 | 265 | |
|
266 | 266 | To use this, you first must obtain a handle on the ipython object as |
|
267 | 267 | indicated above, via: |
|
268 | 268 | |
|
269 | 269 | import IPython.ipapi |
|
270 | 270 | ip = IPython.ipapi.get() |
|
271 | 271 | |
|
272 | 272 | Once this is done, inside a routine foo() where you want to expose |
|
273 | 273 | variables x and y, you do the following: |
|
274 | 274 | |
|
275 | 275 | def foo(): |
|
276 | 276 | ... |
|
277 | 277 | x = your_computation() |
|
278 | 278 | y = something_else() |
|
279 | 279 | |
|
280 | 280 | # This pushes x and y to the interactive prompt immediately, even |
|
281 | 281 | # if this routine crashes on the next line after: |
|
282 | 282 | ip.to_user_ns('x y') |
|
283 | 283 | ... |
|
284 | 284 | # return |
|
285 | 285 | |
|
286 | 286 | If you need to rename variables, just use ip.user_ns with dict |
|
287 | 287 | and update: |
|
288 | 288 | |
|
289 | 289 | # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython |
|
290 | 290 | # user namespace |
|
291 | 291 | ip.user_ns.update(dict(x=foo,y=bar)) |
|
292 | 292 | """ |
|
293 | 293 | |
|
294 | 294 | # print 'vars given:',vars # dbg |
|
295 | 295 | # Get the caller's frame to evaluate the given names in |
|
296 | 296 | cf = sys._getframe(1) |
|
297 | 297 | |
|
298 | 298 | user_ns = self.user_ns |
|
299 | 299 | |
|
300 | 300 | for name in vars.split(): |
|
301 | 301 | try: |
|
302 | 302 | user_ns[name] = eval(name,cf.f_globals,cf.f_locals) |
|
303 | 303 | except: |
|
304 |
|
|
|
304 | print ('could not get var. %s from %s' % | |
|
305 | 305 | (name,cf.f_code.co_name)) |
|
306 | 306 | |
|
307 | 307 | def expand_alias(self,line): |
|
308 | 308 | """ Expand an alias in the command line |
|
309 | 309 | |
|
310 | 310 | Returns the provided command line, possibly with the first word |
|
311 | 311 | (command) translated according to alias expansion rules. |
|
312 | 312 | |
|
313 | 313 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
314 | 314 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
315 | 315 | """ |
|
316 | 316 | |
|
317 | 317 | pre,fn,rest = self.IP.split_user_input(line) |
|
318 | 318 | res = pre + self.IP.expand_aliases(fn,rest) |
|
319 | 319 | return res |
|
320 | 320 | |
|
321 | 321 | def defalias(self, name, cmd): |
|
322 | 322 | """ Define a new alias |
|
323 | 323 | |
|
324 | 324 | _ip.defalias('bb','bldmake bldfiles') |
|
325 | 325 | |
|
326 | 326 | Creates a new alias named 'bb' in ipython user namespace |
|
327 | 327 | """ |
|
328 | 328 | |
|
329 | 329 | |
|
330 | 330 | nargs = cmd.count('%s') |
|
331 | 331 | if nargs>0 and cmd.find('%l')>=0: |
|
332 | 332 | raise Exception('The %s and %l specifiers are mutually exclusive ' |
|
333 | 333 | 'in alias definitions.') |
|
334 | 334 | |
|
335 | 335 | else: # all looks OK |
|
336 | 336 | self.IP.alias_table[name] = (nargs,cmd) |
|
337 | 337 | |
|
338 | 338 | def defmacro(self, *args): |
|
339 | 339 | """ Define a new macro |
|
340 | 340 | |
|
341 | 341 | 2 forms of calling: |
|
342 | 342 | |
|
343 | 343 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
344 | 344 | |
|
345 | 345 | (doesn't put the created macro on user namespace) |
|
346 | 346 | |
|
347 | 347 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
348 | 348 | |
|
349 | 349 | (creates a macro named 'build' in user namespace) |
|
350 | 350 | """ |
|
351 | 351 | |
|
352 | 352 | import IPython.macro |
|
353 | 353 | |
|
354 | 354 | if len(args) == 1: |
|
355 | 355 | return IPython.macro.Macro(args[0]) |
|
356 | 356 | elif len(args) == 2: |
|
357 | 357 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
358 | 358 | else: |
|
359 | 359 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
360 | 360 | |
|
361 | 361 | def set_next_input(self, s): |
|
362 | 362 | """ Sets the 'default' input string for the next command line. |
|
363 | 363 | |
|
364 | 364 | Requires readline. |
|
365 | 365 | |
|
366 | 366 | Example: |
|
367 | 367 | |
|
368 | 368 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
369 | 369 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
370 | 370 | """ |
|
371 | 371 | |
|
372 | 372 | self.IP.rl_next_input = s |
|
373 | 373 | |
|
374 | 374 | |
|
375 | 375 | def launch_new_instance(user_ns = None): |
|
376 | 376 | """ Make and start a new ipython instance. |
|
377 | 377 | |
|
378 | 378 | This can be called even without having an already initialized |
|
379 | 379 | ipython session running. |
|
380 | 380 | |
|
381 | 381 | This is also used as the egg entry point for the 'ipython' script. |
|
382 | 382 | |
|
383 | 383 | """ |
|
384 | 384 | ses = make_session(user_ns) |
|
385 | 385 | ses.mainloop() |
|
386 | 386 | |
|
387 | 387 | |
|
388 | 388 | def make_user_ns(user_ns = None): |
|
389 | 389 | """Return a valid user interactive namespace. |
|
390 | 390 | |
|
391 | 391 | This builds a dict with the minimal information needed to operate as a |
|
392 | 392 | valid IPython user namespace, which you can pass to the various embedding |
|
393 | 393 | classes in ipython. |
|
394 | 394 | """ |
|
395 | 395 | |
|
396 | 396 | if user_ns is None: |
|
397 | 397 | # Set __name__ to __main__ to better match the behavior of the |
|
398 | 398 | # normal interpreter. |
|
399 | 399 | user_ns = {'__name__' :'__main__', |
|
400 | 400 | '__builtins__' : __builtin__, |
|
401 | 401 | } |
|
402 | 402 | else: |
|
403 | 403 | user_ns.setdefault('__name__','__main__') |
|
404 | 404 | user_ns.setdefault('__builtins__',__builtin__) |
|
405 | 405 | |
|
406 | 406 | return user_ns |
|
407 | 407 | |
|
408 | 408 | |
|
409 | 409 | def make_user_global_ns(ns = None): |
|
410 | 410 | """Return a valid user global namespace. |
|
411 | 411 | |
|
412 | 412 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
413 | 413 | embedded applications, where there is a distinction between the user's |
|
414 | 414 | interactive namespace and the global one where ipython is running.""" |
|
415 | 415 | |
|
416 | 416 | if ns is None: ns = {} |
|
417 | 417 | return ns |
|
418 | 418 | |
|
419 | 419 | |
|
420 | 420 | def make_session(user_ns = None): |
|
421 | 421 | """Makes, but does not launch an IPython session. |
|
422 | 422 | |
|
423 | 423 | Later on you can call obj.mainloop() on the returned object. |
|
424 | 424 | |
|
425 | 425 | Inputs: |
|
426 | 426 | |
|
427 | 427 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
428 | 428 | data. |
|
429 | 429 | |
|
430 | 430 | WARNING: This should *not* be run when a session exists already.""" |
|
431 | 431 | |
|
432 | 432 | import IPython |
|
433 | 433 | return IPython.Shell.start(user_ns) |
|
434 | 434 |
General Comments 0
You need to be logged in to leave comments.
Login now