import traceback
import os
import sys

def parent(path):
    if path.endswith(os.path.sep):
        path = path[:len(os.path.sep)]
    return os.path.split(path)[0]

def findpackageparent(path):
    if not os.path.exists(path):
        return None
    path = os.path.abspath(path)
    if not os.path.isdir(path):
        path = parent(path)
    while 1:
        if (not os.path.exists(os.path.join(path, '__init__.py')) and
                not os.path.exists(os.path.join(path, '__init__.pyc'))):
            return path
        path = parent(path)

stack = traceback.extract_stack()
filename = stack[-2][0]
path = findpackageparent(filename)

if path is not None:
    sys.path.insert(0, path)


