I'm looking for a good way to hide input entered for a chat-like system on WIndows
For now, i wrote this
import sys
name = input("Enter your message: ")
sys.stdout.write('\r')
print(message)
But it doesn't do anything.
I'd like to do something like this
Enter your message: Hello
Output:
Hello
That is way better then
Enter your message: Hello
Output:
Enter your message: Hello
Hello
So the final output, after some messages will be
Hello
How are you?
I'm fine thanks.
And not
Enter your message: Hello
Hello
Enter your message: How are you?
How are you?
Enter your message: I'm fine thanks.
I'm fine thanks.
I've seen some questions like mine before asking but i didn't find anything working, i also can't use os because it has to contain more inputs, i also tried using \r but (as i used it) doesn't do what i want it to do, thanks in advance.
Here is how you can do so if you are using command prompt to run your code;
from os import system
name = input('Enter your name: ')
system('cls')
print(f'Your name is {name}')
system('cls') clears the console after the input has been submitted as it is run immediately after the input is provided.
If you are using mac;
system('clear')
If you want to just hide the user input you could use the builtin getpass module. This is designed for passwords so it will not display what the user types on the terminal.
>>> import getpass
>>> name = getpass.getpass(prompt="name: ")
name:
>>> print(name)
Chris
Use this code:
import os
l = []
def main():
empty = ""
while True:
message = input("Enter message: ")
os.system("cls")
if message == empty or message.isspace() == True:
break
l.append(message)
print("Output:")
for i in l:
print(i)
main()
This is now a year old, but I faced the same issue and I think what you'd be looking for is using ANSI escape codes.
Specifically, I used '\033[1A' and '\033[K', I don't have as much experience on them but as far as I can tell they're really good for specific manipulations like this.
'[1A' would be used to go on the line above and '[K' to erase everything on the line. So if you were to print out your "Enter your message: " from your input function, save your text in a variable, use the escape codes and then print your text, I believe you'd get the desired result.
Here I made an infinite texting loop where you can get what I believe is what you're looking for:
while True:
text = input("Enter your message: ")
print('\033[1A' + '\033[K', end='')
print(text)
From here on you can do all kinds of manipulation/validation of your text and such, for example a specific condition for breaking the loop.
While I was looking for an answer I found this question and bashBedlam's answer is particularly useful. They mention ANSI escape codes will not work the same on all terminals though, so it might be worth looking into if this is the solution you want.
Hope this helps!
Related
I recently read about how to type one letter at a time in Python to look old school and cool using loops and time - however, my code has an input. Does anyone know how to do this for and input (in my code , "what is your name?")
I've tried changing the input name but has failed. The code simply prints it at once like usual
If you are looking to do something that looks like this:
Then the easiest way is to do it as it was done back in the good old days. What happened then was that the program would send special codes to the terminal (which back then was a real physical device, not just a window), and the terminal would do whatever codes wanted. There were codes for moving the cursor around, changing colors, beeping and lots of other nifty stuff that you would need.
A common set of codes that still are in use today are known as the ANSI escape codes.
There is an excellent package called Colorama for Python that does all of the heavy-lifting and that is cross-platform. I recommend using that.
Source code for the demo above:
from colorama import init, Fore, Style
import time
def print_old(message):
print(Fore.GREEN, end='', flush=True)
for c in message:
print(c, end='', flush=True)
time.sleep(0.1)
print(Style.RESET_ALL, end='', flush=True)
init()
print_old('What is your name? ')
name = input()
print_old('Nice to meet you %s\n' % name)
Hopefully this is what you are looking for.
This makes it look like what you're talking about
import time
output = "what is your name?"
blank = ""
for i in output:
blank = blank + i
print("\r"+blank, end='')
time.sleep(0.1)
x = input()
The idea is to build larger and larger portions of your output and using the \r you replace the line in the console each time. Waiting 0.1 seconds between loops adds to the effect
If I understand correctly what you are asking, you can print each letter and use input at the end.
Something like this:
output = "what is your name?"
for i in output:
print(i, end='')
x = input()
x will be the string containing what the user inputs.
Imho, it's not cool, just redundant.
If you want a delay between the appearance of each letter, use the time module.
import sys
import time
output = "what is your name?"
for i in output:
print(i, end='')
sys.stdout.flush()
time.sleep(0.1)
x = input()
Note the use of sys.stdout.flush() to push each letter immediately in the output.
I want a percentage sign to display after the users enters their number. Thanks
percent_tip = float(input(" Please Enter the percent of the tip:")("%"))
For example, before the user types anything they should see:
Please Enter the percent of the tip:
Once they begin typing the number 20 they should see:
Please Enter the percent of the tip: 20
After they hit <Enter> they should see:
Please Enter the percent of the tip: 20%
Please try this if this is what you are asking for:
import sys
import time
percent_tip = ""
while percent_tip in "123456789": # This part checks with the "if" statement, if its not a integer then it returns
percent_tip = input("Please Enter the % of the tip: ")
if percent_tip in "123456789":
print(str(percent_tip) + " %") # Prints the number and the percentage symbol
sys.exit() #stops the shell
else:
time.sleep(.100) #Shell waits then goes back in the while loop (unless its controlled by the "while" and "if")
Please do not try to harden yourself with a code that you don't know how to do it.
If you are on Windows, you will have the msvcrt module available. It provides, among others, the getwche() function, giving you the key pressed. This allows you to act on individual characters, and then print the % at the end (if you play around a bit more, you can probably also get it to appear while typing).
Example:
def get_chars():
chars = []
new = msvcrt.getwche()
while new != '\r': # returns \r on <RETURN> press
# you probably want to do some input validation here
chars.append(new)
new = msvcrt.getwche() # get the next one
print(end='%', flush=True)
return ''.join(chars) # this returns a str, you might want to directly get an int
Also, you will probably want to add input validation inside to make sure the input is only numbers.
print "This is a dating message that I am going to test, I want the user to be able to input their own answers."
print "I'd like for this message to work correctly, this is a dating message for Python"
print "Hi there, I think you're very cute and that's why I'm sending you this message"
print "I'm going to prompt you to see if you'd like to go on a date with me, type 'ok' to continue"
raw_input()
print "Type 'y' if you'd like to go out, or 'n' if you're not interested."
raw_input(y) = "Hooray I'm so happy to hear that! You should text me at 888-888-8888"
raw_input(n) = "Awww darnit, well best of luck to you!"
I'm pretty new at programming, I'm actually in college right now, but I'm just curious I've been having trouble trying to assign specific texts like an input to input variables in python, can anybody show me what I'm doing wrong?
raw_input is a function that returns user's answer.
yesno = raw_input("Type 'y' if you'd like to go out, or 'n' if you're not interested.")
if yesno == 'y':
print "Hooray I'm so happy to hear that! You should text me at 888-888-8888"
else:
print "Awww darnit, well best of luck to you!"
If I can comprehend correctly, you're looking to assign the raw_input to some variable. This would be the way to go about it
age = raw_input("Enter your age: ")
print age
good job on trying to learn programming. What are you trying to do?
you can use this print text out in the console:
print "Hello World"
and you can use this to prompt the user and save what is inputted:
something = raw_input("Just type something? ")
After this, you will have the user inputted string in the /something/ variable and you can print it out like this:
print something
Does this help?
You can assign a name to a string object like this:
var = "This is a text string"
Now whenever we use var it refers to 'This is a text string'.
print var
This is a text string
Functions (just named chunks of code) return an object. It can be any Python object, including a text string. We can then use that function call in an assignment:
reply = raw_input("Please type something: ")
raw_input returns whatever the user typed. Now we can use the name reply to refer to that string object.
Of course we can combine these:
prompt = "Please type something: "
reply = raw_input(prompt)
For my program I ask the user to input a command. If the user writes: Input filename (filename being any possible name of a file in the computer) I want my program to only read Input so it knows what if statement to use and then open the file that the user wrote.
There is also another part where I have to do a similar task, where the user inputs: score n goals.(n is the top number of players the program has to read from a list) I want the program to differentiate this from 2 other similar tasks (score n misses and score n passes).
I am not sure if I'm approaching this the correct way, but this was my try for the first case I talked about, but it doesn't work.
user_input = input ('File name:')
input_lowered = user_input.lower()
command = input_lowered[0:4]
if command == 'input' :
fp = open ("soccer.part.txt")
else :
user_upper = input ('Input name:')
Thanks in advance for any clue of how I should aim at fixing this!!!
You can do that as follows:
your_string[0:5]
This will get the first five characters of the string as a string.
If you would like to grab a part of the string from the start then you can use:
my_string[:number]
if you would like to grab a part of the string from the end:
my_string[-number:]
I'm using raw_input() to storing a message inside a variable. So I can't press enter for a carriage return/new line to start a new paragraph. Right now if I press enter it will just proceed to the next portion of my program.
I already tried something like this:
>>> message = raw_input("Message: ")
Message: Hello Sir, \n It's great that..
>>> message
"Hello Sir, \\n It's great that.."
>>>
It didn't worked, and I also tried enclosing it in single and double quotes, which also didn't worked.
I understand that there are other ways of doing this, like using wxpython or tkinter, but I want to keep it strictly console. Is this possible?
Can you use the sys module? This will do the trick if you want. Just hit Ctrl-D to end it.
import sys
message = sys.stdin.readlines()
Otherwise, this answers your question: Python raw_input ignore newline