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

Python filetool.read函数代码示例

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

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



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

示例1: migrateFile

def migrateFile(filePath, compiledPatches, compiledInfos, patchFile, options=None, encoding="UTF-8"):

    logging.info("  - File: %s" % filePath)

    # Read in original content
    fileContent = filetool.read(filePath, encoding)

    fileId = extractFileContentId(fileContent)

    # Apply patches
    patchedContent = fileContent

    if patchFile and fileId is not None:

        # import patch
        patch = {}
        execfile(patchFile, patch)
        tree = treegenerator.createFileTree(tokenizer.Tokenizer().parseStream(fileContent))

        # If there were any changes, compile the result
        if patch["patch"](fileId, tree):
            options.prettyPrint = True  # make sure it's set
            result = [u""]
            # result = pretty.prettyNode(tree, options, result)
            result = formatter_.formatNode(tree, options, result)
            patchedContent = u"".join(result)

    # apply RE patches
    patchedContent = regtool(patchedContent, compiledPatches, True, filePath)
    patchedContent = regtool(patchedContent, compiledInfos, False, filePath)

    # Write file
    if patchedContent != fileContent:
        logging.info("    - %s has been modified. Storing modifications ..." % filePath)
        filetool.save(filePath, patchedContent, encoding)
开发者ID:peuter,项目名称:qooxdoo,代码行数:35,代码来源:migrator.py


示例2: _getSourceTree

    def _getSourceTree(self, cacheId, tradeSpaceForSpeed):

        cache = self.context['cache']
        console = self.context['console']

        # Lookup for unoptimized tree
        tree, _ = cache.read(cacheId, self.path, memory=tradeSpaceForSpeed)

        # Tree still undefined?, create it!
        if tree == None:
            console.debug("Parsing file: %s..." % self.id)
            console.indent()

            fileContent = filetool.read(self.path, self.encoding)
            tokens = tokenizer.parseStream(fileContent, self.id)
            
            console.outdent()
            console.debug("Generating tree: %s..." % self.id)
            console.indent()
            tree = treegenerator.createSyntaxTree(tokens)  # allow exceptions to propagate

            # store unoptimized tree
            #print "Caching %s" % cacheId
            cache.write(cacheId, tree, memory=tradeSpaceForSpeed, writeToFile=True)

            console.outdent()
        return tree
开发者ID:MatiasNAmendola,项目名称:meyeOS,代码行数:27,代码来源:MClassCode.py


示例3: tree

    def tree(self, treegen=treegenerator, force=False):

        cache = self.context["cache"]
        console = self.context["console"]
        tradeSpaceForSpeed = (
            False
        )  # Caution: setting this to True seems to make builds slower, at least on some platforms!?
        cacheId = "tree%s-%s-%s" % (treegen.tag, self.path, util.toString({}))
        self.treeId = cacheId

        # Lookup for unoptimized tree
        tree, _ = cache.read(cacheId, self.path, memory=tradeSpaceForSpeed)

        # Tree still undefined?, create it!
        if tree == None or force:
            console.debug("Parsing file: %s..." % self.id)
            console.indent()

            fileContent = filetool.read(self.path, self.encoding)
            tokens = tokenizer.parseStream(fileContent, self.id)

            console.outdent()
            console.debug("Generating tree: %s..." % self.id)
            console.indent()
            tree = treegen.createSyntaxTree(tokens)  # allow exceptions to propagate

            # store unoptimized tree
            # print "Caching %s" % cacheId
            cache.write(cacheId, tree, memory=tradeSpaceForSpeed, writeToFile=True)

            console.outdent()
        return tree
开发者ID:w495,项目名称:acv,代码行数:32,代码来源:MClassCode.py


示例4: main

def main():
    (options, args) = get_args()
    
    if len(args) == 0:
        print ">>> Missing filename!"
        return

    for fileName in args:
        if not options.quiet:
            print fileName, ":"
            print ">>> Parsing file..."
        fileContent = filetool.read(fileName, "utf-8")

        if options.config:
            read_config(options)

        if options.lint:
            run_lint(fileName, fileContent, options, args)
        elif options.pretty:
            run_pretty(fileName, fileContent, options, args)
        elif options.tree:
            run_tree(fileName, fileContent, options, args)
        elif options.dependencies:
            run_dependencies(fileName, fileContent, options, args)
        else:
            run_compile(fileName, fileContent, options, args)
         
    return
开发者ID:simboyz,项目名称:qooxdoo,代码行数:28,代码来源:compile.py


示例5: migrateFile

def migrateFile(
                filePath, compiledPatches, compiledInfos,
                hasPatchModule=False, options=None, encoding="UTF-8"):

    logging.info("  - File: %s" % filePath)

    # Read in original content
    fileContent = filetool.read(filePath, encoding)

    fileId = extractFileContentId(fileContent);

    # Apply patches
    patchedContent = fileContent

    if hasPatchModule and fileId is not None:

        import patch
        tree = treegenerator.createSyntaxTree(tokenizer.parseStream(fileContent))

        # If there were any changes, compile the result
        if patch.patch(fileId, tree):
            options.prettyPrint = True  # make sure it's set
            result = [u'']
            result = pretty.prettyNode(tree, options, result)
            patchedContent = u''.join(result)

    # apply RE patches
    patchedContent = regtool(patchedContent, compiledPatches, True, filePath)
    patchedContent = regtool(patchedContent, compiledInfos, False, filePath)

    # Write file
    if patchedContent != fileContent:
        logging.info("    - %s has been modified. Storing modifications ..." % filePath)
        filetool.save(filePath, patchedContent, encoding)
开发者ID:Wkasel,项目名称:qooxdoo,代码行数:34,代码来源:migrator.py


示例6: tree

    def tree(self, treegen=treegenerator, force=False):

        cache = self.context['cache']
        console = self.context['console']
        tradeSpaceForSpeed = False  # Caution: setting this to True seems to make builds slower, at least on some platforms!?
        cacheId = "tree%s-%s-%s" % (treegen.tag, self.path, util.toString({}))
        self.treeId = cacheId

        # Lookup for unoptimized tree
        tree, _ = cache.read(cacheId, self.path, memory=tradeSpaceForSpeed)

        # Tree still undefined?, create it!
        if tree == None or force:
            console.debug("Parsing file: %s..." % self.id)
            console.indent()

            # Tokenize
            fileContent = filetool.read(self.path, self.encoding)
            fileId = self.path if self.path else self.id
            try:
                tokens = tokenizer.Tokenizer().parseStream(fileContent, self.id)
            except SyntaxException, e:
                # add file info
                e.args = (e.args[0] + "\nFile: %s" % fileId,) + e.args[1:]
                raise e

            # Parse
            try:
                tree = treegen.createFileTree(tokens, fileId)
            except SyntaxException, e:
                # add file info
                e.args = (e.args[0] + "\nFile: %s" % fileId,) + e.args[1:]
                raise
开发者ID:1and1,项目名称:qooxdoo,代码行数:33,代码来源:MClassCode.py


示例7: getCode

    def getCode(self, compOptions, treegen=treegenerator, featuremap={}):

        # source versions
        if not compOptions.optimize:
            compiled = filetool.read(self.path)
            # assure trailing \n (e.g. to utilise ASI)
            if compiled[-1:] != "\n":
                compiled += '\n'
        # compiled versions
        else:
            optimize  = compOptions.optimize
            variants  = compOptions.variantset
            format_   = compOptions.format
            classVariants     = self.classVariants()
            # relevantVariants is the intersection between the variant set of this job
            # and the variant keys actually used in the class
            relevantVariants  = self.projectClassVariantsToCurrent(classVariants, variants)
            variantsId        = util.toString(relevantVariants)
            optimizeId        = self._optimizeId(optimize)
            cache             = self.context["cache"]

            cacheId = "compiled-%s-%s-%s-%s" % (self.path, variantsId, optimizeId, format_)
            compiled, _ = cache.read(cacheId, self.path)

            if compiled == None:
                tree = self.optimize(None, optimize, variants, featuremap)
                compiled = self.serializeTree(tree, optimize, format_)
                if not "statics" in optimize:
                    cache.write(cacheId, compiled)

        return compiled
开发者ID:1and1,项目名称:qooxdoo,代码行数:31,代码来源:MClassCode.py


示例8: main

def main():
    (options, args) = get_args()

    if len(args) == 0:
        print(">>> Missing filename!")
        return

    for fileName in args:
        if not options.quiet:
            print(fileName, ":")
            print(">>> Parsing file...")

        if fileName == "-":
            # enables: echo "1+2" | compile.py -
            fileContent = sys.stdin.read()
        else:
            fileContent = filetool.read(fileName, "utf-8")

        if options.config:
            read_config(options)

        if options.lint:
            run_lint(fileName, fileContent, options, args)
        elif options.pretty:
            run_pretty(fileName, fileContent, options, args)
        elif options.tree:
            run_tree(fileName, fileContent, options, args)
        elif options.dependencies:
            run_dependencies(fileName, fileContent, options, args)
        else:
            run_compile(fileName, fileContent, options, args)

    return
开发者ID:RemiHeugue,项目名称:qooxdoo,代码行数:33,代码来源:compile.py


示例9: getMeta

    def getMeta(self, fileId):
        fileEntry = self._classes[fileId]
        filePath = fileEntry["path"]
        cacheId = "meta-%s" % fileId

        meta = self._cache.readmulti(cacheId, filePath)
        if meta != None:
            return meta

        meta = {}

        self._console.indent()

        content = filetool.read(filePath, fileEntry["encoding"])

        meta["loadtimeDeps"] = self._extractLoadtimeDeps(content, fileId)
        meta["runtimeDeps"]  = self._extractRuntimeDeps(content, fileId)
        meta["optionalDeps"] = self._extractOptionalDeps(content)
        meta["ignoreDeps"]   = self._extractIgnoreDeps(content)
        meta["assetDeps"]    = self._extractAssetDeps(content)

        self._console.outdent()

        self._cache.writemulti(cacheId, meta)
        return meta
开发者ID:StephanHoyer,项目名称:DJsAdmin,代码行数:25,代码来源:DependencyLoader.py


示例10: toResinfo

 def toResinfo(self):
     result = super(self.__class__, self).toResinfo()
     if self.format == "b64" and self.path:
         cont = filetool.read(self.path)
         cont = json.loads(cont)
         result.append(cont)
     return result
开发者ID:HelderMagalhaes,项目名称:qooxdoo,代码行数:7,代码来源:CombinedImage.py


示例11: getData

def getData():
    data = os.path.join(filetool.root(), os.pardir, "data", "icon", "qooxdoo.dat")
    lines = filetool.read(data).split("\n")
    result = {}

    for line in lines:
        if line == "" or line.startswith(" ") or line.startswith("#"):
            continue

        if ":" in line:
            alternative = line[line.index(":")+1:].split(",")
            key = line[:line.index(":")]
        else:
            alternative = []
            key = line

        if key in result:
            console.error("Duplicate key found: %s" % key)
            sys.exit(1)

        result[key] = alternative

    # convert to array
    arr = []
    keys = result.keys()
    keys.sort()
    for key in keys:
        tmp = []
        tmp.append(key)
        tmp.extend(result[key])
        arr.append(tmp)

    return arr
开发者ID:dominikg,项目名称:qooxdoo,代码行数:33,代码来源:iconpackager.py


示例12: loaderTemplate

 def loaderTemplate(script, compConf):
     templatePath = compConf.get("paths/loader-template", None)
     if not templatePath:
         # use default template
         templatePath = os.path.join(filetool.root(), os.pardir, "data", "generator", "loader.tmpl.js")
     templateCont = filetool.read(templatePath)
     return templateCont, templatePath
开发者ID:MatiasNAmendola,项目名称:meyeOS,代码行数:7,代码来源:CodeGenerator.py


示例13: runFix

def runFix(jobconf, classesObj):

    def fixPng():
        return

    def removeBOM(fpath):
        content = open(fpath, "rb").read()
        if content.startswith(codecs.BOM_UTF8):
            console.debug("removing BOM: %s" % filePath)
            open(fpath, "wb").write(content[len(codecs.BOM_UTF8):])
        return

    # - Main ---------------------------------------------------------------

    if not isinstance(jobconf.get("fix-files", False), types.DictType):
        return

    console = Context.console
    classes = classesObj.keys()
    fixsettings = ExtMap(jobconf.get("fix-files"))

    # Fixing JS source files
    console.info("Fixing whitespace in source files...")
    console.indent()

    console.info("Fixing files: ", False)
    numClasses = len(classes)
    eolStyle = fixsettings.get("eol-style", "LF")
    tabWidth = fixsettings.get("tab-width", 2)
    for pos, classId in enumerate(classes):
        console.progress(pos+1, numClasses)
        classEntry   = classesObj[classId]
        filePath     = classEntry.path
        fileEncoding = classEntry.encoding
        fileContent  = filetool.read(filePath, fileEncoding)
        # Caveat: as filetool.read already calls any2Unix, converting to LF will
        # not work as the file content appears unchanged to this function
        if eolStyle == "CR":
            fixedContent = textutil.any2Mac(fileContent)
        elif eolStyle == "CRLF":
            fixedContent = textutil.any2Dos(fileContent)
        else:
            fixedContent = textutil.any2Unix(fileContent)
        fixedContent = textutil.normalizeWhiteSpace(textutil.removeTrailingSpaces(textutil.tab2Space(fixedContent, tabWidth)))
        if fixedContent != fileContent:
            console.debug("modifying file: %s" % filePath)
            filetool.save(filePath, fixedContent, fileEncoding)
        # this has to go separate, as it requires binary operation
        removeBOM(filePath)

    console.outdent()

    # Fixing PNG files -- currently just a stub!
    if fixsettings.get("fix-png", False):
        console.info("Fixing PNGs...")
        console.indent()
        fixPng()
        console.outdent()

    return
开发者ID:AaronOpfer,项目名称:qooxdoo,代码行数:60,代码来源:CodeMaintenance.py


示例14: loadTemplate

        def loadTemplate(bootCode):
            if bootCode:
                loaderFile = os.path.join(filetool.root(), os.pardir, "data", "generator", "loader-build.tmpl.js")
            else:
                loaderFile = os.path.join(filetool.root(), os.pardir, "data", "generator", "loader-source.tmpl.js")
            template = filetool.read(loaderFile)

            return template
开发者ID:mikegr,项目名称:lectorious-grails-qooxdoo,代码行数:8,代码来源:CodeGenerator.py


示例15: __init__

    def __init__(self, filename, logger=None):
        self.filename = filename
        content = filetool.read(filename)

        self.tree = treegenerator.createSyntaxTree(tokenizer.parseStream(content))
        self.script = Script(self.tree, self.filename)
        if not logger:
            self.logger = ConsoleLogger()
        else:
            self.logger = logger
开发者ID:StephanHoyer,项目名称:DJsAdmin,代码行数:10,代码来源:ecmalint.py


示例16: getPackageApi

 def getPackageApi(self, packageId):
     if not packageId in self._docs:
         self._console.debug("Missing package docs: %s" % packageId)
         return None
         
     packageEntry = self._docs[packageId]
     
     text = filetool.read(packageEntry["path"])
     node = api.createPackageDoc(text, packageId)
     
     return node
开发者ID:leandrorchaves,项目名称:qooxdoo-1.x,代码行数:11,代码来源:ApiLoader.py


示例17: getPackageApi

 def getPackageApi(self, packageId):
     if not packageId in self._docs:
         if packageId:  # don't complain empty root namespace
             self._console.warn("Missing package docs: %s" % packageId)
         return None
         
     packageEntry = self._docs[packageId]
     
     text = filetool.read(packageEntry["path"])
     node = api.createPackageDoc(text, packageId)
     
     return node
开发者ID:bupthzd,项目名称:undergrad_thesis,代码行数:12,代码来源:ApiLoader.py


示例18: parseMetaFile

 def parseMetaFile(self, path):
     # Read the .meta file
     # it doesn't seem worth to apply caching here
     meta_fname   = os.path.splitext(path)[0]+'.meta'
     try:
         meta_content = filetool.read(meta_fname)
         fontDict      = json.loads(meta_content)
     except Exception, e:
         msg = "Reading of .meta file failed: '%s'" % meta_fname + (
             "\n%s" % e.args[0] if e.args else ""
             )
         e.args = (msg,) + e.args[1:]
         raise
开发者ID:RemiHeugue,项目名称:qooxdoo,代码行数:13,代码来源:FontMap.py


示例19: getCode

    def getCode(self, compOptions):

        result = u''
        # source versions
        if not compOptions.optimize:
            result = filetool.read(self.path)
            if result[-1:] != "\n": # assure trailing \n
                result += '\n'
        # compiled versions
        else:
            result = self._getCompiled(compOptions)

        return result
开发者ID:MatiasNAmendola,项目名称:meyeOS,代码行数:13,代码来源:MClassCode.py


示例20: toResinfo

 def toResinfo(self):
     result = super(self.__class__, self).toResinfo()
     if self.format == "b64" and self.path:
         try:
             cont = filetool.read(self.path)
             cont = json.loads(cont)
         except Exception, e:
             msg = "Reading of b64 image file failed: '%s'" % self.path + (
                 "\n%s" % e.args[0] if e.args else ""
                 )
             e.args = (msg,) + e.args[1:]
             raise
         else:
             result.append(cont)
开发者ID:RemiHeugue,项目名称:qooxdoo,代码行数:14,代码来源:CombinedImage.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python filetool.root函数代码示例发布时间:2022-05-27
下一篇:
Python filetool.lock函数代码示例发布时间: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