Elisha512 Elisha512 - 1 month ago 5
Python Question

How to get execution of python print statements as a string?

I am writing a python script which contains a list containing python print statements as a string. In my function, I am using a for loop to run exec function to run those statements.

Here is my function:

g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]

def run_statements():
for item in g_list:

When I run
function, I get the following output:


Basically, I want to save the output as a string so that later, I can save it to my database.

Does anyone have any idea how can I do it?

EDIT: At the following question: python : get the print output in an exec statement He is trying to get output, My question is different in a way that I am trying to get output as a string


If you really need a print statement in the list of strings (as opposed to a print-like function with a different name, as suggested in another answer), you can reassign the name print to your own function, after carefully, carefully, carefully saving the old print function so you can carefully, carefully, carefully restore the name print to its proper definition. Like this:

>>> g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
>>> old_print = print
>>> def print(s): # redefining the built-in print function! terrible idea
...   global catstr
...   catstr += s
>>> catstr = ""
>>> for s in g_list: exec(s)
>>> catstr
>>> print = old_print # Don't forget this step!

This is completely immoral, and I did not advise you to do it. I only said you can do it.

To stress the inadvisability of this plan: exec should be used rarely; it is dangerous; reassigning the names of built-in functions to different functions should be done very rarely; it is dangerous. Doing both in the same code could really ruin your day, especially after a maintenance programmer edits your code "just a little," without realizing the potential impact.