【问题标题】:How do I detect if my Python script is running in the 'Windows Terminal'如何检测我的 Python 脚本是否在“Windows 终端”中运行
【发布时间】:2020-11-02 18:51:25
【问题描述】:

我需要检查我的 Python 脚本是否在 Windows Terminal 内运行(而不是 CMD.exe、Powershell、bash 等)。

如何做到这一点?

【问题讨论】:

    标签: python windows-terminal


    【解决方案1】:

    您可以获得运行/生成并运行您的 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>"
    

    【讨论】:

      【解决方案2】:

      我可以提供这种方法:

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

      但可能有更清洁的解决方案...

      【讨论】:

        猜你喜欢
        • 2020-05-01
        • 2021-12-04
        • 2011-10-20
        • 1970-01-01
        • 1970-01-01
        • 2020-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多