Kazil
Kazil

Reputation: 1

Is there a way I can run code that is printed by a function in python?

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?

Upvotes: 0

Views: 57

Answers (1)

Barmar
Barmar

Reputation: 781721

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.

Upvotes: 1

Related Questions