Possible to get user input without inserting a new line?
You can use getpass
instead of raw_input
if you don't want it to make a new line!
import sys, getpass
def raw_input2(value="",end=""):
sys.stdout.write(value)
data = getpass.getpass("")
sys.stdout.write(data)
sys.stdout.write(end)
return data
But how do I stop raw_input from writing a newline?
In short: You can't.
raw_input()
will always echo the text entered by the user, including the trailing newline. That means whatever the user is typing will be printed to standard output.
If you want to prevent this, you will have to use a terminal control library such as the curses
module. This is not portable, though -- for example, curses
in not available on Windows systems.
I see that nobody has given a working solution, so I decided I might give it a go.
As Ferdinand Beyer said, it is impossible to get raw_input()
to not print a new line after the user input. However, it is possible to get back to the line you were before.
I made it into an one-liner. You may use:
print '\033[{}C\033[1A'.format(len(x) + y),
where x
is an integer of the length of the given user input and y
an integer of the length of raw_input()
's string. Though it might not work on all terminals (as I read when I learned about this method), it works fine on mine. I'm using Kubuntu 14.04.
The string '\033[4C'
is used to jump 4 indexes to the right, so it would be equivalent to ' ' * 4
. In the same way, the string '\033[1A'
is used to jump 1 line up. By using the letters A
, B
, C
or D
on the last index of the string, you can go up, down, right and left respectively.
Note that going a line up will delete the existing printed character on that spot, if there is one.
This circumvents it, somewhat, but doesn't assign anything to variable name
:
print("Hello, {0}, how do you do?".format(raw_input("Enter name here: ")))
It will prompt the user for a name before printing the entire message though.