Run a module from a path and return its variables.
161651
def run_file(path):
    """"""
    if PY26:
        dirpath, name, _ = splitname(path)
        found = imp.find_module(name, [dirpath])
        module = imp.load_module("__main__", *found)
        return vars(module)
    else:
        return runpy.run_path(path, run_name="__main__")
313260
def run(self, module, dependency=False, kwargs={}):
        '''
        
        '''
        try:
            obj = self.load(module, kwargs)

            if isinstance(obj, binwalk.core.module.Module) and obj.enabled:
                obj.main()
                self.status.clear()

            # If the module is not being loaded as a dependency, add it to the executed modules dictionary.
            # This is used later in self.execute to determine which objects
            # should be returned.
            if not dependency:
                self.executed_modules[module] = obj

                # The unload method tells the module that we're done with it, and gives it a chance to do
                # any cleanup operations that may be necessary. We still retain
                # the object instance in self.executed_modules.
                obj._unload_dependencies()
                obj.unload()
        except KeyboardInterrupt as e:
            # Tell the status server to shut down, and give it time to clean
            # up.
            if self.status.running:
                self.status.shutdown = True
                while not self.status.finished:
                    time.sleep(0.1)
            raise e

        return obj
1238524
def find_module(module, paths=None):
    """"""

    parts = module.split('.')

    while parts:
        part = parts.pop(0)
        f, path, (suffix, mode, kind) = info = imp.find_module(part, paths)

        if kind == PKG_DIRECTORY:
            parts = parts or ['__init__']
            paths = [path]

        elif parts:
            raise ImportError("Can't find %r in %s" % (parts, module))

    return info
6076
def my_import(name, path=None):
    """"""

    # Documentation for importlib says this may be needed to pick up
    # modules created after the program has started
    if hasattr(importlib, 'invalidate_caches'):
        # python 3.3+
        importlib.invalidate_caches()

    if path is not None:
        directory, src_file = os.path.split(path)

        # TODO: use the importlib.util machinery
        sys.path.insert(0, directory)
        try:
            mod = importlib.import_module(name)
        finally:
            sys.path.pop(0)

    else:
        mod = importlib.import_module(name)

    return mod
463926
def load_yaml_by_path(cls, path, log_debug=False):
        """"""
        try:
            if isinstance(path, six.string_types):
                return yaml.load(open(path, 'r'), Loader=Loader) or {}
            else:
                return yaml.load(path, Loader=Loader) or {}
        except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e:
            log_level = logging.DEBUG if log_debug else logging.WARNING
            logger.log(log_level, 'Yaml error in {path} (line {ln}, column {col}): {err}'.
                       format(path=path,
                              ln=e.problem_mark.line,
                              col=e.problem_mark.column,
                              err=e.problem))
            return None
409229
def get_mod_paths(mod_name, out_dir):
    """"""
    paths = []
    try:
        mod = get_loader(mod_name)
        source = Path(mod.path)
        if source.name.endswith(".py"):
            source_rel = Path(*mod_name.split("."))
            if source.name == "__init__.py":
                source_rel = source_rel.joinpath("__init__.py")
            destination = Path(out_dir, source_rel.with_suffix(".pyi"))
            paths.append((source, destination))
    except Exception as e:
        _logger.debug(e)
        _logger.warning("cannot handle module, skipping: %s", mod_name)
    return paths
95172
def run_example(path):
    
    cmd = "{0} {1}".format(sys.executable, path)
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    res = proc.communicate()
    if proc.returncode:
        print(res[1].decode())
    return proc.returncode
1210674
def path_from_pythonpath(pythonpath):
    """"""
    path = fs.Path()
    for p in pythonpath.split(os.pathsep):
        path.add_path(utils.expand_path(p), 'os')
    return path
783982
def run_module(self, resource, args=None, stdin=None, stdout=None):
        
        perform_doa = self.project.prefs.get('perform_doi', True)
        perform_doa = self.project.prefs.get('perform_doa', perform_doa)
        receiver = self.object_info.doa_data_received
        if not perform_doa:
            receiver = None
        runner = rope.base.oi.doa.PythonFileRunner(
            self, resource, args, stdin, stdout, receiver)
        runner.add_finishing_observer(self.module_cache.forget_all_data)
        runner.run()
        return runner
891635
def run(self, path=None):
        
        if path is None:
            path = '.'

        for prop in self._properties.values():
            if not prop.prompt():
                return False

        return self.build(path)
529373
def exec_module(self, module):
        """"""
        path = [os.path.dirname(module.__file__)]  # file should have been resolved before (module creation)
        file = None
        try:
            file, pathname, description = imp.find_module(module.__name__.rpartition('.')[-1], path)
            module = imp.load_module(module.__name__, file, pathname, description)
        finally:
            if file:
                file.close()
183540
def _import_module(self, module_path):
        
        LOGGER.debug('Importing %s', module_path)
        try:
            return __import__(module_path)
        except ImportError as error:
            LOGGER.critical('Could not import %s: %s', module_path, error)
            return None
782824
def run(self, conn, tmp, module_name, module_args, inject):
        '''  '''

        # shell and command module are the same
        if module_name == 'shell':
            module_name = 'command'
            module_args += " #USE_SHELL"

        (module_path, is_new_style, shebang) = self.runner._copy_module(conn, tmp, module_name, module_args, inject)
        self.runner._low_level_exec_command(conn, "chmod a+rx %s" % module_path, tmp)

        return self.runner._execute_module(conn, tmp, 'async_wrapper', module_args,
           async_module=module_path,
           async_jid=self.runner.generated_jid,
           async_limit=self.runner.background,
           inject=inject
        )
894553
def create_module(name, path):
    
    module = imp.new_module(name)
    module.__file__ = path
    execfile(path, module.__dict__)
    return module
147859
def load_module(module_name, file_path):
    
    if sys.version_info >= (3,5,):
        import importlib.util

        spec = importlib.util.spec_from_file_location(module_name, file_path)
        if not spec:
            return

        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)

        return module
    else:
        import imp
        mod = imp.load_source(module_name, file_path)
        return mod
29555
def load_modules_from_python(self, route_list):
        """"""
        for name, modpath in route_list:
            if ':' in modpath:
                path, attr = modpath.split(':', 1)
            else:
                path, attr = modpath, None
            self.commands[name] = ModuleLoader(path, attr=attr)
33041
def run(path='', code=None, rootdir=CURDIR, options=None):
    
    errors = []
    fileconfig = dict()
    linters = LINTERS
    linters_params = dict()
    lname = 'undefined'
    params = dict()
    path = op.relpath(path, rootdir)

    if options:
        linters = options.linters
        linters_params = options.linters_params
        for mask in options.file_params:
            if mask.match(path):
                fileconfig.update(options.file_params[mask])

        if options.skip and any(p.match(path) for p in options.skip):
            LOGGER.info('Skip checking for path: %s', path)
            return []

    try:
        with CodeContext(code, path) as ctx:
            code = ctx.code
            params = prepare_params(parse_modeline(code), fileconfig, options)
            LOGGER.debug('Checking params: %s', params)

            if params.get('skip'):
                return errors

            for item in params.get('linters') or linters:

                if not isinstance(item, tuple):
                    item = item, LINTERS.get(item)

                lname, linter = item

                if not linter:
                    continue

                lparams = linters_params.get(lname, dict())
                LOGGER.info("Run %s %s", lname, lparams)

                ignore, select = merge_params(params, lparams)

                linter_errors = linter.run(
                    path, code=code, ignore=ignore, select=select, params=lparams)
                if not linter_errors:
                    continue

                errors += filter_errors([
                    Error(filename=path, linter=lname, **er) for er in linter_errors
                ], ignore=ignore, select=select)

    except IOError as e:
        LOGGER.error("IOError %s", e)
        errors.append(Error(text=str(e), filename=path, linter=lname))

    except SyntaxError as e:
        LOGGER.error("SyntaxError %s", e)
        errors.append(
            Error(linter='pylama', lnum=e.lineno, col=e.offset,
                  text='E0100 SyntaxError: {}'.format(e.args[0]),
                  filename=path))

    except Exception as e:  # noqa
        import traceback
        LOGGER.error(traceback.format_exc())

    errors = list(remove_duplicates(errors))

    if code and errors:
        errors = filter_skiplines(code, errors)

    if options and options.sort:
        sort = dict((v, n) for n, v in enumerate(options.sort, 1))

        def key(e):
            return (sort.get(e.type, 999), e.lnum)
    else:
        def key(e):
            return e.lnum

    return sorted(errors, key=key)