[python] 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")
print tag.getArtist()

How do I assign the output of print tag.getArtist to a variable?

This question is related to python function unix variables

The answer is


probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using


somevar = tag.getArtist()

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


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

def print_audio_tagging_result(value):
    print(f"value = {value}")

tag_list = []
for i in range(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)

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

do the following :

from io import StringIO
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 function containing the previous lines
my_function()

sys.stdout = old_stdout

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())

Please note, I wrote this answer based on Python 3.x. No worries you can assign print() statement to the variable like this.

>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>

According to the documentation,

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). So print() also a function with the return value with None. So the return value of python function is None. But you can call the function(with parenthesis ()) and save the return value in this way.

>>> var = some_function()

So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

So we get a string object, then you can modify the below code line as follows,

>>> var = str(some_function())

or you can use str.join() if you really have a string object.

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

change can be as follows,

>>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?