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. The description of the value is
16 word. If the value is non-atomic (a list or a dictionary) it has to be
17 in in Python-notation. Parts of the expression can be accessed by
18 using the Python-notation for accessing sub-expressions.
19
20 Example of usage:
21 > pyFoamWriteDictionary.py --test pitzDaily/0/U "boundaryField['inlet']['type']" zeroGradient <
22 """
23
24 PyFoamApplication.__init__(self,
25 args=args,
26 description=description,
27 usage="%prog [options] <dictfile> <key> <val>",
28 changeVersion=False,
29 nr=3,
30 interspersed=False)
31
33 self.parser.add_option("--test",
34 action="store_true",
35 dest="test",
36 default=False,
37 help="Doesn't write to the file, but outputs the result on stdout")
38
39 self.parser.add_option("--strip-quotes-from-value",
40 action="store_true",
41 dest="stripQuotes",
42 default=False,
43 help="Strip the quotes from the value if they had to be defined")
44
45 self.parser.add_option("--evaluate",
46 action="store_false",
47 dest="verbatim",
48 default=True,
49 help="Interpret the string as a python expression before assigning it")
50
51
53 fName=self.parser.getArgs()[0]
54 all=self.parser.getArgs()[1]
55 if all[0]=='"':
56 all=all[1:]
57 if all[-1]=='"':
58 all=all[:-1]
59
60 val=self.parser.getArgs()[2]
61 if self.opts.stripQuotes:
62 if val[0]=='"':
63 val=val[1:]
64 if val[-1]=='"':
65 val=val[:-1]
66
67
68 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all)
69 if match==None:
70 self.error("Expression",all,"not usable as an expression")
71
72 key=match.group(1)
73 sub=None
74 if len(match.groups())>1:
75 if match.group(2)!="":
76 sub=match.group(2)
77
78 if self.opts.verbatim:
79 newValue=val
80 else:
81 newValue=eval(val)
82
83 try:
84 dictFile=ParsedParameterFile(fName,backup=True)
85 val=dictFile[key]
86 except KeyError:
87 self.error("Key: ",key,"not existing in File",fName)
88 except IOError,e:
89 self.error("Problem with file",fName,":",e)
90
91 if sub==None:
92 dictFile[key]=newValue
93 else:
94 try:
95 exec "dictFile[key]"+sub+"=newValue"
96 except Exception,e:
97 self.error("Problem with subexpression:",sys.exc_info()[0],":",e)
98
99 if self.opts.test:
100 print str(dictFile)
101 else:
102 dictFile.writeFile()
103