【发布时间】:2020-11-02 18:51:25
【问题描述】:
我需要检查我的 Python 脚本是否在 Windows Terminal 内运行(而不是 CMD.exe、Powershell、bash 等)。
如何做到这一点?
【问题讨论】:
我需要检查我的 Python 脚本是否在 Windows Terminal 内运行(而不是 CMD.exe、Powershell、bash 等)。
如何做到这一点?
【问题讨论】:
您可以获得运行/生成并运行您的 python 脚本的进程的父进程 ID (PID),并在 windows CMD 的任务列表中搜索并查看此 pid 属于谁:
在你的 python 脚本中添加这些行
import psutil
my_father_pid = str(psutil.Process().ppid())
print my_father_pid # or print(my_father_pid) in python3
现在在任务列表中搜索您获得的“my_father_pid”:
tasklist /v | findstr "<my_father_pid>"
【讨论】:
我可以提供这种方法:
is_windows_terminal = sys.platform == "win32" and os.environ.get("WT_SESSION")
但可能有更清洁的解决方案...
【讨论】: