ATLAS Offline Software
meta-reader.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
4 # This script reads metadata from a given file
5 
6 from __future__ import print_function
7 
8 import sys
9 import json
10 import argparse
11 import time
12 import logging
13 import os
14 
15 # escape sequence [?1034h which appear on several runs due to smm capability (Meta Mode On) for xterm.
16 if 'TERM' in os.environ:
17  del os.environ['TERM']
18 
19 msg = logging.getLogger('MetaReader')
20 
21 from PyUtils.MetaReader import read_metadata, trigger_keys
22 
23 
24 def _tree_print(content, indent=2, pad=0, list_max_items=-1, dict_sort=None, ascii=False, hide_content=False, hide_trigger=False):
25  s = ''
26 
27  if isinstance(content, dict):
28 
29  if dict_sort == 'key':
30  items = list(sorted(content.items(), key = lambda t: t[0]))
31  elif dict_sort == 'value':
32  items = list(sorted(content.items(), key = lambda t: t[1]))
33  else:
34  items = list(content.items())
35 
36  items_count = len(items)
37  for i in range(items_count):
38 
39  key, value = items[i]
40 
41  last = i == items_count - 1
42 
43  if hide_content and (key in ['itemList', 'metadata_items'] or 'EventFormatStream' in key):
44  continue
45 
46  if hide_trigger and key in trigger_keys:
47  continue
48 
49  if pad == 0:
50  skey = str(key)
51  elif pad < 0:
52  skey = str(key).rjust(-pad)
53  else:
54  skey = str(key).ljust(pad)
55 
56  if not ascii:
57  s += ('├' if not last else '└') + '─' * indent + ' ' + skey + ': '
58  else:
59  s += ('|' if not last else '`') + '-' * indent + ' ' + skey + ': '
60 
61  lines = _tree_print(value, indent=indent, pad=pad, dict_sort=dict_sort, list_max_items=list_max_items, ascii=ascii,
62  hide_content=hide_content, hide_trigger=hide_trigger).split('\n')
63 
64  if len(lines) == 1:
65  s += lines[0] + '\n'
66  else:
67  for line in lines:
68  if line.strip():
69  if not ascii:
70  s += '\n' + ('│' if not last else ' ') + ' ' * indent + ' ' + str(line)
71  else:
72  s += '\n' + ('|' if not last else ' ') + ' ' * indent + ' ' + str(line)
73 
74  s += '\n'
75  elif isinstance(content, (list, tuple)) and list_max_items >= 0 and len(content) > list_max_items:
76 
77  items = list(content)
78  items_count = len(items)
79 
80  for i in range(items_count):
81  value = items[i]
82 
83  last = i == items_count - 1
84 
85  if not ascii:
86  s += ('├' if not last else '└') + '─' * indent + ' ' + str(value) + '\n'
87  else:
88  s += ('|' if not last else '`') + '-' * indent + ' ' + str(value) + '\n'
89  else:
90  s += str(content)
91 
92  return s
93 
94 
95 def _main():
96  # Parsing the arguments provided by user
97  parser = argparse.ArgumentParser(description='This script reads metadata from a given file')
98  parser.add_argument('filenames',
99  nargs = '+',
100  help= 'The filenames to read. User can provide a single file or a list of files.')
101  parser.add_argument('-v',
102  '--verbose',
103  action='store_true',
104  help='print detailed output on screen')
105  parser.add_argument('-o',
106  '--output',
107  metavar='FILE',
108  default=None,
109  help="Saves the output in a file. By default, the output is written on the screen (stdout) in a prettier format for better readabiilty.")
110  parser.add_argument('--json',
111  action='store_true',
112  help="Sets the output file format as json.")
113  parser.add_argument('--indent',
114  metavar='N',
115  type=int,
116  default=2,
117  help="Sets the indent spaces in the output either on screen (without -o flag) either on file (with -o flag). By default, uses two spaces as indent.")
118  parser.add_argument('-m',
119  '--mode',
120  default= 'lite',
121  metavar='MODE',
122  type=str,
123  choices=['tiny', 'lite', 'full', 'peeker', 'iov'],
124  help="This flag provides the user capability to select the amount of metadata retrieved. There are five options: "
125  "tiny (only those values used in PyJobTransforms), "
126  "lite, "
127  "peeker, "
128  "full (all available data found), "
129  "and iov (full+iov details)" )
130 
131  parser.add_argument('-t',
132  '--type',
133  default= None,
134  metavar='TYPE',
135  type=str,
136  choices=['POOL', 'BS'],
137  help="The file type of the input filename. By default, it tries to determine itself the file type of the input.")
138  parser.add_argument('-f',
139  '--filter',
140  default= [],
141  metavar='FILTER',
142  nargs = '+',
143  type=str,
144  help="The metadata keys to filter. ")
145  parser.add_argument('--promote',
146  default=None,
147  type=bool,
148  help="Force promotion or not of the metadata keys ")
149  parser.add_argument('--hideContentList',
150  action='store_true',
151  help="Hide content lists (event-level and metadata containers)")
152  parser.add_argument('--hideTrigger',
153  action='store_true',
154  help="Hide trigger metadata")
155  args = parser.parse_args()
156 
157  verbose = args.verbose
158  filenames = args.filenames
159  output = args.output
160  is_json = args.json
161  indent = args.indent
162  mode = args.mode
163  file_type = args.type
164  meta_key_filter = args.filter
165 
166  msg.setLevel(logging.INFO if verbose else logging.WARNING)
167  # create a stream handler
168  handler = logging.StreamHandler()
169  handler.setLevel(logging.INFO if verbose else logging.WARNING)
170  # create a logging format
171  formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
172  handler.setFormatter(formatter)
173  # add the handlers to the logger
174  msg.addHandler(handler)
175 
176  startTime = time.time()
177  msg.info('Imported headers in: {0} miliseconds'.format((time.time() - startTime) * 1e3))
178  msg.info('The output file is: {0}'.format(output))
179  metadata = read_metadata(filenames, file_type, mode= mode, meta_key_filter= meta_key_filter, promote=args.promote)
180 
181  if output is None:
182  if is_json:
183  print(json.dumps(metadata, indent=indent))
184  else:
185  enc = sys.stdout.encoding
186  ascii = not sys.stdout.isatty() or not enc or enc.lower().find('ansi') >= 0 or enc.lower().find('ascii') >= 0
187  print(_tree_print(metadata, indent=indent, pad=18, dict_sort='key', list_max_items=8, ascii=ascii,
188  hide_content=args.hideContentList, hide_trigger=args.hideTrigger))
189 
190  else:
191  if is_json:
192  with open(output, 'w') as fd:
193  print(json.dumps(metadata, indent=indent), file=fd)
194  else:
195  with open(output, 'w') as fd:
196  print(_tree_print(metadata, indent=indent, pad=18, dict_sort='key', list_max_items=8, ascii=True,
197  hide_content=args.hideContentList, hide_trigger=args.hideTrigger),
198  file=fd)
199 
200  msg.info('Done!')
201 
202 if __name__ == '__main__':
203  _main()
meta-reader._main
def _main()
Definition: meta-reader.py:95
vtune_athena.format
format
Definition: vtune_athena.py:14
find
std::string find(const std::string &s)
return a remapped string
Definition: hcg.cxx:135
python.MetaReader.read_metadata
def read_metadata(filenames, file_type=None, mode='lite', promote=None, meta_key_filter=None, unique_tag_info_values=True, ignoreNonExistingLocalFiles=False)
Definition: MetaReader.py:52
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
meta-reader._tree_print
def _tree_print(content, indent=2, pad=0, list_max_items=-1, dict_sort=None, ascii=False, hide_content=False, hide_trigger=False)
Definition: meta-reader.py:24
Trk::open
@ open
Definition: BinningType.h:40
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
str
Definition: BTagTrackIpAccessor.cxx:11
Trk::split
@ split
Definition: LayerMaterialProperties.h:38