简体   繁体   中英

How to detect if Python is running in Git Bash terminal, or Windows cmd?

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), eg 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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM