Python - Modify previous line in console [duplicate] - python

I would like to overwrite something on a line above in a serial console. Is there a character that allows me to move up?

Most terminals understand ANSI escape codes. The relevant codes for this use case:
"\033[F" – move cursor to the beginning of the previous line
"\033[A" – move cursor up one line
Example (Python):
print("\033[FMy text overwriting the previous line.")

No, not really easily, for that you'd have to use something like the curses library, especially if you want to have more control over cursor placement and do more things programatically.
Here's a link for the Python docs on Programming with Curses, and this short tutorial/example might be of interest too.
I just found this note in the docs in case you are using Windows:
No one has made a Windows port of the curses module. On a Windows
platform, try the Console module written by Fredrik Lundh. The Console
module provides cursor-addressable text output, plus full support for
mouse and keyboard input, and is available from
http://effbot.org/zone/console-index.htm.
I believe for C++ there is the NCurses library, the linked page has a section on moving the cursor if you want to poke around with C++. Also there's the NCurses Programming HowTo.
Long time ago I used the curses library with C quite successfully.
Update:
I missed the part about running this on a terminal/serially, for that the ANSI escape sequence, especially for a simple task like yours, will be easiest and I agree with #SvenMarnach solution for this.

for i in range(10):
print("Loading" + "." * i)
doSomeTimeConsumingProcessing()
sys.stdout.write("\033[F") # Cursor up one lin
Try this in Python and replace doSomeTimeConsumingProcessing() with any routine needed, and hope it helps

Carriage return can be used to go to the beginning of line, and ANSI code ESC A ("\033[A") can bring you up a line. This works on Linux. It can work on Windows by using the colorama package to enable ANSI codes:
import time
import sys
import colorama
colorama.init()
print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3 (no eol)", end="")
sys.stdout.flush()
time.sleep(1)
print("\rLine 3 the sequel")
time.sleep(1)
print("\033[ALine 3 the second sequel")
time.sleep(1)
print("\033[A\033[A\033[ALine 1 the sequel")
time.sleep(1)
print() # skip two lines so that lines 2 and 3 don't get overwritten by the next console prompt
print()
Output:
> python3 multiline.py
Line 1 the sequel
Line 2
Line 3 the second sequel
>
Under the hood, colorama presumably enables Console Virtual Terminal Sequences
using SetConsoleMode.

I may be wrong but :
#include <windows.h>
void gotoxy ( int column, int line )
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle( STD_OUTPUT_HANDLE ),
coord
);
}
in windows standard console.

A simple way based on #Sven Marnach answer:
print(f'\033[A\rxxx')
\033[A: Move cursor one line up.
\r: Move the cursor to the beginning of the line.
xxx: The string to be printed. {xxx} if it is a variable
If you have some extra characters from the previous line after your string, overwrite them with white space, depending on the length of the previous line. Below I added 10 white spaces.
print(f'\033[A\rxxx{' '* 10}')

Related

How to overwrite an input line [duplicate]

I would like to overwrite something on a line above in a serial console. Is there a character that allows me to move up?
Most terminals understand ANSI escape codes. The relevant codes for this use case:
"\033[F" – move cursor to the beginning of the previous line
"\033[A" – move cursor up one line
Example (Python):
print("\033[FMy text overwriting the previous line.")
No, not really easily, for that you'd have to use something like the curses library, especially if you want to have more control over cursor placement and do more things programatically.
Here's a link for the Python docs on Programming with Curses, and this short tutorial/example might be of interest too.
I just found this note in the docs in case you are using Windows:
No one has made a Windows port of the curses module. On a Windows
platform, try the Console module written by Fredrik Lundh. The Console
module provides cursor-addressable text output, plus full support for
mouse and keyboard input, and is available from
http://effbot.org/zone/console-index.htm.
I believe for C++ there is the NCurses library, the linked page has a section on moving the cursor if you want to poke around with C++. Also there's the NCurses Programming HowTo.
Long time ago I used the curses library with C quite successfully.
Update:
I missed the part about running this on a terminal/serially, for that the ANSI escape sequence, especially for a simple task like yours, will be easiest and I agree with #SvenMarnach solution for this.
for i in range(10):
print("Loading" + "." * i)
doSomeTimeConsumingProcessing()
sys.stdout.write("\033[F") # Cursor up one lin
Try this in Python and replace doSomeTimeConsumingProcessing() with any routine needed, and hope it helps
Carriage return can be used to go to the beginning of line, and ANSI code ESC A ("\033[A") can bring you up a line. This works on Linux. It can work on Windows by using the colorama package to enable ANSI codes:
import time
import sys
import colorama
colorama.init()
print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3 (no eol)", end="")
sys.stdout.flush()
time.sleep(1)
print("\rLine 3 the sequel")
time.sleep(1)
print("\033[ALine 3 the second sequel")
time.sleep(1)
print("\033[A\033[A\033[ALine 1 the sequel")
time.sleep(1)
print() # skip two lines so that lines 2 and 3 don't get overwritten by the next console prompt
print()
Output:
> python3 multiline.py
Line 1 the sequel
Line 2
Line 3 the second sequel
>
Under the hood, colorama presumably enables Console Virtual Terminal Sequences
using SetConsoleMode.
I may be wrong but :
#include <windows.h>
void gotoxy ( int column, int line )
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle( STD_OUTPUT_HANDLE ),
coord
);
}
in windows standard console.
A simple way based on #Sven Marnach answer:
print(f'\033[A\rxxx')
\033[A: Move cursor one line up.
\r: Move the cursor to the beginning of the line.
xxx: The string to be printed. {xxx} if it is a variable
If you have some extra characters from the previous line after your string, overwrite them with white space, depending on the length of the previous line. Below I added 10 white spaces.
print(f'\033[A\rxxx{' '* 10}')

how to change the position of the cursor in python 3

I am on windows 10 and I prefer not to install a new module (standard library solutions are accepted). I want the text that the user enters to start at the end of the third line.
My code:
print(" Enter password to unlock the Safe .\n\n password : \n\n\t2 attempts remaining .")
# code to move the cursor to the end of " password : " goes here
x = input()
output:
wanted output:
Also ANSI escape sequences don't seem to work without colorama(which unfortunately is an external module).
On Windows 10 you can use ANSI escape sequences as found in Console Virtual Terminal Sequences.
Before using them you need subprocess.run('', shell=True) (prior to Python 3.5, use subprocess.call). These sequences make possible what you are looking for.
Caution: Also original Microsoft, the documentation of Erase in Display and Erase in Line is partly faulty. The parameters 1 and 2 are reversed.
This should work (although, actually entering the password seems to destroy the layout):
import subprocess
subprocess.run('', shell=True)
print(' enter password : \0337', end='')
print('\n\n\t2 attempts remaining .\0338', end='')
x = input()
With Python 3 use;
print("...", end="")

Adding line breaks in ipython

If introduce a for loop in iPython, or any multi-line command, how do I go back and add lines to it? I ran this:
for row in table.find_all('tr'):
cells = row.find_all('td')
for c,cell in enumerate(cells):
print c,":",cell.get_text().strip()
try:
this = cells[0]
that = cells[1]
the_docket = cells[2]
other_thign = cells[3]
jumble = re.sub('\s+',' ',str(cells[5])).strip()
except:
"Nope"
And realized I need to add a line to it, but I can't just hit "enter" in iPython, b/c that runs the command. So can I edit that multi-line command w/in iPython?
Been suffering this problem for a while. I just found that when using Ctrl-qCtrl-j (That's lowercase Q, J, no need to hold the shift key) will add a linefeed to an existing IPython edit session.
for li in some_list: print(li)
Moving the cursor after the colon and pressing Ctrl-qCtrl-j
for li in some_list:
print(li)
IPython: 5.2.1, iTerm2: 3.0.15, macOS: 10.12.6
The %edit magic function in iPython lets you edit code in your favorite editor and will then execute it as if it was typed directly. You can also edit code you've already typed into the repl since it's stored in a special variable, for example:
In [1]: def foo(x):
...: print x
...:
In [2]: %edit _i1
There is also a way to add a newline directly in the repl: ctrl-v, ctrl-j
The ctrl-v basically lets you send a control code and then the ctrl-j is the code for a newline (line-feed). It's a bit awkward to type but has the advantage of also working in the regular Python shell as well as in Bash itself.
Edit: At least in iTerm2, you can assign it to a single hotkey as well. I set ctrl-enter to "Send hex codes" of 0x16 0x0a. Could also use cmd-enter or whatever else.
You can use ctrl+on (i.e. press the control button and enter the characters 'o', 'n' while holding it). You can also do it in two steps - ctrl+o ctrl+n but I find the former easier.
ctrl-o - enter the multiline mode
ctrl-n - access command history going forward.
But since there is no forward history, cursor just moves to the next line.
I verified that it works with both IPython 5.3.0 and IPython 7.3.0 on a machine running git bash 2.18.0 + windows 7.
A easy way of doing it is using the ;\ operator. ; to signal that its the end of a command and \ to indicate the the command follows in a new line as follows:
In[4]: password = "123";\
username = "alpha"
This will let you have multiple line commands in ipython without invoking the editor
For completeness: newer IPython versions (0.11+) have a very nice graphical console which allows you to navigate your code with the arrows and even reposition the cursor with the mouse.
In multi-line statements, some keys take on a special function (arrows to navigate, Enter to insert a line break and others). You'll have to position the cursor at the end of the last line of the statement in order to get default behaviour, e.g. get the Up arrow ↑ to mean "previous statement" instead of "move the cursor to the previous line". Or get Enter to mean "execute code" instead of "insert line break in the middle of code".
The documentation on it is a bit sparse and fragmented in different pages, so here are the essential three links for getting started with it:
Intro to the Qt Console
Configuring IPython using nice per-user profile files instead of command line arguments
You are interested in the ipython_qtconsole_config.py
How to get an ipython graphical console on Windows 7?
Type Ctrl+q then Enter. As other pointed out, Ctrl+q lets you send a character code, but hitting Ctrl+q then Enter may be more natural than Ctrl+q then Ctrl+j.
Another option is to type ( then Enter, write, and delete the ( afterwards. This solution is similar to the one where you to type ;\ to say the statement is not completed.
Bit late to the party! But I noticed many people are talking about using Ctrl combinations to add extra lines. This didn't work for me until I saw a comment about it being the Emacs binding. I have set my in line editor to be Vi, if you have too then pressing Esc to go into "Normal" mode on the line before you want to add an extra line then press o (or O if you are after the line). Just like in normal Vi(m). Works for me!

Is there go up line character? (Opposite of \n)

I would like to overwrite something on a line above in a serial console. Is there a character that allows me to move up?
Most terminals understand ANSI escape codes. The relevant codes for this use case:
"\033[F" – move cursor to the beginning of the previous line
"\033[A" – move cursor up one line
Example (Python):
print("\033[FMy text overwriting the previous line.")
No, not really easily, for that you'd have to use something like the curses library, especially if you want to have more control over cursor placement and do more things programatically.
Here's a link for the Python docs on Programming with Curses, and this short tutorial/example might be of interest too.
I just found this note in the docs in case you are using Windows:
No one has made a Windows port of the curses module. On a Windows
platform, try the Console module written by Fredrik Lundh. The Console
module provides cursor-addressable text output, plus full support for
mouse and keyboard input, and is available from
http://effbot.org/zone/console-index.htm.
I believe for C++ there is the NCurses library, the linked page has a section on moving the cursor if you want to poke around with C++. Also there's the NCurses Programming HowTo.
Long time ago I used the curses library with C quite successfully.
Update:
I missed the part about running this on a terminal/serially, for that the ANSI escape sequence, especially for a simple task like yours, will be easiest and I agree with #SvenMarnach solution for this.
for i in range(10):
print("Loading" + "." * i)
doSomeTimeConsumingProcessing()
sys.stdout.write("\033[F") # Cursor up one lin
Try this in Python and replace doSomeTimeConsumingProcessing() with any routine needed, and hope it helps
Carriage return can be used to go to the beginning of line, and ANSI code ESC A ("\033[A") can bring you up a line. This works on Linux. It can work on Windows by using the colorama package to enable ANSI codes:
import time
import sys
import colorama
colorama.init()
print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3 (no eol)", end="")
sys.stdout.flush()
time.sleep(1)
print("\rLine 3 the sequel")
time.sleep(1)
print("\033[ALine 3 the second sequel")
time.sleep(1)
print("\033[A\033[A\033[ALine 1 the sequel")
time.sleep(1)
print() # skip two lines so that lines 2 and 3 don't get overwritten by the next console prompt
print()
Output:
> python3 multiline.py
Line 1 the sequel
Line 2
Line 3 the second sequel
>
Under the hood, colorama presumably enables Console Virtual Terminal Sequences
using SetConsoleMode.
I may be wrong but :
#include <windows.h>
void gotoxy ( int column, int line )
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle( STD_OUTPUT_HANDLE ),
coord
);
}
in windows standard console.
A simple way based on #Sven Marnach answer:
print(f'\033[A\rxxx')
\033[A: Move cursor one line up.
\r: Move the cursor to the beginning of the line.
xxx: The string to be printed. {xxx} if it is a variable
If you have some extra characters from the previous line after your string, overwrite them with white space, depending on the length of the previous line. Below I added 10 white spaces.
print(f'\033[A\rxxx{' '* 10}')

Indentation in a Python GUI

As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected...
It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or something?
For example:
def somefunction:
x =5
return x
If I want to add a control block
For example:
def somefunction:
if True:
x =5
return x
return 0
this small change of adding a control block took a lot of tab work...
Is there a shortcut or something to do this easily?
I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.
This is true for Visual Studio, Notepad2, e, Textmate, Slickedit, #Develop, etc. etc. etc.
If you're not doing large multi-file projects, I strongly recommend Notepad2. Its a very lightweight, free, easy-to-use notepad replacement with just enough code-centric features (line numbers, indentation guides, code highlighting, etc.)
In the Idle editor, you can just select the lines you want to indent and hit Tab.
I should note that this doesn't actually insert any tabs into your source, just spaces.
In IDLE I just use ctrl+] and ctrl+[ on a block of code.
With emacs there's Python mode. In that mode you highlight and do:
ctrl-c >
ctrl-c <
Use VI and never program the same again. :^)
[Funny ;-)] Dude, I told you that you would need one developer less if you had this new keyboard model
Pythonic keyboard http://img22.imageshack.us/img22/7318/pythonkeyboard.jpg
If you are using vim there is a plugin specifically for this: Python_fn.vim
It provides useful python functions (and menu equivalents):
]t -- Jump to beginning of block
]e -- Jump to end of block
]v -- Select (Visual Line Mode) block
]< -- Shift block to left
]> -- Shift block to right
]# -- Comment selection
]u -- Uncomment selection
]c -- Select current/previous class
]d -- Select current/previous function
]<up> -- Jump to previous line with the same/lower indentation
]<down> -- Jump to next line with the same/lower indentation
Vim: switch to visual mode, select the block, use > to indent (or < to unindent).
See also: Indent multiple lines quickly in vi
In TextMate, just highlight the lines you want to indent and use:
⌘ + [
or
⌘ + ]
To move the text in the appropriate direction.
PyDev, which you can find at http://pydev.sourceforge.net/ has a "Code Formatter". It also has autoindent feature. It is a plugin for Eclipse which is freely available for Mac too.
Another option would be http://code.google.com/p/macvim/ if you are familiar or invest time for Vim, which has lots of autoindent features not just for Python.
But, do not forget that, in Python, indentation changes the meaning of the program unlike C family languages. For example for C or C#, a utility program can beautify the code according to the "{" and "}" symbols. But, in Python that would be ambiguous since a program can not format the following:
#Say we wrote the following and expect it to be formatted.
a = 1
for i in range(5):
print i
a = a + i
print a
Do you expect it to be
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 5
or
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 11
which are two different snippets.
In Komodo the Tab and Shift Tab both work as expected to indent and unindent large blocks of code.
In vim, you can enter:
>>
to indent a line. If you enter:
5>>
you indent the 5 lines at and below the cursor. 5<< does the reverse.

Categories

Resources