簡體   English   中英

在Python中,如何在打印后更改文本?

[英]In Python, how to change text after it's printed?

我有一個我正在編寫的Python程序,我希望它能夠在打印后更改文本。 例如,假設我想打印“你好”並每秒擦除一個字母。 我該怎么做呢?

此外,我聽說過詛咒,但我無法讓它工作,我不想簡單地創建新行,直到舊文本離開屏幕。

這是一種方法。

print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()

您也可以通過ANSI轉義獲得聰明。 就像是

sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
    time.sleep(1)
    sys.stdout.write('\033[D \033[D')
    sys.stdout.flush()

對於多行輸出,您還可以每次清除屏幕並重新打印整個屏幕

from time import sleep
import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

message = 'hello'
for i in range(len(message), 0, -1):
    cls()
    print message[:i]
    sleep(1)

你可以用這個:

稱這些模塊為:

import time
import sys

然后復制此方法:

    # Custom Print Method
    def custom_print(string, how = "normal", dur = 0, inline = True):

僅復制此部分以進行鍵入的方法

# string = the string to print & how = way to print & dur = time to print whole word or letter & inline = print on single line or not
if how == "typing": # if how is equal to typing then run this block of code
    letter = 1
    while letter <= len(string):
        new_string = string[0:letter]
        if inline: sys.stdout.write("\r")
        sys.stdout.write("{0}".format(new_string))
        if inline == False: sys.stdout.write("\n")
        if inline: sys.stdout.flush()
        letter += 1 
        time.sleep(float(dur))

或者只是方法的這一部分,以反向打印字符串

if how == "reverse": # if how is equal to reverse then run this block of code
    new_string = string
    while len(new_string) > 0:
        if inline == True: sys.stdout.write("\r")
        sys.stdout.write('{message: <{fill}}'.format(message=new_string, fill=str(len(string))))
        if inline == False: sys.stdout.write("\n")
        if inline == True: sys.stdout.flush()
        new_string = new_string[0:len(new_string) - 1]
        time.sleep(float(dur))

或者只是普通字符串正常打印方法的這一部分

if how == "normal": # if how is equal to normal then run this block of code
    sys.stdout.write("\r")
    sys.stdout.write(string)
    time.sleep(float(dur))
    sys.stdout.write("\n")

或者您可以將所有選項放在方法中

您所要做的就是調用custom_print() instead of print`

# custom_print("string", "howtoprint", seconds in int, inline:true or false)
custom_print("hello", "reverse", 1) # for reverse printing hello
custom_print("hello", "typing", 1) # for typing hello slowly
custom_print("hello", "normal", 0) # for just printing hello
custom_print("hello") # for just printing hello

這里似乎運作良好:

import time

text = '\rgood-bye'
for i in xrange(len(text), 0, -1):
    print text[0:i],
    time.sleep(1)
print ' '

你可以使用帶有getch()字符和循環的動態標准輸出

示例: https//asciinema.org/a/238478

碼:

# Script make you able to edit printed text
# stdin and stdout at the same time
# https://asciinema.org/a/238478
# https://gist.github.com/SoleSensei/05a97bbe8b75cd2368a8e6d5e00d6047
import sys
from getch import getch

def flush_append(char):
    # just append char to the end
    sys.stdout.write(char)
    sys.stdout.flush()

def flush_write(line):
    # clear all and rewrite line
    sys.stdout.write(f"\r{' '*100}\r")
    sys.stdout.flush()
    sys.stdout.write(line)
    sys.stdout.flush()

def interactive_input(line):
    flush_write(line)
    c = getch()
    while ord(c) not in (13, 3): # 13 - Enter, 3 - Ctrl+C
        if ord(c) in (127, 8): # 127,8 - Backspace (Unix, Windows)
            line = line[:-1]
            flush_write(line)
        else:
            # decode to string if byte
            c = c.decode('ascii') if str(c)[0] == 'b' else c
            line += c
            flush_append(c)
        c = getch()
    print() # add EOL
    return line


s = interactive_input('stdout editable line')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM