I'm writing a program in python and I'd like to replace more than one line in the console with new text.
For example if I have 3 sentences printed to the console with:
print("Hello World!")
print("How are you!")
print("What's going on?")
Where each on is on a different line (and so has an \n).
How do I go about replacing all of this text when it displays in the console? I can't us \r in this situation due to the \n.
This is kind of an old post, but I came across it and worked out a solution as well. Added a timer, because otherwise the print statements bury each other and you'll only be able to read the last one. I'm on python 2.7:
import os
import time
os.system("printf 'Hello World!'")
time.sleep(1)
os.system("printf '\rHow are you?!'")
time.sleep(1.5)
os.system("printf '\rWhats going on?'")
os.system("echo ")
A simple fix would be to simply change the end separator for printing your strings. you can specify how you want the print function to separate calls with the end argument
print("hello world!", end="")
print("\rhello world again!")
In this case, we're setting the separator to "", which is nothing. So printing the next strings starts on the same line thus \r can be used. Compiling that gives you hello world again! on one line.
Related
For example, let's say one of the printed things is "Hello World" and the second is "Hello". How would I print "Hello" on the same line as the one that says "Hello World"? This is just an example. Realistically I have no idea how long the printed text will be.
Here is an example script:
x = open("file.txt", "r+").read().split("\n")
for i in x:
print(something)
where something = I don't know. I want the output to be what the first line of the text file says, then what the second line says, and so on except print the second/third/fourth... line over the first line and each line is an unknown length, some shorter than others. Lets say the file.txt says:
Overflow
Stack
I would want it to print "Overflow" then "Stack", except each word gets printed on the first line and once you print "Stack", every part of "Overflow" can't be seen
Keep in mind that print("Hello World", end="\r") won't work because of the length.
You could work around the \r solution by padding each line with spaces according to the previous line:
prev_size = 0
with open("file.txt", "r+") as f:
for line in f:
print(f"{line.strip()}{' '*prev_size}", end='\r')
prev_size = len(line)
You would probably want to add a sleep between prints to be able to actually see the text changing...
When you use the print function in python, you're just pushing characters onto a pipe somewhere (the pipe might be connected to the standard out, but your program doesn't know that). Once its, pushed, there is nothing you can do to un-push it. Afterall, the pipe might not even be connected to a screen. It might be directly connected to the input of another program, or it might be using a physical printer for display. What would un-pushing even mean in those cases?
There are, however, special control characters (such as the "backspace" character) that you push to the pipe to signal that you want to erase characters. However, The terminal you are connected to is free to do what it wants with these characters. It can respect your wishes and erase characters, or it can print the literal '\b' characters to indicate a backspace, or it can completely ignore you and continue to print after the previous letters. That's completely out of your control.
Assuming the terminal that print the characters supports overwriting the characters, you can use the ANSI control sequences. The sequence for moving cursor to beginning of line is '\033[1G' and for erasing the everything from current cursor position to end of line is '\033[0K'. So,
import time
print('hello world', end='', flush=True) # prints "hello world" with no newline at the end
time.sleep(2) # wait 2 seconds
print('\033[1G\033[0K', end='') # moves cursor to beginning of line and erases the line
print('hi') # prints "hi" with newline at the end
flush=True is needed because the print function is buffered by default and doesn't actually print anything until it hits a newline. This tells the function you want to flush the buffer immediately.
Take a look at ANSI escape codes, section on "CSI sequences" to see what other codes are available.
Everyone all of you. I am learning python right now.
In python, As you know that when we print anything using print() function it prints line by line like this:
print("Hello ")
print("World!")
When we do this then output would be:
Hello
World!
but if we want to be in same line we add end="" like this:
print("Hello ", end="")
print("World!")
Its output:
Hello World!
But I have curiosity that how does it exactly works. Why it comes in same line. The work of end="____" is to add some texts after sentences or words.
Please explain me why it comes in same line and what is the reason.
Thanks in advance!
'end' tells the print function what to end your text with. Think of it as appending that string. 'end' defaults as '\n' meaning that a new line is appended to your string by default. So, if you change it to "", you are telling it not to alter or append to your string. Which means you simply print "Hello " instead of "Hello \n"
print ("Hello, Python")
The preceeding line will print to the console "Hello, Python\n" '\n' is a new line and it is the default behavior for the print function. It will by default always add '\n' to your string. If you supply 'end' to the function, it will print that instead of '\n'.
For example, the following two lines are identical in behavior:
print ("Hello, Python")
print ("Hello, Python",end="\n")
You could however provide your own 'end' to append a different string, if you so chose. For example:
print ("Hello, Python",end="!")
The preceeding line will print, "Hello, Python!"
For more information regarding new lines, check out the following:
https://wtmatter.com/python-new-line/
It is because In python when you print statement there is end="\n" as default in the python which allow it to print in another line but you will not see it. When you put end="" then it will replace with \n which print in different line and then it prints in same line. Hope it will help
I'm writing a simple command line prompt script and noticed that lines printed immediately after doing a readline start with a leading space. Is there any way to avoid this behavior?
Sample function to demonstrate:
import sys
def foo():
print 'Enter some text.\n> ',
bar = sys.stdin.readline()[:-1]
print 'You entered "{0}"'.format(bar)
When I run this code I get:
>>> foo()
Enter some text.
> Hi
You entered "Hi"
^ the leading space I want to get rid of
This is Python 2's "soft-space" behavior. After a print thing, statement, the next print will print a leading space to separate the output from the previous print output. This can look weird when a different text source, such as user input, causes the output of the two prints to appear on different lines.
There are various ways to get around soft-spacing, but here, the most appropriate would be to use raw_input instead of sys.stdin.readline. It auto-strips the newline for you and allows you to specify a prompt:
print 'Enter some text.'
foo = raw_input('> ')
print 'You entered "{0}"'.format(foo)
Is it possible to manipulate lines of text that have already been printed to the console?
For example,
import time
for k in range(1,100):
print(str(k)+"/"+"100")
time.sleep(0.03)
#>> Clear the most recent line printed to the console
print("ready or not here I come!")
I've seen some things for using custom DOS consoles under Windows, but I would really like something that works on the command_line like does print without any additional canvases.
Does this exist? If it doesn’t, why not?
P.S.: I was trying to use curses, and it was causing problems with my command line behaviour outside of Python. (After erroring out of a Python script with curses in it, my Bash shell stopped printing newline -unacceptable- ).
What you're looking for is:
print("{}/100".format(k), "\r", end="")
\r is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. end="" is to prevent \n after printing (to stay on the same line).
A simpler form as suggested by sonrad10 in the comments:
print("{}/100".format(k), end="\r")
Here, we're simply replacing the end character with \r instead of \n.
In Python 2, the same can be achieved with:
print "{}/100".format(k), "\r",
What you need are ANSI Command Codes.
http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
You also need code to activate ANSI Command Codes. I would use Colorama.
https://pypi.python.org/pypi/colorama
OR
Use curses (Python 3.4+) module.
The simplest method (at least for Python 2.7) is to use the syntax:
print 'message', '\r',
print 'this new message now covers the previous'
Notice the extra ',' at the end of the first print. This makes print stay on the same line. Meanwhile, the '\r' puts the print at the beginning of that line. So the second print statement overwrites the first.
For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline