[python] 이전 출력을 덮어 쓰는 동일한 줄로 출력 하시겠습니까?

FTP 다운로더를 작성 중입니다. 코드의 일부는 다음과 같습니다.

ftp.retrbinary("RETR " + file_name, process)

콜백을 처리하기 위해 함수 프로세스를 호출하고 있습니다.

def process(data):
    print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
    file.write(data)

출력은 다음과 같습니다.

1784  KB / KB 1829 downloaded!
1788  KB / KB 1829 downloaded!
etc...   

하지만이 줄을 인쇄하고 다음에 다시 인쇄 / 새로 고침하여 한 번만 표시하고 해당 다운로드의 진행 상황을 볼 수 있도록합니다.

어떻게 할 수 있습니까?



답변

다음은 Python 3.x 용 코드입니다.

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

end=키워드 여기에 작업을 수행 무엇인가 – 기본적으로 print()줄 바꿈 (의 끝 \n) 문자는, 그러나 이것은 다른 문자열로 대체 할 수 있습니다. 이 경우 캐리지 리턴으로 줄을 끝내면 커서가 현재 줄의 시작 부분으로 돌아갑니다. 따라서 sys이러한 종류의 간단한 사용을 위해 모듈 을 가져올 필요가 없습니다 . print()실제로 코드를 크게 단순화하는 데 사용할 수 있는 여러 키워드 인수 가 있습니다.

Python 2.6 이상에서 동일한 코드를 사용하려면 파일 맨 위에 다음 줄을 추가합니다.

from __future__ import print_function


답변

한 줄만 변경하면 \r. \r캐리지 리턴을 의미합니다. 그 효과는 전적으로 현재 줄의 시작 부분에 캐럿을 다시 놓는 것입니다. 아무것도 지우지 않습니다. 마찬가지로 \b한 문자 뒤로 이동하는 데 사용할 수 있습니다. (일부 단말기는 이러한 모든 기능을 지원하지 않을 수 있습니다)

import sys

def process(data):
    size_str = os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
    sys.stdout.write('%s\r' % size_str)
    sys.stdout.flush()
    file.write(data)


답변

curses 모듈 문서curses 모듈 HOWTO를 살펴보십시오 .

정말 기본적인 예 :

import time
import curses

stdscr = curses.initscr()

stdscr.addstr(0, 0, "Hello")
stdscr.refresh()

time.sleep(1)

stdscr.addstr(0, 0, "World! (with curses)")
stdscr.refresh()


답변

다음은 텍스트 블록을 다시 인쇄 할 수있는 내 작은 수업입니다. 이전 텍스트를 제대로 지워서 엉망이되지 않고 더 짧은 새 텍스트로 이전 텍스트를 덮어 쓸 수 있습니다.

import re, sys

class Reprinter:
    def __init__(self):
        self.text = ''

    def moveup(self, lines):
        for _ in range(lines):
            sys.stdout.write("\x1b[A")

    def reprint(self, text):
        # Clear previous text by overwritig non-spaces with spaces
        self.moveup(self.text.count("\n"))
        sys.stdout.write(re.sub(r"[^\s]", " ", self.text))

        # Print new text
        lines = min(self.text.count("\n"), text.count("\n"))
        self.moveup(lines)
        sys.stdout.write(text)
        self.text = text

reprinter = Reprinter()

reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")


답변

python 2.7의 간단한 print 문의 경우 '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

이것은 다른 비 Python 3 솔루션보다 짧지 만 유지 관리가 더 어렵습니다.


답변

문자열 끝에 ‘\ r’을 추가하고 인쇄 기능 끝에 쉼표를 추가 할 수 있습니다. 예를 들면 :

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),


답변

나는 spyder 3.3.1-windows 7-python 3.6을 사용하고 있지만 flush가 필요하지 않을 수도 있습니다. 이 게시물을 기반으로-https: //github.com/spyder-ide/spyder/issues/3437

   #works in spyder ipython console - \r at start of string , end=""
import time
import sys
    for i in range(20):
        time.sleep(0.5)
        print(f"\rnumber{i}",end="")
        sys.stdout.flush()