简体   繁体   English

如何检测我的 Python 脚本是否在“Windows 终端”中运行

[英]How do I detect if my Python script is running in the 'Windows Terminal'

I need to check if my Python script is running inside the Windows Terminal (as opposed to the CMD.exe, Powershell, bash, etc.).我需要检查我的 Python 脚本是否在Windows 终端内运行(相对于 CMD.exe、Powershell、bash 等)。

How can this be done?如何才能做到这一点?

I can offer this approach:我可以提供这种方法:

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

But there may be a cleaner solution...但可能有一个更清洁的解决方案......

you can get the parent process id ( PID ) for the process that run/spawned and run your python script and search in the tasklist in windows CMD and see this pid belongs to whom:您可以获取运行/生成并运行 python 脚本的进程的父进程 ID ( PID ),并在 windows CMD 的任务列表中搜索并查看此pid属于谁:

In you python script add those lines在您的 python 脚本中添加这些行

import psutil
my_father_pid = str(psutil.Process().ppid())
print my_father_pid   # or print(my_father_pid) in python3

Now search for 'my_father_pid` that you have get, in the task list:现在在任务列表中搜索您获得的“my_father_pid”:

tasklist /v  | findstr "<my_father_pid>"

I have created a package for this problem: https://pypi.org/project/AssertWT/我为这个问题创建了一个 package: https://pypi.org/project/AssertWT/

import assertwt
assertwt.is_wt()  # True,False

The source code for the is_wt method can be found on github is_wt方法的源码可以在github找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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