我需要检查我的Python脚本是否在Windows终端内部运行(而不是cmd.exe,Powershell,bash等)。
如何才能做到这一点呢?
我可以提供这种方法:
is_windows_terminal = sys.platform == "win32" and os.environ.get("WT_SESSION")
但也许有更干净的解决办法。。。
您可以获取运行/派生进程的父进程id(PID
),并运行python脚本,然后在windows CMD的任务列表中搜索,并查看此PID
属于WHOWN:
在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>"