Python: 脚本运行后退出IDLE
有没有办法在我的Python代码/脚本运行结束后,从Windows的Python IDLE中退出呢?
我试过类似这样的代码:
import sys
sys.exit(0) # or exit(1)
但是没有成功。可能只是结束了当前正在运行的Python脚本的“进程”。非常感谢!
3 个回答
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的命令行。
4
这段代码会完全按照你的需求来做。没有任何提示。
import os
os.system("taskkill /f /im pythonw.exe")
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都退出了。希望这能帮到你。