代码之家  ›  专栏  ›  技术社区  ›  mar10

如何检测Python脚本是否在“Windows终端”中运行

  •  0
  • mar10  · 技术社区  · 4 年前

    Windows Terminal (与命令行,Powershell、bash等)。

    如何做到这一点?

    0 回复  |  直到 4 年前
        1
  •  0
  •   mar10    4 年前

    我可以提供这种方法:

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

    但也许有更干净的解决办法。。。

        2
  •  0
  •   Adam    4 年前

    PID )对于运行/派生并运行python脚本的进程,请在windows CMD的tasklist中搜索 pid

    在python脚本中添加这些行

    import psutil
    my_father_pid = str(psutil.Process().ppid())
    print my_father_pid   # or print(my_father_pid) in python3
    

    现在在任务列表中搜索您得到的“我的父亲”:

    tasklist /v  | findstr "<my_father_pid>"
    
    推荐文章