0

I am making a python IDE and I wanted to print the output of a file's code to the output text box. My current code doesnt work, it executes in the shell and the output is to the box is "None". Code:

from tkinter import *
input_box = Text()
output_box = Text()
def execute():
    code = input_box.get(1.0, END)
    out = exec(code)
    output.insert(1.0, str(out))

  • 2
    try `eval` instead of `exec`... `eval` can return a value where `exec` does not – Anentropic Jul 20 '22 at 12:42
  • But does eval work with every type of code? Also thanks –  Jul 20 '22 at 12:45
  • It give me an error –  Jul 20 '22 at 12:46
  • "args should be '.23918448 insert index chars ?tagList chars tagList –  Jul 20 '22 at 12:47
  • "print the output of a file's code" is not a well defined goal, most code doesn't output anything unless it contains e.g. `print` call. `exec("print('hello')")` works but you will need to capture stdout rather than return value – Anentropic Jul 20 '22 at 12:55

1 Answers1

2

You can do this by redirecting the standard output as described in this answer.

import sys
from io import StringIO
def execute():
    code = input_box.get(1.0, "end")
    old_stdout = sys.stdout
    redirected_output = sys.stdout = StringIO()
    exec(code)
    sys.stdout = old_stdout
    output_box.delete(1.0, "end")
    output_box.insert(1.0, redirected_output.getvalue())
Henry
  • 3,472
  • 2
  • 12
  • 36