此答案目前特定于 Windows,但理论上可以重新配置以与其他操作系统一起使用。您可以使用 subprocess 模块和 Windows tasklist 命令显式获取 Python 程序的父进程的名称,而不是像大多数这些答案推荐的那样安装 psutil 模块。
import os
import subprocess
shells = {"bash.exe", "cmd.exe", "powershell.exe", "WindowsTerminal.exe"}
# These are standard examples, but it can also be used to detect:
# - Nested python.exe processes (IDLE, etc.)
# - IDEs used to develop your program (IPython, Eclipse, PyCharm, etc.)
# - Other operating system dependent shells
s = subprocess.check_output(["tasklist", "/v", "/fo", "csv", "/nh", "/fi", f"PID eq {os.getppid()}"])
# Execute tasklist command to get the verbose info without the header (/nh) of a single process in CSV format (/fo csv)
# Such that its PID is equal to os.getppid()
entry = s.decode("utf-8").strip().strip('"').split('","')
# Decode from bytes to str, remove end whitespace and quotations from CSV format
# And split along the quote delimited commas
# This process may differ and require adjustment when used for an OS other than Windows
condition = entry and entry[0] in shells
# Check first that entry is not an empty sequence, meaning the process has already ended
# If it still exists, check if the first element -- the executable -- exists as an element of the set of executables you're looking for
我希望这对任何寻求此问题的答案的人有所帮助,同时最大限度地减少您需要的依赖项数量。
这是在 Python 3.8 中测试的,并在代码的subprocess.check_output 行中使用了 f 字符串,因此如果您之前使用过 Python 版本,请务必将 f 字符串转换为兼容的语法引入了 f 字符串。