1 """
2 Application class that implements pyFoamWriteDictionary
3 """
4
5 import sys,re
6
7 from PyFoamApplication import PyFoamApplication
8
9 from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile
10
13 description="""
14 Write a value to a Foam-Dictionary.
15 The description of the value is word. If the value is
16 non-atomic (a list or a dictionary) it has to be in in Python-notation.
17 Parts of the expression can be accessed with an option
18 """
19
20 PyFoamApplication.__init__(self,description=description,usage="%prog [options] <dictfile> <key> <val>",nr=3,interspersed=True)
21
23 self.parser.add_option("--subexpression",action="store",default=None,dest="subexpression",help="A subexpression (in python notation to access parts of the value)")
24 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")
25 self.parser.add_option("--verbatim",action="store_true",dest="verbatim",default=False,help="Use the string without interpreting it as a Python-expression")
26
27
29 fName=self.parser.getArgs()[0]
30 key=self.parser.getArgs()[1]
31 val=self.parser.getArgs()[2]
32
33 if self.opts.verbatim:
34 newValue=val
35 else:
36 newValue=eval(val)
37
38 try:
39 dictFile=ParsedParameterFile(fName,backup=True)
40 val=dictFile[key]
41 except KeyError:
42 self.error("Key: ",key,"not existing in File",fName)
43 except IOError,e:
44 self.error("Problem with file",fName,":",e)
45
46 if self.opts.subexpression==None:
47 dictFile[key]=newValue
48 else:
49 try:
50 exec "dictFile[key]"+self.opts.subexpression+"=newValue"
51 except Exception,e:
52 self.error("Problem with subexpression:",sys.exc_info()[0],":",e)
53
54 if self.opts.test:
55 print dictFile.makeString()
56 else:
57 dictFile.writeFile()
58