How to repeat last command in python interpreter shell?
Asked Answered
S

26

155

How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters.

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 
Slosh answered 27/11, 2010 at 3:9 Comment(6)
Up arrow works correctly for me (Ubuntu), it's weird.Lombard
Ditto, up arrow works for me on Windows. What shell are you using, and what terminal program on what OS?Candlelight
I installed a separate python 2.6.6 installation on Fedora 13, run virtualenv, using the default python shell, on gnome-terminalSlosh
You should install ipython. It's a much better interpreter than the default.Kreisler
just a FYI, those "nonsensical" characters are "escape sequences" developed by DEC and others back in the days when mainframe computers were accessed by terminals over phone lines. ^[ is ESC (escape), ^[[ is escape-[ or CSI (control sequence initiator, IIRC) and CSI-A is the sequence for "up". and when you enable ncurses, using the answer below, those sequences are interpreted rather than displayed.Addia
I had this problem due to installing a version of Python from source (Python3.4). Some of the comments below recommend installing Ipython and I want to mention that I have the same behavior even with Ipython. For Ubuntu 12.04 server, I had to install libncurses-dev libreadline-dev and then configure-make-install Python and it worked after that. Added as an answer...Harvin
I
66

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:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html
Implausibility answered 27/11, 2010 at 3:13 Comment(5)
@user496852: Just set the env variable PYTHONSTARTUP to the filepath containing above code. Also check, if you have the required modules.Implausibility
it is not necessary, just follow instruction of basak's answer and assign key bindingsWist
An overkill. Just do alt+pCarnauba
As a Windows user, I had to first install pyreadline, and change the histfile definition by using histfile = pathlib.Path.home().joinpath('.pythonhistory').Sicanian
This worked, but now my python shell is broken: I get some IOT error if I try to import anything, and the shell crashes. >>> import pandas \ double free or corruption (out) \ [1] 63827 IOT instruction pythonWasteful
A
187

In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys.

Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.

Airwaves answered 25/9, 2012 at 19:41 Comment(10)
For searchers, this works in Linux Mint 17 Cinnamon too.Bosco
works for windows 10, python 3.6.1 as well. Thanks a lot, this is clean and clear, esp. useful for new learners.Elswick
Most appropriate answer. Should have been chosen as the correct one.Wistrup
there is no Options -> Configure IDLE for Python 2.7 :/Mural
I needed to go to settings/preferences (python 2.7, IDLE for mac) and there I found the history-next, thanks so much you are the best :)Mural
does not work, the old shortcut persists even after resetting.Outbid
To get to IDLE, run idle3 in shellPacificism
This didn't work for me: UnicodeEncodeError: 'ascii' codec can't encode character u'\uf700' in position 0: ordinal not in range(128) UnicodeEncodeError: 'ascii' codec can't encode character u'\uf701' in position 0: ordinal not in range(128)Rubierubiginous
what's IDLE? How do do this in pycharm console?Criminality
How to put it to "bottom arrow" as in a bash shell ?Hypnotism
I
66

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:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html
Implausibility answered 27/11, 2010 at 3:13 Comment(5)
@user496852: Just set the env variable PYTHONSTARTUP to the filepath containing above code. Also check, if you have the required modules.Implausibility
it is not necessary, just follow instruction of basak's answer and assign key bindingsWist
An overkill. Just do alt+pCarnauba
As a Windows user, I had to first install pyreadline, and change the histfile definition by using histfile = pathlib.Path.home().joinpath('.pythonhistory').Sicanian
This worked, but now my python shell is broken: I get some IOT error if I try to import anything, and the shell crashes. >>> import pandas \ double free or corruption (out) \ [1] 63827 IOT instruction pythonWasteful
L
52

Alt + p for previous command from histroy, Alt + n for next command from history.

This is default configure, and you can change these key shortcut at your preference from Options -> Configure IDLE.

Ligulate answered 23/7, 2013 at 1:24 Comment(3)
it's called history-next / history-previousMural
How does one change these bindings? I'm just using python in bash, not IDLE. Alt+p,n works. I'd like them to be mapped to up/down arrows. This works fine in bash.Numbers
What about for macOS? I'm using macOS, and I don't have an Alt key.Galvani
R
22

You didn't specify which environment. Assuming you are using IDLE.

From IDLE documentation: Command history:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.
Rebbeccarebe answered 9/7, 2013 at 15:51 Comment(2)
For further information: docs.python.org/2/library/idle.html#python-shell-windowHanako
This is the solution I am looking for in IDLE. Up arrow worked on python interpreter launched from bash shell.Kyliekylila
H
8

On Ubuntu Server 12.04, I had this problem after installing a version of Python from source (Python3.4).

Some of the comments here recommend installing Ipython and I want to mention that I have the same behavior even with Ipython. From what I can tell, this is a readline problem.

For Ubuntu 12.04 server, I had to install libncurses-dev and libreadline-dev and then install Python from source for up-history (readline) behavior to be enabled. I pretty much did this:

sudo apt-get install libncurses-dev libreadline-dev

After that, I deleted the previously installed Python (NOT THE SYSTEM PYTHON, the one I had installed from source!) and reinstalled it from source and everything worked as expected.

I did not have to install anything with pip or edit .pythonstartup.

Harvin answered 19/9, 2014 at 21:39 Comment(3)
For anyone who encounters this problem, I am on 14.04 and was still able to use this solution to fix this problem going from 3.4.0 to 3.4.2.Peachey
I needed to do sudo pip install readline after this to get it to work (python 2.7.11)Gallery
This worked for me on 64-bit Ubuntu 16 as well. I have 32-bit Python 3.5.2, compiled and installed from sources, in addition to the already apt-installed 64-bit Pythons. Just did sudo apt-get install libncurses-dev libncurses-dev:i386 libreadline-dev libreadline-dev:i386 and reinstalled the source-built Python.Lianeliang
U
7

Ctrl+p is the normal alternative to the up arrow. Make sure you have gnu readline enabled in your Python build.

Underpass answered 27/11, 2010 at 3:26 Comment(1)
this asks if I want to printCheesecake
M
7

ALT + p works for me on Enthought Python in Windows.

Misshape answered 3/10, 2012 at 3:28 Comment(0)
M
7

By default use ALT+p for previous command, you can change to Up-Arrow instead in IDLE GUi >> OPtions >> Configure IDLE >>Key >>Custom Key Binding It is not necesary to run a custom script, besides readlines module doesnt run in Windows. Hope That Help. :)

Mizzenmast answered 4/9, 2016 at 20:54 Comment(0)
H
4

On CentOS, I fix this by

yum install readline-devel

and then recompile python 3.4.

On OpenSUSE, I fix this by

pip3 install readline

Referring to this answer:https://mcmap.net/q/116730/-seeing-escape-characters-when-pressing-the-arrow-keys-in-python-shell. Perhaps "pip3 install readline" is a general solution. Haven't tried on my CentOS.

Hf answered 24/1, 2015 at 22:48 Comment(0)
A
4

I find information that I copied below answer the question

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press "enter", that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the "Options" menu, select "Configure IDLE", and then "Keys". Changing the key that is associated with the "previous command" and "next command" actions to be the up arrow, and down arrow, respectively.

source

Anemia answered 31/3, 2017 at 12:14 Comment(0)
E
3

In my mac os python3 you can use: control+p early command contrlo+n next command

Entablement answered 21/11, 2016 at 13:15 Comment(0)
E
2
alt+p  
go into options tab
configure idle
Keys

look under history-previous for the command, you can change it to something you like better once here.

Erma answered 12/11, 2012 at 1:21 Comment(0)
W
2

This can happen when you run python script.py vs just python to enter the interactive shell, among other reasons for readline being disabled.

Try:

import readline
Weft answered 3/4, 2013 at 18:53 Comment(0)
P
2

I don't understand why there are so many long explanations about this. All you have to do is install the pyreadline package with:

pip install pyreadline

sudo  port install py-readline (on Mac)

(Assuming you have already installed PIP.)

Pesticide answered 21/12, 2013 at 11:34 Comment(8)
'pip install readline' worked for me. All my control sequences were coming out with bracket prefixes on Centos 7 after python 3.4 manual installTamarisk
"Could not find a version that satisfies the requirement py-readline (from versions: ) No matching distribution found for py-readline" I hate this worldMural
Make sure you use pip2 or pip3, depending on what version you have installed.Pesticide
This breaks python for version 3.8. Do not install!Hermetic
@WolfgangKuehn Have any bug issue been filed about this to their repo? (if not, please file it.) Sound pretty serious.Pesticide
@Pesticide I have not. This issue was on a compiled Python 3.8.6 on a current Amazon Linux 2. I still don't know why readline is not working (lib missing, compile switch, etc.), haven't got the time.Hermetic
Indeed, on Windows, with Python 3.9, "pip install pyreadline" was all it took to make up-arrow fetch the previous comment, which wasn't happening previously. Thanks.Piroshki
pyreadline is dead meat. Use pyreadline3 which now works with Py3.10.Pesticide
C
2

You don't need a custom script like pyfunc's answer for OSX (at least on mavericks). In Idle click on Idle -> Preferences -> Keys, locate "history-next" and "history-previous", and either leave them with their default keyboard shortcut or assign "up arrow" and "down arrow" per typical expected terminal behavior.

This is on Idle 2.7 on OSX Mavericks.

Comportment answered 1/10, 2014 at 9:29 Comment(0)
S
2

If you use Debian Jessie run this to fix your system installation 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

To fix my other 3.5.2 installation which I installed with pyenv :

pip install readline

Sources:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://mcmap.net/q/116730/-seeing-escape-characters-when-pressing-the-arrow-keys-in-python-shell

Spumescent answered 26/11, 2016 at 20:14 Comment(2)
Installing libncurses5-dev and libncursesw5-dev was sufficient to fix my Python 3.5 installation, but Python 3.6 broke up after I installed readline module for it. Probably need to recompile.Pianism
It helped me Ubuntu 18.04 python version 3.7.3 pip install readlineCarree
L
2

Using arrow keys to go to the start of the command and hitting enter copies it as the current command.

Then just hit enter to run it again.

Lessielessing answered 24/7, 2018 at 14:59 Comment(0)
C
2

For repeating the last command in python, you can use <Alt + n> in windows

Coacervate answered 6/5, 2020 at 7:36 Comment(2)
If arrow-up doesn't work, you need to fix your installation. Probably need pyreadline.Pesticide
Use pyreadline3 which now works with Py3.10.Pesticide
I
1

Ipython isn't allways the way... I like it pretty much, but if you try run Django shell with ipython. Something like>>>

ipython manage.py shell

it does'n work correctly if you use virtualenv. Django needs some special includes which aren't there if you start ipython, because it starts default system python, but not that virtual.

Intension answered 10/7, 2011 at 12:36 Comment(0)
A
1

Up Arrow works only in Python command line.

In IDLE (Python GUI) the defaults are: Alt-p : retrieves previous command matching what you have typed. Alt-n : retrieves next... In Python 2.7.9 for example, you can see/change the Action Keys selecting: Options -> Configure IDLE -> (Tab) Keys

Alkalize answered 11/5, 2015 at 17:23 Comment(0)
F
1

For anaconda for python 3.5, I needed to install ncurses

conda install ncurses

After the ncurses install tab complete, history, and navigating via left and right arrows worked in the interactive shell.

Foltz answered 23/8, 2016 at 7:47 Comment(0)
U
1

On Mac with Python 2.x

➜ ~ brew install rlwrap

Start with rlwrap

➜ ~ rlwrap python

Urology answered 20/7, 2017 at 0:58 Comment(0)
A
0

Up arrow works for me too. And i don't think you need to install the Readline module for python builtin commandline. U should try Ipython to check. Or maybe it's the problem of your keybord map.

Ammonia answered 27/11, 2010 at 3:14 Comment(0)
L
0

If using MacOSX, press control p to cycle up and control n to cycle down. I am using IDLE Python 3.4.1 Shell.

Lucaslucca answered 11/8, 2014 at 4:23 Comment(0)
C
0

it is control + p in Mac os in python 3.4 IDEL

Conjurer answered 30/7, 2015 at 18:21 Comment(0)
C
0

On Ubuntu 16.04, I had the same problem after upgrading Python from the preloaded 3.5 to version 3.7 from source code. As @erewok suggested, I did

sudo apt-get install libncurses-dev libreadline-dev

followed by: sudo make install After that, the arrow-up key worked. Not sure which module is required to fix the problem or both, but without "make install", none would work. During initial make, there were some red-flag errors, but ignored and completed the build. This time, there didn't seem to have any errors.

Cia answered 25/8, 2018 at 2:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.