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