【问题标题】:Clear/overwrite standard output in Python在 Python 中清除/覆盖标准输出
【发布时间】:2016-05-06 11:27:11
【问题描述】:

您好,我正在尝试用 Python 制作井字游戏,但遇到了问题。

正如你在图片上看到的那样,它在输入后重写了棋盘,我想要它做的是清除输出然后重写棋盘。因此,与其一直打印新板,不如只清除当前板并重写它。我搜索了“清除输出”等,但只找到了这些 sn-ps:

import os

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

import os

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

但是,它对我不起作用。它只返回这个符号:

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

【问题讨论】:

  • 您确定实际调用了 clear 函数吗? clear()
  • 是的,但它只返回了这个符号:i.gyazo.com/d928370f9a4ebaf1ba3d7e07142d7489.png 对不起,我可以提到它:P
  • 您是否尝试过在终端中运行您的代码(即在 Pycharm 之外)?
  • 不,我没有,但我有点想使用 pycharm,因为我喜欢它作为 IDE。 @SiHa
  • 好的,但这很可能是您的代码不起作用的原因。 IDE 用于开发(因此得名),实际上您的代码将在此环境之外运行。根据我的经验,当您尝试执行此类非标准操作时,IDE 会崩溃,因为它们只是在模拟 CMD 窗口。另见stackoverflow.com/questions/27241268/clear-pycharm-run-window

标签: python python-3.x command-line-interface stdout


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    但是避免使用 lambda 并为 clear 定义一个函数,因为它更易于阅读。

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

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

    clear()
    

    【讨论】:

    • 当我使用 clear 时它只返回 i.gyazo.com/d928370f9a4ebaf1ba3d7e07142d7489.png
    • 你在哪里运行你的代码?鉴于您正在使用 CLS,这意味着您是 Windows 并在 CMD.exe 窗口中运行 python。如果你不尝试,看看是否能解决问题。
    • 我在 pycharm 中运行我的代码,这可能是 'cls' 不起作用的原因,但这是我尝试谷歌搜索时发现的唯一方法。
    【解决方案3】:

    在 Python for Linux 中清除控制台输出的代码:

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

    【讨论】:

      【解决方案4】:

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

      pip install IPython
      

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

      form IPython.display import clear_output
      

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

      【讨论】:

        【解决方案5】:

        这取决于操作系统, 如果你想确定你能做到:

        import os, platform
        def clear():
           if platform.system() == 'Windows':
              os.system('cls')
           else:
              os.system('clear')
        

        并调用函数:

        clear()
        

        但如果您只想要 Windows 操作系统(Windows 10/11/7/8/8.1 ecc..)就可以了:

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

        你也这么称呼它:

        clear()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-27
          • 2010-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-06
          • 2023-04-08
          相关资源
          最近更新 更多