3

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.

5
  • Try using os and psutil modules. For example, import os, psutil # Get the parent process name. pprocName = psutil.Process(os.getppid()).name() Commented Oct 17, 2021 at 5:23
  • Also, please check this geeksforgeeks.org/clear-screen-python Commented Oct 17, 2021 at 5:26
  • Thanks, your example works for my particular use case. Commented Oct 17, 2021 at 5:45
  • Cool, I am glad to help. Do you want me to add it as an answer? Commented Oct 17, 2021 at 6:16
  • Yeah go for it. Commented Oct 17, 2021 at 6:28

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.