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

Source Code for Module PyFoam.Applications.WriteDictionary

 1  #  ICE Revision: $Id: WriteDictionary.py 9161 2008-08-04 08:01:05Z 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, 26 args=args, 27 description=description, 28 usage="%prog [options] <dictfile> <key> <val>", 29 changeVersion=False, 30 nr=3, 31 interspersed=True)
32
33 - def addOptions(self):
34 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") 35 self.parser.add_option("--evaluate",action="store_false",dest="verbatim",default=True,help="Interpret the string as a python expression before assigning it")
36 37
38 - def run(self):
39 fName=self.parser.getArgs()[0] 40 all=self.parser.getArgs()[1] 41 val=self.parser.getArgs()[2] 42 43 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all) 44 if match==None: 45 self.error("Expression",all,"not usable as an expression") 46 47 key=match.group(1) 48 sub=None 49 if len(match.groups())>1: 50 if match.group(2)!="": 51 sub=match.group(2) 52 53 if self.opts.verbatim: 54 newValue=val 55 else: 56 newValue=eval(val) 57 58 try: 59 dictFile=ParsedParameterFile(fName,backup=True) 60 val=dictFile[key] 61 except KeyError: 62 self.error("Key: ",key,"not existing in File",fName) 63 except IOError,e: 64 self.error("Problem with file",fName,":",e) 65 66 if sub==None: 67 dictFile[key]=newValue 68 else: 69 try: 70 exec "dictFile[key]"+sub+"=newValue" 71 except Exception,e: 72 self.error("Problem with subexpression:",sys.exc_info()[0],":",e) 73 74 if self.opts.test: 75 print str(dictFile) 76 else: 77 dictFile.writeFile()
78