Skip to content Skip to sidebar Skip to footer

Python: Assign Print Output To A Variable

I would like to know how to assign the output of the print function (or any function) to a variable. To give an example: import eyeD3 tag = eyeD3.Tag() tag.link('/some/file.mp3') p

Solution 1:

The print statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:

a = str(tag.getArtist())

Solution 2:

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io importStringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your functioncontainingthepreviouslinesmy_function()

sys.stdout = old_stdout

Solution 3:

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

Solution 4:

somevar = tag.getArtist()

http://docs.python.org/tutorial/index.html

Solution 5:

This is a standalone example showing how to save the output of a user-written function in Python 3:

from io import StringIO
import sys

defprint_audio_tagging_result(value):
    print(f"value = {value}")

tag_list = []
for i inrange(0,1):
    save_stdout = sys.stdout
    result = StringIO()
    sys.stdout = result
    print_audio_tagging_result(i)
    sys.stdout = save_stdout
    tag_list.append(result.getvalue())
print(tag_list)

Output

['value = 0\n']

Post a Comment for "Python: Assign Print Output To A Variable"