首页 > 解决方案 > subprocess.Popen 返回不存在的 pid - Windows 10

问题描述

我正在尝试打开一个进程,等待几分钟然后关闭它。我正在使用 Windows 10 和 python 3.7。使用 subprocess.Popen 时,程序可以正常打开,但是当我尝试关闭使用多个选项时,没有任何效果。proc.pid 似乎没有有效的 PID,所以无论我如何尝试关闭它,都没有任何效果。知道该怎么做吗?

import subprocess
import signal
import os
import time
import psutil

def kill_proc_tree(pid, including_parent=True):
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    for child in children:
        child.kill()
    gone, still_alive = psutil.wait_procs(children, timeout=5)
    if including_parent:
        parent.kill()
        parent.wait(5)

def kill_child_processes(parent_pid, sig=signal.SIGTERM):
    try:
      parent = psutil.Process(parent_pid)
    except psutil.NoSuchProcess:
      return
    children = parent.children(recursive=True)
    for process in children:
      process.send_signal(sig)

proc = subprocess.Popen([r"C:\Program Files (x86)\Google\Chrome\Application\chrome_proxy.exe",
                  '--profile-directory=Default',
                  '--app-id=asdbiflszpsdsdn'])

time.sleep(5)
os.kill(proc.pid, signal.SIGTERM) #or signal.SIGKILL
proc.terminate()
proc.kill()
kill_proc_tree(proc.pid, True)
kill_child_processes(proc.pid)
os.killpg(proc.pid, signal.SIGTERM)
subprocess.Popen("taskkill /F /T /PID %i"%proc.pid , shell=True)

os.kill(proc.pid, signal.SIGTERM)

标签: pythonoperating-systemsubprocess

解决方案


推荐阅读