简体   繁体   中英

Python: Quit IDLE after Script running

Is it possible to somehow quit Python IDLE under Windows from within my python code/script at the end after running?

I tried something like:

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

didn't work. Probably only quits the current "process" of the running python script. Thanks a lot

If you can run IDLE from the command line (or edit your shortcut), I found this in the IDLE help.

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.

Which seems to imply that the script is running inside IDLE. I did a quick test script, and calling exit() brought up a box asking to kill the program. Clicked yes, and the script and IDLE both quit. Hope that can help.

This will do exactly what you want. No prompt.

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

To quit Python IDLE under Windows from within a python code/script without a further prompt, try:

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

This works with IDLE, PyCharm and even the command line in Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM