Get last result in interactive Python shell
Underscore.
>>> 5+5
10
>>> _
10
>>> _ + 5
15
>>> _
15
Why does _ not always give me the last result in interactive shell
The reason is pretty simple- try doing
[i for i in range(1000)]
and then accessing i- you'll see that i isn't defined (it's scope is within the list comprehension- when you exit the list comprehension, there "is no i").
This is in contrast to a for loop, where the scope of i is NOT within the actual for loop- so you can access it from outside.
So if we go to your case (with the _), if the _ is defined, like with a regular for loop, then you need to del
it. If you do it within a list comprehension, once the list comprehension is over, the underscore is no longer defined- which means it'll just be the last value
How to repeat last command in python interpreter shell?
I use the following to enable history on python shell.
This is my .pythonstartup file . PYTHONSTARTUP environment variable is set to this file path.
# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter
You will need to have the modules readline, rlcompleter to enable this.
Check out the info on this at : http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP.
Modules required:
- http://docs.python.org/library/readline.html
- http://docs.python.org/library/rlcompleter.html
How to get the python interactive shell output of a python code in a variable?
if you really must run strings as python code, you COULD spawn another python process with the subprocess.Popen
function, specify stdout, stderr, stdin
each to subprocess.PIPE
and use the .communicate()
function to retrieve the output.
python takes a -c argument to specify you're giving it python code as the next argument to execute/interpret.
IE python -c "print(5+5)"
will output 10
to stdout
IE
proc = subprocess.Popen(["python", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print(stdout.decode('utf-8'))
Is there any python equivalent of haskell's it , to get last successful command in REPL
_
will give you the result of the last line evaluated (that wasn't None
).
Python 3.7.1 (default, Nov 8 2018, 09:08:57)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+5
7
>>> _
7
How do I retrieve the output of a previous command and save it in a variable inside the Python interactive shell?
_
(single underscore) works for me in python 3 for windows, should work for other versions as well:
>>> 1 + 1
2
>>> x = _
>>> x
2
Get result of line above
This behavior of _
is only available in REPL. _
holds the output of that the last expression evaluated to. It should be noted, if the previous expression produced a TRACEBACK, _
will hold the last valid output. You could also chain _
upto three times (in IPython), to go fetch the 3rd last output:
>>> 5
5
>>> 6
6
>>> 7
7
>>> ___
5
>>> __
7
>>> _
7
If you use it in actual scripts, you can treat it _
as a variable name (not recommended, if you plan to use the variable), for example:
_ = 10
print(_)
# will print 10
But the behavior you get at REPL
can't be emulated in an actual script.
Related Topics
List Comprehension and Lambdas in Python
Pandas Sum by Groupby, But Exclude Certain Columns
How Does Keras Calculate the Accuracy
Delete File from Zipfile with the Zipfile Module
Pandas - Convert Strings to Time Without Date
Python - How to Check List Monotonicity
Operationalerror: Database Is Locked
Failed to Upload Packages to Pypi: 410 Gone
Datetime Timezone Conversion Using Pytz
Editing Workbooks with Rich Text in Openpyxl
How Does Python Importing Exactly Work
String Formatting: Columns in Line
How to Rotate Xticklabels in Matplotlib So That the Spacing Between Each Xticklabel Is Equal
Google Search from a Python App
How to Convert Column with List of Values into Rows in Pandas Dataframe