From d6f5892b69eed28b0248b464402169c3e729b6ca Mon Sep 17 00:00:00 2001 From: Michael Hanselmann Date: Thu, 3 Sep 2009 12:45:04 +0200 Subject: [PATCH] Move LoadModule function to utils It can be used by unittests for daemons/* or scripts/*. Signed-off-by: Michael Hanselmann Reviewed-by: Luca Bigliardi --- autotools/build-bash-completion | 19 +++---------------- lib/utils.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/autotools/build-bash-completion b/autotools/build-bash-completion index 6f39ef5..b0522b1 100755 --- a/autotools/build-bash-completion +++ b/autotools/build-bash-completion @@ -19,7 +19,6 @@ # 02110-1301, USA. -import imp import optparse import os import sys @@ -504,19 +503,6 @@ def GetFunctionName(name): return "_" + re.sub(r"[^a-z0-9]+", "_", name.lower()) -def LoadModule(filename): - """Loads an external module by filename. - - """ - (name, ext) = os.path.splitext(filename) - - fh = open(filename, "U") - try: - return imp.load_module(name, fh, filename, (ext, "U", imp.PY_SOURCE)) - finally: - fh.close() - - def GetCommands(filename, module): """Returns the commands defined in a module. @@ -551,10 +537,11 @@ def main(): WriteCompletion(sw, scriptname, GetFunctionName(scriptname), - commands=GetCommands(filename, LoadModule(filename))) + commands=GetCommands(filename, + utils.LoadModule(filename))) # Burnin script - burnin = LoadModule("tools/burnin") + burnin = utils.LoadModule("tools/burnin") WriteCompletion(sw, "%s/burnin" % constants.TOOLSDIR, "_ganeti_burnin", opts=burnin.OPTIONS, args=burnin.ARGUMENTS) diff --git a/lib/utils.py b/lib/utils.py index 5a23d70..1e78b7f 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -42,6 +42,7 @@ import fcntl import resource import logging import signal +import imp from cStringIO import StringIO @@ -1992,6 +1993,25 @@ def ReadWatcherPauseFile(filename, now=None, remove_after=3600): return value +def LoadModule(filename): + """Loads an external module by filename. + + Use this function with caution. Python will always write the compiled source + to a file named "${filename}c". + + @type filename: string + @param filename: Path to module + + """ + (name, ext) = os.path.splitext(filename) + + fh = open(filename, "U") + try: + return imp.load_module(name, fh, filename, (ext, "U", imp.PY_SOURCE)) + finally: + fh.close() + + class FileLock(object): """Utility class for file locks. -- 1.7.10.4