首页 > 解决方案 > 如何检测 Python 是否在 Git Bash 终端或 Windows cmd 中运行?

问题描述

我想让我的 Python 脚本能够检测它是在 Git Bash 终端还是在 Windows cmd 命令行界面中执行的。例如,我正在尝试编写一个函数来清除终端(无论它是哪个终端),例如,clear如果在 Git Bash 中或cls在 cmd 中,则回显命令。

我尝试使用 sys.platform 来检测这一点,但win32无论它运行在哪种类型的终端中,它都会返回。

标签: pythoncmdgit-bash

解决方案


请尝试使用ospsutil模块。

例如,

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

然后你可以有你的逻辑取决于外壳。

此外,您可能需要检查https://www.geeksforgeeks.org/clear-screen-python/


推荐阅读