Rewriting the second to last printed line - python

In python is there an easy way to rewrite printed line?
But I'm not talking about last printed line because for that is:
print("text", end="\r")
Then my last resort is using os.system("cls") and printing all info with changed line again.
I wanted to recreate anaconda downloading or docker build.
I know maybe it's duplicate question but I haven't found it if so my bad.
Example:
text
text2
text3
After change:
text
hello_world
text3
It could be this code:
import os
print('text')
print('text2')
print('text3')
os.system('cls')
print('text')
print('hello_world')
print('text3')
But with more printed lines it would be quite annoying to always rewriting all lines
Maybe it is C magic that's my only way to describe what they have done in anaconda or docker.

Related

Python - TQDM Clearing the line above it before printing

So, I've ran into a bit of a problem because my vocabulary isn't big enough to define it. TQDM in python has a specific function that, when printed, deletes the line above it and only the singular line above it. I've tried looking through the documentation to see if there's a simple way to do it outside of the TQDM module, but I can't seem to find anything. For reference, here is the image of my console after fully printing, and the code along with it. Screenshot of my console
while xLoad == False:
string1 = ''' Loading Prerequisites. . . " '''
sleep(1)
for letter in string1:
sleep(0.01)
sys.stdout.write(letter)
sys.stdout.flush()
for i in tqdm(range(_RAND_(800, 1999))):
sleep(.0001)
xLoad = True
# Responsible for making a fake loading bar to simulate loading files before startup
sleep(3)
# End of File
The code above is specifically for the last lines where the actual loading bar is displayed, not the top or the rest of the file. I can send the rest if needed, but what i'm referring to in this specific post is the ability to clear a line before printing a new one without clearing console entirely. I want to keep the "Modeni" and "Thank You" Message on the screen at all times while the rest of the text is displayed below. I hope I made sense in this post, and I appreciate any and all the help.
If I'm understanding your situation correctly, I was wanting to do the same thing and found a solution from this entry: TQDM Printing to Newline: Solution
Add ", position=0, leave=False" inside your tqdm call. For example:
for item in tqdm(list_of_items, desc='Item Description', position=0, leave=False):
Once the loop has finished, it will clear the line making it usable for the next thing, be that another tqdm or whatever.
Hope this helps, and thanks for articulating the question better than I could ever have hoped to have done.

Using Python3.x , in nano, the first line cannot be edited

In Python3, using nano, the very first line I create somehow gets "tabbed" over about several characters. This does not happen when the source code is initially created. E.g. the program can contain only one line, a simple:
print ("Hello World")
Once you save and you re-enter the program, it looks like this (moved to the right several spaces)on the first line:
print ("Hello World")
A 'cat' on the program does not show the first line "tabbing". The line is left justified (i.e., it looks normal). The program runs fine and without errors. It is important to note that re-entering the source in nano OR vi subsequently makes that first line totally disabled and it cannot be edited. What is possibly causing this?

How to edit console output

I have the following very simple code
stdout.write("Hello World")
stdout.write("\rBye world")
stdout.write("\rActually hello back")
Which prints as expected 'Actually hello back' however if i were to add a newline
stdout.write("\n")
How can I go back a newline and then to the beginning of the line so I can actually just output "Hi" instead of
Actually hello back
Hi
I tried
stdout.write("\r")
stdout.write("\b")
However none of them seem to do the trick. The end goal is to display a big chunk of text and then update the output in real time without having to write again. How can I achieve this in python?
EDIT
My question is different than the one suggested as I don't want to modify a single line. I want to be able to print 4-5 lines of text and then replace them in real time instead of just one line that is modified.
Well, if You want to gain full control over the terminal, I would suggest to use the curses library.
The curses module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.
Using it, You can edit multiple lines in terminal like this:
import curses
import time
stdscr = curses.initscr()
stdscr.addstr("line 1\n")
stdscr.addstr("line 2\n")
stdscr.refresh()
time.sleep(3)
stdscr.erase()
stdscr.addstr("edited line 1\n")
stdscr.addstr("edited line 2\n")
stdscr.refresh()
time.sleep(3)
curses.endwin()
The capabilities of this library are much greater though. Full tutorial here.

Print over Current Line in Python Shell

I'm trying to make a percentage text that displays a progress amount but i'm trying to avoid the percentages printing out like this:
Progress: 10%
Progress: 11%
Progress: 12%
Progress: 13%
How can erase and write over the current line? Iv'e tried using the \r and \b characters but neither seems to work. Every single thing I found before has been for either for Python 2 or Unix so i'm not even sure which of those is the problem (if even one of them) because i'm not using either. Does anyone know how I can do this with Python 3 running Windows 7? This is the unworking code that I have currently, but I've tried plenty of other things.
print('Progress: {}%'.format(solutions//possibleSolutions),flush=True,end="\r")
EDIT:
This is not a problem if I'm executing the program from command prompt so I don't think it is a problem with windows. I tried updating Python from what i was using previously (3.4.1) to the latest v3.4.3 and the issue is the same.
Heres a screenshot of the problem:
This is the best I can do at taking a screenshot of the issue. It appears as if each time I move the cursor farther to the left (passed one of the Progress:'s) that the gray area between the text and the cursor gets larger
EDIT 2: The problem is that IDLE does not support ASCII control codes. Solution: Use a different IDE.
You can use print:
print('Progress: {}%'.format(solutions),flush=True,end="\r")
You can't use '\r' and '\b' in IDLE. If you want to use it, try adding these lines at the start of your program:
import sys
sys.stdout = sys.__stdout__
and running idle with this batch script:
#echo off
echo Running IDLE...
py -m idlelib
then, you see output in cmd window and there are '\r' and '\b'.
Use the character '\r' for the print function. Default is '\n'.
'\r' stands for carriage return, '\n' means new line.
You can create a new class called Printer like this:
class Printer():
def __init__(self, data):
sys.stdout.write("\r\x1b[K"+data.__str__())
sys.stdout.flush()
Then, let's say you want to print the progress of a for loop:
for i in range(0, 100):
p = i * 100
output = "%d%% of the for loop completed" % p
Printer(output)

How to remove lines from stdout in python?

I have a program that grabs some data through ssh using paramiko:
ssh = paramiko.SSHClient()
ssh.connect(main.Server_IP, username=main.Username, password=main.Password)
ssh_stdin_host, ssh_stdout_host, ssh_stderr_host =ssh_session.exec_command(setting.GetHostData)
I would like to remove the first 4 lines from ssh_stdout_host. I've tried using StringIO to use readlines like this:
output = StringIO("".join(ssh_stdout_host))
data_all = output.readlines()
But I'm lost after this. What would be a good approach? Im using python 2.6.5. Thanks.
How to remove lines from stdout in python?
(this is a general answer for removing lines from the stdout Python console window, and has nothing to do with specific question involving paramiko, ssh etc)
see also: here and here
Instead of using the print command or print() function, use sys.stdout.write("...") combined with sys.stdout.flush(). To erase the written line, go 'back to the previous line' and overwrite all characters by spaces using sys.stdout.write('\r'+' '*n), where n is the number of characters in the line.
a nice example says it all:
import sys, time
print ('And now for something completely different ...')
time.sleep(0.5)
msg = 'I am going to erase this line from the console window.'
sys.stdout.write(msg); sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\r' + ' '*len(msg))
sys.stdout.flush()
time.sleep(0.5)
print('\rdid I succeed?')
time.sleep(1)
edit
instead of sys.stdout.write(msg); sys.stdout.flush(), you could also use
print(msg, end='')
For Python versions below 3.0, put from __future__ import print_function at the top of your script/module for this to work.
Note that this solution works for the stdout Python console window, e.g. run the script by right-clicking and choosing 'open with -> python'. It does not work for SciTe, Idle, Eclipse or other editors with incorporated console windows. I am waiting myself for a solution for that here.
readlines provides all the data
allLines = [line for line in stdout.readlines()]
data_no_firstfour = "\n".join(allLines[4:])

Categories