Python:运行脚本后退出IDLE

3

在我的 Python 代码/脚本运行结束后,我是否可以通过某种方式从 Windows 中退出 Python IDLE?

我尝试过以下方法:

import sys
sys.exit(0) # or exit(1)

这个似乎没有起作用。可能只是退出了正在运行的Python脚本的当前“进程”。

非常感谢。


3
为什么需要这样做?(如果我遇到这个问题,我会使用WinKill命令创建一个简短的AutoHotKey脚本,然后从我的Python脚本中调用它。) - Steven Rumbalski
3个回答

4
如果您可以从命令行运行IDLE(或编辑您的快捷方式),我在IDLE帮助中找到了这个内容。
If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.

这似乎意味着脚本正在IDLE内运行。我进行了简单的测试脚本,调用exit()会弹出一个框询问是否终止程序。点击是,脚本和IDLE都退出了。希望这有所帮助。


1
谢谢,这个方法可行,但是IDLE在退出前会提示我。能否不让它提示呢? - tim

4
这将完全按照您的要求执行,不会有提示。
import os
os.system("taskkill /f /im pythonw.exe")

2
谢谢,现在它可以工作了,但它也会关闭所有其他的Python程序。有没有可能只关闭shell? - ands

1

如果在Windows中从Python代码/脚本内部退出Python IDLE而不需要进一步提示,请尝试以下方法:

parent_pid = os.getppid()  # Get parent's process id
parent_process = None
for proc in psutil.process_iter(attrs=['pid']):  # Check all processes
    if proc.pid == parent_pid:  # Parent's Process class
        parent_process = proc
        break

if parent_process is not None:
    parent_process.kill()  # Kill the parent's process


这适用于IDLE,PyCharm甚至Windows命令行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接