当前位置: 首页>>代码示例>>Python>>正文


Python inspect.getmodulename方法代码示例

本文整理汇总了Python中inspect.getmodulename方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getmodulename方法的具体用法?Python inspect.getmodulename怎么用?Python inspect.getmodulename使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.getmodulename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: from_command_line

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def from_command_line(cls, *args, **keys):
        params = list()
        for name, param in cls.params():
            if name not in keys:
                params.append((name, param))

        bot_name = inspect.getmodulename(inspect.stack()[1][1])

        if "ABUSEHELPER_CONF_FROM_STDIN" in os.environ:
            defaults = dict(pickle.load(sys.stdin))
            defaults.setdefault("bot_name", bot_name)
            added = cls._from_dict(params, **defaults)
        else:
            added = cls._from_sys_argv(params, bot_name=bot_name)

        added.update(keys)
        return cls(*args, **added) 
开发者ID:abusesa,项目名称:abusehelper,代码行数:19,代码来源:bot.py

示例2: omap

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def omap(fun, arglist):
    print banner("Starting omap")
    N_tasks = len(arglist)
    jobname = str(npr.RandomState().randint(10**12))
    working_dir = path.join(root_working_dir, jobdir(jobname))
    module_path = path.join(os.getcwd(), inspect.getsourcefile(fun))
    module_name = inspect.getmodulename(module_path)
    run_signal_path = path.join('..', run_signal(jobname))
    fun_name = fun.__name__
    slurm_str = slurm_template.format(jobname=jobname,
                                      N_tasks=N_tasks,
                                      other_options=slurm_options,
                                      module_name=module_name,
                                      fun_name=fun_name)
    with temp_dir(working_dir):
        shutil.copy(module_path, ".")
        with open(arg_fname, 'w') as f: pickle.dump(arglist, f)
        with open(slurm_fname, 'w') as f: f.write(slurm_str)
        with open(run_signal_path, 'w'): pass
        print "Submitting {0} tasks (output in {1})".format(N_tasks, working_dir)
        while path.exists(run_signal_path): time.sleep(1)
        print "Tasks submitted"

    return collect_results(jobname) 
开发者ID:bigaidream-projects,项目名称:drmad,代码行数:26,代码来源:odyssey.py

示例3: __str__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def __str__(self):
    stack_iter = iter(self._stack)
    for stack in stack_iter:
      # Find the caller of AssertThat(...).
      if stack[3] == 'AssertThat':
        caller = next(stack_iter)
        return ('{0}({1}) created in module {2}, line {3}, in {4}:\n'
                '      {5}'
                .format(self.__class__.__name__, self._GetSubject(),
                        inspect.getmodulename(caller[1]),   # Module name.
                        caller[2],                          # Line number.
                        caller[3],                          # Function name.
                        caller[4][0].strip()))              # Code snippet.

    # The subject was not created by AssertThat().
    return '{0}({1})'.format(self.__class__.__name__, self._GetSubject()) 
开发者ID:google,项目名称:pytruth,代码行数:18,代码来源:truth.py

示例4: modulesInPackage

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def modulesInPackage(self, packageName, package):
        docless = []
        directory = path.dirname(package.__file__)
        for modfile in glob.glob(path.join(directory, '*.py')):
            moduleName = inspect.getmodulename(modfile)
            if moduleName == '__init__':
                # These are tested by test_packages.
                continue
            elif moduleName in ('spelunk_gnome','gtkmanhole'):
                # argh special case pygtk evil argh.  How does epydoc deal
                # with this?
                continue
            try:
                module = reflect.namedModule('.'.join([packageName,
                                                       moduleName]))
            except Exception, e:
                # print moduleName, "misbehaved:", e
                pass
            else:
                if not inspect.getdoc(module):
                    docless.append(modfile) 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:23,代码来源:test_doc.py

示例5: module_from_path

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def module_from_path(package_path, filename):
    if filename is None:
        name = inspect.getmodulename(package_path)
    else:
        name = inspect.getmodulename(package_path + '/' + filename + '.py')
    python_path = package_path.replace(sharpydir.SharpyDir, "")
    if python_path[0] == '/':
        python_path = python_path[1:]
    python_path = python_path.replace("/", ".")
    python_path = python_path.replace('.__init__.py', '')

    if name == '__init__':
        module_path = python_path
        # module_path = module_path.replace('..py', '')
    else:
        module_path = python_path + '.' + name
    module = importlib.import_module(module_path)

    return module, module_path 
开发者ID:ImperialCollegeLondon,项目名称:sharpy,代码行数:21,代码来源:docutils.py

示例6: iter_modules

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def iter_modules(self, prefix=''):
        if self.path is None or not os.path.isdir(self.path):
            return

        yielded = {}
        import inspect

        filenames = os.listdir(self.path)
        filenames.sort()  # handle packages before same-named modules

        for fn in filenames:
            modname = inspect.getmodulename(fn)
            if modname=='__init__' or modname in yielded:
                continue

            path = os.path.join(self.path, fn)
            ispkg = False

            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                for fn in os.listdir(path):
                    subname = inspect.getmodulename(fn)
                    if subname=='__init__':
                        ispkg = True
                        break
                else:
                    continue    # not a package

            if modname and '.' not in modname:
                yielded[modname] = 1
                yield prefix + modname, ispkg 
开发者ID:glmcdona,项目名称:meddle,代码行数:33,代码来源:pkgutil.py

示例7: iter_zipimport_modules

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def iter_zipimport_modules(importer, prefix=''):
        dirlist = zipimport._zip_directory_cache[importer.archive].keys()
        dirlist.sort()
        _prefix = importer.prefix
        plen = len(_prefix)
        yielded = {}
        import inspect
        for fn in dirlist:
            if not fn.startswith(_prefix):
                continue

            fn = fn[plen:].split(os.sep)

            if len(fn)==2 and fn[1].startswith('__init__.py'):
                if fn[0] not in yielded:
                    yielded[fn[0]] = 1
                    yield fn[0], True

            if len(fn)!=1:
                continue

            modname = inspect.getmodulename(fn[0])
            if modname=='__init__':
                continue

            if modname and '.' not in modname and modname not in yielded:
                yielded[modname] = 1
                yield prefix + modname, False 
开发者ID:glmcdona,项目名称:meddle,代码行数:30,代码来源:pkgutil.py

示例8: iter_modules

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def iter_modules(self, prefix=''):
        if self.path is None or not os.path.isdir(self.path):
            return

        yielded = {}
        import inspect
        try:
            filenames = os.listdir(self.path)
        except OSError:
            # ignore unreadable directories like import does
            filenames = []
        filenames.sort()  # handle packages before same-named modules

        for fn in filenames:
            modname = inspect.getmodulename(fn)
            if modname=='__init__' or modname in yielded:
                continue

            path = os.path.join(self.path, fn)
            ispkg = False

            if not modname and os.path.isdir(path) and '.' not in fn:
                modname = fn
                try:
                    dircontents = os.listdir(path)
                except OSError:
                    # ignore unreadable directories like import does
                    dircontents = []
                for fn in dircontents:
                    subname = inspect.getmodulename(fn)
                    if subname=='__init__':
                        ispkg = True
                        break
                else:
                    continue    # not a package

            if modname and '.' not in modname:
                yielded[modname] = 1
                yield prefix + modname, ispkg 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:41,代码来源:pkgutil.py

示例9: param_defaults

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def param_defaults(cls, **defaults):
        result = dict()
        for name, param in cls.params():
            if param.has_default():
                result[name] = param.default
            elif name == "bot_name":
                modulename = inspect.getmodulename(inspect.getfile(cls))
                result["bot_name"] = modulename
        result.update(defaults)
        return result 
开发者ID:abusesa,项目名称:abusehelper,代码行数:12,代码来源:bot.py

示例10: reload_mod

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def reload_mod(mod_name: str):
    mod = mods.get(mod_name)
    if mod is None:
        raise ValueError(f'could not find mod by the name of "{mod_name}"')

    try:
        # get the module's file path, this is needed to add it to python's import search paths
        path = Path(getfile(mod.__class__))
        with temp_syspath(path.parent):
            # this is needed to make python import the latest version from disk,
            # python caches imports in sys.modules
            # doing this removes it from the cache, so the latest version from the disk is imported
            prev_module = sys.modules[getmodulename(path)]
            del sys.modules[getmodulename(path)]
            # this dict stores the Mod's / global objects in the Mod's .py file
            # it lets us iterate over its value to check for the Mod that we want to reload
            module = __import__(getmodulename(path), locals={}, globals={})
            for item in module.__dict__.values():
                if is_mod(item) and item.name == mod.name:
                    unregister_mod(mod)
                    reloaded_mod = item()
                    register_mod(reloaded_mod)

                    # removed previous events that were registered via @event_handler
                    # this prevents event duplication and stacking
                    for var in prev_module.__dict__.values():
                        if isinstance(var, AsyncEventWrapper):
                            var.unregister()

                    # trigger events
                    get_event_loop().create_task(trigger_mod_event(Event.on_mod_reloaded, reloaded_mod))
                    get_event_loop().create_task(get_bot().on_mod_reloaded(reloaded_mod))
                    get_event_loop().create_task(trigger_event(Event.on_mod_reloaded, reloaded_mod))
                    return True

    except Exception as e:
        print(f'error trying to reload Mod "{mod.name}", error type: {type(e)}, error: {e}')
        print_exc()
    return False 
开发者ID:sharkbound,项目名称:PythonTwitchBotFramework,代码行数:41,代码来源:modloader.py

示例11: name_for_module

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def name_for_module(filename, frame):
    """Get the name of the module for a filename and frame.

    For configurability's sake, we allow __main__ modules to be matched by
    their importable name.

    If loaded via runpy (aka -m), we can usually recover the "original"
    full dotted module name, otherwise, we resort to interpreting the
    file name to get the module's name.  In the case that the module name
    can't be determined, None is returned.

    """
    module_globals = frame.f_globals if frame is not None else {}
    if module_globals is None:          # pragma: only ironpython
        # IronPython doesn't provide globals: https://github.com/IronLanguages/main/issues/1296
        module_globals = {}

    dunder_name = module_globals.get('__name__', None)

    if isinstance(dunder_name, str) and dunder_name != '__main__':
        # This is the usual case: an imported module.
        return dunder_name

    loader = module_globals.get('__loader__', None)
    for attrname in ('fullname', 'name'):   # attribute renamed in py3.2
        if hasattr(loader, attrname):
            fullname = getattr(loader, attrname)
        else:
            continue

        if isinstance(fullname, str) and fullname != '__main__':
            # Module loaded via: runpy -m
            return fullname

    # Script as first argument to Python command line.
    inspectedname = inspect.getmodulename(filename)
    if inspectedname is not None:
        return inspectedname
    else:
        return dunder_name 
开发者ID:nedbat,项目名称:coveragepy-bbmirror,代码行数:42,代码来源:inorout.py

示例12: getFunctionCaller

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def getFunctionCaller(depth: int = 3) -> str:
		return inspect.getmodulename(inspect.stack()[depth][1]) 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:4,代码来源:CommonsManager.py

示例13: decorate

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def decorate(self, msg: str, depth: int) -> str:
		try:
			return f'[{inspect.getmodulename(inspect.stack()[depth][1])}] {msg}'
		except Exception:
			return f'[Unknown] {msg}' 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:7,代码来源:Logger.py

示例14: _iter_file_finder_modules

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def _iter_file_finder_modules(importer, prefix=''):
    if importer.path is None or not os.path.isdir(importer.path):
        return

    yielded = {}
    import inspect
    try:
        filenames = os.listdir(importer.path)
    except OSError:
        # ignore unreadable directories like import does
        filenames = []
    filenames.sort()  # handle packages before same-named modules

    for fn in filenames:
        modname = inspect.getmodulename(fn)
        if modname=='__init__' or modname in yielded:
            continue

        path = os.path.join(importer.path, fn)
        ispkg = False

        if not modname and os.path.isdir(path) and '.' not in fn:
            modname = fn
            try:
                dircontents = os.listdir(path)
            except OSError:
                # ignore unreadable directories like import does
                dircontents = []
            for fn in dircontents:
                subname = inspect.getmodulename(fn)
                if subname=='__init__':
                    ispkg = True
                    break
            else:
                continue    # not a package

        if modname and '.' not in modname:
            yielded[modname] = 1
            yield prefix + modname, ispkg 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:41,代码来源:pkgutil.py

示例15: iter_zipimport_modules

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmodulename [as 别名]
def iter_zipimport_modules(importer, prefix=''):
        dirlist = sorted(zipimport._zip_directory_cache[importer.archive])
        _prefix = importer.prefix
        plen = len(_prefix)
        yielded = {}
        import inspect
        for fn in dirlist:
            if not fn.startswith(_prefix):
                continue

            fn = fn[plen:].split(os.sep)

            if len(fn)==2 and fn[1].startswith('__init__.py'):
                if fn[0] not in yielded:
                    yielded[fn[0]] = 1
                    yield fn[0], True

            if len(fn)!=1:
                continue

            modname = inspect.getmodulename(fn[0])
            if modname=='__init__':
                continue

            if modname and '.' not in modname and modname not in yielded:
                yielded[modname] = 1
                yield prefix + modname, False 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:29,代码来源:pkgutil.py


注:本文中的inspect.getmodulename方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。