1
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
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
34 self.parser.add_option("--test",
35 action="store_true",
36 dest="test",
37 default=False,
38 help="Doesn't write to the file, but outputs the result on stdout")
39
40 self.parser.add_option("--strip-quotes-from-value",
41 action="store_true",
42 dest="stripQuotes",
43 default=False,
44 help="Strip the quotes from the value if they had to be defined")
45
46 self.parser.add_option("--evaluate",
47 action="store_false",
48 dest="verbatim",
49 default=True,
50 help="Interpret the string as a python expression before assigning it")
51
52
54 fName=self.parser.getArgs()[0]
55 all=self.parser.getArgs()[1]
56 if all[0]=='"':
57 all=all[1:]
58 if all[-1]=='"':
59 all=all[:-1]
60
61 val=self.parser.getArgs()[2]
62 if self.opts.stripQuotes:
63 if val[0]=='"':
64 val=val[1:]
65 if val[-1]=='"':
66 val=val[:-1]
67
68
69 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all)
70 if match==None:
71 self.error("Expression",all,"not usable as an expression")
72
73 key=match.group(1)
74 sub=None
75 if len(match.groups())>1:
76 if match.group(2)!="":
77 sub=match.group(2)
78
79 if self.opts.verbatim:
80 newValue=val
81 else:
82 newValue=eval(val)
83
84 try:
85 dictFile=ParsedParameterFile(fName,backup=True)
86 val=dictFile[key]
87 except KeyError:
88 self.error("Key: ",key,"not existing in File",fName)
89 except IOError,e:
90 self.error("Problem with file",fName,":",e)
91
92 if sub==None:
93 dictFile[key]=newValue
94 else:
95 try:
96 exec "dictFile[key]"+sub+"=newValue"
97 except Exception,e:
98 self.error("Problem with subexpression:",sys.exc_info()[0],":",e)
99
100 if self.opts.test:
101 print str(dictFile)
102 else:
103 dictFile.writeFile()
104