ATLAS Offline Software
PyStep.py
Go to the documentation of this file.
1 #
2 # Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
3 #
4 
5 """
6 Step implemented as python function
7 """
8 
9 from TrigValTools.TrigValSteering.Step import Step
10 import contextlib
11 import sys
12 
13 class PyStep(Step):
14  """Step calling a python function"""
15 
16  def __init__(self, func, **kwargs):
17  name = kwargs.get('name') or func.__name__
18  super(PyStep, self).__init__(name)
19  self.func = func
20  self.func_kwargs = dict([(k,v) for k,v in kwargs.items() if k != 'name'])
21  self.output_stream = Step.OutputStream.STDOUT_ONLY
22 
23  def run(self, dry_run=False):
24 
25  self.log.info('Running %s step', self.name)
26 
27  dest = sys.stdout
28  if self.output_stream == self.OutputStream.NO_PRINT:
29  dest = None
30  elif self.output_stream in [self.OutputStream.FILE_ONLY, self.OutputStream.FILE_AND_STDOUT]:
31  dest = open(self.get_log_file_name(), 'w')
32 
33  if dry_run:
34  self.result = 0
35  else:
36  try:
37  with contextlib.redirect_stdout(dest), contextlib.redirect_stderr(dest):
38  self.result = self.func(**self.func_kwargs)
39 
40  # Poor man's implementation of 'tee'
41  if self.output_stream == self.OutputStream.FILE_AND_STDOUT:
42  dest.close()
43  print(open(dest.name).read())
44 
45  # In case function does not return a value, assume success
46  if self.result is None:
47  self.result = 0
48  except Exception as e:
49  self.log.error('Exception calling %s: %s', self.func.__name__, e)
50  self.result = 1
51 
52  return self.result, f'# (internal) {self.func.__name__}'
grepfile.info
info
Definition: grepfile.py:38
read
IovVectorMap_t read(const Folder &theFolder, const SelectionCriterion &choice, const unsigned int limit=10)
Definition: openCoraCool.cxx:569
python.TrigValSteering.PyStep.PyStep.output_stream
output_stream
Definition: PyStep.py:21
python.TrigValSteering.PyStep.PyStep.run
def run(self, dry_run=False)
Definition: PyStep.py:23
python.TrigValSteering.PyStep.PyStep.func
func
Definition: PyStep.py:19
python.TrigValSteering.PyStep.PyStep.func_kwargs
func_kwargs
Definition: PyStep.py:20
python.TrigValSteering.PyStep.PyStep.result
result
Definition: PyStep.py:34
Trk::open
@ open
Definition: BinningType.h:40
python.TrigValSteering.PyStep.PyStep
Definition: PyStep.py:13
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
python.TrigValSteering.PyStep.PyStep.__init__
def __init__(self, func, **kwargs)
Definition: PyStep.py:16
error
Definition: IImpactPoint3dEstimator.h:70