1
2 """
3 Application class that implements pyFoamReadDictionary
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_
13
16 description="""\
17 Reads a value from a Foam-Dictionary and prints it to the screen. The
18 description of the value is word. If the value is non-atomic (a list
19 or a dictionary) it is output in Python-notation. Parts of the
20 expression can be accessed by using the Python-notation for accessing
21 sub-expressions.
22
23 Example of usage:
24 pyFoamReadDictionary.py pitzDaily/0/U "boundaryField['inlet']['type']"
25 """
26
27 PyFoamApplication.__init__(self,
28 args=args,
29 description=description,
30 usage="%prog [options] <dictfile> <key>",
31 nr=2,
32 changeVersion=False,
33 interspersed=True)
34
36 self.parser.add_option("--debug",
37 action="store_true",
38 default=None,
39 dest="debug",
40 help="Debugs the parser")
41
42
44 fName=self.parser.getArgs()[0]
45 all=self.parser.getArgs()[1]
46 if all[0]=='"':
47 all=all[1:]
48 if all[-1]=='"':
49 all=all[:-1]
50
51 match=re.compile("([a-zA-Z_][a-zA-Z0-9_]*)(.*)").match(all)
52 if match==None:
53 self.error("Expression",all,"not usable as an expression")
54
55 key=match.group(1)
56 sub=None
57 if len(match.groups())>1:
58 if match.group(2)!="":
59 sub=match.group(2)
60
61 try:
62 dictFile=ParsedParameterFile(fName,backup=False,debug=self.opts.debug)
63 val=dictFile[key]
64 except KeyError:
65 self.error("Key: ",key,"not existing in File",fName)
66 except IOError:
67 e = sys.exc_info()[1]
68 self.error("Problem with file",fName,":",e)
69
70 if sub==None:
71 erg=val
72 else:
73 try:
74 erg=eval(str(val)+sub)
75 except Exception:
76 e = sys.exc_info()[1]
77 self.error("Problem with subexpression:",sys.exc_info()[0],":",e)
78
79 print_(erg)
80
81
82