Welcome, guest | Sign In | My Account | Store | Cart

Add all dirs under folder to sys.path if any .py files are found. Use an abspath if you'd rather do it that way.

Uses the current working directory as the location of using.py. Keep in mind that os.walk goes all the way down the directory tree.

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import sys, os.path

def all_from(folder='', abspath=None):
    """add all dirs under `folder` to sys.path if any .py files are found.
    Use an abspath if you'd rather do it that way.

    Uses the current working directory as the location of using.py. 
    Keep in mind that os.walk goes *all the way* down the directory tree.
    With that, try not to use this on something too close to '/'

    """
    add = set(sys.path)
    if abspath is None:
        cwd = os.path.abspath(os.path.curdir)
        abspath = os.path.join(cwd, folder)
    for root, dirs, files in os.walk(abspath):
        for f in files:
            if f[-3:] in '.py':
                add.add(root)
    for i in add: sys.path.append(i)

I made this because I have a random folder here and there that isn't packaged with disutils, but never the less I might need it from time to time. Using this, I just point to the folder, or it's parent, and grab every .py file under it to my sys.path.

Obviously, there might be some naming conflicts if you're bringing in lots of modules at once. Try not to use this on something too close to '/'