-2

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?

4
  • 6
    Why are you using eva()l? You are getting None because print() has no return value thus it evaluates to None. What are you trying to do? Commented May 24, 2016 at 20:25
  • @TessellatingHeckler eval and external commands aren't related. Commented May 24, 2016 at 20:29
  • 2
    This is a classic XY Problem. If you figure out a proper solution to the problem you're facing rather than using eval(), you won't have this new problem to solve. Can you tell us the original problem you're trying to solve? Commented May 24, 2016 at 20:39
  • I want to create a telegram bot that acts like a python shell. I know that print() doesn't return anything so that is why I asked how can I store all python shell output as if I wrote print() in terminal. Commented May 24, 2016 at 21:01

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

4 Comments

This is correct but is missing a lot. The duplicate I linked has more thorough answers.
No module named 'StringIO' Any ideas?
Is it possible to read sys.stdout? Because if so, my problem is solved.
@adamkatav sorry updated for 3.x

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.