How to include a newline in the python raw_input() function? - python

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

Related

Delete the input line right after input has been sent

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!

sys.stdin in for loop is not grabbing user input

I have this code (test.py) below:
import sys
for str in sys.stdin.readline():
print ('Got here')
print(str)
For some reason when I run the program python test.py and then I type in abc into my terminal I get this output:
>>abc
THIS IS THE OUTPUT:
Got here
a
Got here
b
Got here
c
Got here
It prints out Got here five times and it also prints out each character a, b, c individually rather than one string like abc. I am doing sys.stdin.readline() to get the entire line but that doesn't seem to work either. Does anyone know what I am doing wrong?
I am new to python and couldn't find this anywhere else on stackoverflow so sorry if this is a obvious question.
readline() reads a single line. Then you iterate over it. Iterating a string gives you the characters, so you are running your loop once for each character in the first line of input.
Use .readlines(), or better, just iterate over the file:
for line in sys.stdin:
But the best way to get interactive input from stdin is to use input() (or raw_input() in Python 2).
You are looping through each character in the string that you got inputted.
import sys
s = sys.stdin.readline()
print ('Got here')
print(s)
# Now I can use string `s` for whatever I want
print(s + "!")
In your original code you got a string from stdin and then you looped through ever character in that input string and printed it out (along with "Got here").
EDIT:
import sys
while True:
s = sys.stdin.readline()
# Now I can do whatever I want with string `s`
print(s + "!")

Delete last printed character python

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

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.

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