【问题标题】:How to get type of hosting window from inside Python?如何从 Python 内部获取托管窗口的类型?
【发布时间】:2022-01-16 12:13:13
【问题描述】:

我想知道哪个窗口托管着运行 Python 的终端。具体来说,我想在 Windows 机器上区分 windows terminal 和旧的 CMD 控制台。

编辑: 我不确定我是否使用了正确的单词,并且无论如何都会出现大量单词。更具体地说,我想知道host window,因为他们有不同的行为。这是一张不同窗户的照片,其中一个是Windows Terminalpowershellcmd 可以在任一窗口中运行,我有兴趣找出那个窗口主机。

【问题讨论】:

标签: python shell cmd terminal console


【解决方案1】:

如果你使用 psutil 和 os 包,你可以使用

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

获取父进程的名称。

【讨论】:

  • 在两个终端上都得到了这个输出ipython.exe。我对托管外壳感兴趣。难道是知道这个的IPython?
  • @AlexDeft 这是因为您使用 ipython 运行程序,而不是直接从 cmd 或 powershell 运行。因为我不使用 Windows,所以真的帮不上什么忙。
  • 嗯,你想让我从终端本身运行它吗?那么是的,它有效。我刚试过python -c "import os;import psutil;print(psutil.Process(os.getppid()).name())"得到pwsh。我应该修改我的问题以突出显示 IPython 吗?
  • 请看修改后的问题
【解决方案2】:

您可以查询WMI,因为我更喜欢使用操作系统工具(也应该使用psutil,正如@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)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2023-01-31
    • 2019-01-26
    • 2011-02-26
    • 2022-10-04
    相关资源
    最近更新 更多