diff options
Diffstat (limited to 'shellutils.py')
-rw-r--r-- | shellutils.py | 59 |
1 files changed, 57 insertions, 2 deletions
diff --git a/shellutils.py b/shellutils.py index 18bd75d..da4f355 100644 --- a/shellutils.py +++ b/shellutils.py @@ -1,4 +1,4 @@ -# Copyright (c) 2003-2005 LOGILAB S.A. (Paris, FRANCE). +# Copyright (c) 2003-2006 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # This program is free software; you can redistribute it and/or modify it under @@ -14,13 +14,16 @@ # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ -Some shell utilities, usefull to write some python scripts instead of shell +Some shell/term utilities, useful to write some python scripts instead of shell scripts """ import os import glob import shutil +import sys +import tempfile +import time from os.path import exists, isdir, basename, join def mv(source, destination, _action=os.rename): @@ -59,3 +62,55 @@ def cp(source, destination): """ mv(source, destination, _action=shutil.copy) + +class Execute: + """This is a deadlock safe version of popen2 (no stdin), that returns + an object with errorlevel, out and err + """ + + def __init__(self, command): + outfile = tempfile.mktemp() + errfile = tempfile.mktemp() + self.status = os.system("( %s ) >%s 2>%s" % + (command, outfile, errfile)) >> 8 + self.out = open(outfile,"r").read() + self.err = open(errfile,"r").read() + os.remove(outfile) + os.remove(errfile) + +def acquire_lock(lock_file, max_try=10, delay=10): + """acquire a lock represented by a file on the file system""" + count = 0 + while max_try <= 0 or count < max_try: + if not exists(lock_file): + break + count += 1 + time.sleep(delay) + else: + raise Exception('Unable to acquire %s' % lock_file) + stream = open(lock_file, 'w') + stream.write(str(os.getpid())) + stream.close() + +def release_lock(lock_file): + """release a lock represented by a file on the file system""" + os.remove(lock_file) + + +class ProgressBar(object): + """a simple text progression bar""" + + def __init__(self, nbops, size=20., stream=sys.stdout): + self._dotevery = max(nbops / size, 1) + self._fstr = '\r[%-20s]' + self._dotcount, self._dots = 1, [] + self._stream = stream + + def update(self): + """update the progression bar""" + self._dotcount += 1 + if self._dotcount >= self._dotevery: + self._dotcount = 1 + self._dots.append('.') + self._stream.write(self._fstr % ''.join(self._dots)) + self._stream.flush() |