我尝试了以下代码
s='Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales'
s1='Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library'
print(s,end='\r')
print(s1)
我得到的输出是
Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides con
Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library
第一个字符串s
在两行上打印。 \r
然后从第二行的开头打印第二个字符串。
我希望第二个字符串从第一个字符串的开头开始打印。
是否可以使用print
进行操作,还是应该使用其他功能?
答案 0 :(得分:1)
这是您使用的终端仿真器的功能。是的,您可以使用print来执行此操作,您需要为您的终端类型输出适当的终端转义序列。
例如,如果您使用的是类似终端仿真器的xterm,则转义序列为described here(该页面用于bash,但是python的语法非常相似)。您可能最感兴趣的转义序列是:
如果您要做的事情要复杂得多,您可能还会对curses库感兴趣。
答案 1 :(得分:1)
这很棘手。首先,并非所有终端都具有相同的功能。例如,李瑞安谈到的\033[s
和\033[r
在我的终端上不起作用。从终端数据库中读取控制序列更安全:
import os
sc = os.popen('tput sc').read()
rc = os.popen('tput rc').read()
print(sc + s, end='\r')
print(rc + s1, end='\r')
但是,这在Windows上将不起作用。同样,它只是将光标的坐标保存在视图中,而不是在滚动历史记录中。因此,如果将光标保存在最后一行,打印一些滚动屏幕并还原光标的内容,则根本不会移动(因为它将返回到-最后一行!)
我之前在评论中建议的解决方法是:
import os
columns = int(os.popen('tput cols').read())
need_for_up = (len(s) - 1) // columns
cuu = os.popen('tput cuu %s' % need_for_up).read()
print(s, end='\r' + cuu)
print(s1)
因为这不适用于坐标,但实际上是将光标从其位置向上移动,因此无论是否在底部都可以工作。
由于这也会使用tput
查询Terminfo数据库,因此它也无法在Windows上运行。我不知道(如果不是Windows用户)是否对cuu = "\033[%sA" % need_for_up
进行硬编码也可以。