簡體   English   中英

如何檢測我的 Python 腳本是否在“Windows 終端”中運行

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

我需要檢查我的 Python 腳本是否在Windows 終端內運行(相對於 CMD.exe、Powershell、bash 等)。

如何才能做到這一點?

我可以提供這種方法:

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

但可能有一個更清潔的解決方案......

您可以獲取運行/生成並運行 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>"

我為這個問題創建了一個 package: https://pypi.org/project/AssertWT/

import assertwt
assertwt.is_wt()  # True,False

is_wt方法的源碼可以在github找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM