将 Python 输出存储在字符串中

Storing Python output in a string

我使用 eval() 并且我需要打印输出。例如,eval('1+1') 将 return 2 但 eval('print('hello')') 将 return None。如何存储 Python Shell 的输出?

如果你真的想将标准输出重定向到一个变量,对变量使用 StringIO 或使用文件

from io import StringIO
# from StringIO import StringIO -- python 2.x
import sys
my_out = StringIO()
sys.stdout = my_out
print("hello") # now stored in my_out

my_file = open('my_file.txt', 'w')
sys.stdout = my_file
print("hello") # now written to my_file.txt