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?
Asked
Active
Viewed 515 times
-2

kylieCatt
- 10,672
- 5
- 43
- 51

Adam Katav
- 328
- 3
- 13
-
6Why 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? – kylieCatt May 24 '16 at 20:25
-
@TessellatingHeckler eval and external commands aren't related. – Alex Hall May 24 '16 at 20:29
-
2This is a classic [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-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? – TigerhawkT3 May 24 '16 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. – Adam Katav May 24 '16 at 21:01
1 Answers
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

C.B.
- 8,096
- 5
- 20
- 34
-
This is correct but is missing a lot. The duplicate I linked has more thorough answers. – Alex Hall May 24 '16 at 20:32
-
-
Is it possible to read sys.stdout? Because if so, my problem is solved. – Adam Katav May 24 '16 at 21:38
-