是否存在任何标准的“附带电池”方法来清除Python脚本中的终端屏幕,或者我必须去诅咒(库,而不是单词)?
当前回答
如果您希望在使用python shell时清除您的终端。然后,您可以执行以下操作清除屏幕
import os
os.system('clear')
其他回答
如果您所需要的只是清除屏幕,那么这可能就足够了。问题是在linux版本之间甚至没有一个100%跨平台的方法来做到这一点。问题是终端的实现都支持略微不同的东西。我很确定“clear”在任何地方都适用。但是更“完整”的答案是使用xterm控制字符来移动光标,但这需要xterm本身。
在不了解更多问题的情况下,你的解决方案似乎已经足够好了。
前段时间偶然发现的
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
然后使用clearscreen()
这适用于所有平台,并且在Python 2和3中都有效。
def clear(number):
for i in range(number):
print(" ")
然后输入clear(numberhere)来清除。
所以我想在这里发表我的意见…
似乎没有人对这个问题提供一个真实的答案,每个人的回答都是“不使用os.system()这是邪恶的!!”没有解释,也没有提供依赖于打印新行的解决方案。
对于那些需要清除终端屏幕并向后滚动的用户,无论出于何种原因,您都可以使用以下代码:
import os
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')
print('A bunch of garbage so we can garble up the screen...')
clear()
# Same effect, less characters...
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls||echo -e \\\\033c')
这达到了OP所期望的效果。它确实使用os.system()命令,所以如果这是邪恶的,有人知道使用subprocess.call()实现这一点的方法,请评论,因为我也更喜欢使用subprocess,但根本不熟悉它。
转义序列呢?
print(chr(27) + "[2J")