<p>由于您已经在使用<code>psutil</code>,我建议您将对<code>subprocess</code>模块的调用替换为对{a1}的调用。此类具有相同的<code>subprocess.Popen</code>接口,但提供<code>psutil.Process</code>的所有功能。在</p>
<p>还要注意,<code>psutil</code>库已经预先检查PID重用了</strong>,至少有很多方法包括<code>terminate</code>和{<cd8>}(只需阅读<a href="http://pythonhosted.org/psutil/#psutil.Popen" rel="nofollow">documentation for ^{<cd9>}</a>)。在</p>
<p>这意味着以下代码:</p>
<pre><code>cmd = ["bash", "script.sh", self.get_script_path()]
process = psutil.Popen(cmd)
time.sleep(10) # process running here...
children = process.children(recursive=True)
for child in children:
child.terminate() # try to close the process "gently" first
child.kill()
</code></pre>
<p>请注意,<code>children</code>的文档说明:</p>
<blockquote>
<p><strong>children(recursive=False)</strong></p>
<p>Return the children of this process as a list of <code>Process</code> objects, <strong>preemptively checking whether PID has been reused.</strong></p>
</blockquote>
<p>总之,这意味着:</p>
<ol>
<li>当您调用<code>children</code>时,<code>psutil</code>库会检查是否需要正确进程的子进程,而不是恰好具有相同pid的进程的子进程</li>
<li>当您调用<code>terminate</code>或<code>kill</code>时,库会确保您正在杀死子进程,而不是一个具有相同pid的随机进程。在</li>
</ol>