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

时间:2011-03-24 22:54:22

标签: python

我正在编写一个Python程序,我希望它能够在打印后更改文本。例如,假设我想打印“你好”并每秒擦除一个字母。我该怎么做呢?

另外,我听说过诅咒,但我无法让它工作,我不想简单地创建新行,直到旧文本离开屏幕。

5 个答案:

答案 0 :(得分:11)

这是一种方法。

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()

答案 1 :(得分:3)

对于多行输出,您每次还可以clear the screen并重新打印整个内容:

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)

答案 2 :(得分: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

答案 3 :(得分:0)

这里似乎运作良好:

import time

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

答案 4 :(得分:0)

您可以将动态stdout与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')