i am trying to create a line of code that prints the first line like it normally would do then after printing it, it will then erase that output and write something else
print("This text is about to vanish - from first line",end='')
import time
time.sleep(3)
print("\rSame line output by Thirumalai")
i have this code from another user, how would i go about having it so that it shows the first line aswell, because when i run the py in terminal it doesnt do that, im using ubuntu
To make the first line appear, you need to turn off buffering. You can specify
print("This text is about to vanish - from first line",end='', flush=True)
# ~~~~~~~~~~
for the print (Python 3.3+ needed, see here for the details and ways how to do that in older versions).
You also need to print some spaces at the end of the second print to overwrite the remaining text.
print("\rSame line output by Thirumalai", ' ' * 15)
Related
I am new to python. I am trying to open a text file with name 'P' and show the lines as an output. I wrote the code below, and it runs but not output. Why is this so?
with open('/Users/LENOVO/Desktop/P.txt','rt') as a_file:
for lines in a_file.readlines():
print(lines,ends='')`
because your print contains end=""
usually the \n is used to flush the output.
if you want to force it to flush the buffer (so to print it without the \n) you can add the flush option :
print(lines,end='', flush=True)
But maybe you just want to remove the end keyword:
print(lines)
When to use end=''?
When you use the end parameter you replace the usual \n (carret return) by something else, that is useful if you want to display a série of things next to each other without going next line everytime. (for instance if you want to print a dot . or x for each call to a function that you're calling in a loop for a big number of times.
And yes it should be end and not ends
See reference here :
https://www.w3schools.com/python/ref_func_print.asp
I do not know where you got ends='' from, but if you remove it, it produces an output.
I also figured I would also add that you are most likely referring to end, this will essentially just replace the \n which is the default value with whatever you wish.
So as I'm sure you know there's a specific operator for print() functions called end.
#as an example
print('BOB', end='-')
#would output
BOB-
So is there something like this for inputs? For example, if I wanted to have an input that would look something like this:
Input here
►
-------------------------------------------------------
And have the input at the ► and be inside the dashes using something like
x = input('Input here\n►', end='-------')
Would there be some equivalent?
EDIT:
Just to be clear, everything will be printed at the same time. The input would just be on the line marked with the ►, and the ---- would be printed below it, but at the SAME time. This means that the input would be "enclosed" by the ---.
Also, there has been a comment about curses - can you please clarify on this?
Not exactly what you want, but if the --- (or ___) can also be on the same line, you could use an input prompt with \r:
input("__________\r> ")
This means: print 10 _, then go back \r to the beginning of the line, print > overwriting the first two _, then capture the input, overwriting more _. This shows the input prompt > ________. After typing some chars: > test____. Captured input: 'test'
For more complex input forms, you should consider using curses.
When using basic console IO, once a line has been ended with a newline, it's gone and can't be edited. You can't move the cursor up to do print anything above that last line, only add on a new line below.
That means that without using a specialized "console graphics" library like curses (as tobias_k suggests), you pretty much can't do what you're asking. You can mess around a little with the contents of the last line (overwriting text you've already written there), but you can't write to any line other than the last one.
To understand why console IO works this way, you should know that very early computers didn't have screens. Instead, their console output was directly printed out one line at a time on paper. While some line printers could print several characters on the same spot (to get effects line strikethrough or underline), you couldn't unprint anything once it was on the paper. Furthermore, the paper feed only worked in one direction. Once you had sent a newline character that told the printer to advance the paper, you couldn't go back to an old line again.
I believe this would solve your problem:
print(f">>> {input()} ------")
OR
print(f"{input(">>>")} ------")
F-strings are quite useful when it comes to printing text + variables.
I just wrote my first program in python, but when I launch it on the IDLE the cursor immediately starts a line below my print() statement. Is there a way to set the cursor to start next to my print statement? Also I have noticed when I ran different programs that take user input, sometimes the cursors will appear above my print(). Is there any fixes to this?
When you prompt for input, you can put the prompt in the input call.
>>> name = input('What is your name? ')
What is your name? |
print() in Python, by default inserts a new line. In order to modify this behaviour, you have to explicitly call print with following args
print(string, end="")
Source:-
https://docs.python.org/3/library/functions.html#print
I am trying to print the report for each iteration. Since each iteration takes a really long time to run, therefore, I use print together with end="\r" to show the current item being processed.
Here's the dummy code:
import time
y = list(range(50))
print("epoch\ttrain loss\ttest loss\ttrain avg\ttest avg\ttime\tutime")
for e in range(10):
for i in range(50):
print("training {}/{} batches".format(i,50), end = '\r')
time.sleep(0.05)
print('{}\t{:2f}\t{:2f}\t{:2f}\t{:2f}\t{:2.1f}\t{:2.1f}'.format(y[0]+e,y[1]+e,y[2]+e,y[3]+e,y[4]+e,y[5]+e,y[6]+e))
Expected Result
This is my expected result, where the progress information is completely erased after each iteration. (I am running it in Jupyter notebook, and it looks fine)
The Result that I am getting
However, when I run it on linux terminal, the progress information is not completely erased, and the result is overlaying on top of the progress.
Why is it so? How to solve it?
\r simply moves the cursor back to the beginning of the current line. Anything printed after the \r is printed "on top of" the content previously there. On a real printer/teletype this would be literally true, with two characters getting printed in the same position ("overstruck"). On a terminal, the new characters replace the old ones (but only in positions that you actually write to).
You can take advantage of this behavior of terminals by printing spaces. You need at least as many spaces as the content you want to erase, but not enough to make the terminal wrap to the next line (this may be impossible if the line was printed all the way to the last character).
In your case, you know that the line won't be more than 22 characters long, so you could use end='\r \r' (go back to the beginning of the line, print 22 blanks, then go back to the beginning of the line again).
\r option will set (move) the cursor to start. It will not clear the text.
You have to make sure your printed data has enough space to overwrite the previous printed data or be of the same length since just moving to the same line would not automatically clear the previous contents.
I have a function that prints the number of pixels found in an image and then asks the user how they would like to proceed. As long as the interpreter hasn't moved on from the function I want all the output to be indented accordingly.
One such 'sub output' (the input prompt) needs to be multiple lines. So I kick off with the 3*quote (''') followed by two spaces to create the indentation. At the end of the question 'how would you like to proceed?' I use a hard return. An extra indentation is assumed by the text editor so I remove it causing the following list of suggestions to line up flush with the input variable command. Here's how it looks:
def returnColors():
#
# lots of code that does stuff...
#
print("The source image contains", lSize, "px.")
print("")
command=input(''' What would you like to do? You can say:
get all
get unique
''')
The problem with this is that the interpreter is acknowledging the indentation that separates the function body from the function statement as actual string contents, causing the output to look like this:
The source image contains 512 px.
What would you like to do? You can say...
get all
get unique
|
The only way to avoid this is by breaking indentation in the interpreter. Although I know it works, it doesn't look very good. So what options do I have?
EDIT: Just because I have the screenshot_
One thing that you should keep in mind is that once you have start a multiline string declaration, all the text until it is closed is taken as is and syntax (ie, indentation) is no longer considered.
You can start your multiline with an explicit new line so that everything in the multiline string can be indented together in code.
IE.
command=input('''
What would you like to do? You can say:
get all
get unique
''')
would print out the prompt with a new line on top, but the formatting of the text is more explicitly shown and should appear as seen.
OR you could use the \n for each new line in the string to get it formatted more correctly and remember to use a single \ after each new line. E.g.
instead of:
''' What would you like to do? You can say:
get all
get unique
'''
Try
' What would you like to do? You can say:\
\n\
\n get all\
\n get unique\
\n'
The indent won't matter, no matter where you use \n at the beginning of new line, the input() will output the same. This is will give the same input() string:
' What would you like to do? You can say:\
\n\
\n get all\
\n get unique\
\n'