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


Python reflect.filenameToModuleName函数代码示例

本文整理汇总了Python中twisted.python.reflect.filenameToModuleName函数的典型用法代码示例。如果您正苦于以下问题:Python filenameToModuleName函数的具体用法?Python filenameToModuleName怎么用?Python filenameToModuleName使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: test_directory

 def test_directory(self):
     """
     L{filenameToModuleName} returns the correct module (a package) given a
     directory.
     """
     module = reflect.filenameToModuleName(self.path)
     self.assertEqual(module, 'fakepackage.test')
     module = reflect.filenameToModuleName(self.path + os.path.sep)
     self.assertEqual(module, 'fakepackage.test')
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:9,代码来源:test_reflect.py

示例2: test_directory

 def test_directory(self):
     """
     Tests it finds good name for directories/packages.
     """
     module = reflect.filenameToModuleName(os.path.join('twisted', 'test'))
     self.assertEquals(module, 'test')
     module = reflect.filenameToModuleName(os.path.join('twisted', 'test')
                                           + os.path.sep)
     self.assertEquals(module, 'test')
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:9,代码来源:test_reflect.py

示例3: parseArgs

    def parseArgs(self, *args):
        def _dbg(msg):
            if self._logObserver is not None:
                log.msg(iface=ITrialDebug, parseargs=msg)

        if self.extra is not None:
            args = list(args)
            args.extend(self.extra)

        for arg in args:
            _dbg("arg: %s" % (arg,))
            
            if not os.sep in arg and not arg.endswith('.py'):
                # simplest case, someone writes twisted.test.test_foo on the command line
                # only one option, use namedAny
                try:
                    self._tryNamedAny(arg)
                except ArgumentError:
                    pass
                else:
                    continue
            
            # make sure the user isn't smoking crack
            if not os.path.exists(arg):
                raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), arg)

            # if the argument ends in os.sep, it *must* be a directory (if it's valid)
            # directories must be modules/packages, so use filenameToModuleName
            if arg.endswith(os.sep) and arg != os.sep:
                _dbg("arg endswith os.sep")
                arg = arg[:-len(os.sep)]
                _dbg("arg now %s" % (arg,))
                modname = reflect.filenameToModuleName(arg)
                self._tryNamedAny(modname)
                continue
                
            elif arg.endswith('.py'):
                _dbg("*Probably* a file.")
                if osp.exists(arg):
                    self._handleFile(arg)
                    continue

            elif osp.isdir(arg):
                if osp.exists(opj(arg, '__init__.py')):
                    modname = reflect.filenameToModuleName(arg)
                    self._tryNamedAny(modname)
                    continue
                
            raise ArgumentError, ("argument %r appears to be "
                 "invalid, rather than doing something incredibly stupid, "
                 "I'm blowing up" % (arg,))
开发者ID:pwarren,项目名称:AGDeviceControl,代码行数:51,代码来源:trial.py

示例4: parseArgs

    def parseArgs(self, *args):
        if self['extra'] is not None:
            args = list(args)
            args.append(self['extra'])
        for arg in args:
            if (os.sep in arg):
                # It's a file.
                if not os.path.exists(arg):
                    import errno
                    raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), arg)
                if arg.endswith(os.sep) and (arg != os.sep):
                    arg = arg[:-len(os.sep)]
                name = reflect.filenameToModuleName(arg)
                if os.path.isdir(arg):
                    self['packages'].append(name)
                else:
                    self['modules'].append(name)
                continue

            if arg.endswith('.py'):
                # *Probably* a file.
                if os.path.exists(arg):
                    arg = reflect.filenameToModuleName(arg)
                    self['modules'].append(arg)
                    continue

            # a non-default reactor must have been installed by now: it
            # imports the module, which installs a reactor
            try:
                arg = reflect.namedAny(arg)
            except ValueError:
                raise usage.UsageError, "Can't find anything named %r to run" % arg
            except:
                self['_couldNotImport'][arg] = failure.Failure()
                continue

            if inspect.ismodule(arg):
                filename = os.path.basename(arg.__file__)
                filename = os.path.splitext(filename)[0]
                if filename == '__init__':
                    self['packages'].append(arg)
                else:
                    self['modules'].append(arg)
            elif inspect.isclass(arg):
                self['testcases'].append(arg)
            elif inspect.ismethod(arg):
                self['methods'].append(arg)
            else:
                # Umm, seven?
                self['methods'].append(arg)
开发者ID:fxia22,项目名称:ASM_xf,代码行数:50,代码来源:trial.py

示例5: test_file

 def test_file(self):
     """
     L{filenameToModuleName} returns the correct module given the path to
     its file.
     """
     module = reflect.filenameToModuleName(os.path.join(self.path, "test_reflect.py"))
     self.assertEqual(module, "fakepackage.test.test_reflect")
开发者ID:Guokr1991,项目名称:VTK,代码行数:7,代码来源:test_reflect.py

示例6: test_file

 def test_file(self):
     """
     Test it finds good name for files.
     """
     module = reflect.filenameToModuleName(
         os.path.join('twisted', 'test', 'test_reflect.py'))
     self.assertEquals(module, 'test_reflect')
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:7,代码来源:test_reflect.py

示例7: main

def main(target):
    mf = mymf(sys.path[:], 0, [])

    moduleNames = []
    for path, dirnames, filenames in os.walk(target):
        if 'test' in dirnames:
            dirnames.remove('test')
        for filename in filenames:
            if not filename.endswith('.py'):
                continue
            if filename == '__init__.py':
                continue
            if '-' in filename:
                # a script like update-documentation.py
                continue
            moduleNames.append(
                reflect.filenameToModuleName(os.path.join(path, filename)))

    with tempfile.NamedTemporaryFile() as tmpfile:
        for moduleName in moduleNames:
            tmpfile.write('import %s\n' % moduleName)
        tmpfile.flush()
        mf.run_script(tmpfile.name)

    with open('twisted-deps.json', 'wb') as outfile:
        json.dump(mf.as_json(), outfile)

    port_status = {}
    for module in dist3.modules:
        port_status[module] = 'ported'
    for module in dist3.almostModules:
        port_status[module] = 'almost-ported'

    with open('twisted-ported.json', 'wb') as outfile:
        json.dump(port_status, outfile)
开发者ID:djmitche,项目名称:twisted-depgraph,代码行数:35,代码来源:twisted-depgraph.py

示例8: filenameToModule

def filenameToModule(fn):
    """
    Given a filename, do whatever possible to return a module object matching
    that file.

    If the file in question is a module in Python path, properly import and
    return that module. Otherwise, load the source manually.

    @param fn: A filename.
    @return: A module object.
    @raise ValueError: If C{fn} does not exist.
    """
    if not os.path.exists(fn):
        raise ValueError("%r doesn't exist" % (fn,))
    try:
        ret = reflect.namedAny(reflect.filenameToModuleName(fn))
    except (ValueError, AttributeError):
        # Couldn't find module.  The file 'fn' is not in PYTHONPATH
        return _importFromFile(fn)
    # ensure that the loaded module matches the file
    retFile = os.path.splitext(ret.__file__)[0] + '.py'
    # not all platforms (e.g. win32) have os.path.samefile
    same = getattr(os.path, 'samefile', samefile)
    if os.path.isfile(fn) and not same(fn, retFile):
        del sys.modules[ret.__name__]
        ret = _importFromFile(fn)
    return ret
开发者ID:shelmesky,项目名称:twisted,代码行数:27,代码来源:runner.py

示例9: _determine_calling_module

    def _determine_calling_module(self, by_module):
        if not by_module:
            # if the caller did not specify a module that made the logging call, attempt to find
            # the module by inspecting the stack: record 0 is this, 1 is _should_log, 2 is the
            # logging function, and 3 will be the caller.
            record = inspect.stack()[3]
            # the first element of the record is the frame, which contains the locals and globals
            frame = record[0]
            f_globals = frame.f_globals

            # check the stack frame's globals for the __name__ attribute, which is the module name
            if '__name__' in f_globals:
                by_module = f_globals['__name__']
            else:
                # but it might not be a regular python module (such as a service.tac),
                # in which case we have to fall back to using the __file__ attribute.
                by_module = reflect.filenameToModuleName(f_globals['__file__'])

        elif not isinstance(by_module, basestring):
            # if the caller gave us an actual module, and not just its name, determine its
            # name and use it.
            by_module = reflect.fullyQualifiedName(by_module)
        
        modules = by_module.split('.')
        return modules
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:25,代码来源:log.py

示例10: test_bytes

 def test_bytes(self):
     """
     L{filenameToModuleName} returns the correct module given a C{bytes}
     path to its file.
     """
     module = reflect.filenameToModuleName(os.path.join(self.path.encode("utf-8"), b"test_reflect.py"))
     # Module names are always native string:
     self.assertEqual(module, "fakepackage.test.test_reflect")
开发者ID:Guokr1991,项目名称:VTK,代码行数:8,代码来源:test_reflect.py

示例11: _packageRecurse

 def _packageRecurse(self, arg, dirname, names):
     import fnmatch
     OPJ = os.path.join
     testModuleNames = fnmatch.filter(names, self.moduleGlob)
     testModules = [ reflect.filenameToModuleName(OPJ(dirname, name))
                     for name in testModuleNames ]
     for module in testModules:
         self.addModule(module)
开发者ID:fxia22,项目名称:ASM_xf,代码行数:8,代码来源:unittest.py

示例12: __init__

    def __init__(self, original):
        self.original = o = original
        self.runs = 0
        self.klass = "doctests have no class"
        self.module = "doctests have no module"
        # the originating module of this doctest
        self.module = reflect.filenameToModuleName(self.original._dtest.filename)

        self.fullName = self.filename = o._dtest.filename
        self.lineno = o._dtest.lineno
        self.docstr= "doctest, file: %s lineno: %s" % (osp.split(self.filename)[1], self.lineno)
        self.name = o._dtest.name
        self.fullname = repr(o._dtest)
        self._regex = re.compile(r'\S')
开发者ID:pwarren,项目名称:AGDeviceControl,代码行数:14,代码来源:tdoctest.py

示例13: _packageRecurse

    def _packageRecurse(self, arg, dirname, names):

        # Only recurse into packages
        for ext in 'py', 'so', 'pyd', 'dll':
            if os.path.exists(os.path.join(dirname, os.extsep.join(('__init__', ext)))):
                break
        else:
            return

        testModuleNames = fnmatch.filter(names, self.moduleGlob)
        testModules = [ reflect.filenameToModuleName(opj(dirname, name))
                        for name in testModuleNames ]
        for module in testModules:
            self.addModule(module)
开发者ID:pwarren,项目名称:AGDeviceControl,代码行数:14,代码来源:runner.py

示例14: _handleFile

 def _handleFile(self, filename):
     m = None
     if osp.isfile(filename):
         try:
             mname = reflect.filenameToModuleName(filename)
             self._tryNamedAny(mname)
         except ArgumentError:
             # okay, not in PYTHONPATH...
             path, fullname = osp.split(filename)
             name, ext = osp.splitext(fullname)
             m = new.module(name)
             sourcestring = file(filename, 'rb').read()
             exec sourcestring in m.__dict__
             sys.modules[name] = m
             
     self['modules'].append(m)
开发者ID:pwarren,项目名称:AGDeviceControl,代码行数:16,代码来源:trial.py

示例15: loadFile

    def loadFile(self, fileName, recurse=False):
        """
        Load a file, and then the tests in that file.

        @param fileName: The file name to load.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.
        """
        from importlib.machinery import SourceFileLoader

        name = reflect.filenameToModuleName(fileName)
        try:
            module = SourceFileLoader(name, fileName).load_module()
            return self.loadAnything(module, recurse=recurse)
        except OSError:
            raise ValueError("{} is not a Python file.".format(fileName))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:17,代码来源:runner.py


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