동일한 라인으로 출력하여 이전 출력을 덮어쓰시겠습니까?
저는 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)
저주 모듈 설명서와 저주 모듈 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")
플러시가 필요 없을 수도 있지만 스파이더 3.3.1 - 윈도우 7 - 파이썬 3.6을 사용하고 있습니다. 이 게시물을 기반으로 - 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()
2은 python 2.7 .'\r'
.
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',
이것은 다른 비-피톤 3 솔루션보다 짧지만 유지하기가 더 어렵습니다.
python에서 이전 행을 덮어쓰려면 인쇄 기능에 end='\r'을 추가하면 됩니다. 다음 예제를 테스트하십시오.
import time
for j in range(1,5):
print('waiting : '+j, end='\r')
time.sleep(1)
문자열 끝에 '\r'을 추가하고 인쇄 기능 끝에 쉼표를 추가하면 됩니다.예:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
파이썬 3.9
for j in range(1,5):
print('\rwaiting : '+str(j), end='')
훌륭한 출발점을 제공하는 그들의 답변에 대해 부크 베르스티에 감사드립니다.하지만 나는 그것에 대한 문제를 발견했습니다.sys.stdout
원래대로 플러시되지 않았고, 다시 인쇄된 텍스트가 화면 아래로 반복적으로 이동했습니다.
여기서 제 솔루션은 해당 문제를 해결하기 위해 재구현된 답변에 대한 자세한 설명입니다.__call__
보다 편리한 재인쇄 호출 방법입니다.
Python 3.8에서 테스트 및 작업
import re, sys
class Reprinter:
def __init__(self):
self.text = ''
def write(self, text):
"""Writes text to stdout."""
sys.stdout.write(text)
sys.stdout.flush()
def cursor_prev_line(self):
"""Moves cursor up a line."""
self.write("\x1b[A")
def cursor_prev_line_start(self):
"""Moves cursor to start of previous line."""
self.write("\x1b[F")
def cursor_line_start(self):
"""Moves cursor to start of current line."""
self.write("\r")
def cursor_text_start(self):
"""Moves cursor to start of current text."""
num_newlines = self.text.count("\n")
if not num_newlines:
return self.cursor_line_start()
for _ in range(num_newlines+1):
self.cursor_prev_line_start()
def erase(self):
"""Erases current text by replacing non-whitespace chars with spaces."""
self.cursor_text_start()
self.write(re.sub(r"[^\s]", " ", self.text))
self.cursor_text_start()
def __call__(self, text):
"""Prints `text` & overwrites all existing text."""
self.erase()
self.write(text)
self.text = text
reprint = Reprinter()
reprint("How now\nbrown cow")
reprint("The rain\nin Spain")
파이썬 2.7:
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',
sys.stdout.flush()
자주 인쇄하는 경우 플러시가 필요합니다.
이것이 제 대답입니다.저도 그것을 검색해 봤습니다.나는 많은 해결책을 얻었지만 이것은 나에게 효과가 있습니다.
from time import sleep
for _ in range(5):
sleep(1)
print(f'\rWritting on same line with chaning number {_}.',end='')
else:
print()
- 예, 사용할 수 있습니다.
else:
와의 진술.for
블록. 그러면 새로운 선이 추가됩니다.for
루프 마감 - 루프에서만 작동합니다.다른 사람에게 영향을 미치지 않습니다.
print()
진술들.
언급URL : https://stackoverflow.com/questions/4897359/output-to-the-same-line-overwriting-previous-output
'sourcecode' 카테고리의 다른 글
클래스가 하위 분류될 때 코드를 실행하는 방법은 무엇입니까? (0) | 2023.07.18 |
---|---|
세션 상태가 세션 ID를 생성했지만 응답이 응용 프로그램에 의해 이미 플러시되었기 때문에 저장할 수 없습니다."를 발생시키는 원인 (0) | 2023.07.18 |
잭슨 연속화 시 속성을 동적으로 무시하는 방법 (0) | 2023.07.18 |
딜레마: Fragments vs Activities: (0) | 2023.07.13 |
불만족스러운 종속성 예외:이름이 'entityManagerFactory'인 빈을 생성하는 동안 오류가 발생했습니다. (0) | 2023.07.13 |