treporting.py - pism - [fork] customized build of PISM, the parallel ice sheet model (tillflux branch)
(HTM) git clone git://src.adamsgaard.dk/pism
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) LICENSE
---
treporting.py (5990B)
---
1 ############################################################################
2 #
3 # This file is a part of siple.
4 #
5 # Copyright 2010-2011 David Maxwell
6 #
7 # siple is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 ############################################################################
13
14 import inspect
15 import os.path
16 # This file contains functions helpful work working with python in an interactive session.
17
18 logFile = None
19 def logToFile(b):
20 """Indicates if |siple| output should be saved to a log file. If *b* is a file name, output
21 is saved there. Otherwise *b* should be a boolean. If it is :data:`True`, the log file name
22 is taken from the name of the calling python file (with '.py' replaced with '.log').
23 If *b* is :data:`False` then file logging is turned off.
24 """
25 global logFile
26 if isinstance(b,str):
27 logFile = file(string,'w')
28 else:
29 if b:
30 calling_file=inspect.getouterframes(inspect.currentframe())[1][1]
31 log_file = os.path.splitext(calling_file)[0]+'.log'
32 logFile=file(log_file,'w')
33 else:
34 if not logFile is None:
35 logFile.close()
36 logFile = None
37
38 kPRATTLE=4
39 kDEBUG=3
40 kMESSAGE=2
41 kWARNING=1
42 kERROR=0
43 kSeverityDesc = [ "Error", "Warning", "Message", "DEBUG", "BLAHBLAH"]
44
45 # Default loggers
46 def logprint(message,severity):
47 print(message)
48 if severity <= kWARNING:
49 beep()
50
51 def logfile(message,severity):
52 global logFile
53 if not logFile is None:
54 logFile.write(message)
55 logFile.write('\n')
56 logFile.flush()
57
58 loggers = [ logprint, logfile ]
59
60 def clear_loggers():
61 global loggers
62 loggers = []
63
64 def add_logger(logger):
65 global loggers
66 loggers.append(logger)
67
68 def _format_message(caller_level,severity,s,*args):
69 framerec = inspect.stack()[1+caller_level]
70 calling_module = inspect.getmodule(framerec[0])
71 f=inspect.getouterframes(inspect.currentframe())[1+caller_level]
72 caller_name = os.path.basename(f[1])
73 if isinstance(f[3],str):
74 caller_name += (':%s' % f[3])
75 if severity == kMESSAGE:
76 sevdesc = ""
77 else:
78 sevdesc = "(%s)" % kSeverityDesc[severity]
79
80 message = '%s:%s %s' % (caller_name, sevdesc, s % args)
81 return message
82
83 format_message = _format_message
84 def set_message_formatter(formatter):
85 global format_message
86 format_message = formatter
87
88 def msg(s,*args):
89 """
90 Print a nicely formatted message.
91 """
92 global loggers
93 caller_level = 1
94 severity=kMESSAGE
95 message = format_message(caller_level,severity,s,*args)
96 for l in loggers:
97 l(message,severity)
98
99 def prattle(s,*args):
100 """
101 Print a nicely formatted message.
102 """
103 global loggers
104 caller_level=1
105 severity=kPRATTLE
106 message = _format_message(caller_level,severity,*args)
107 for l in loggers:
108 l(message,severity)
109
110 def debug(s,*args):
111 global loggers
112 caller_level=1
113 severity=kDEBUG
114 message = _format_message(caller_level,severity,*args)
115 for l in loggers:
116 l(message,severity)
117
118 def pause(message_in="Computation paused. Press any key to continue.",
119 message_out='Continued'):
120 pause_callback(message_in,message_out)
121
122 def set_pause_callback(callback):
123 global pause_callback
124 pause_callback = callback
125
126 def std_pause(message_in=None,message_out=None):
127 """
128 Halt computation until a key is pressed.
129 """
130 if not message_in is None:
131 print(message_in)
132 getch()
133 if not message_out is None:
134 print(message_out)
135
136 pause_callback = std_pause
137
138
139
140 def in_ipython():
141 "Determines if the python interpreter is ipython."
142 try:
143 __IPYTHON__
144 except NameError:
145 return False
146 else:
147 return True
148
149 def endpause(message_in='Script done. Press any key to continue',message_out=None,
150 python_only=True):
151 """
152 Wait for a keypress after displaying a helpful message. Typically used at
153 the end of a script. If python_only=True, the message and wait are skipped
154 when running under ipython.
155 """
156 if (not python_only) or (not in_ipython()):
157 pause(message_in,message_out)
158
159 def beep():
160 "Beeps."
161 print('\a')
162
163
164 ## The following Getch fucntions are taken from {{{ http://code.activestate.com/recipes/134892/ (r2)
165 class _Getch:
166 """Gets a single character from standard input. Does not echo to the
167 screen."""
168 def __init__(self):
169 try:
170 self.impl = _GetchWindows()
171 except ImportError:
172 self.impl = _GetchUnix()
173
174 def __call__(self): return self.impl()
175
176 class _GetchUnix:
177 def __init__(self):
178 import sys, termios, fcntl, os
179
180 def __call__(self):
181 import sys, termios, fcntl, os
182 fd = sys.stdin.fileno()
183 oldattr = termios.tcgetattr(fd)
184 oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
185 c = 0
186 try:
187 newattr = termios.tcgetattr(fd)
188 newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
189 termios.tcsetattr(fd, termios.TCSANOW, newattr)
190 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
191
192 while True:
193 try:
194 c=sys.stdin.read(1)
195 break
196 except IOError: pass
197
198 finally:
199 termios.tcsetattr(fd, termios.TCSADRAIN, oldattr)
200 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
201
202 return c
203
204 class _GetchUnixOrig:
205 def __init__(self):
206 import tty, sys, termios
207
208 def __call__(self):
209 fd = sys.stdin.fileno()
210 old_settings = termios.tcgetattr(fd)
211 try:
212 tty.setraw(sys.stdin.fileno())
213 ch = sys.stdin.read(1)
214 finally:
215 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
216 return ch
217
218
219 class _GetchWindows:
220 def __init__(self):
221 import msvcrt
222
223 def __call__(self):
224 import msvcrt
225 return msvcrt.getch()
226
227
228 getch = _Getch()
229 ## end of http://code.activestate.com/recipes/134892/ }}}