How to print between the last and second-last lines in the console?

Using Python 3.4, is there an agnostic printing mechanism between the last and second to last lines? What I'm trying to execute is basically a progress bar always on the last line. The second line and up are debug logs only. For instance:

[DEBUG] Some info...
[DEBUG] More info...
Download Progress: [####      ] 40% (3 of 20)

I run some downloads in a loop. Each iteration of the loop I run to print the execution line:

def _print_progress_bar(self):
    amt_done = self._count / self._max
    print('\rDownload Progress: [{:20s}] {:.1f}% ({})'.format(
        '#' * int(amt_done * 20),
        amt_done * 100,
        self._padded_counter(' of ')), end='')

Between calls to this method, in order to display a progress bar, I want to insert diagnostic messages into it (I do not want instructions to printoverwrite the progress bar basically after that).

How can i do this?

+4
source share
3 answers

, , '\r'. Windows , ('\n') . Unix , '\r' - . , print('hi\rhello') 'hi', 'hello', 'hello'. end='' print(). , - , , , , , .

>>> import time, sys
>>> def doit():
...     print('part 1')
...     print(0, end='')
...     sys.stdout.flush()
...     time.sleep(1)
...     print('\rpart 2')
...     print(1)
...
>>> doit()
part 1
part 2
1
0

, , - , :

for i in range(10):
    time.sleep(0.1)
    print('%s\n%s\r\033[F' % (i,i), end="")

, , . , .

Windows.

0

You need to change the DEBUG function to delete the line before printing. This is the only agnostic way that I know.

A utility specific to the Windows platform is to use WinAPI to scroll to the top of the window and write exactly to the line above the last. Perhaps a library like https://pypi.python.org/pypi/asciimatics/1.5.0.post1 can help you .

0
source

Source: https://habr.com/ru/post/1589105/


All Articles