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?
CodePudding user response:
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.
CodePudding user response:
In Python, as well as other interpreted languages, there exists the ability to turn string data into executable code dynamically. This is due to the nature of interpreted languages. In Python there are two ways to do this:
The exec()
function will run its argument.
e.g. exec("print('hello')")
The eval()
function will evaluate its argument.
e.g. eval("5>2")
would return True
.