Python:脚本运行后退出IDLE

时间:2014-06-04 18:35:22

标签: python exit python-idle

是否有可能以某种方式在运行后从我的python代码/脚本中以某种方式退出Windows下的Python IDLE?

我尝试过类似的事情:

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

没用。可能只退出正在运行的python脚本的当前“进程”。 非常感谢

3 个答案:

答案 0 :(得分: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 :(得分:2)

这将完全符合您的要求。没有提示。

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

答案 2 :(得分:0)

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