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