CoolFace
Apppublic

AtharvaThakur/Insights

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
python_interpreter.py63 linesDownload Raw Back to Modules
1import subprocess2import os3import datetime4import threading5 6 7class PythonInterpreter:8    def __init__(self):9        self.use_local_model = True10        self.output_file = "output/" + \11            datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".py"12 13    def run_python_code(self, filename):14        # Function to run Python code and handle errors15        try:16            code_ran = subprocess.run(17                ["python", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)18 19            if code_ran.returncode == 0:20                print("Python code ran successfully")21                return code_ran.stdout22            else:23                print("Python code ran with errors")24                print("Error:", code_ran.stderr)25                return code_ran.stderr26        except subprocess.CalledProcessError as e:27            print("Error:", str(e))28            return str(e)29        except Exception as e:30            print("Error:", str(e))31            return str(e)32 33    def save_python_code(self, python_code, output_file):34        # Function to save Python code to a file35        try:36            with open(output_file, "w") as f:37                f.write(python_code)38            print("Python code saved as", output_file)39        except Exception as e:40            print("Error:", str(e))41 42    def get_user_input_for_code(self):43        save_python_code = input(44            "Do you want to save the Python code? (y/n): ")45        run_python_code = input("Do you want to run the Python code? (y/n): ")46        return save_python_code.lower() == "y", run_python_code.lower() == "y"47 48 49def run_interpreter(code=None):50    interpreter = PythonInterpreter()51 52    if code:53        filename='code.py'54        interpreter.save_python_code(code,filename)55        output = interpreter.run_python_code(filename)56        if output:57            print("Python code output:\n", output)58            return output59 60 61if __name__ == "__main__":62    run_interpreter()63