2

I'd like to give my Python scripts the ability to detect whether it was executed in a Git Bash terminal, or the Windows cmd command line interface. For example, I'm trying to write a function to clear the terminal (regardless of which terminal it is), e.g. echoes the clear command if in Git Bash, or cls if in cmd.

I've tried using sys.platform to detect this, but it returns win32 regardless of which type of terminal it was ran in.

oguz ismail
  • 1
  • 16
  • 47
  • 69
mbg117
  • 35
  • 5

2 Answers2

2

Please try using os and psutil modules.

For example,

import os, psutil  # Get the parent process name. 
pprocName = psutil.Process(os.getppid()).name()

Then you can have your logic depending on the shell.

Additionally, you may want to check https://www.geeksforgeeks.org/clear-screen-python/

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
programandoconro
  • 2,378
  • 2
  • 18
  • 33
  • 2
    This works. Tested with Command Prompt, Powershell, and Git Bash in a Windows x64 environment. Output will return cmd.exe, powershell.exe, or winpty-agent.exe respectively. This output, combined with the output from the sys.platform module in a conditional statement, will enable a user to issue terminal commands that are effectively shell agnostic, as well as os agnostic if desired. – mbg117 Oct 18 '21 at 07:18
0

I don't believe what you're asking for is possible, but there are several answers here that show all the detections you can do to use the correct type of clear. Usually, it's just best to either make your own window or not clear the screen, sadly.

hopperelec
  • 133
  • 1
  • 2
  • 13