/usr/share/pyshared/FreeFOAM/util.py is in libfreefoam1 0.1.0+dfsg-1build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | #-------------------------------------------------------------------------------
# ______ _ ____ __ __
# | ____| _| |_ / __ \ /\ | \/ |
# | |__ _ __ ___ ___ / \| | | | / \ | \ / |
# | __| '__/ _ \/ _ ( (| |) ) | | |/ /\ \ | |\/| |
# | | | | | __/ __/\_ _/| |__| / ____ \| | | |
# |_| |_| \___|\___| |_| \____/_/ \_\_| |_|
#
# FreeFOAM: The Cross-Platform CFD Toolkit
#
# Copyright (C) 2008-2012 Michael Wild <themiwi@users.sf.net>
# Gerber van der Graaf <gerber_graaf@users.sf.net>
#-------------------------------------------------------------------------------
# License
# This file is part of FreeFOAM.
#
# FreeFOAM is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# FreeFOAM is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with FreeFOAM. If not, see <http://www.gnu.org/licenses/>.
#
# Description
# Useful Python functionality
#
#-------------------------------------------------------------------------------
"""Classes and functions to manage FreeFOAM cases."""
from FreeFOAM.compat import *
import sys as _sys
import os as _os
import os.path as _op
import re as _re
import FreeFOAM as _f
class NoPolyMeshDirectoryError(Exception):
"""Thrown if no polyMesh directory could be found"""
def __init__(self):
Exception.__init__(self)
def __str__(self):
return 'Failed to find a polyMesh directory'
class Tee:
"""A simple class which writes both to a file and standard output.
It only implements the following functions from `file`:
* `Tee.write`
* `Tee.writelines`
* `Tee.flush`
* `Tee.fileno`
"""
def __init__(self, fname, *args):
"""Initializes a new instance of `Tee`.
Parameters
----------
fname : name of the file to write to
mode : file mode (as in `open()`)
buffering : buffering option (as in `open()`)
"""
self._file = open(fname, *args)
self._stdout = _os.fdopen(_os.dup(_sys.stdout.fileno()), 'w')
def write(self, string):
"""Write `string` to the file and standard output"""
self._file.write(string)
self._stdout.write(string)
def writelines(self, strings):
"""Write `strings` to the file and standard output"""
self._file.writelines(strings)
self._stdout.writelines(strings)
def flush(self):
"""Flush the streams"""
self._file.flush()
self._stdout.flush()
def fileno(self):
"""Return the handle of the file stream"""
return self._file.fileno()
def clone_case(old_case, new_case, verbose=True):
"""Clone a FreeFOAM case if the `new_case+'/system'` directory doesn't exist
Parameters
----------
old_case : The source case to be cloned.
new_case : The destination case to be created.
"""
if not _op.exists(_op.join(new_case, 'system')):
if verbose: echo('Cloning case %s'%old_case)
for d in ['0', 'system', 'constant', 'chemkin']:
if _op.isdir(_op.join(old_case, d)):
copytree(
_op.join(old_case, d),
_op.join(new_case, d),
symlinks=True)
def remove_case(case='.', verbose=True):
"""Removes a case directory"""
echo('Removing case %s'%case)
rmtree(case)
def clean_case(case='.', verbose=True):
"""Clean a case by removing generated files and directories"""
import glob
import shutil
case=_op.abspath(case)
if verbose: echo('Cleaning case', case)
patterns = ['[1-9]*', '-[1-9]*', 'log', 'log.*', 'log-*', 'logSummary.*',
'.fxLock', '*.xml', 'ParaView*', 'paraFoam*', '*.OpenFOAM',
'processor*', 'probes*', 'forces*', 'system/machines', 'VTK']
for nZeros in range(8):
timeDir = '0.'+nZeros*'0'+'[1-9]*'
for p in ['', '-']:
patterns.append(_op.join(case, p+timeDir))
for p in ('allOwner cell face meshModifiers owner neighbour point edge'+
'cellLevel pointLevel refinementHistory surfaceIndex sets').split():
patterns.append(_op.join(case, 'constant', 'polyMesh', p+'*'))
for p in 'cellToRegion cellLevel pointLevel'.split():
patterns.append(_op.join(case, 'constant', p+'*'))
for p in patterns:
for dd in glob.glob(_op.join(case, p)):
rmtree(dd)
def clean_samples(case='.'):
"""Remove sample directories"""
for d in 'sets samples sampleSurfaces'.split():
rmtree(d)
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete all files/directories under `path`
(if `path` exists)"""
import shutil
import os
path = _op.abspath(path)
if _op.isdir(path):
shutil.rmtree(path, ignore_errors, onerror)
elif _op.isfile(path) or _op.islink(path):
os.remove(path)
def copytree(src, dst, symlinks=True):
"""Recursively copies `src` to `dst`. If `dst` exists,
it is removed first."""
import shutil
src = _op.abspath(src)
dst = _op.abspath(dst)
rmtree(dst)
parent = _op.dirname(dst)
if not _op.isdir(parent):
_os.makedirs(parent)
if _op.isdir(src):
shutil.copytree(src, dst, symlinks)
else:
shutil.copy2(src, dst)
def rename(src, dst):
"""Forcebly renames `src` to `dst`. `dst` is removed first if it exists."""
import shutil
src = _op.normpath(src)
dst = _op.normpath(dst)
if _op.exists(dst):
rmtree(dst)
shutil.move(src, dst)
def clear_polymesh(case=None, region=None):
"""Remove the contents of the constant/polyMesh directory as per the
Foam::polyMesh::removeFiles() method.
Parameters
----------
case : Case directory from which to clear the mesh
region : Mesh region to clear.
"""
meshDir = 'polyMesh'
if region:
meshDir = _op.join(region, meshDir)
tmp = _op.join('constant', meshDir)
if case:
meshDir = _op.join(case, tmp)
else:
if _op.isdir(tmp):
meshDir = tmp
elif _op.isdir(meshDir):
# probably already in 'constant'
pass
elif _op.basename(_os.getcwd()) == 'polyMesh':
# probably already in 'polyMesh'
meshDir = _os.getcwd()
if not _op.isdir(meshDir):
raise NoPolyMeshDirectoryError()
for f in """points faces owner neighbour cells boundary pointZones faceZones
cellZones meshModifiers parallelData sets cellLevel pointLevel
refinementHistory surfaceIndex""".split():
f = _op.join(meshDir, f)
if _op.isfile(f):
_os.remove(f)
def make_short_path(path, maxlen=40):
"""Abbreviate `path` to a maximum length of `maxlen` characters."""
path = _op.abspath(path)
first = 2-maxlen
if len(path) > maxlen:
idx = path.find(_os.sep, first)
if idx < 0:
idx = first
path = '...'+path[idx:]
return path
class TerminalController:
"""
A class that can be used to portably generate formatted output to
a terminal.
`TerminalController` defines a set of instance variables whose
values are initialized to the control sequence necessary to
perform a given action. These can be simply included in normal
output to the terminal:
>>> term = TerminalController()
>>> print 'This is '+term.GREEN+'green'+term.NORMAL
Alternatively, the `render()` method can used, which replaces
'${action}' with the string required to perform 'action':
>>> term = TerminalController()
>>> print term.render('This is ${GREEN}green${NORMAL}')
If the terminal doesn't support a given action, then the value of
the corresponding instance variable will be set to ''. As a
result, the above code will still work on terminals that do not
support color, except that their output will not be colored.
Also, this means that you can test whether the terminal supports a
given action by simply testing the truth value of the
corresponding instance variable:
>>> term = TerminalController()
>>> if term.CLEAR_SCREEN:
... print 'This terminal supports clearning the screen.'
Finally, if the width and height of the terminal are known, then
they will be stored in the `COLS` and `LINES` attributes.
Copied from http://code.activestate.com/recipes/475116-using-terminfo-for-portable-color-output-cursor-co
"""
# Cursor movement:
BOL = '' #: Move the cursor to the beginning of the line
UP = '' #: Move the cursor up one line
DOWN = '' #: Move the cursor down one line
LEFT = '' #: Move the cursor left one char
RIGHT = '' #: Move the cursor right one char
# Deletion:
CLEAR_SCREEN = '' #: Clear the screen and move to home position
CLEAR_EOL = '' #: Clear to the end of the line.
CLEAR_BOL = '' #: Clear to the beginning of the line.
CLEAR_EOS = '' #: Clear to the end of the screen
# Output modes:
BOLD = '' #: Turn on bold mode
BLINK = '' #: Turn on blink mode
DIM = '' #: Turn on half-bright mode
REVERSE = '' #: Turn on reverse-video mode
NORMAL = '' #: Turn off all modes
# Cursor display:
HIDE_CURSOR = '' #: Make the cursor invisible
SHOW_CURSOR = '' #: Make the cursor visible
# Terminal size:
COLS = None #: Width of the terminal (None for unknown)
LINES = None #: Height of the terminal (None for unknown)
# Foreground colors:
BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = ''
# Background colors:
BG_BLACK = BG_BLUE = BG_GREEN = BG_CYAN = ''
BG_RED = BG_MAGENTA = BG_YELLOW = BG_WHITE = ''
_STRING_CAPABILITIES = """
BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1
CLEAR_SCREEN=clear CLEAR_EOL=el CLEAR_BOL=el1 CLEAR_EOS=ed BOLD=bold
BLINK=blink DIM=dim REVERSE=rev UNDERLINE=smul NORMAL=sgr0
HIDE_CURSOR=civis SHOW_CURSOR=cnorm""".split()
_COLORS = """BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE""".split()
_ANSICOLORS = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".split()
def __init__(self, term_stream=_sys.stdout):
"""
Create a `TerminalController` and initialize its attributes
with appropriate values for the current terminal.
`term_stream` is the stream that will be used for terminal
output; if this stream is not a tty, then the terminal is
assumed to be a dumb terminal (i.e., have no capabilities).
"""
# Curses isn't available on all platforms
try: import curses
except: return
# If the stream isn't a tty, then assume it has no capabilities.
if hasattr(_sys.stdout, 'isatty'):
if not term_stream.isatty(): return
# Check the terminal type. If we fail, then assume that the
# terminal has no capabilities.
try: curses.setupterm()
except: return
# Look up numeric capabilities.
self.COLS = curses.tigetnum('cols')
self.LINES = curses.tigetnum('lines')
# Look up string capabilities.
for capability in self._STRING_CAPABILITIES:
(attrib, cap_name) = capability.split('=')
setattr(self, attrib, self._tigetstr(cap_name) or '')
# Colors
set_fg = self._tigetstr('setf')
if set_fg:
for i,color in enumerate(self._COLORS):
setattr(self, color,
self._tparm(set_fg, i) or '')
set_fg_ansi = self._tigetstr('setaf')
if set_fg_ansi:
for i,color in enumerate(self._ANSICOLORS):
setattr(self, color,
self._tparm(set_fg_ansi, i) or '')
set_bg = self._tigetstr('setb')
if set_bg:
for i,color in enumerate(self._COLORS):
setattr(self, 'BG_'+color,
self._tparm(set_bg, i) or '')
set_bg_ansi = self._tigetstr('setab')
if set_bg_ansi:
for i,color in enumerate(self._ANSICOLORS):
setattr(self, 'BG_'+color,
self._tparm(set_bg_ansi, i) or '')
def _tigetstr(self, cap_name):
# String capabilities can include "delays" of the form "$<2>".
# For any modern terminal, we should be able to just ignore
# these, so strip them out.
import curses
cap = curses.tigetstr(cap_name)
if cap:
cap = cap.decode()
else:
cap = ''
return _re.sub(r'\$<\d+>[/*]?', '', cap)
def _tparm(self, parm, i):
import curses
res = curses.tparm(parm, i)
if res:
res = res.decode()
return res
def render(self, template):
"""
Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not).
"""
return _re.sub(r'\$\$|\${\w+}', self._render_sub, template)
def _render_sub(self, match):
s = match.group()
if s == '$$': return s
else:
return getattr(self, s[2:-1])
def cecho(*args, **kwargs):
"""print() replacement which does colored output if supported.
The following sequences will be replaced in the `args`:
* ${BOLD} : Turn on bold mode
* ${BLINK} : Turn on blink mode
* ${DIM} : Turn on half-bright mode
* ${REVERSE} : Turn on reverse-video mode
* ${NORMAL} : Turn off all modes
* ${<COLOR>} : Set text color to <COLOR>
* ${<BG_COLOR>} : Set background color to <BG_COLOR>
The available colors are:
* BLACK
* BLUE
* GREEN
* CYAN
* RED
* MAGENTA
* YELLOW
* WHITE
The valid background colors are:
* BG_BLACK
* BG_BLUE
* BG_GREEN
* BG_CYAN
* BG_RED
* BG_MAGENTA
* BG_YELLOW
* BG_WHITE
"""
term = TerminalController()
parts = list(args)
for i, s in enumerate(parts):
if type(s) == str:
parts[i] = term.render(s)
echo(*parts, **kwargs)
def cerror(*args, **kwargs):
"""Print a message, preceded with a bold, red '*** Error***' flag"""
cecho("${RED}${BOLD}*** Error ***${NORMAL}", *args, **kwargs)
# ------------------------- vim: set sw=3 sts=3 et: --------------- end-of-file
|