I am trying to write a program that will accept user input which will be a pasted block of text (including multiple newlines/carriage-returns). I'm having trouble finding info on how (if) Python can handle this. Normal behavior is for the input command to complete as soon as the first \n is encountered.
When I first saw your question I read "input command" as "the command being input", not as "the input() function". I'm now assuming here that you're gathering data from the command line.
The problem with taking input with newlines in it is: when do you stop accepting input? The following example gets around this by waiting for the user to hit ctrl-d. This triggers an exception in the raw_input() function and then breaks out of the while loop.
text = ''
# keep looping forever
while True:
try:
# grab the data from the user, and add back the newline
# which raw_input() strips off
text += raw_input() + "\n"
except EOFError:
# if you encounter EOF (which ctrl-d causes) break out of the loop
break
# print the text you've gathered after a dashed line
print "\n------------\n" + text
Obviously you'll want to warn your user that they'll have to use ctrl-d to stop entering text, which might be a bit awkward — but if they're already on the command prompt it shouldn't be so bad.
Also, here I've used raw_input(), which gathers input but doesn't exec() it as input() does. If you're looking to execute the results, you could just replace the print() call with :
exec(text)
to have similar results.
Related
I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov
Is it possible to create scrolling text in the Python command line by repeatedly updating the same line of text with small time.sleep() delays?
I believe that the \b (backspace) character can effectively move the cursor backward over text already written. I thought that combining this with end="" parameter in Python 3 might allow subsequent print commands to update a previous print command. With careful tracking of the length of the text and insertion of backspace and other characters it should be possible to create static lines of text that animate in place.
Unfortunately none of this works and even the \b character seems to do nothing:
word = input("Type something-> ")
print(word+"\b\b\bHello", end="")
print("New text")
Anyone got any ideas?
Many thanks,
Kw
Maybe you need carriage return, or \r. This takes you to the beginning of the line. It is the same effect as in a physical typewriter when you move your carriage to the beginning and overwrite whatever is there.
If you use this:
print("Hello", end=" ")
print("world")
The output will be:
Hello World
But if you use:
print("Hello", end="\r")
print("world")
The output will be only:
world
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.
Background
Hi I am trying to write a custom display for my tab completion output in readline. Here is my display hook function-
Code
def match_display_hook(self, substitution, matches, longest_match_length):
print ''
for match in matches:
print match
readline.redisplay()
Question
But the problem is that I have to press the return key to get a prompt unlike the default tab completion output where I can get the prompt right away. I see rl module has been suggested by someone in another thread, but is there no way to get it done through readline itself?
Okay i found a way, not sure if this is the right way to fix it. But i printed the prompt and readline buffer at the end of the match_display_hook and all seems well and good. Here is my new match_display_hook:
def match_display_hook(self, substitution, matches, longest_match_length):
print ''
for match in matches:
print match
print self.prompt.rstrip(),
print readline.get_line_buffer(),
readline.redisplay()
This works well.
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)