简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM