33import sys
44import os
55import warnings
6+ import tempfile
67from pathlib import Path
78
89token_specification = [
@@ -231,6 +232,16 @@ def process_includes(code, input_file):
231232
232233 return header_code , code_without_includes
233234
235+ def execute_code_temporarily (code ):
236+ with tempfile .TemporaryDirectory () as tmpdir :
237+ temp_file_path = os .path .join (tmpdir , "compiled_repy.py" )
238+ with open (temp_file_path , 'w' ) as temp_file :
239+ temp_file .write (code )
240+ try :
241+ exec (open (temp_file_path ).read (), {"__name__" : "__main__" })
242+ except Exception as e :
243+ print (f"Error during execution: { e } " )
244+ print (f"You can view the generated file at { (temp_file_path )} " )
234245
235246def main ():
236247 parser = argparse .ArgumentParser (description = "Compile REPY files." )
@@ -258,8 +269,38 @@ def main():
258269 with open (output_file , 'w' ) as f :
259270 f .write (final_code )
260271
261- print (f"Successfully compiled { input_file } to { output_file } " )
272+ print (f"Successfully compiled { input_file } to { output_file } " )
273+
274+ def launch ():
275+ parser = argparse .ArgumentParser (description = "Preview REPY execution." )
276+ parser .add_argument ("filename" , help = "The REPY file to preview." )
277+ args = parser .parse_args ()
278+
279+ input_file = args .filename
280+
281+ if not os .path .exists (input_file ):
282+ print (f"Error: The file { input_file } does not exist." )
283+ return
284+
285+ with open (input_file , 'r' ) as f :
286+ source_code = f .read ()
287+
288+ header_code , code_without_includes = process_includes (
289+ source_code , input_file )
290+
291+ python_code = parse_repython (code_without_includes )
292+
293+ final_code = header_code + python_code
294+
295+ # Execute the compiled code directly
296+ try :
297+ execute_code_temporarily (final_code )
298+ except Exception as e :
299+ print (f"Error during execution: { e } " )
262300
263301
264302if __name__ == "__main__" :
265- main ()
303+ main (1 )
304+
305+ if __name__ == "__launch__" :
306+ main (2 )
0 commit comments