import sys import ast def evaulate_expressions_in_a_file(filename = "expr_ex.py"): """ Opens a file and prints each line prefixed with its line number. Args: filename (str): The path to the file to be read. """ try: with open(filename, 'r') as file: for line_number, line in enumerate(file, start=1): # rstrip() removes trailing whitespace, including newline characters, # preventing double newlines in the output. expr = line.lstrip().rstrip() if expr[0] == '#': print(expr) else: exec(expr) try: tree = ast.parse(expr, mode='eval') print(f"[line {line_number}] {expr}: {eval(expr)}") except: print(expr) except FileNotFoundError: print(f"Error: The file '{filename}' was not found.") except Exception as e: print(f"An unexpected error occurred: {e}") # usage: python eval.exp.py input_python_expression_filename if __name__ == "__main__": if len(sys.argv) > 1: evaulate_expressions_in_a_file(sys.argv[1]) else: infile = "expr_ex.py" # Replace with your desired filename evaulate_expressions_in_a_file(infile)