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

StackOverflow https://stackoverflow.com/questions/22310778

  •  12-06-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

>>> 1 + 1
2
>>> x = _
>>> x
2

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top