Reputation: 367
I'm used to typing !!
in bash when I want to reference the last command executed in that shell.
$ ls -la
drwxr-xr-x 4 me wheel 136 Jan 19 2013 wireshark_stuff
... (etc) ...
-rw-r--r-- 1 me wheel 11 Mar 13 13:51 old_PS1
$ !! |grep for_something_in_those_results
ls -la |grep for_something_in_those_results
/grep_results
Is there a way to do this in python?
>>> complicated_dict.['long_key_name'][0]
(response)
>>> my_func(!!)
This would get really handy as the interpreter commands become increasingly complicated. Sure, I could just use a plethora of local variables - but sometimes it's handy to just invoke the last thing run...
Upvotes: 3
Views: 166
Reputation: 21996
Up-arrow / return! As long as your interpreter was compiled with readline
support.
Upvotes: 0
Reputation: 531948
Using default Readline bindings, Control-P + Enter is probably the closest exact equivalent to !!
; the first key fetches the previous command; the second executes it. You can probably add a custom binding to .inputrc
to execute both functions with one keystroke. Note, though, this is entirely line-oriented; if you try to use this following a multi-line for
statement, for example, you'll only get the very last line of the body, not the entire for
statement.
The _
variable stores the result of the last evaluated expression; it doesn't reevaluate, though. This can be seen most clearly with something like datetime.datetime.now
:
>>> datetime.datetime.now()
datetime.datetime(2018, 3, 22, 14, 14, 50, 360944)
>>> datetime.datetime.now()
datetime.datetime(2018, 3, 22, 14, 14, 51, 665947)
>>> _
datetime.datetime(2018, 3, 22, 14, 14, 51, 665947)
>>> _
datetime.datetime(2018, 3, 22, 14, 14, 51, 665947)
>>> _
datetime.datetime(2018, 3, 22, 14, 14, 51, 665947)
>>> datetime.datetime.now()
datetime.datetime(2018, 3, 22, 14, 14, 58, 404816)
Upvotes: 1
Reputation: 51165
You can use the _
character to reference the last calculated value, and use it in other calculations:
>>> x = 5
>>> x + 10
15
>>> _
15
>>> _ + 2
17
Upvotes: 4
Reputation: 599856
The value of the last expression evaluated in the Python shell is available as _
, ie the single underscore.
Upvotes: 4