이전 출력을 덮어 쓰는 동일한 줄에 출력? 파이썬 (2.5)
간단한 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',
This is shorter than other non-python 3 solutions, but also more difficult to maintain.
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - 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()
to overwiting the previous line in python all wath you need is to add end='\r' to the print function, test this example:
import time
for j in range(1,5):
print('waiting : '+j, end='\r')
time.sleep(1)
'developer tip' 카테고리의 다른 글
std :: move ()는 어떻게 값을 RValues로 전송합니까? (0) | 2020.09.12 |
---|---|
ListView에서 바닥 글을 추가하는 방법은 무엇입니까? (0) | 2020.09.11 |
'모듈'에 'urlencode'속성이 없습니다. (0) | 2020.09.11 |
Web.Config에서 변수 읽기 (0) | 2020.09.11 |
명령 프롬프트에서 PowerShell 스크립트에 부울 값을 전달하는 방법 (0) | 2020.09.11 |