1+ # copythefile.py
2+ import sys
3+ import os
4+
5+ def create_modified_script (template_script_path , zmq_port_name_val , zmq_port_val , output_dir ):
6+
7+ try :
8+ with open (template_script_path , 'r' ) as f :
9+ lines = f .readlines ()
10+ except FileNotFoundError :
11+ print (f"Error: Template script '{ template_script_path } ' not found." )
12+ sys .exit (1 )
13+ except Exception as e :
14+ print (f"Error reading template script '{ template_script_path } ': { e } " )
15+ sys .exit (1 )
16+
17+ definitions = [
18+ '\n ' ,
19+ f'ZMQ_PORT_NAME = "{ zmq_port_name_val } "\n ' ,
20+ f'ZMQ_PORT = "{ zmq_port_val } "\n ' ,
21+ '\n '
22+ ]
23+
24+ insert_index = 0
25+ for i , line in enumerate (lines ):
26+ stripped_line = line .strip ()
27+ if stripped_line .startswith ('import ' ) or stripped_line .startswith ('from ' ):
28+ insert_index = i + 1
29+ elif insert_index > 0 and stripped_line and not stripped_line .startswith ('#' ):
30+ break
31+ if insert_index == 0 and lines and lines [0 ].startswith ('#!' ):
32+ insert_index = 1
33+
34+ modified_lines = lines [:insert_index ] + definitions + lines [insert_index :]
35+
36+ # Determine output filename
37+ base_template_name = os .path .basename (template_script_path )
38+ template_root , template_ext = os .path .splitext (base_template_name )
39+ output_filename = f"{ template_root } { template_ext } "
40+ output_script_path = os .path .join (output_dir , output_filename )
41+
42+ try :
43+ if not os .path .exists (output_dir ):
44+ os .makedirs (output_dir )
45+ print (f"Created output directory: { output_dir } " )
46+
47+ with open (output_script_path , 'w' ) as f :
48+ f .writelines (modified_lines )
49+
50+ print (f"Successfully created '{ output_script_path } ' with:" )
51+ print (f" ZMQ_PORT_NAME = \" { zmq_port_name_val } \" " )
52+ print (f" ZMQ_PORT = \" { zmq_port_val } \" " )
53+
54+ except Exception as e :
55+ print (f"Error writing output script '{ output_script_path } ': { e } " )
56+ sys .exit (1 )
57+
58+ if __name__ == "__main__" :
59+ if len (sys .argv ) != 5 :
60+ print ("Usage: python3 copy_with_port_portname.py <New_ZMQ_PORT_NAME> <New_ZMQ_PORT> <TEMPLATE_SCRIPT_PATH> <OUTPUT_DIRECTORY>" )
61+ print ("Example: python3 copy_with_port_portname.py FUNBODY_REP_1 \" 2355\" \" ./templates/funbody_base.py\" \" ./generated_scripts/\" " )
62+ sys .exit (1 )
63+
64+ new_port_name_arg = sys .argv [1 ]
65+ new_bind_address_arg = sys .argv [2 ]
66+ template_script_path_arg = sys .argv [3 ]
67+ output_directory_arg = sys .argv [4 ]
68+
69+ create_modified_script (template_script_path_arg , new_port_name_arg , new_bind_address_arg , output_directory_arg )
0 commit comments