Python:在脚本运行后退出空闲状态

Python:在脚本运行后退出空闲状态,python,exit,python-idle,Python,Exit,Python Idle,运行结束后,是否可以在我的Python代码/脚本中退出Windows下的Python IDLE 我试过这样的方法: import sys sys.exit(0) # or exit(1) 没用。可能只会退出正在运行的python脚本的当前“进程”。 非常感谢如果您可以从命令行运行IDLE(或编辑快捷方式),我在IDLE帮助中找到了这一点 If IDLE is started with the -n command line switch it will run in a single proc

运行结束后,是否可以在我的Python代码/脚本中退出Windows下的Python IDLE

我试过这样的方法:

import sys
sys.exit(0) # or exit(1)
没用。可能只会退出正在运行的python脚本的当前“进程”。
非常感谢

如果您可以从命令行运行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.

这似乎意味着脚本正在空闲中运行。我编写了一个快速测试脚本,调用
exit()
弹出一个框,要求终止程序。单击yes,脚本和IDLE都退出。希望能有所帮助。

这正是你想要的。没有提示

import os
os.system("taskkill /f /im pythonw.exe")

要在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中的命令行。

为什么需要这样做?(如果我有这个问题,我会使用这个命令创建一个简短的自动热键脚本,然后从我的Python脚本中调用它。)谢谢,这是可行的,但是IDLE会在退出之前提示我。避免这种提示是很好的——不知怎么可能!?谢谢,它现在可以工作了,但它也会杀死所有其他python程序。有可能只杀死贝壳吗?