當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。