清除输出并用python重写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37071230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:45:59  来源:igfitidea点击:

Clear output and rewrite it in python

pythonpython-3.x

提问by Anton M

Hi I'm trying to make a tic tac toe game in python and I've run into a problem. enter image description here

嗨,我正在尝试用 python 制作井字游戏,但遇到了一个问题。 在此处输入图片说明

As you can see on the picture it rewrites the playing board after your input, what I want it to do is to clear the output and then rewrite the board. So instead of just printing new boards all the time it only clears the current board and rewrites it. I've searched on "clear output" etc, but all I find is these kind of codes:

正如您在图片上看到的那样,它在您输入后重写了播放板,我想要它做的是清除输出然后重写板。因此,它不是一直打印新板,而是只清除当前板并重写它。我搜索了“清除输出”等,但我发现的只是这些代码:

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

or

或者

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

Using this clear function above don't work for me. It only returns this symbol:enter image description here

使用上面的这个 clear 函数对我不起作用。它只返回这个符号:在此处输入图片说明

I am currently writing my code in Pycharm and just to make it clear, I wanna keep it in pycharm.

我目前正在 Pycharm 中编写代码,为了清楚起见,我想将其保留在 pycharm 中。

回答by devil in the detail

Adding following in jupyter worked for me:

在 jupyter 中添加以下内容对我有用:

from IPython.display import clear_output
clear_output(wait=True)

回答by Barry Scott

I see a syntax error from your code, you are missing the ":".

我从您的代码中看到语法错误,您缺少“:”。

clear = lambda : os.system('cls')

However avoid lambda and define a function for clear because it is easier to read.

然而,避免使用 lambda 并定义一个 clear 函数,因为它更容易阅读。

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

then you can clear the window with:

然后您可以使用以下命令清除窗​​口:

clear()

回答by kmaork

clscommand will not clear the output when you run your code in pycharm. It will work if you run it in cmd - python <pathTOPyFile>

cls在 pycharm 中运行代码时,命令不会清除输出。如果您在 cmd 中运行它,它将起作用-python <pathTOPyFile>

回答by kmaork

You can include the following in the beginning of your code, to make it call itself from cmd and exit if it isn't in cmd already:

您可以在代码的开头包含以下内容,使其从 cmd 调用自身并退出(如果它不在 cmd 中):

import os
import sys
import subprocess

clear = lambda: os.system('cls')

if len(sys.argv) < 2:
    subprocess.call('cmd /K python "' + sys.argv[0] + '" cmd')
    exit(0)

print 'this was cleared'
clear()

回答by erfan karimian

if you use it in linux

如果你在linux中使用它

def clear():
os.system( 'clear')

回答by Specter Paul

First, install IPython using the Python package installer pip:

首先,使用 Python 包安装程序 pip 安装 IPython:

pip install IPython

In your script write the following

在你的脚本中写下以下内容

form IPython.display import clear_output

I guess by now it should be working

我想现在它应该可以工作了