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

Source Code for Module PyFoam.Applications.WriteDictionary

 1  #  ICE Revision: $Id: WriteDictionary.py 9861 2009-01-05 16:22:37Z 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 if all[0]=='"': 42 all=all[1:] 43 if all[-1]=='"': 44 all=all[:-1] 45 val=self.parser.getArgs()[2] 46 47 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all) 48 if match==None: 49 self.error("Expression",all,"not usable as an expression") 50 51 key=match.group(1) 52 sub=None 53 if len(match.groups())>1: 54 if match.group(2)!="": 55 sub=match.group(2) 56 57 if self.opts.verbatim: 58 newValue=val 59 else: 60 newValue=eval(val) 61 62 try: 63 dictFile=ParsedParameterFile(fName,backup=True) 64 val=dictFile[key] 65 except KeyError: 66 self.error("Key: ",key,"not existing in File",fName) 67 except IOError,e: 68 self.error("Problem with file",fName,":",e) 69 70 if sub==None: 71 dictFile[key]=newValue 72 else: 73 try: 74 exec "dictFile[key]"+sub+"=newValue" 75 except Exception,e: 76 self.error("Problem with subexpression:",sys.exc_info()[0],":",e) 77 78 if self.opts.test: 79 print str(dictFile) 80 else: 81 dictFile.writeFile()
82