14 parser = argparse.ArgumentParser(description=
"Split an LHE file into chunks")
15 parser.add_argument(
'inputFile', help=
"Input file")
16 parser.add_argument(
'--events',
'-e', type=int, required=
True,
17 help=
"Number of events per output file")
18 parser.add_argument(
'--directory',
'-d', help=
'Output directory (optional; default ".")')
19 args = vars(parser.parse_args(sys.argv[1:]))
22 if not os.access( args[
'inputFile'] , os.R_OK ):
23 print(f
'Error: cannot access input file {args["inputFile"][0]}')
25 in_file =
open( args[
'inputFile'] ,
'r' )
28 last_dot = os.path.basename( args[
'inputFile'] ).rfind(
'.')
29 out_stem = os.path.basename( args[
'inputFile'] )[ : last_dot ]
30 if 'directory' in args
and args[
'directory']
is not None:
31 out_stem = args[
'directory']+
'/'+out_stem
32 out_ext =
'' if last_dot < 0
else os.path.basename( args[
'inputFile'] )[ last_dot : ]
37 if '<event>' in line
or '<event ' in line:
41 print(f
'Attempting to split file of {n_events} events into files of {args["events"]} events each')
42 if n_events < args[
'events']:
43 print(f
'Fewer events than requested {args["events"]} in input file. No action needed.')
45 if not (n_events/args[
'events']).is_integer():
46 print(f
'Warning: the final file will only have {n_events%args["events"]} events')
52 n_files = math.ceil(n_events/args[
'events'])
54 for i
in range(n_files):
55 if os.access( f
'{out_stem}_{i}{out_ext}' , os.R_OK ):
56 print(f
'Error: output file {out_stem}_{i}{out_ext} exists. Please cleanup and try again')
58 out_files += [
open( f
'{out_stem}_{i}{out_ext}',
'w' ) ]
66 if (this_event==-1
and '<event>' not in line
and '<event ' not in line)
or this_event==n_events:
67 for i
in range(n_files):
68 out_files[i].
write(line)
73 if '<event>' in line
or '<event ' in line:
77 my_file = math.floor(this_event/args[
'events'])
79 print(f
'Uh oh. {this_event} {args["events"]} {my_file}')
80 out_files[my_file].
write(line)
83 if '</event>' in line
and this_event==n_events-1:
87 for i
in range(n_files):