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


Python LineReader.read方法代码示例

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


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

示例1: replaceParameter

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def replaceParameter(self,parameter,newval):
        """writes the value of a parameter

        :param parameter: name of the parameter
        :param newval: the new value
        :return: old value of the parameter"""
        
        oldVal=self.readParameter(parameter)
        
        exp=self.parameterPattern(parameter)

        l=LineReader()
        self.openFile()

        (fh,fn)=self.makeTemp()

        while l.read(self.fh):
            toPrint=l.line

            m=exp.match(l.line)
            if m!=None:
                if m.group(1).find(self.removedString)<0:
                    toPrint =self.removedString+l.line+"\n"
                    toPrint+=parameter+" "+str(newval)+"; "+self.addedString
            fh.write(toPrint+"\n")

        self.closeFile()
        fh.close()
        os.rename(fn,self.name)

        return oldVal
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:33,代码来源:ParameterFile.py

示例2: purgeFile

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def purgeFile(self):
        """Undo all the manipulations done by PyFOAM

        Goes through the file and removes all lines that were added"""
        rmExp= re.compile("^"+self.removedString+"(.*)$")
        addExp=re.compile("^(.*)"+self.addedString+"$")

        l=LineReader()
        self.openFile()

        (fh,fn)=self.makeTemp()

        while l.read(self.fh):
            toPrint=l.line

            m=addExp.match(l.line)
            if m!=None:
                continue

            m=rmExp.match(l.line)
            if m!=None:
                toPrint=m.group(1)

            self.writeEncoded(fh,toPrint+"\n")

        self.closeFile()
        fh.close()
        os.rename(fn,self.name)
开发者ID:martinep,项目名称:foam-extend-svn,代码行数:30,代码来源:FileBasis.py

示例3: refineMesh

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def refineMesh(self,factors,offset=(0,0,0)):
        """Refine the Mesh by multiplying the number of cells in the blocks
        @param factors: either a scalar to scale in all directions or a
        tuple with the value for each direction
        @param offset: an optional tuple for an additionnal offset value
        for each direction"""

        if type(factors)!=tuple:
            f=(factors,factors,factors)
        else:
            f=factors

        startPattern=re.compile("^\s*blocks")
        endPattern=re.compile("^\s\);")
        hexPattern=re.compile("^(\s*hex\s*\(.+\)\s+\(\s*)(\d+)\s+(\d+)\s+(\d+)(\s*\).*)$")

        inBlock=False

        l=LineReader()
        self.openFile()

        (fh,fn)=self.makeTemp()

        while l.read(self.fh):
            toPrint=l.line

            if not inBlock:
                if startPattern.match(l.line):
                    inBlock=True
            else:
                if endPattern.match(l.line):
                    inBlock=False
                else:
                    m=hexPattern.match(l.line)
                    if m!=None:
                        g=m.groups()
                        toPrint =self.removedString+l.line+"\n"
                        toPrint+="%s%d %d %d%s" % (
                            g[0],
                            int(g[1])*f[0]+offset[0],
                            int(g[2])*f[1]+offset[1],
                            int(g[3])*f[2]+offset[2],
                            g[4])
                        toPrint+=" "+self.addedString

            fh.write(toPrint+"\n")

        self.closeFile()
        fh.close()
        os.rename(fn,self.name)
开发者ID:martinep,项目名称:foam-extend-svn,代码行数:52,代码来源:BlockMesh.py

示例4: readInternalUniform

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def readInternalUniform(self):
        """read the value of the internal field"""
        exp=self.internalPatternUniform()
        erg=""

        l=LineReader()
        self.openFile()

        while l.read(self.fh):
            m=exp.match(l.line)
            if m!=None:
                erg=m.group(1)
                break

        self.closeFile()
        return erg
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:18,代码来源:SolutionFile.py

示例5: readDimension

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def readDimension(self):
        """read the dimension of the field"""
        exp=self.dimensionPattern()
        erg=""

        l=LineReader()
        self.openFile()

        while l.read(self.fh):
            m=exp.match(l.line)
            if m!=None:
                erg=m.group(1)
                break

        self.closeFile()
        return erg
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:18,代码来源:SolutionFile.py

示例6: getSize

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def getSize(self):
        """:return: the size of the list"""

        size=-1 # should be long

        l=LineReader()
        self.openFile()

        while l.read(self.fh):
            try:
                size=long(l.line)
                break
            except ValueError:
                pass

        self.closeFile()

        return size
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:20,代码来源:ListFile.py

示例7: readParameter

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
    def readParameter(self,parameter):
        """reads the value of a parameter

        parameter - name of the parameter"""
        exp=self.parameterPattern(parameter)
        
        l=LineReader()
        self.openFile()

        erg=""
        
        while l.read(self.fh):
            m=exp.match(l.line)
            if m!=None:
                if m.group(1).find(self.removedString)<0:
                    erg=m.group(2)
                    break

        self.closeFile()
        return erg
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:22,代码来源:ParameterFile.py

示例8: FoamThread

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
class FoamThread(Thread):
    """Thread running an OpenFOAM command

    The output of the command can be accessed in a thread-safe manner,
    line by line

    Designed to be used by the BasicRunner-class"""
    
    def __init__(self,cmdline,runner):
        """@param cmdline:cmdline - Command line of the OpenFOAM command
        @param runner: the Runner-object that started this thread"""
        Thread.__init__(self)
        self.cmdline=cmdline
        self.runner=runner
        self.output=None
        self.reader=LineReader()

        self.isLinux=False
        self.isDarwin=False
        self.threadPid=-1
        self.who=RUSAGE_CHILDREN
        
        if uname()[0]=="Linux":
            self.isLinux=True
            self.linuxMaxMem=0
        elif uname()[0]=="Darwin":
            self.isDarwin=True
            
        self.resStart=None
        self.resEnd=None

        self.timeStart=None
        self.timeEnd=None
        
        self.timerTime=5.
        
        self.stateLock=Lock()
        self.setState(False)

        self.status=None
        self.returncode=None
        
        self.lineLock=Lock()
        self.line=""

        self.stateLock.acquire()

    def run(self):
        """start the command"""
        # print "Starting ",self.cmdline
        self.resStart=getrusage(self.who)
        self.timeStart=time()

        if sys.version_info<(2,4):
            run=Popen4(self.cmdline)
            self.output=run.fromchild
        else:
            run=subprocess.Popen(self.cmdline,shell=True,bufsize=0,
                      stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT,close_fds=True)
            self.output=run.stdout
        self.run=run
        self.threadPid=run.pid
        foamLogger().info("Started with PID %d" % self.threadPid)
        if self.isLinux:
            #            print "Starting Timer"
            self.timer=Timer(0.1*self.timerTime,getLinuxMem,args=[self])
            self.timer.start()

        #            print "Starting Timer"
        self.timer2=Timer(0.5*self.timerTime,checkForStopFile,args=[self])
        self.timer2.start()
            
        self.hasSomethingToSay=True
        self.stateLock.release()

        try:
            # print "Waiting",time()
            self.status=run.wait()
            # Python 2.3 on Mac OS X never seems to reach this point
            # print "After wait",time()
            # print "Status:",self.status

            # to give a chance to read the remaining output
            if self.hasSomethingToSay:
                sleep(2.)
            while self.reader.read(self.output):
                print "Unused output:",self.reader.line
        except OSError,e:
            print "Exeption caught:",e

        self.stopTimer()
        
        self.threadPid=-1

        self.resEnd=getrusage(self.who)
        self.timeEnd=time()
        #        print "End:",self.timeEnd
        # print "Returned",self.status

#.........这里部分代码省略.........
开发者ID:floli,项目名称:tools,代码行数:103,代码来源:FoamThread.py

示例9: FoamLogAnalyzer

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]

#.........这里部分代码省略.........
            self.timeListeners.append(listener)

    def listAnalyzers(self):
        """@returns: A list with the names of the Analyzers"""
        return list(self.analyzers.keys())

    def hasAnalyzer(self,name):
        """Is this LogLineAnalyzer name there"""
        return name in self.analyzers

    def getAnalyzer(self,name):
        """Get the LogLineAnalyzer name"""
        if name in self.analyzers:
            return self.analyzers[name]
        else:
            return None

    def addAnalyzer(self,name,obj):
        """Adds an analyzer

        obj - A LogLineAnalyzer
        name - the name of the analyzer"""

        obj.setParent(self)
        self.analyzers[name]=obj

    def analyzeLine(self,line):
        """Calls all the anlyzers for a line"""
        for nm in self.analyzers:
            self.analyzers[nm].doAnalysis(line)

    def analyze(self,fh):
        """Analyzes a file (one line at a time)

        fh - handle of the file"""
        while(self.line.read(fh)):
            self.analyzeLine(self.line.line)

    def goOn(self):
        """Checks with all the analyzers

        If one analyzer returns False it returns False"""
        result=True

        for nm in self.analyzers:
            #            print nm,self.analyzers[nm].goOn()
            result=result and self.analyzers[nm].goOn()

        return result

    def getTime(self):
        """Gets the current time"""
        return str(self.time)

    def setDirectory(self,d):
        """Sets the output directory for all the analyzers"""
        self.oDir=d
        for nm in self.analyzers:
            self.analyzers[nm].setDirectory(self.oDir)

    def getDirectory(self):
        """Gets the output directory"""
        return self.oDir

    def addTrigger(self,time,func,once=True,until=None):
        """Adds a trigger function that is to be called as soon as
        the simulation time exceeds a certain value
        @param time: the time at which the function should be triggered
        @param func: the trigger function
        @param once: Should this function be called once or at every time-step
        @param until: The time until which the trigger should be called"""

        data={}
        data["time"]=float(time)
        data["func"]=func
        if until!=None:
            data["until"]=float(until)
            once=False
        data["once"]=once

        self.timeTriggers.append(data)

    def checkTriggers(self):
        """Check for and execute the triggered functions"""

        remove=[]
        for i in range(len(self.timeTriggers)):
            t=self.timeTriggers[i]
            if t["time"]<=self.time:
                t["func"]()
                if t["once"]:
                    remove.append(i)
                elif "until" in t:
                    if t["until"]<=self.time:
                        remove.append(i)

        remove.reverse()

        for i in remove:
            self.timeTriggers.pop(i)
开发者ID:LeeRuns,项目名称:PyFoam,代码行数:104,代码来源:FoamLogAnalyzer.py

示例10: BasicWatcher

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
class BasicWatcher(object):
    """Base class for watching the output of commands

    Works like the UNIX-command 'tail -f <file>': the last lines of the file are output.
    If the file grows then these lines are output as they arrive"""

    def __init__(self,filenames,
                 silent=False,
                 tailLength=1000,
                 sleep=0.1,
                 follow=True):
        """:param filename: name of the logfile to watch
        :param silent: if True no output is sent to stdout
        :param tailLength: number of bytes at the end of the fail that should be output.
        :param follow: if the end of the file is reached wait for further input
        Because data is output on a per-line-basis
        :param sleep: interval to sleep if no line is returned"""

        if type(filenames) is list:
            meshTimes=[]
            createMesh="Create mesh for time = "
            for fName in filenames:
                meshTime=None
                with open(fName) as f:
                    for l in f.readlines()[:100]:
                        if l.find(createMesh)==0:
                            meshTime=float(l[len(createMesh):])
                            break
                meshTimes.append((fName,meshTime))
            meshTimes.sort(key=lambda x:1e50 if x[1] is None else x[1])
            filenames=[m[0] for m in meshTimes]
            self.filename=filenames[0]
            self.nextFiles=filenames[1:]
            self.changeTimes=[m[1] for m in meshTimes[1:]]
        else:
            self.filename=filenames
            self.nextFiles=[]
            self.changeTimes=[]

        self._changeFileHooks=[]

        self.silent=silent
        self.tail=tailLength
        self.sleep=sleep
        self.follow=follow
        self.isTailing=False

        if not path.exists(self.filename):
            print_("Error: Logfile ",self.filename,"does not exist")

        self.reader=LineReader(config().getboolean("SolverOutput","stripSpaces"))

    def getSize(self,filename):
        """:return: the current size (in bytes) of the file"""
        return os.stat(filename)[stat.ST_SIZE]

    def addChangeFileHook(self,func):
        self._changeFileHooks.append(func)

    def changeFile(self,filename):
        currSize=self.getSize(filename)

        fn,ext=path.splitext(filename)
        if ext=='.gz':
            fh=gzip.open(filename)
        else:
            fh=open(filename)

        for f in self._changeFileHooks:
            f()

        return fh,currSize

    def start(self):
        """Reads the file and does the processing"""

        fh,currSize=self.changeFile(self.filename)
        switchTime=None if len(self.changeTimes)==0 else self.changeTimes[0]
        self.changeTimes=self.changeTimes[1:]

        self.startHandle()

        while self.follow or currSize>self.reader.bytesRead() or len(self.nextFiles)>0:
            if not currSize>self.reader.bytesRead() or self.analyzer.isPastTime(switchTime):
                if len(self.nextFiles)>0:
                    print_("\n\nSwitching from logfile",self.filename,
                           "to",self.nextFiles[0],"\n\n")
                    self.filename=self.nextFiles[0]
                    self.nextFiles=self.nextFiles[1:]
                    fh,currSize=self.changeFile(self.filename)
                    switchTime=None if len(self.changeTimes)==0 else self.changeTimes[0]
                    self.changeTimes=self.changeTimes[1:]
                    self.reader.reset()
                    self.analyzer.resetFile()
                    if currSize==0:
                        continue
                else:
                    if not self.follow:
                        break
            try:
#.........这里部分代码省略.........
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:103,代码来源:BasicWatcher.py

示例11: FoamThread

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
class FoamThread(Thread):
    """Thread running an OpenFOAM command

    The output of the command can be accessed in a thread-safe manner,
    line by line

    Designed to be used by the BasicRunner-class"""

    def __init__(self,cmdline,runner):
        """:param cmdline:cmdline - Command line of the OpenFOAM command
        :param runner: the Runner-object that started this thread"""
        Thread.__init__(self)
        self.cmdline=cmdline
        self.runner=runner
        self.output=None
        self.reader=LineReader(config().getboolean("SolverOutput","stripSpaces"))
        self.keyboardInterupted=False

        self.isLinux=False
        self.isDarwin=False
        self.isWindows=False
        self.threadPid=-1
        self.who=RUSAGE_CHILDREN

        if uname()[0]=="Linux":
            self.isLinux=True
            self.linuxMaxMem=0
        elif uname()[0]=="Darwin":
            self.isDarwin=True
        elif uname()[0]=="Windows":
            self.isWindows=True

        self.resStart=None
        self.resEnd=None

        self.timeStart=None
        self.timeEnd=None

        self.timerTime=5.

        self.stateLock=Lock()
        self.setState(False)

        self.status=None
        self.returncode=None

        self.lineLock=Lock()
        self.line=""

        self.stateLock.acquire()

    def run(self):
        """start the command"""
        # print "Starting ",self.cmdline
        self.resStart=getrusage(self.who)
        self.timeStart=time()

        if sys.version_info<(2,4):
            run=Popen4(self.cmdline)
            self.output=run.fromchild
        else:
            run=subprocess.Popen(shellExecutionPrefix()+self.cmdline,
                                 shell=True,
                                 bufsize=0,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT,
                                 close_fds=True)
            self.output=run.stdout
        self.run=run
        self.threadPid=run.pid
        foamLogger().info("Started with PID %d" % self.threadPid)
        if self.isLinux:
            #            print "Starting Timer"
            self.timer=Timer(0.1*self.timerTime,getLinuxMem,args=[self])
            self.timer.start()

        #            print "Starting Timer"
        self.timer2=Timer(0.5*self.timerTime,checkForStopFile,args=[self])
        self.timer2.start()

        self.hasSomethingToSay=True
        self.stateLock.release()

        try:
            # print "Waiting",time()
            self.status=run.wait()
            # Python 2.3 on Mac OS X never seems to reach this point
            # print "After wait",time()
            # print "Status:",self.status

            # to give a chance to read the remaining output
            if self.hasSomethingToSay:
                sleep(2.)
            while self.reader.read(self.output):
                print_("Unused output:",self.reader.line)
        except OSError:
            e = sys.exc_info()[1] # compatible with 2.x and 3.x
            print_("Exeption caught:",e)

#.........这里部分代码省略.........
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:103,代码来源:FoamThread.py

示例12: BasicWatcher

# 需要导入模块: from PyFoam.Basics.LineReader import LineReader [as 别名]
# 或者: from PyFoam.Basics.LineReader.LineReader import read [as 别名]
class BasicWatcher(object):
    """Base class for watching the output of commands

    Works like the UNIX-command 'tail -f <file>': the last lines of the file are output.
    If the file grows then these lines are output as they arrive"""

    def __init__(self,filename,
                 silent=False,
                 tailLength=1000,
                 sleep=0.1,
                 follow=True):
        """@param filename: name of the logfile to watch
        @param silent: if True no output is sent to stdout
        @param tailLength: number of bytes at the end of the fail that should be output.
        @param follow: if the end of the file is reached wait for further input
        Because data is output on a per-line-basis
        @param sleep: interval to sleep if no line is returned"""

        self.filename=filename
        self.silent=silent
        self.tail=tailLength
        self.sleep=sleep
        self.follow=follow
        self.isTailing=False

        if not path.exists(self.filename):
            print_("Error: Logfile ",self.filename,"does not exist")

        self.reader=LineReader()

    def getSize(self):
        """@return: the current size (in bytes) of the file"""
        return os.stat(self.filename)[stat.ST_SIZE]

    def start(self):
        """Reads the file and does the processing"""

        currSize=self.getSize()

        fn,ext=path.splitext(self.filename)
        if ext=='.gz':
            fh=gzip.open(self.filename)
        else:
            fh=open(self.filename)

        self.startHandle()

        while self.follow or currSize>self.reader.bytesRead():
            try:
                status=self.reader.read(fh)
                if status:
                    line=self.reader.line
                    if (currSize-self.reader.bytesRead())<=self.tail:
                        if not self.isTailing:
                            self.isTailing=True
                            self.timeHandle()
                            self.tailingHandle()

                        if not self.silent:
                            print_(line)

                    self.lineHandle(line)
                else:
                    if self.reader.userSaidStop():
                        break
                    sleep(self.sleep)
            except KeyboardInterrupt:
                print_("Watcher: Keyboard interrupt")
                break

        self.stopHandle()

        fh.close()

    def startHandle(self):
        """to be called before the program is started"""
        pass

    def stopHandle(self):
        """called after the program has stopped"""
        pass

    def tailingHandle(self):
        """called when the first line is output"""
        pass

    def lineHandle(self,line):
        """called every time a new line is read"""
        pass
开发者ID:LeeRuns,项目名称:PyFoam,代码行数:91,代码来源:BasicWatcher.py


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