Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python command line: editing mistake on previous line?

When using python via the command line, if I see a mistake on a previous line of a nested statement is there any way to remove or edit that line once it has already been entered?

e.g.:

>>> file = open("file1", "w")
>>> for line in file:
...     parts = line.split('|')   <-- example, I meant to type '\' instead
...     print parts[0:1]
...     print ";"
...     print parts[1:]

so rather than retyping the entire thing all over to fix one char, can I go back and edit something in hindsight? I know I could just code it up in vim or something and have a persistent copy I can do anything I want with, but I was hoping for a handy-dandy trick with the command line.

-- thanks!

like image 741
ash Avatar asked Aug 05 '11 16:08

ash


People also ask

How do you recall a line in Python?

Recalling Python code Lines of code executed in previous lines can be recalled using the up and down arrow keys. This recall inserts the specified line at the current command prompt location. The line of code can be edited and executed or run as-is a second time.

How do I go back to the previous line in terminal?

You can try to use '\033[1A' to go back one line (substitute 1 with number of lines to jump. It will probably break in some terminals.


2 Answers

You can't do such a thing in the original python interpreter, however, if you use the last version of IPython, it provides a lightweight GUI (looks like a simple shell, but is a GUI in fact) which features multi-line editing, syntax highlighting and a bunch of other things. To use IPython GUI, run it with the ipython qtconsole command.

like image 155
mdeous Avatar answered Sep 22 '22 05:09

mdeous


Maybe. The Python Tutorial says:

Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.

like image 21
ben Avatar answered Sep 19 '22 05:09

ben