0

For example, say I have a function like

def example():
    print("print('Hello')\nprint('There')")

Is there a way I can run the text outputted without having to run the function, copy the output and rerun the output?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Kazil
  • 1
  • 1
  • 1
    This part is not clear: "*without having to run the function*". The string is hardcoded inside the `print(...)`. You want to get that string without _calling_ the function? – Gino Mempin Oct 15 '21 at 03:34
  • 2
    You could set `sys.stdout` to a `StringIO` stream. Then you can call the function, get the contents of the stream, and call `exec()` – Barmar Oct 15 '21 at 03:35
  • 1
    @GinoMempin I think he means without having to copy and paste it from the terminal output. – Barmar Oct 15 '21 at 03:36
  • 5
    This sounds like an [XY Problem](https://meta.stackexchange.com/q/66377/478746). Could you comment what your use case is for printing Python code to stdout? – Brian61354270 Oct 15 '21 at 03:37

1 Answers1

1

See Can I redirect the stdout into some sort of string buffer? for many ways to capture standard output in a string variable.

Use that when calling the function, then use exec(variable) to execute the output.

Barmar
  • 741,623
  • 53
  • 500
  • 612