Updated to accept the += operator, uses stdin/stdout, and will now handle arrays
[sfa.git] / cmdline / getRecord.py
1 #!/usr/bin/python
2
3 """
4 Filters/Prints record objects
5
6
7 faiyaza at cs dot princeton dot edu
8 Copyright (c) 2009 Board of Trustees, Princeton University
9
10 $Id$
11 $HeadURL$
12 """
13
14 import sys
15 import os
16 from optparse import OptionParser
17 from pprint import pprint
18 from xml.parsers.expat import ExpatError
19 from geni.util.rspec import RecordSpec
20
21
22 def create_parser():
23     command = sys.argv[0]
24     argv = sys.argv[1:]
25     usage = "%(command)s [options]" % locals()
26     description = """getRecord will parse a supplied (via stdin) record and print all values or key/values, and filter results based on a given key or set of keys."""
27     parser = OptionParser(usage=usage,description=description)
28     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
29         default=False,  help = "record file path")
30     parser.add_option("-k", "--key", dest="withkey", action="store_true",
31         default=False,  help = "print keys")
32    
33     return parser    
34
35 def printRec(record, filters, options):
36     line = ""
37     if len(filters):
38         for filter in filters:
39             if options.DEBUG:  print "Filtering on %s" %filter
40             if options.withkey:
41                 line += "%s: " %filter
42             line += "%s\n" % \
43                 printVal(record.dict["record"].get(filter, None))
44             print line
45     else:
46         # print the wole thing
47         for (key, value) in record.dict["record"].iteritems():
48             if options.withkey:
49                 line += "%s: " % key
50             line += "%s\n" % printVal(value)
51         print line
52
53 # fix the iteratable values
54 def printVal(value):
55     line = ""
56     if type(value) in (tuple, list):
57         for i in value:
58             line += "%s " % i
59     else:
60         line += value
61     return line.rstrip("\n")
62
63 def main():
64     parser = create_parser(); 
65     (options, args) = parser.parse_args()
66
67     stdin = sys.stdin.read()
68     
69     record = RecordSpec(xml = stdin)
70     
71     if not record.dict.has_key("record"):
72         raise "RecordError", "Input record does not have 'record' tag."
73
74     if options.DEBUG: 
75         record.pprint()
76         print "#####################################################"
77
78     printRec(record, args, options)
79
80 if __name__ == '__main__':
81     try: main()
82     except ExpatError, e:
83         print "RecordError.  Is your record valid XML?"
84         print e
85     except Exception, e:
86         print e