I use eval() and I need to print the output. For example, eval('1+1') will return 2 but eval('print('hello')') will return None. How can I store the output of Python Shell?
1 Answer
If you really want to redirect standard output to a variable, use StringIO for a variable or use a file
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
or
my_file = open('my_file.txt', 'w')
sys.stdout = my_file
print("hello") # now written to my_file.txt
4 Comments
Alex Hall
This is correct but is missing a lot. The duplicate I linked has more thorough answers.
Adam Katav
No module named 'StringIO' Any ideas?
Adam Katav
Is it possible to read sys.stdout? Because if so, my problem is solved.
C.B.
@adamkatav sorry updated for 3.x
eva()l? You are gettingNonebecauseprint()has no return value thus it evaluates toNone. What are you trying to do?eval(), you won't have this new problem to solve. Can you tell us the original problem you're trying to solve?