2

I am currently using VS Code to learn Python . So i have to run scripts like 10-15 times a minute , just doing small edits and learning all things. I am running the scripts in integrated terminal of VS code

So apparently the terminal gets horribly cluttered and i have to always clear the terminal manually by running clear, I want the terminal to automatically get cleared every time I execute the Python script . Please note that I am not looking for a keyboard shortcut to clear terminal , rather I need the terminal to automatically clear the old output before displaying the output of the present script. I couldn't find anything that does this , hopefully someone can provide a way out

Musab Guma'a
  • 175
  • 2
  • 9
Sachin
  • 1,217
  • 2
  • 11
  • 31
  • 1
    This is not a duplicate and I am not satisfied with the accepted answer and all other answers. Why should we have to add extra lines of code for this. There should be a configuration feature builtin with VScode. Clear terminal before each run. Is it too much to ask? – AmanDeepSharma Jul 20 '21 at 04:39

3 Answers3

3

You could import os and then at the top of your script run os.system('clear')

Example:

import os
os.system('cls||clear') # this line clears the screen 'cls' = windows 'clear' = unix
# below is my main script
print("hello world!")
Jacques
  • 927
  • 9
  • 18
  • Yes working thanks , i am at a very early stage in learning Python so didn't knew it could done using python itself. I thought i would need to fiddle with some advanced settings in VSCode to achieve it – Sachin Jul 05 '20 at 14:50
3

A simple native vscode solution is to take advantage of a launch.json file configurable. Specifically:

internalConsoleOptions

Controls when the internal debug console should open

redirectOutput

Both of these used in tandem will open the 'Debug Console' instead of terminal and just provide the necessary output; though it still sends to terminal should you still want it:

"version": "0.2.0",
"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "internalConsoleOptions": "openOnSessionStart",
        "redirectOutput": true
    }
]

debug console

soulshined
  • 9,612
  • 5
  • 44
  • 79
1

Building on @Jacques answer, you can use the sys module to dynamically perform a platform check:

import os
import sys

# Linux
if sys.platform.startswith('linux'):
    os.system('clear')
# Windows
elif sys.platform.startswith('win32'):
    os.system('cls')

Alternatively, see this post on configuring vscode to do this for all programs: How do I automatically clear VS Code terminal when starting a build?

Jacques
  • 927
  • 9
  • 18
Musab Guma'a
  • 175
  • 2
  • 9