how to change the position of the cursor in python 3 - python

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="")

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}')

Python - Modify previous line in console [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 not issue a new line in Python 3 when entering text with input()

I'm making a basic utility in Python 3 where the user inputs a command and gets feedback printed out into the console. When entering data using the input() or sys.stdin.readline() functions this is what the command-line session may look like (including \r and \n characters)
1. What is your name:\n
2. <user input>\n
3. Your name is <variable>.\n
But, I would like to display a \r character after the user hits enter instead of the \n character, as shown on line 2. After the user had typed everything in and hit enter it would look like this
1. What is your name:\n
2. Your name is <variable>.\n
(because line 2 would have a \r character after the entered data, returning the cursur back to the far left)
Does anybody know of a way I might accomplish this?
Well, I discovered this method although I am almost cirtain that the msvcrt module is for Windows only.
import msvcrt
import sys
def msgInput(prompt):
print(prompt, end='')
data= b''
while True:
char= msvcrt.getch()
if char != b'\r':
print(char.decode(), end='')
sys.stdout.flush()
data= data+char
else:
print('\r', end='')
break
return data.decode()
If anybody knows of any cross-platform methods, please share.
Update - Unfortunately this method has many limitations, such as the user cannot navigate the entered text with the arrow keys.
Well, I believe I found the solution you wanted:
strng=input("Enter String - ")
Where strng is just a variable to hold the input response. This will return the string in the interpreter Enter String - (without any quote) and allow you to save the response in the variable strng.

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}')

Prevent python from printing newline

I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
You are correct - a newline is included in inputted. To remove it, you can just call strip("\r\n") to remove the newline from the end:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
This won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.
If you don't want any newlines in the text at all, you can use inputted.replace("\r\n", "") to remove all newlines.
Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.
I investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!
So I wrote this little script to see what actually happens:
import sys
from io import StringIO
for stdin in [sys.stdin, StringIO("test\r\ntest\r\n")]:
sys.stdin = stdin
print("readline returns this: " + repr(sys.stdin.readline()))
inputted = input("Enter in something: ")
print("inputted: " + repr(inputted))
print("inputted is printed like this: --> {0} <--".format(inputted))
It first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\r\ntest\r\n.
Try and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF ("\r\n"). Printing "\r" in the Eclipse console will jump to the next line.
On the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO("test\r\n"), the input() result is "test\r" as in Eclipse (although not printed as newline).
Hope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.
If you only want to stript the last line endings, you could use rstrip.
inputted.rstrip ("\r\n")
inputted = inputted.strip()
Edit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:
import re
inputted = re.sub("[\n\r]+$", "", inputted)

Categories

Resources