• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python reflect.filenameToModuleName函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: _runTest

def _runTest(testCase, testFilePath):
    """
    Run a functional test.

    @param testCase: The test case on which to call assertions.
    @type testCase: L{unittest.TestCase}

    @param testFilePath: The path to the module to test.
    @type testFilePath: L{str}
    """
    pathResultFile = testFilePath.replace(".py", ".result")
    moduleName = filenameToModuleName(testFilePath)
    outputStream = io.BytesIO()

    runner = Runner()
    runner.allowOptions = False
    runner.setOutput(outputStream)
    runner.setReporter(TestReporter())

    limits = _parseLimitMessages(testFilePath)
    if limits is not None:
        action, messages = limits
        _setLinterLimits(runner.linter, action, messages)

    _enablePEP8Checker(runner.linter)

    exitCode = None
    try:
        runner.run([moduleName])
    except SystemExit as error:
        exitCode = error.code

    # Check the results
    expectedResult = open(pathResultFile).read().strip()
    outputResult = outputStream.getvalue().strip()

    try:
        testCase.assertEqual(expectedResult, outputResult)
    except unittest.FailTest:
        testCase.fail(_formatResults(moduleName, expectedResult, outputResult))

    if not expectedResult:
        testCase.assertEqual(0, exitCode)
    else:
        testCase.assertNotEqual(0, exitCode)
开发者ID:pombredanne,项目名称:twistedchecker,代码行数:45,代码来源:test_functionaltests.py


示例17: _testsForModules

def _testsForModules(testModules):
    """
    Return a dictionary of test names and test functions.

    @param testModules: An iterable list of functional test module names.
    @type testModules: L{iter}

    @return: A dictionary of test functions keyed by test name.
    @rtype: L{dict} of (L{str}, L{callable})
    """
    t = []
    for modulePath in testModules:
        moduleName = filenameToModuleName(modulePath)
        t.append(
            (_testNameFromModuleName(moduleName),
             _partial2(_runTest, testFilePath=modulePath))
        )
    return dict(t)
开发者ID:jml,项目名称:twistedchecker,代码行数:18,代码来源:test_functionaltests.py


示例18: loadModule

def loadModule(app):
    """
    Given an module or python file, load the module. Returns a tuple
    containing the loaded module and the name of the app.
    """
    if hasattr(os, "getuid") and os.getuid() != 0:
        sys.path.insert(0, os.path.abspath(os.getcwd()))
    args = sys.argv[:]
    sys.argv = []
    if app[-3:] == ".py" and os.path.exists(app):
        path = os.path.dirname(app)
        if not path: path = "."
        sys.path.insert(0, path)
        from twisted.python import reflect
        app = reflect.filenameToModuleName(app)
    try:
        mod = __import__(app, None, None, app.split(".")[-1])
    except ImportError:
        sys.argv = args
        raise usage.UsageError("Application not found: " + app)
    sys.argv = args
    return mod, app
开发者ID:arjan,项目名称:sparked,代码行数:22,代码来源:launcher.py


示例19: main

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

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

    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)
        outfile.write('\n')

    port_status = {}
    for module in mf._depgraph.iterkeys():
        if module not in _setup.notPortedModules:
            port_status[module] = 'ported'
    with open('twisted-ported.json', 'wb') as outfile:
        json_dump(port_status, outfile)
        outfile.write('\n')
开发者ID:habnabit,项目名称:twisted-depgraph,代码行数:38,代码来源:twisted-depgraph.py


示例20: getSynopsis

    def getSynopsis(self):
        """
        Returns a string containing a description of these options and how to
        pass them to the executed file.
        """
        executableName = reflect.filenameToModuleName(sys.argv[0])

        if executableName.endswith('.__main__'):
            executableName = '{} -m {}'.format(os.path.basename(sys.executable), executableName.replace('.__main__', ''))

        if self.parent is None:
            default = "Usage: %s%s" % (executableName,
                                       (self.longOpt and " [options]") or '')
        else:
            default = '%s' % ((self.longOpt and "[options]") or '')
        synopsis = getattr(self, "synopsis", default)

        synopsis = synopsis.rstrip()

        if self.parent is not None:
            synopsis = ' '.join((self.parent.getSynopsis(),
                                 self.parent.subCommand, synopsis))
        return synopsis
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:23,代码来源:usage.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reflect.fullyQualifiedName函数代码示例发布时间:2022-05-27
下一篇:
Python reflect.accumulateClassList函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap