Python get module path

25 Python code examples are found related to " get module path". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: utils.py    From mgear_core with MIT License 6 votes vote down vote up
def getModuleBasePath(directories, moduleName):
    """search component path"""

    for basepath, modules in directories.iteritems():
        if moduleName in modules:
            # moduleBasePath = os.path.basename(basepath)
            moduleBasePath = basepath
            break
    else:
        moduleBasePath = ""
        message = "= GEAR RIG SYSTEM ======"
        message += "component base directory not found " \
                   " for {}".format(moduleName)
        mgear.log(message, mgear.sev_error)

    return moduleBasePath 
Example 2
Source File: translate.py    From LibrERP with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_module_from_path(path, mod_paths=None):
        if not mod_paths:
            # First, construct a list of possible paths
            def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons'))     # default addons path (base)
            ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(','))
            mod_paths=[def_path]
            for adp in ad_paths:
                mod_paths.append(adp)
                if not os.path.isabs(adp):
                    mod_paths.append(adp)
                elif adp.startswith(def_path):
                    mod_paths.append(adp[len(def_path)+1:])
        for mp in mod_paths:
            if path.startswith(mp) and (os.path.dirname(path) != mp):
                path = path[len(mp)+1:]
                return path.split(os.path.sep)[0]
        return 'base'   # files that are not in a module are considered as being in 'base' module 
Example 3
Source File: conftest.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def get_module_fqdn_for_path(module_path):
    # type: (str) -> str
    """
    Return fully qualified module name for the provided absolute module path starting with
    scalyr_agent. package.
    """
    index = module_path.find("scalyr_agent")
    if index != -1:
        module_path = module_path[module_path.find("scalyr_agent") :]

    index = module_path.find("tests/unit")
    if index != -1:
        module_path = module_path[module_path.find("tests/unit") :]

    module_fqdn = module_path.replace(os.path.sep, ".").replace(".py", "")

    return module_fqdn


# Skip unloadable modules under different versions 
Example 4
Source File: config.py    From winpython with MIT License 5 votes vote down vote up
def get_module_data_path(
    modname, relpath=None, attr_name='DATAPATH'
):
    """Return module *modname* data path
    Note: relpath is ignored if module has an attribute named *attr_name*

    Handles py2exe/cx_Freeze distributions"""
    datapath = getattr(sys.modules[modname], attr_name, '')
    if datapath:
        return datapath
    else:
        datapath = get_module_path(modname)
        parentdir = osp.join(datapath, osp.pardir)
        if osp.isfile(parentdir):
            # Parent directory is not a directory but the 'library.zip' file:
            # this is either a py2exe or a cx_Freeze distribution
            datapath = osp.abspath(
                osp.join(
                    osp.join(parentdir, osp.pardir), modname
                )
            )
        if relpath is not None:
            datapath = osp.abspath(
                osp.join(datapath, relpath)
            )
        return datapath 
Example 5
Source File: shallow_indexer.py    From SourcetrailPythonIndexer with GNU General Public License v3.0 5 votes vote down vote up
def getNameHierarchyFromModuleFilePath(self, filePath):
		if filePath is None:
			return None

		if filePath == _virtualFilePath:
			return NameHierarchy(NameElement(os.path.splitext(_virtualFilePath)[0]), '.')

		filePath = os.path.abspath(filePath)
		# First remove the suffix.
		for suffix in ['.py']:
			if filePath.endswith(suffix):
				filePath = filePath[:-len(suffix)]
				break

		for p in self.sysPath:
			if filePath.startswith(p):
				rest = filePath[len(p):]
				if rest.startswith(os.path.sep):
					# Remove a slash in cases it's still there.
					rest = rest[1:]
				if rest:
					split = rest.split(os.path.sep)
					for string in split:
						if not string:
							return None

					if split[-1] == '__init__':
						split = split[:-1]

					nameHierarchy = None
					for namePart in split:
						if nameHierarchy is None:
							nameHierarchy = NameHierarchy(NameElement(namePart), '.')
						else:
							nameHierarchy.nameElements.append(NameElement(namePart))
					return nameHierarchy

		return None 
Example 6
Source File: indexer.py    From SourcetrailPythonIndexer with GNU General Public License v3.0 5 votes vote down vote up
def getNameHierarchyFromModulePathOfDefinition(self, definition):
		nameHierarchy = self.getNameHierarchyFromModuleFilePath(definition.module_path)
		if nameHierarchy is not None:
			if nameHierarchy.nameElements[-1].name != definition.name:
				nameHierarchy.nameElements.append(NameElement(definition.name))
		return nameHierarchy 
Example 7
Source File: __init__.py    From pch2csd with MIT License 5 votes vote down vote up
def get_template_module_path(name: int) -> str:
    fn = '{}.txt'.format(name)
    user_tpl = os.path.join(get_template_user_dir(), 'modules', fn)
    if os.path.isfile(user_tpl):
        return user_tpl
    else:
        return os.path.join(get_template_dir(), 'modules', fn) 
Example 8
Source File: path.py    From mindmeld with Apache License 2.0 5 votes vote down vote up
def get_app_module_path(app_path):
    """Gets the path to the application file (app.py) for a given application if it exists.

    Args:
        app_path (str): The path to the app data.

    Returns:
        str: The path of the app module file.
    """
    return APP_MODULE_PATH.format(app_path=app_path) 
Example 9
Source File: path.py    From mindmeld with Apache License 2.0 5 votes vote down vote up
def get_config_module_path(app_path):
    """Gets the path to the configuration file (config.py) for a given application.

    Args:
        app_path (str): The path to the app data.

    Returns:
        str: The path of the config module file.
    """
    return CONFIG_MODULE_PATH.format(app_path=app_path) 
Example 10
Source File: env.py    From polyaxon-client with MIT License 5 votes vote down vote up
def get_module_path():
    try:
        return os.path.dirname(os.path.realpath('__file__'))
    except Exception as e:
        logger.debug('Could not detect module path, %s', e)
        return 'not found' 
Example 11
Source File: env.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def get_module_path():
    try:
        return os.path.dirname(os.path.realpath("__file__"))
    except Exception as e:
        logger.debug("Could not detect module path, %s", e)
        return "not found" 
Example 12
Source File: compatible.py    From OWASP-Honeypot with Apache License 2.0 5 votes vote down vote up
def get_module_dir_path(module):
    """
    get a module path

    Args:
        module: module

    Returns:
        path
    """
    return os.path.dirname(
        inspect.getfile(module)
    ) 
Example 13
Source File: trace.py    From trains-agent with Apache License 2.0 5 votes vote down vote up
def get_module_path(module):
    """
    :param module: Module object or name
    :return: module path
    """
    if isinstance(module, six.string_types):
        module = sys.modules[module]
    path = Path(module.__file__)
    return path.parent if path.stem == '__init__' else path 
Example 14
Source File: conftest.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def get_module_path_for_fqdn(module_fqdn):
    # type: (str) -> str
    """
    Return path to the module based on the module fqdn.
    """
    module_path = module_fqdn.replace(".", os.path.sep) + ".py"
    module_path = os.path.abspath(module_path)
    return module_path 
Example 15
Source File: disthelpers.py    From winpython with MIT License 5 votes vote down vote up
def get_module_path(modname):
    """Return module *modname* base path"""
    module = sys.modules.get(modname, __import__(modname))
    return osp.abspath(osp.dirname(module.__file__))


# ==============================================================================
# Dependency management
# ============================================================================== 
Example 16
Source File: wmme.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def GetModulePath():
   # (hopefully) return the path of the .py file.
   # idea is to leave wmme.py in the same directory as the wmme executable,
   # and import invoke the scripts using it via, for example,
   #   PYTHONPATH=$HOME/dev/wmme:$PYTHONPATH python myscriptfile.py
   import inspect
   return path.dirname(path.abspath(inspect.getfile(inspect.currentframe()))) 
Example 17
Source File: utils.py    From bandit with Apache License 2.0 5 votes vote down vote up
def get_module_qualname_from_path(path):
    '''Get the module's qualified name by analysis of the path.

    Resolve the absolute pathname and eliminate symlinks. This could result in
    an incorrect name if symlinks are used to restructure the python lib
    directory.

    Starting from the right-most directory component look for __init__.py in
    the directory component. If it exists then the directory name is part of
    the module name. Move left to the subsequent directory components until a
    directory is found without __init__.py.

    :param: Path to module file. Relative paths will be resolved relative to
            current working directory.
    :return: fully qualified module name
    '''

    (head, tail) = os.path.split(path)
    if head == '' or tail == '':
        raise InvalidModulePath('Invalid python file path: "%s"'
                                ' Missing path or file name' % (path))

    qname = [os.path.splitext(tail)[0]]
    while head not in ['/', '.', '']:
        if os.path.isfile(os.path.join(head, '__init__.py')):
            (head, tail) = os.path.split(head)
            qname.insert(0, tail)
        else:
            break

    qualname = '.'.join(qname)
    return qualname 
Example 18
Source File: __init__.py    From rush with MIT License 5 votes vote down vote up
def getModulePath(moduleDirPath):
    """ Create and return a list of module paths

    Args:
        moduleDirPath (str): directory path to search modules

    Return:
        mods (list): List of module paths
        None: if the path doesn't exist

    """
    if not os.path.exists(moduleDirPath):
        return None

    # Get all files in the directory
    allFiles = [os.path.join(root, filePath) for root, _, files
                in os.walk(moduleDirPath) for filePath in files]

    # Get only python files
    pythonFiles = [i for i in allFiles if i.endswith(".py")]

    # Remove __init__ and main plugin file
    mods = [filePath for filePath in pythonFiles
            if not filePath.endswith("__init__.py") and not filePath.endswith("Rush.py")]

    return mods 
Example 19
Source File: module.py    From royal-chaos with MIT License 5 votes vote down vote up
def get_module_path(self):
        """Get the full [module, submodule, submodule,...] path """
        names = [self.name]
        parent = self.parent
        while parent is not None:
            names.insert(0, parent.name)
            parent = parent.parent
        return names 
Example 20
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 5 votes vote down vote up
def get_module_path(): # Redundant with os.getcwd() at opening; not needed?  Tacotime
    """Return the folder containing this script (or its .exe)."""
    module_name = sys.executable if hasattr(sys, 'frozen') else __file__
    abs_path = os.path.abspath(module_name)
    return os.path.dirname(abs_path) 
Example 21
Source File: setup.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getModulePath():
    '''
    Returns the Main path to the root module folder
    '''
    return os.path.join(os.path.dirname(SCRIPT_DIRECTORY),'').replace('\\', '/')

#---------------------------------------------------------------------- 
Example 22
Source File: path.py    From Computable with MIT License 5 votes vote down vote up
def get_ipython_module_path(module_str):
    """Find the path to an IPython module in this version of IPython.

    This will always find the version of the module that is in this importable
    IPython package. This will always return the path to the ``.py``
    version of the module.
    """
    if module_str == 'IPython':
        return os.path.join(get_ipython_package_dir(), '__init__.py')
    mod = import_item(module_str)
    the_path = mod.__file__.replace('.pyc', '.py')
    the_path = the_path.replace('.pyo', '.py')
    return py3compat.cast_unicode(the_path, fs_encoding) 
Example 23
Source File: git_utils.py    From nucleus7 with Mozilla Public License 2.0 5 votes vote down vote up
def get_git_revision_hash_from_module_path(module_path,
                                           default_package='nucleus7'
                                           ) -> Union[str, None]:
    """

    Parameters
    ----------
    module_path
        path to imported module
    default_package
        name of default package of that module to use if the module has no
        __file__ attribute

    Returns
    -------
    git_hash
        ash of the git directory with module
    """
    if module_path is None:
        module_path = ''
    package = '.'.join(module_path.split('.')[:-1]) or default_package
    try:
        package_path = importlib.import_module(package).__file__
    except (AttributeError, ImportError):
        return None
    try:
        cwd = os.path.split(package_path)[0]
        git_hash = get_git_revision_hash_from_dir(cwd)
    except (subprocess.CalledProcessError, NotADirectoryError):
        git_hash = None
    return git_hash 
Example 24
Source File: TestRunner.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_module_path():
    frame = inspect.currentframe().f_back
    info = inspect.getframeinfo(frame)
    file_name = info.filename
    return os.path.dirname(os.path.abspath(file_name)) 
Example 25
Source File: pycompat.py    From YAPyPy with MIT License 5 votes vote down vote up
def get_yapypy_module_spec_from_path(names, module_path):
    with Path(module_path).open('r') as fr:
        spec = ModuleSpec(names, YAPyPyLoader(names, module_path))
        __source__ = fr.read()
        result = parse(__source__, module_path)
        check_parsing_complete(__source__, result.tokens, result.state)

        __bytecode__ = py_compile(
            result.result, filename=module_path, is_entrypoint=False)
        spec.__source__ = __source__
        spec.__bytecode__ = __bytecode__
        return spec