Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the output of a previous command and save it in a variable inside the Python interactive shell?

Say I ran an expensive operation foo() which returns me a large list, but I forgot to save the output of foo() inside a variable.

Let's assume if I run foo() again, I will get a different output.

But I really need the output from the first time I ran foo().

In effect, I am asking if there is some buffer that stores the output of the last command, which I could read?

like image 734
n00shie Avatar asked Mar 10 '14 20:03

n00shie


2 Answers

_ (single underscore) works for me in python 3 for windows, should work for other versions as well:

>>> 1 + 1
2
>>> x = _
>>> x
2
like image 101
khachik Avatar answered Oct 19 '22 23:10

khachik


The _ character (single underscore) is defined as the output of the last evaluation in all versions of Python, but only in the interactive shell. See: the docs

Example:

>>> def foo():
>>>     return 3
>>> foo()
3
>>> _ + 1
4

Based on your question, it sounds like you only care about how to do this in an interactive shell; for the interest of completeness the above functionality is not defined for the non-interactive shell.

like image 27
TheKevJames Avatar answered Oct 20 '22 01:10

TheKevJames