1

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:
        exec(item)

When I run run_statements() function, I get the following output:

Wow! 
Great! 
Epic!

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

Community
  • 1
  • 1
sshussain270
  • 1,785
  • 4
  • 25
  • 49
  • The point of `print` is to send text somewhere, not to save it in memory. If you want to save that as a string, you should simply do so, and then print it when appropriate. Also, it's likely that `exec` is the wrong approach for whatever goal you're trying to achieve. – TigerhawkT3 Sep 13 '16 at 01:18
  • Can you give an exact sample output of what you're expecting the final result to be? You said a string`. So you want: `"Wow!\nGreat!\nEpic\n"`? – idjaw Sep 13 '16 at 01:18
  • @idjaw yes! thats exactly what I want – sshussain270 Sep 13 '16 at 01:19
  • @idjaw it gives syntax error that way – sshussain270 Sep 13 '16 at 01:23
  • @Elisha512 Look at the duplicate that was posted. – idjaw Sep 13 '16 at 01:25
  • @idjaw the other question posted here is a bit confusing for me. Can you explain how will it integrate in my code? – sshussain270 Sep 13 '16 at 01:27

2 Answers2

2

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
'Wow!Great!Epic!'
>>> 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.

D-Von
  • 416
  • 2
  • 5
  • thankyou @D-Von I understand the dangers of it but it might be something exactly what I am looking for. I will test it and if works alright will mark it as correct – sshussain270 Sep 13 '16 at 02:36
  • this statement gives out error: old_print = print that invalid syntax – sshussain270 Sep 13 '16 at 21:03
  • Are you on Python 3.x? That's where I ran the code. It won't work on Python 2.x, where `print` is a built-in command, not a function. – D-Von Sep 13 '16 at 21:25
  • do you have any solution in mind for python 2. I am using python 2.7.11 – sshussain270 Sep 13 '16 at 21:55
  • it works perfectly correct in python 3. I have checked but it doesn't work when I include this in a function. I have added it as update to this answer. Can you please check? – sshussain270 Sep 13 '16 at 22:15
  • I can't think of any way of making the same idea work in Python 2. What about the two ideas in the linked answer? They are: (1) changing sys.stdout to an object that writes to a string; and (2) sending the output outside the process on stdout, grabbing it on an I/O pipe, and sending it back into the process. – D-Von Sep 13 '16 at 22:27
  • can you check the problem I have written as UPDATE at the end of question and guide me please? – sshussain270 Sep 13 '16 at 22:31
  • That update isn't going to help. There is no way to fix the problem, as far as I know. You can't replace the built-in `print` statement in Python 2. I think you need to take the time to understand the two ideas in the linked answer. They both seem workable to me. – D-Von Sep 13 '16 at 22:35
  • No no, I have upgraded my python to 3. And in IDLE, your solution is working but it is not working within a function – sshussain270 Sep 13 '16 at 22:48
  • Put `global print` near the top of the function. You can't refer to a name outside the function without telling Python that that is what you're up to. Along the same lines, you don't show where you set `catstr=""`, but if it's global, you will need to say `global catstr`, and if it's inside `execute`, which is where it should be, you will need to say `nonlocal catstr`. You should look up these `global` and `nonlocal` keywords and understand how they affect the visibility of names inside a function, when the names are outside the function. – D-Von Sep 13 '16 at 22:54
  • can you please update the answer with the corrected function. I am really confused right now – sshussain270 Sep 13 '16 at 22:59
  • I don't want to write for you the exact code that you need, because you won't learn anything that way. I want you to think about the problem. Please look up the uses of the `global` and `nonlocal` keywords, then explain what problem they solve and how that problem occurs in your function. I am happy to help you some more after that. – D-Von Sep 13 '16 at 23:16
1

If you want to save what you print, you could create a custom command, and save the output to a variable. For example

output_bin = ""

def printsave(string):
    print string
    if len(string) > 1:
        if string[-2] == "\n":
            output_bin = output_bin + string
        else:
            output_bin = output_bin + string + "\n"
    else:
        output_bin = output_bin + string + "\n

Then, whenever you call printsave() it is saved to the string output_bin. And if you want it to be saved to an array...

output_bin = []

def printsave(string):
    print string
    if len(string) > 1:
        if string[-2] == "\n":
            output_bin.append(string)
        else:
            output_bin.append(string + "\n")
    else:
        output_bin.append(string + "\n)
baranskistad
  • 2,176
  • 1
  • 21
  • 42