1

我需要检查我的 Python 脚本是否在Windows 终端中运行(而不是 CMD.exe、Powershell、bash 等)。

如何才能做到这一点?

4

2 回答 2

0

您可以获取PID运行/生成并运行您的 python 脚本的进程的父进程 id (),并在 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>"
于 2020-07-13T14:57:46.240 回答
0

我可以提供这种方法:

is_windows_terminal = sys.platform == "win32" and os.environ.get("WT_SESSION")

但可能有一个更清洁的解决方案......

于 2020-07-13T14:51:02.150 回答