在 Python 中清除终端(和历史!) [英] clear terminal (and history!) in Python

查看:158
本文介绍了在 Python 中清除终端(和历史!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎python中的清除终端的副本,但不完全是.

This is almost a duplicate of clear terminal in python, but not quite.

那个问题是:是否存在任何标准的附带电池"方法来清除 python 脚本中的终端屏幕,或者我必须去诅咒(图书馆,而不是单词)?

That question reads: Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?

那里的所有响应都会导致您在终端上输入 clear 时发生的情况 - 除了最顶部的空命令行外,屏幕上的所有内容都消失了.但是,如果您愿意,可以向上滚动以查看您之前在做什么.

All of the responses there result in what happens when you enter clear on your terminal - everything on your screen disappears except for an empty command line at the very top. But, if you'd like, you can scroll back up to see what you were doing earlier.

我正在寻找一种方法来做到这一点,但不允许用户向上滚动.它相当于 command+K 在 macOS 上的作用.

I'm looking for a way to do this, but to not allow the user to scroll back up. It's the equivalent of what command+K does on macOS.

该应用程序是一款多人纸牌游戏,我不希望玩家能够向上滚动以查看其他玩家的手牌.

The application is a multiplayer card game, and I don't want a player to be able to scroll back up to see another player's hand.

推荐答案

您可以使用 subprocess.call() 从标准库 subprocess 模块发送 reset 命令到终端重新初始化终端并实际上执行类似于 clear 的操作,但同时也清除回滚历史记录.

You could use subprocess.call() from the standard library subprocess module to send the reset command to the terminal which will reinitialize the terminal and in effect do something similar to clear but also clear the scrollback history.

import subprocess
subprocess.call('reset')

或者,我从 this answer 中了解到,您可以使用命令 tput reset 相反,它会立即清除终端,而单独使用 reset 时,您会遇到轻微的延迟.这也可以使用 subprocess.call() 调用,如下所示:

Alternatively, I have learned from this answer, that you can use the command tput reset instead, which will clear the terminal instantly, whereas with reset alone you will experience a slight delay. This can also be called with subprocess.call() as follows:

subprocess.call(['tput', 'reset'])

有关 reset 命令的更多信息,请执行:

For more info on the reset command, do:

$ man reset

有关 subprocess 模块的更多信息,请参阅 文档.

For more info on the subprocess module, see the documentation.

我已经在 Ubuntu 上测试了这两个,但希望它们也能在 OSX/macOS 上运行.如果没有,也许您可​​以将 subprocessthis solution 结合使用,但我无法测试

I have tested both of these on Ubuntu, but hopefully the will work on OSX/macOS as well. If not, perhaps you can use subprocess combined with this solution, but I am unable to test that.

这篇关于在 Python 中清除终端(和历史!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆