librelist archives

« back to archive

Fabric tip

Fabric tip

From:
Jonas Galvez
Date:
2010-11-29 @ 19:38
I've been using Fabric to manage all my projects. But it got to a
point where I had dozens of unrelated tasks in fabfile.py.

The latest stable version of Fabric lets you use a module (i.e.,
fabfile directroy with a __init__.py file in it). But I didn't want to
a) have to manually import the "sub-fabfiles" manually neither did I
want to import all tiny dependencies in each of my sub-fabfiles.
Here's I came up with:

In __init__.py, load all dependencies at the top, and place the
following piece of code to automatically load all .py files under
fabfile/ and update their namespaces with the contents of the current
namespace:

import glob

pre_globals = dict([(key, value) for key, value in globals().items()])

for fabfile in [py for py in glob.glob('fabfile/*.py') if not
py.endswith('__init__.py')]:
  module_name = os.path.splitext(os.path.split(fabfile)[1])[0]
  module = __import__(module_name, globals(), locals(), ['*'], -1)
  for key in pre_globals.keys():
    setattr(module, key, pre_globals[key])
  for key in dir(module):
    if not re.match('^__.+__$', key):
      globals()[key] = getattr(module, key)

Works in 2.5. So now I have a fabfile/ directroy under my project with
files like database.py, backup.py, serving.py, tests.py etc. And I can
add as many as I want without touching __init__.py and without having
to import all needed libraries in each one of them.

Hope this is useful to somebody.

-- Jonas

Re: Fabric tip

From:
Jonas Galvez
Date:
2010-11-29 @ 19:39
> The latest stable version of Fabric lets you use a module (i.e.,
> fabfile directroy with a __init__.py file in it). But I didn't want to
> a) have to manually import the "sub-fabfiles" manually neither did I
> want to import all tiny dependencies in each of my sub-fabfiles.

Heh, that sentence came out broken!

-- Jonas