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


this question has answer here:

i writing python script contains list containing python print statements string. in function, using loop run exec function run statements.

here function:

g_list = ["print('wow!')\n", "print('great!')\n", "print('epic!')\n"]  def run_statements():     item in g_list:         exec(item) 

when run run_statements() function, following output:

wow!  great!  epic! 

basically, want save output string later, can save database.

does have idea how can it?

edit: @ following question: python: print output in exec statement trying output, question different in way trying output string

if need print statement in list of strings (as opposed print-like function different name, suggested in answer), can reassign name print own function, after carefully, carefully, saving old print function can carefully, carefully, restore name print proper definition. this:

>>> g_list = ["print('wow!')\n", "print('great!')\n", "print('epic!')\n"] >>> old_print = print >>> def print(s): # redefining built-in print function! terrible idea ...   global catstr ...   catstr += s ... >>> catstr = "" >>> s in g_list: exec(s) ... >>> catstr 'wow!great!epic!' >>> print = old_print # don't forget step! 

this immoral, , did not advise it. said can it.

to stress inadvisability of plan: exec should used rarely; dangerous; reassigning names of built-in functions different functions should done rarely; dangerous. doing both in same code ruin day, after maintenance programmer edits code "just little," without realizing potential impact.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -