How to get type of hosting window from inside Python?

Viewed 65

I would like to know which window is hosting the terminal running Python. In specific, I would like to distinguish between windows terminal and the old CMD console on Windows machine.

EDIT: I'm not sure I'm using correct words and there is an overload of words anyway. To be more specifc, I want to know the host window becaue they have different behaviours. Here's a photo of different windows, one of which Windows Terminal. powershell or cmd can be run in either of the windows, I'm interested in figuring out that window host.

enter image description here

2 Answers

If you use the psutil and os packages, you can use

parent_pid = os.getppid()
print(psutil.Process(parent_pid).name())

to get the parent process' name.

You could query WMI as I prefer to use OS tools (should work with psutil aswell, as mentioned by @BaguetteYeeter):

import os
import subprocess
import sys

print("Python interpreter: %s" % sys.executable)
parentShellName = None
# root process to look for parents until we find a process name
# which has not python in it's name
parentPid = os.getpid()

while 1:
    # In case of ipython the second parent process is the Shell, so we are looping!
    # Probably there should be a counter to finish the while loop in case no shell could be detected!
    cmd = 'wmic process where "ProcessId=%s" get parentprocessid /format:list' % parentPid
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, err = proc.communicate()
    key, parentPid = out.strip().decode('utf-8').split('=')

    print("Parent ProcessId: %s" % parentPid)

    cmd2 = 'wmic process where "ProcessId=%s" get name /format:list' % parentPid
    proc = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, err = proc.communicate()
    key, parentShellName = out.strip().decode('utf-8').split('=')

    if 'python' not in parentShellName.lower():
        break

print(parentShellName)

Out:

enter image description here

Related