<p>不幸的是,没有简单的方法可以做到这一点。您需要使用<code>psutil</code>和<code>signal</code>模块。为此,您需要安装<code>psutil</code>,最好的方法是通过<code>pip</code>:</p>
<pre><code>pip install psutil
</code></pre>
<p>所以,假设我们在这里,展示一:</p>
<pre><code>while True:
try:
time.sleep(3)
print "Zzzz"
time.sleep(3)
print("gong!")
except KeyboardInterrupt as e:
print "Closed by an Interrupt"
break
</code></pre>
<p>你在PyCharm管理这个。确保正在使用的解释器已安装<code>psutils</code>。您可以检查:</p>
<p><img src="https://i.stack.imgur.com/e2bqv.png" alt="enter image description here"/></p>
<p>确保您正确设置了口译员:</p>
<p><img src="https://i.stack.imgur.com/b5NJa.png" alt="enter image description here"/></p>
<p>如果尚未安装<code>psutil</code>,则始终可以通过<kbd>安装</kbd>按钮进行安装。</p>
<p>好吧,那么现在我们已经设置好了所有内容,让我们调试程序:</p>
<p><img src="https://i.stack.imgur.com/x5mUF.png" alt="enter image description here"/></p>
<p>现在我们要做的就是得到进程ID,我们可以在程序的一开始就得到它:</p>
<p><img src="https://i.stack.imgur.com/8DiQt.png" alt="enter image description here"/></p>
<p>所以,让我们打开控制台,发送一个信号:</p>
<p><img src="https://i.stack.imgur.com/i94Ve.png" alt="enter image description here"/></p>
<p>如果工作正常,您应该看到while循环结束:</p>
<p><img src="https://i.stack.imgur.com/jVIIg.png" alt="enter image description here"/></p>
<p>通过在控制台的启动脚本中添加发送中断的函数,可以进一步简化此过程:</p>
<p><img src="https://i.stack.imgur.com/uLGW0.png" alt="enter image description here"/></p>
<p>完成所有这些操作后,只需调用<code>interrupt(<pid here>)</code>来调用进程中的键盘中断。</p>
<p>我希望这能回答你的问题。</p>