Hướng dẫn print overwrite python - in ghi đè python

50

Nội dung chính ShowShow

  • Làm thế nào để bạn ghi đè một dòng in trong Python?
  • Làm thế nào để bạn ghi đè một dòng trước trong Python?
  • Làm thế nào để bạn in nhiều dòng trên một dòng trong Python?
  • Làm thế nào để bạn in nhiều dòng trên một vòng lặp trong Python?

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.Learn more.
Learn more.

Tôi biết có thể viết lại dòng cuối cùng được hiển thị trong thiết bị đầu cuối với "\ r", nhưng tôi gặp khó khăn khi tìm ra nếu có cách nào để quay lại và chỉnh sửa các dòng trước được in trong bảng điều khiển.

Điều tôi muốn làm là in lại nhiều dòng cho một game nhập vai dựa trên văn bản, tuy nhiên, một người bạn cũng đang tự hỏi về điều này cho một ứng dụng có một dòng dành riêng cho một thanh tiến trình và một người khác mô tả việc tải xuống.

tức là bảng điều khiển sẽ in:

Moving file: NameOfFile.txt  
Total Progress: [########              ] 40%

và sau đó cập nhật một cách thích hợp (cho cả hai dòng) khi chương trình đang chạy.

Hướng dẫn print overwrite python - in ghi đè python

mkrieger1

15.8k4 Huy hiệu vàng46 Huy hiệu bạc57 Huy hiệu Đồng4 gold badges46 silver badges57 bronze badges4 gold badges46 silver badges57 bronze badges

hỏi ngày 27 tháng 7 năm 2011 lúc 6:47Jul 27, 2011 at 6:47Jul 27, 2011 at 6:47

3

Trên UNIX, sử dụng mô -đun Curses.

Trên Windows, có một số tùy chọn:

  • Pdcurses: http://www.lfd.uci.edu/~gohlke/pythonlibs/
  • Howto được liên kết ở trên giới thiệu mô -đun bảng điều khiển
  • http://newcenturycomputers.net/projects/wconio.html
  • http://docs.activestate.com/activepython/2.6/pywin32/win32console.html

Ví dụ đơn giản sử dụng những lời nguyền (tôi là tổng số N00B):

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()

Galigator

7.8532 Huy hiệu vàng23 Huy hiệu bạc35 Huy hiệu Đồng2 gold badges23 silver badges35 bronze badges2 gold badges23 silver badges35 bronze badges

Đã trả lời ngày 27 tháng 7 năm 2011 lúc 6:51Jul 27, 2011 at 6:51Jul 27, 2011 at 6:51

codeapecodeapecodeapecodeape

95,4K24 Huy hiệu vàng151 Huy hiệu bạc180 Huy hiệu đồng24 gold badges151 silver badges180 bronze badges24 gold badges151 silver badges180 bronze badges

3

Như thế này:

#!/usr/bin/env python

import sys
import time
from collections import deque

queue = deque([], 3)
for t in range(20):
    time.sleep(0.5)
    s = "update %d" % t
    for _ in range(len(queue)):
        sys.stdout.write("\x1b[1A\x1b[2K") # move up cursor and delete whole line
    queue.append(s)
    for i in range(len(queue)):
        sys.stdout.write(queue[i] + "\n") # reprint the lines

Tôi phát hiện ra điều này trong dự án Jiri, được viết trong Go.

Thậm chí tốt hơn: Xóa tất cả các dòng sau khi hoàn thành:

#!/usr/bin/env python

import sys
import time
from collections import deque

queue = deque([], 3)
t = 0
while True:
    time.sleep(0.5)
    if t <= 20:
        s = "update %d" % t
        t += 1
    else:
        s = None
    for _ in range(len(queue)):
        sys.stdout.write("\x1b[1A\x1b[2K") # move up cursor and delete whole line
    if s != None:
        queue.append(s)
    else:
        queue.popleft()
    if len(queue) == 0:
        break
    for i in range(len(queue)):
        sys.stdout.write(queue[i] + "\n") # reprint the lines

Đã trả lời ngày 2 tháng 12 năm 2019 lúc 22:44Dec 2, 2019 at 22:44Dec 2, 2019 at 22:44

LeedehaileedehaiLeedehaiLeedehai

3,4802 Huy hiệu vàng17 Huy hiệu bạc40 Huy hiệu đồng2 gold badges17 silver badges40 bronze badges2 gold badges17 silver badges40 bronze badges

Đây là một mô -đun Python cho cả Python 2/3, có thể chỉ cần giải quyết tình huống như vậy bằng một vài dòng mã; D

In lại - Một mô -đun đơn giản cho Python 2/3 để in và làm mới nội dung đầu ra nhiều dòng trong thiết bị đầu cuối

Bạn có thể chỉ cần coi ví dụ ____1010 đó là bình thường

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
1 hoặc ________ 12 (phụ thuộc vào chế độ bạn sử dụng). Khi bạn sửa đổi nội dung đó trong phiên bản
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
0, đầu ra trong thiết bị đầu cuối sẽ tự động làm mới: D

Đối với nhu cầu của bạn, đây là mã:

from reprint import output
import time

if __name__ == "__main__":
    with output(output_type='dict') as output_lines:
        for i in range(10):
            output_lines['Moving file'] = "File_{}".format(i)
            for progress in range(100):
                output_lines['Total Progress'] = "[{done}{padding}] {percent}%".format(
                    done = "#" * int(progress/10),
                    padding = " " * (10 - int(progress/10)),
                    percent = progress
                    )
                time.sleep(0.05)

Đã trả lời ngày 10 tháng 11 năm 2016 lúc 15:21Nov 10, 2016 at 15:21Nov 10, 2016 at 15:21

YinzoyinzoYinzoYinzo

1552 Huy hiệu bạc6 Huy hiệu đồng2 silver badges6 bronze badges2 silver badges6 bronze badges

2

Cuối cùng, nếu bạn muốn thao tác với màn hình, bạn cần sử dụng các thư viện HĐH cơ bản, thường sẽ là:

  • Các lời nguyền (hoặc mã điều khiển đầu cuối cơ bản được theo dõi bởi cơ sở dữ liệu Terminfo/TermCap) trên Linux hoặc OSX
  • API bảng điều khiển Win32 trên Windows.

Câu trả lời từ @Codeape đã cung cấp cho bạn một số tùy chọn nếu bạn không ngại gắn bó với một HĐH hoặc rất vui khi cài đặt các thư viện của bên thứ ba trên Windows.

Tuy nhiên, nếu bạn muốn một giải pháp đa nền tảng mà bạn có thể chỉ cần cài đặt PIP, bạn có thể sử dụng asciimatics. Là một phần của việc phát triển gói này, tôi đã phải giải quyết sự khác biệt giữa các môi trường để cung cấp một API duy nhất hoạt động trên Linux, OSX và Windows.

Đối với các thanh tiến trình, bạn có thể sử dụng đối tượng Barchart như được hiển thị trong bản demo này bằng mã này.

Đã trả lời ngày 22 tháng 12 năm 2015 lúc 16:18Dec 22, 2015 at 16:18Dec 22, 2015 at 16:18

Peter Brittainpeter BrittainPeter BrittainPeter Brittain

13.3k3 Huy hiệu vàng40 Huy hiệu bạc54 Huy hiệu đồng3 gold badges40 silver badges54 bronze badges3 gold badges40 silver badges54 bronze badges

2

Trả lại vận chuyển có thể được sử dụng để đi đến đầu dòng và mã ANSI

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
4 (
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
5) có thể đưa bạn lên một dòng. Điều này hoạt động trên Linux. Nó có thể hoạt động trên Windows bằng cách sử dụng gói
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
6 để bật mã ANSI:
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
0

Output:

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
1

Dưới mui xe, Colorama có lẽ cho phép các chuỗi đầu cuối ảo của bảng điều khiển bằng cách sử dụng

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
7.

(Cũng được đăng ở đây: https://stackoverflow.com/a/64360937/461834)

Đã trả lời ngày 14 tháng 10 năm 2020 lúc 22:05Oct 14, 2020 at 22:05Oct 14, 2020 at 22:05

JTPEREYDAJTPEREYDAjtpereydajtpereyda

6.4779 Huy hiệu vàng49 Huy hiệu bạc76 Huy hiệu đồng9 gold badges49 silver badges76 bronze badges9 gold badges49 silver badges76 bronze badges

Bạn có thể thử TQDM.

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
3

Ngoài ra còn có tính năng thanh tiến độ lồng của

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
8
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
5

Lưu ý rằng các thanh tiến trình lồng nhau trong

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
8 có một số vấn đề đã biết:
  • Bảng điều khiển nói chung: Yêu cầu hỗ trợ cho việc di chuyển con trỏ lên đến dòng trước. Ví dụ, Idle, Conemu và Pycharm (cũng ở đây, ở đây, và ở đây) thiếu sự hỗ trợ đầy đủ.
  • Windows: Ngoài ra, có thể yêu cầu mô -đun Python
    import curses
    import time
    
    def report_progress(filename, progress):
        """progress: 0-10"""
        stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
        stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
        stdscr.refresh()
    
    if __name__ == "__main__":
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
    
        try:
            for i in range(10):
                report_progress("file_{0}.txt".format(i), i+1)
                time.sleep(0.5)
        finally:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
    
    6 để đảm bảo các thanh lồng nhau nằm trong các dòng tương ứng của chúng.

Đối với thanh tiến trình lồng nhau trong Python, thanh tiến độ kép trong Python - Stack Overflow có nhiều thông tin hơn.

Đã trả lời ngày 16 tháng 7 lúc 7:09Jul 16 at 7:09Jul 16 at 7:09

YnjxsjmhynjxsjmhYnjxsjmhYnjxsjmh

24.3k6 Huy hiệu vàng24 Huy hiệu bạc44 Huy hiệu đồng6 gold badges24 silver badges44 bronze badges6 gold badges24 silver badges44 bronze badges

Tôi tìm thấy giải pháp đơn giản với "Magic_char".

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
8

Đã trả lời ngày 16 tháng 4 năm 2020 lúc 14:25Apr 16, 2020 at 14:25Apr 16, 2020 at 14:25

Làm thế nào để bạn ghi đè một dòng in trong Python?

Sử dụng Trở lại vận chuyển "\ r" để in trên cùng một dòng Sử dụng in cú pháp (chuỗi, end = "\ r") để làm cho dòng stdout tiếp theo bắt đầu ở đầu dòng hiện tại. Do đó, chuỗi được ghi đè bởi câu lệnh in () sau. Use the syntax print(string, end = "\r") to make the next stdout line begin at the beginning of the current line. As a result, string is overwritten by the following print() statement. Use the syntax print(string, end = "\r") to make the next stdout line begin at the beginning of the current line. As a result, string is overwritten by the following print() statement.

Làm thế nào để bạn ghi đè một dòng trước trong Python?

Tóm tắt: Cách đơn giản nhất để ghi đè lên bản in trước đó thành stdout là đặt ký tự trả về vận chuyển ('\ r') trong câu lệnh in dưới dạng in (chuỗi, end = "\ r").Điều này trả lại dòng stdout tiếp theo cho đầu dòng mà không cần tiến hành dòng tiếp theo.set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.

Làm thế nào để bạn in nhiều dòng trên một dòng trong Python?

Để in nhiều biểu thức vào cùng một dòng, bạn có thể kết thúc câu lệnh in trong Python 2 bằng dấu phẩy (,).Bạn có thể đặt đối số cuối thành chuỗi ký tự khoảng trắng để in vào cùng một dòng trong Python 3.end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3.end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3.

Làm thế nào để bạn in nhiều dòng trên một vòng lặp trong Python?

Bạn có thể sử dụng chức năng \ n "được xây dựng trong trình biên dịch Python 3 hoặc bạn có thể in các trích dẫn đôi trống ....

in ("\ n").

print("").