Package PyFoam :: Package Applications :: Module WriteDictionary
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Applications.WriteDictionary

 1  #  ICE Revision: $Id: WriteDictionary.py 8450 2008-01-27 20:37:07Z bgschaid $  
 2  """ 
 3  Application class that implements pyFoamWriteDictionary 
 4  """ 
 5   
 6  import sys,re 
 7   
 8  from PyFoamApplication import PyFoamApplication 
 9   
10  from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile 
11   
12 -class WriteDictionary(PyFoamApplication):
13 - def __init__(self,args=None):
14 description=""" 15 Write a value to a Foam-Dictionary. 16 The description of the value is word. If the value is 17 non-atomic (a list or a dictionary) it has to be in in Python-notation. 18 Parts of the expression can be accessed by using the Python-notation for accessing 19 sub-expressions. 20 21 Example of usage: 22 > pyFoamWriteDictionary.py --test pitzDaily/0/U "boundaryField['inlet']['type']" zeroGradient < 23 """ 24 25 PyFoamApplication.__init__(self,args=args,description=description,usage="%prog [options] <dictfile> <key> <val>",nr=3,interspersed=True)
26
27 - def addOptions(self):
28 self.parser.add_option("--test",action="store_true",dest="test",default=False,help="Doesn't write to the file, but outputs the result on stdout") 29 self.parser.add_option("--evaluate",action="store_false",dest="verbatim",default=True,help="Interpret the string as a python expression before assigning it")
30 31
32 - def run(self):
33 fName=self.parser.getArgs()[0] 34 all=self.parser.getArgs()[1] 35 val=self.parser.getArgs()[2] 36 37 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all) 38 if match==None: 39 self.error("Expression",all,"not usable as an expression") 40 41 key=match.group(1) 42 sub=None 43 if len(match.groups())>1: 44 if match.group(2)!="": 45 sub=match.group(2) 46 47 if self.opts.verbatim: 48 newValue=val 49 else: 50 newValue=eval(val) 51 52 try: 53 dictFile=ParsedParameterFile(fName,backup=True) 54 val=dictFile[key] 55 except KeyError: 56 self.error("Key: ",key,"not existing in File",fName) 57 except IOError,e: 58 self.error("Problem with file",fName,":",e) 59 60 if sub==None: 61 dictFile[key]=newValue 62 else: 63 try: 64 exec "dictFile[key]"+sub+"=newValue" 65 except Exception,e: 66 self.error("Problem with subexpression:",sys.exc_info()[0],":",e) 67 68 if self.opts.test: 69 print str(dictFile) 70 else: 71 dictFile.writeFile()
72