Sunday, 31 January 2021

How do I get the parent shell's path on windows in pure python?

The following will return the shell that launched the current process & the shell's full path. However, it uses a python library full of c extensions. Sometimes a shell launches a shell, etc. I'm just looking for the "most recent ancestor" process that is a shell.

How do I do this with just pure python? (i.e. no c extensions, using windll.kernel32 and the like are fine- of course at some point to get process info code will have to access platform-specific native code, it just needs to be something already buried in the python standard library, not something that needs compiling c)

Shellingham at the moment can't do this.

from typing import Tuple, List

import os

import psutil

SHELL_NAMES = {
    'sh', 'bash', 'dash', 'ash',    # Bourne.
    'csh', 'tcsh',                  # C.
    'ksh', 'zsh', 'fish',           # Common alternatives.
    'cmd', 'powershell', 'pwsh',    # Microsoft.
    'elvish', 'xonsh',              # More exotic.
}

def find_shell_for_windows() -> Tuple[str,str]:
    names_paths:List[Tuple[str,str]]=[]
    current_process = psutil.Process(os.getppid())
    process_name, process_path = current_process.name(), current_process.exe()
    names_paths.append((process_name, process_path))
    for parent in current_process.parents():
        names_paths.append((parent.name(), parent.exe()))
    for n,p in names_paths:
        if n.lower() in SHELL_NAMES or n.lower().replace(".exe","") in SHELL_NAMES:
            return n,p
    return ["",""]

if __name__ == '__main__':
    print(find_shell_for_windows())


from How do I get the parent shell's path on windows in pure python?

No comments:

Post a Comment