Wil*_*son 22 python unix variables function
我想知道如何将print
函数(或任何函数)的输出分配给变量.举个例子:
import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
Run Code Online (Sandbox Code Playgroud)
如何将输出分配给print tag.getArtist
变量?
Sve*_*ach 24
print
Python中的语句将其参数转换为字符串,并将这些字符串输出到stdout.要将字符串保存到变量,只需将其转换为字符串:
a = str(tag.getArtist())
Run Code Online (Sandbox Code Playgroud)
Arc*_*yno 20
更笼统地回答这个问题 how to redirect standard output to a variable ?
请执行下列操作 :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
Run Code Online (Sandbox Code Playgroud)
如果您只需要在某些功能中执行此操作,请执行以下操作:
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
Run Code Online (Sandbox Code Playgroud)
slu*_*uki 12
您可以使用参数file
来重定向print
函数的输出
from io import StringIO
s = StringIO()
print(42, file=s)
result = s.getvalue()
Run Code Online (Sandbox Code Playgroud)
或许你需要的一个 str
,repr
或unicode
功能
somevar = str(tag.getArtist())
Run Code Online (Sandbox Code Playgroud)
取决于你使用的是哪个python shell
somevar = tag.getArtist()
Run Code Online (Sandbox Code Playgroud)
http://docs.python.org/tutorial/index.html