Как очистить консоль в pycharm командой
Перейти к содержимому

Как очистить консоль в pycharm командой

  • автор:

 

Очистить окно запуска PyCharm

Есть ли способ очистить консоль «Выполнить» в PyCharm? Мне нужен код, который удаляет / скрывает все ранее сделанные print (). Как кнопка «clear_all», но без необходимости нажимать ее вручную.

Я читал, что есть способ сделать это в терминале с помощью os.system («cls»), но в PyCharm он добавляет только маленький квадрат, ничего не очищая.

Кроме того, я не хочу использовать print («\ n» * 100), так как не хочу иметь возможность прокручивать назад и видеть предыдущие отпечатки.

12 ответов

Как

  1. Загрузите этот пакет https://github.com/asweigart/pyautogui. Это позволяет питону отправлять нажатия клавиш.

Возможно, вам сначала придется установить некоторые другие пакеты

Если вы устанавливаете PyAutoGUI из PyPI с помощью pip:

Windows не имеет зависимостей. Расширения Win32 устанавливать не нужно.

OS X требует установленных модулей pyobjc-core и pyobjc (в указанном порядке).

Linux требует установленного модуля python3-xlib (или python-xlib для Python 2). Необходимо установить Pillow, а в Linux вам может потребоваться установить дополнительные библиотеки, чтобы убедиться, что PNG / JPEG Pillow работает правильно. Видеть:

  1. Установите сочетание клавиш для очистки окна запуска в pycharm, как объяснил Тайлан Айдынли.
  1. CMD + (или настройки Pycharm);
  1. Поиск: «очистить все»; Двойной щелчок ->
  1. Добавить сочетание клавиш (установите для него CTRL + L или что-нибудь еще)
  1. Наслаждайтесь этой новой горячей клавишей в консоли Pycharm!

Затем, если вы установите сочетание клавиш для «очистить все» на Command + L , используйте это в своем скрипте python

Пример программы

Это очистит экран после того, как пользователь введет ввод.

Если вы не сфокусированы на окне инструментов, ваша чистая горячая клавиша не будет работать, вы можете убедиться в этом сами, если попробуете нажать горячую клавишу, когда, скажем, на редакторе, вы не очистите содержимое встроенных терминалов.

PyAutoGUI не имеет возможности напрямую сосредоточиться на окнах, чтобы решить эту проблему, вы можете попытаться найти координату, в которой расположен терминал запуска, а затем отправить левый щелчок для фокусировки, если вы еще не знаете координаты, по которым вы можете щелкнуть мышью вы можете узнать это с помощью следующего кода:

А теперь собственно код:

Простой метод: ярлык: Control K, щелкните правой кнопкой мыши терминал и очистите буфер

Просто щелкните значок корзины слева от окна команд, и история команд очистится!

Pycharm Community Edition 2020.1.3

Вы можете щелкнуть правой кнопкой мыши в любом месте над текущей строкой на консоли и выбрать опцию «Очистить все». Это очистит консоль

enter image description here

В терминале PyCharm вы можете ввести cls, как в терминале Linux.

Для консоли Python (где вы видите результат) назначьте сочетание клавиш для «очистить все» в меню «Файл» -> «Настройки» -> «Раскладка» -> «Другое» -> «Очистить все».

Вы также можете щелкнуть где-нибудь в консоли Python -> Правая кнопка -> очистить.

Надеюсь, это поможет

Я просто сообщил, что вместо того, чтобы создавать ярлык, вы можете просто настроить команду с помощью PyAutoGUI, чтобы щелкнуть мусорное ведро сбоку окна, например

Обратите внимание, чтобы установить pyautogui, щелкните в конце строки import pyautogui , затем нажмите alt + enter и щелкните установить pyautogui.

(это не идеально из-за времени, необходимого для запуска кода и использования мыши, но это разумное решение в зависимости от того, для чего вы его используете.) Я надеюсь, что этот ответ будет полезен, хотя это старый вопрос.

how to clear the screen in pycharm

I know these are questions: this and this and this. I have tried all of these methods in pycharm, but they either a) not work or b) I get a weird character on my screen, that looks like a 0 with diagonal line going through it. I can’t copy it for some reason, so I can’t show you.

For instance this:

What should happen in the above is tht the message should be displayed for 5 seconds then disappear, but all I get is that weird character. In contrast when I ran my python program from command line, it worked as expected i.e. the screen cleared. I am very confused.

So my questions are:

Why don’t any of them work in pycharm?

What does work in pycharm?

 

khelwood's user avatar

4 Answers 4

Ok, so, I have been having this problem as well — after scouring the internet, the os commands work BUT you need to enable the terminal emulator.

In the PyCharm toolbar, click Run, Edit Configurations, and the toggle for "Emulate Terminal in Output Console" should be under Execution in the pop up. Emulate Terminal toggle

I had to get help from the PyCharm team on this one, so here’s to them responding at lightning speed.

Answer
The cls command doesn’t work on a standard pycharm project because it is an IDE and certain os commands don’t work in the same way it would with the windows command line.

There is currently no way to clear the console output in PyCharm, other than to manually do it by using the cls command through the terminal in PyCharm or through a keyboard shortcut set through the pycharm preferences menu. You can try to emulate a keyboard shortcut, but this would be difficult, and unless you absolutely need it, I would not recommend clearing the terminal output after a program is run.

I don’t know in which version of PyCharm this was introduced. I guess it must have been after this question was asked.

The way to clear the PyCharm Python Console is by using the context menu. Right mouse click in the upper part of the console (where the lines with >>> prompts are closer together) and select Clear All .
Alse see this PyCharm Support Community article.

enter image description here

Incidentally, none of the questions linked to in the OP’s original post relate to PyCharm and do not answer the OP’s question.

Clear PyCharm Run Window

Is there a way to clear the «Run» console in PyCharm? I want a code that delete/hide all the print() made previously. Like the «clear_all» button, but without having to press it manually.

I have read that there is a way to do it in a terminal with os.system(«cls»), but in PyCharm, it only adds a small square without clearing anything.

Also, I don’t want to use print(«\n» *100) since I don’t want to be able to scroll back and see the previous prints.

13 Answers 13

  1. CMD + , (or Pycharm preferences);
  2. Search: «clear all«;
  3. Double click ->Add keyboard shortcut (set it to CTRL + L or anything)
  4. Enjoy this new hot key in your Pycharm console!

Taylan Aydinli's user avatar

Pycharm Community Edition 2020.1.3

You can right click anywhere above the current line on the console, and choose the "Clear All" option. It’ll clear the console

enter image description here

Krishnakant Pandey's user avatar

How to

  1. Download this package https://github.com/asweigart/pyautogui. It allows python to send key strokes.

You may have to install some other packages first

If you are installing PyAutoGUI from PyPI using pip:

Windows has no dependencies. The Win32 extensions do not need to be installed.

OS X needs the pyobjc-core and pyobjc module installed (in that order).

Linux needs the python3-xlib (or python-xlib for Python 2) module installed. Pillow needs to be installed, and on Linux you may need to install additional libraries to make sure Pillow’s PNG/JPEG works correctly. See:

  1. Set a keyboard shortcut for clearing the run window in pycharm as explained by Taylan Aydinli
  1. CMD + , (or Pycharm preferences);
  1. Search: "clear all"; Double click ->
  1. Add keyboard shortcut (set it to CTRL + L or anything)
  1. Enjoy this new hot key in your Pycharm console!

Then if you set the keyboard shortcut for ‘clear all’ to Command + L use this in your python script

Example program

This will clear the screen after the user types an input.

If you aren’t focused on the tool window then your clear hot-key won’t work, you can see this for yourself if you try pressing your hot-key while focused on, say, the editor, you won’t clear the embedded terminals contents.

PyAutoGUI has no way of focusing on windows directly, to solve this you can try to find the coordinate where the run terminal is located and then send a left click to focus, if you don’t already know the coordinates where you can click your mouse you can find it out with the following code:

Как очистить консоль python?

Пишу простой алгоритм reinforcement learning, в котором есть простенькая анимация, посредствам вывода в консоль. Так вот, чтобы показать новый кадр анимации, мне надо как-то эту консоль очистить. Сейчас использую print(100*’\n’), но это выглядит не очень красиво из-за прокрутки консоли. Использую PyCharm IDE, если это важно. Пробовал os.system(‘cls’) и print(‘\k’) — не работает. Можно ли как-то очищать консоль, чтобы заново выводить в нее новый кадр анимации?

P.S. Стоит добавить: кадр — квадратная матрица размера n, каждый элемент которой — отдельный символ: =, если клетка пустая, А — если в клетке агент, Е — если в клетке враг. Матрица обновляется и выводится новый кадр. Сейчас n=7. Общее количество кадров заранее не может быть известно.

  • Вопрос задан более двух лет назад
  • 25909 просмотров
  • Facebook
  • Вконтакте
  • Twitter

hottabxp

Вот такое в Linux работает:

У вас наверное windows. И пробовать нужно в консоли ОС, а не в консоли PyCharm. Ведь странно было бы, если бы для запуска программы(или игру) нужно было бы устанавливать среду разработки)

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *