Find Packages in Python

This may not be the best way to do it, but getting stuff into the PYTHONPATH can be kind of a pain. Here’s some code that traverses the directory structure and adds any packages it finds.

There are lots of reasons you shouldn’t do this 😉 but I might use it as a starting point later if I have a good-sized app that I want to pull into an app.

Note that in this form, it starts at “os.getcwd()” (i.e. the current working directory) instead of “os.dirname(__file__)” (i.e. the directory containing the current file). That’s just because of the context I’m using it in.

def add():
    for root, dirs, files in os.walk(os.getcwd()):
        if root != os.getcwd():
            init = os.path.join(root, '__init__.py')
            if os.path.isfile(init):
                logging.info('add {}'.format(root))
                sys.path.append(root)

    logging.info(pformat(sys.path))
Advertisements

Leave a comment

Filed under python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s