English 中文(简体)
露天终点站
原标题:Clear terminal in Python [duplicate]

是否存在任何标准“与电池配对”方法,以从灰色字母中清除终端屏幕,或者我是否必须去做曲线(图书馆,而不是口号)?

最佳回答

越狱顺序如何?

print(chr(27) + "[2J")
问题回答

简单和跨平台的解决办法是使用Windows上的cls指挥系统,或clear。 http://docs.python.org/3/library/os.html#os.system” rel=“noreferer”>

import os
os.system( cls  if os.name ==  nt  else  clear )

Why hasn t anyone talked about just simply doing Ctrl+L in Windows or Cmd+L in Mac. Surely the simplest way of clearing screen.

就我而言,最典型的变量是:

import os
os.system( cls||clear )

视窗、麦克风和赖恩可使用以下代码:

import subprocess, platform

if platform.system()=="Windows":
    if platform.release() in {"10", "11"}:
        subprocess.run("", shell=True) #Needed to fix a bug regarding Windows 10; not sure about Windows 11
        print("33c", end="")
    else:
        subprocess.run(["cls"])
else: #Linux and Mac
    print("33c", end="")

jamesnotjim测试了Mac的print ("33c”, end=",,我测试了该编码的有赖恩和Windows(视窗的t工作,因此使用其他代码cls)。 我不记得,我第一次看到使用<代码>("33c)和(或)印刷版:subprocess.run(printf 33c”、hell=True)

rolika指出,end=”将防止其随后印刷一个新的线路。

请注意,与旧版本不同的是,乌兰巴托的新版本将用<代码>clear(而不是仅仅通过滚滚滚而来)来清除屏幕上的微薄(似乎已经清除)。

请注意,将终端与ESC(“33c”)重新定位,将使 cur子得以强调和连接。 如果你不希望,你可以使用这些代码将它改成另一种风格(在GNOME终端3.44.0上测试,使用VTE 0.68.0 +BIDI +GNUTLS +ICU +SYSTEMD):

  • underscore blinking: "33[0 q"
  • block blinking: "33[1 q"
  • block: "33[2 q"
  • underscore blinking: "33[3 q"
  • underscore: "33[4 q"
  • thin bar blinking: "33[5 q"
  • thin bar: "33[6 q" (numbers above 6 seem to do this, too)

还指出,你可以做任何事情,以清除关于含水层的屏幕:

  • print("33c", end=""):
  • print("u001bc", end="")
  • print("U0000001bc", end="")
  • print("x1bc", end="")
  • subprocess.run(["clear"]) #This doesn t reset the whole terminal
  • subprocess.run( echo -ne "33c" , shell=True)
  • subprocess.run( echo -ne "ec" , shell=True)
  • subprocess.run( echo -ne "u001bc" , shell=True)
  • subprocess.run( echo -ne "U0000001bc" , shell=True)
  • subprocess.run( echo -ne "x1bc" , shell=True)
  • subprocess.run("printf 33c ", shell=True)
  • subprocess.run("printf ec ", shell=True)
  • subprocess.run("printf u001bc ", shell=True)
  • subprocess.run("printf U0000001bc ", shell=True)
  • subprocess.run("printf x1bc ", shell=True)

我认为,以下法典应当明确你必须掌握的内容,以便了解(但很难与另一个指挥部门一起使用,没有问题):

  • print("33[3J")

它可以做与<代码>clear相同的事情。 用于这样做(因此,你可以总结一下删除的内容,但将 cur子带上顶部的情况除外):

  • print("33[2J")

如果你处于一个Liberin/UNIX系统,那么就应当印刷ANSI的脱节顺序,以清除屏幕。 你也希望把 cur子转移到屏幕上。 这将在支持ANSI的任何终点站开展工作。

import sys
sys.stderr.write("x1b[2Jx1b[H")

除非ANSI提供支持,否则不会在Windows上工作。 视窗可能有一个类似的控制序列,但我不知道。

公正使用:

print("33c")

这将清除终端窗口。

一段时间前

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

然后使用清晰筛选()

你们可以努力依靠明确,但可能无法在所有的含水层分布上。 在窗户使用cl时,你提到。

import subprocess
import platform

def clear():
    subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)

clear()

注:对终端屏幕的控制可能被视为不好的形式。 你们是否考虑采用一种选择? 让用户决定他是否想要清除屏幕可能更好。

这两项工作将同时进行:

print (u"{}[2J{}[;H".format(chr(27), chr(27)))

因此,我只想把两点 throw在座......

没有人对欧佩组织的问题提供真正的答案,似乎每个人都要么与诺瓦特·德瓦尼埃的系统(NDO NT USE os.system(O)一起 evil! 没有解释或提供依靠印刷新线路的解决办法。

对于需要清除终端屏幕和排泄剂的人,无论出于何种原因,你均可使用以下代码:

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 )

这产生了预期的效果。 如果这种恶魔和有人知道采用分程序来实施,那么它确实使用“s.system()”指挥系统。

A Pure Python solution.
Does not rely on either ANSI, or external commands.
Only your terminal has to have the ability to tell you how many lines are in view.

from shutil import get_terminal_size
print("
" * get_terminal_size().lines, end=  )

甲型六氯环己烷

这一职能在定点上运行,因为缺席,它承认ANSI逃脱顺序。 它给你一个CLEAN PROMPTrows_max远离终点站,但恰恰是远离终点站。 要求你完全控制着多少东西。

def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
          store_max=[]):
    """clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don t clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
    from os import linesep
    if rows_max and rows_max != -1:
        store_max[:] = [rows_max, False]
    elif not store_max or store_max[1] or rows_max == -1 or absolute:
        try:
            from shutil import get_terminal_size
            columns_max, rows_max = get_terminal_size()
        except ImportError:
            columns_max, rows_max = 80, 24
        if absolute is None:
            store_max[:] = [rows_max, True]
    if store_max:
        if rows == -1:
            rows = store_max[0]
        elif isinstance(rows, float):
            rows = round(store_max[0] * rows)
        if rows > store_max[0] - 2:
            rows = store_max[0] - 2
    if absolute is None:
        s = ( 33[1A  +     * 30 if calling_line else   ) + linesep * rows
    else:
        s =  33[{}A .format(absolute + 2) + linesep
        if absolute > rows_max - 2:
            absolute = rows_max - 2
        s += (    * columns_max + linesep) * absolute +     * columns_max
        rows = absolute
    print(s +  33[{}A .format(rows + 1))

执行:

clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don t clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

参数:<代码>rows是指在终端的迅速和底层添加明确案文的行文数目,从而推动一切工作。 <代码>rows_max是文本行文中的终端高度(或最大结算高度),只需要一劳永逸,但可随时重新启用。 <代码>*、,在第三个参数的位置上,系指所有以下参数只是关键词(例如,明确(绝对=5)。 <条码>电话_line=True(default)在互动方式上更好。 <代码> 电话_line=False对基于文字的终端应用程序更有利。 absolute在缩小终点站面积后试图解决互动模式中的冰川差距问题,但也可用于终端应用。 价值;没有明确使用这一参数。 (如未通过<代码>的书库_max的论据,则更改<代码>的目录内容:max。) 改变该参数的违约值。 因此,长期储存。

便携式: Sorry, this don t work in IDLE, but it work >> VERY COOL << inactive way in a 起终点站(console)承认ANSI逃跑。 我在乌班图13.10中仅用3.3英诺梅-终点进行测试。 因此,我只能假定可移植性取决于<代码>shutil.get_terminal_size(size(BEST results)和ANSI的承认。

www.un.org/Depts/DGACM/index_spanish.htm 供互动使用: 第一版和过去版<代码>copy(......)以互动方式运作,看它是否为你工作。 如果是的话,上述职能就列入一份名为“清晰”的文件。 在终点站,有Python3。 进入:

>>> import sys
>>> sys.path
[  ,  /usr/lib/python3.3 , ...

现在,情况已经明显。 py file into one of the pathDirectories listed so , 即, 能够找到(说服任何现有档案)。 从现在起就很容易使用:

>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don t clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

www.un.org/Depts/DGACM/index_spanish.htm 用于终端应用: Put the copy(...) function into a file listed clear. 页: 1 这里是Tic Tac Toe游戏应用(从终点站起:python3 tictactoe.py):

from os import linesep

class TicTacToe:    
    def __init__(self):
        # Clear screen, but not calling line
        try:
            from clear import clear
            self.clear = clear
            self.clear(calling_line=False)
        except ImportError:
            self.clear = False
        self.rows = 0    # Track printed lines to clear

        # ...
        self.moves = [   ] * 9

    def do_print(self, *text, end=linesep):
        text = list(text)
        for i, v in enumerate(text[:]):
            text[i] = str(v)
        text =    .join(text)
        print(text, end=end)
        self.rows += text.count(linesep) + 1

    def show_board(self):
        if self.clear and self.rows:
            self.clear(absolute=self.rows)
        self.rows = 0
        self.do_print( Tic Tac Toe )
        self.do_print(      |   |
 {6} | {7} | {8}
   |   |
-----------
   |   |
 {3} | {4} | {5}
   |   |
-----------
   |   |
 {0} | {1} | {2}
   |   |   .format(*self.moves))

    def start(self):
        self.show_board()
        ok = input("Press <Enter> to continue...")
        self.moves = [ O ,  X ] * 4 + [ O ]
        self.show_board()
        ok = input("Press <Enter> to close.")

if __name__ == "__main__":
    TicTacToe().start()

解释:do_print(...) on line 19 is a edition of print(......) need to ensurelines of how many new Line have been published ( Self.rows). 否则,在全程打电话到<条码>(......)的地方,您就得自<条码>。 因此,每当委员会通过打电话show_板(<>)加以撤销时,前一个委员会即予撤销,新委员会应在什么地方印刷。 <通知代码>自行.clear(电话_line=False) on行文9基本将一切有关事宜推向终点站的底层,但并不清楚原来的电话线。 相比之下,<代码>本身.clear(asolute=本国.rows)第29条绝对明确了所有<代码>本身.rows的距离向上,而不是仅仅把所有东西推向终端底层。

乌班图用户,第3.3段:Put#!/usr/bin/env python3 缩略语 py file. 右边瞄准。 py file => Property => Permissions tab => Check Execute:Allow implementing file as program。 案卷上的双点点击=>Click Run in码头纽顿。 如果一个开放的终端站目前的目录是tic。 py file, You can alsostart the file with ./tictactoe.py.

如果你在使用平坐机时要清除您的终点。 然后,你可以做以下工作来清除屏幕。

import os
os.system( clear )

视窗可使用:

>>> import os
>>> clear = lambda: os.system( cls )
>>> clear()

可通过术语信息数据库删除,但这方面的职能载于<代码>。

python -c “ from os import system; system( clear )>

您可使用<条码>:功能执行终端指挥:

from subprocess import call
call("clear")

您可以自行决定。 这并不取决于您的终点站或专业单位的类型。

def clear(num):
    for i in range(num): print 

clear(80)
print "hello"

如果你们都需要清除屏幕,这或许是好的。 问题甚至没有100%的跨平台方式在中程式各样。 问题在于终端的安装,所有支持都略有不同。 我确信,“扫雷”将在各地发挥作用。 但是,比较“完整”的答案是使用X级控制特性来转移 cur子,但这本身也要求Xterm。

如果不了解你的更多问题,你的解决办法似乎足够好。

这将明确25条新行:

def clear():
    print(  
  * 25)

clear()

I use eclipse with pydev. I like the newline solution better than the for num in range . The for loop throws warnings, while the print newline doesn t. If you want to specify the number of newlines in the clear statement try this variation.

def clear(j):
    print(  
  * j)

clear(25)

或许是清扫屏幕的精干方法,但将在我知道的任何平台上工作的方法如下:

for i in xrange(0,100):
    print ""

我这样做是为了让更多的人看上去。

仅仅在家事局创建名为“开端”的档案,并在一项职能中使用烟 answer回答

关于LC:

echo "from subprocess import call
def clear(int=None):  
    call( clear )
    if int == 0:
       exit()
clear()" >> $HOME/.pythonstartup ; export PYTHONSTARTUP=$HOME/.pythonstartup ; python

页: 1 档案

由于我所关心的是空间;要求这一功能的人在启动时不会展示假肢描述,但你可以删除<代码>clear(,以保留。

借助于正常功能,在不印刷退出状况的情况下,应做到trick:

>>> clear()

如果你将第0号论点传到功能中,它将成功地清除屏幕,以便你能够继续用碎机在干净的屏幕上使用。

>>> clear(0)

For Windows, on the interpreter command line only (not the GUI)! Simply type: (Remember to use proper indentation with python):

import os
def clear():
    os.system( cls )

每当你打字(通向线)<代码>clear()时,就会在座标上打上屏幕。 如果你离开这辆车,那么当你打开新的Adhur(通向线)炮弹时,你必须再 above。

注:不值得注意的是,你正在使用什么版本(2.5、2.7、3.3和amp;3.4)。

可接受的答案是“。 问题在于,迄今为止,它只使用Windows 10、64/1和Mac。 是Windows(因缺乏ANSI支持而闻名)! 这一新特点在Windows 10(及以上)上得到了实施,其中包括ANSI的支持,尽管你们必须这样做。 这将以跨平台的方式清除屏幕:

import os

print ( Hello World )
os.system(  ) 
print ("x1B[2J")

然而,在“Windows 10”以下任何内容上,它还是:

[2J

这是因为在以前的Windows建筑上缺乏ANSI的支持。 然而,可以通过colorama模块加以解决。 这为Windows上的ANSI特性提供了支持:

长期以来,ANSI的越轨顺序一直被用于制作彩色的终端案文和位于Unix和Macs的曲线定位。 科罗拉马也把这项工作放在Windows上,其方法是总结 st,淡化其发现的ANSI序列(这似乎在产出中是可喜的),并将之转换成适当的双筒,以更改终端状态。 在其他平台上,科罗拉马没有任何东西。

因此,这里是一种跨平台方法:

import sys

if sys.platform ==  win32 :
    from colorama import init
    init()

print( Hello World )

print("x1B[2J")

(chr(27)+“[2J”>>,代替(”x1B[2J]


@poke的答案在Windows上非常不安全,但的确是一ck。 同一字典中的“cls.batcl.exe号文档将与指令发生冲突,而不是指挥,从而造成巨大的安全危害。

尽量减少风险的一种方法可以是改变<代码>cls的指挥地点:

import os
os.system( cd C:\Windows|cls  if os.name ==  nt  else  clear )

这将将Currant Dictionary to C:Window (backslash is important here) 然后执行。 <条码>C:Windows/code>始终存在,需要行政许可才能写到这里,从而在风险最小的情况下执行这一指挥。 另一种解决办法是,通过PowerShell而不是突击指挥部来管理指挥,因为指挥是防范这种弱点的。

这里还提到了其他方法:





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签