CMS 3D CMS Logo

addLHEnumbers.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 from __future__ import print_function
4 import logging
5 import argparse
6 import sys
7 import os
8 import re
9 
10 
11 def number_events(input_file, output_file=None, offset=0):
12  if output_file is None:
13  output_file = input_file
14  if not os.path.exists(os.path.dirname(os.path.realpath(output_file))):
15  os.makedirs(os.path.dirname(os.path.realpath(output_file)))
16 
17  nevent = offset
18  with open('tmp.txt', 'w') as fw:
19  with open(input_file, 'r') as ftmp:
20  for line in ftmp:
21  if re.search('\s*</event>', line):
22  nevent += 1
23  fw.write('<event_num num="' + str(nevent) + '"> ' + str(nevent) + '</event_num>\n')
24  fw.write(line)
25  if output_file is not None:
26  os.rename("tmp.txt", output_file)
27  else:
28  os.rename("tmp.txt", input_file)
29  return nevent
30 
31 
32 if __name__=="__main__":
33 
34  parser = argparse.ArgumentParser(
35  description="Add numbers to lhe")
36  parser.add_argument("input_file", type=str,
37  help="Input LHE file path.")
38  parser.add_argument("-o", "--output-file", default=None, type=str,
39  help="Output LHE file path. If not specified, output to input file")
40  args = parser.parse_args()
41 
42  logging.info('>>> launch addLHEnumbers.py in %s' % os.path.abspath(os.getcwd()))
43 
44  logging.info('>>> Input file: [%s]' % args.input_file)
45  logging.info('>>> Write to output: %s ' % args.output_file)
46 
47  number_events(args.input_file, args.output_file)
def number_events(input_file, output_file=None, offset=0)
#define str(s)