运行Python脚本的批处理执行完毕后如何关闭CMD窗口?
Problem Description
I have a .bat batch file that runs a Python script. Once the Python script finishes executing, the CMD window stays open instead of closing automatically. I’m looking for ways to fix this, and also wondering if it’s possible to make the window close directly from the Python script itself.
Solution 1 (The Self-Discovered Fix)
As you’ve already worked out, the simplest and most straightforward solution is to add the exit command at the very end of your batch file.
For example, if your original batch file looked like this:
python my_script.py
Update it to include the exit command:
python my_script.py exit
This ensures that as soon as the Python process finishes running, the batch script immediately exits, closing the CMD window along with it.
Solution 2 (Closing via the Python Script)
If you prefer to handle the window closure directly from your Python script (instead of modifying the batch file), you can use platform-specific code targeting Windows. Here’s how:
A basic approach (though it closes all CMD windows, so use with caution):
import os os.system("taskkill /f /im cmd.exe")
A more targeted method that only closes the specific CMD window running your script (requires the psutil library):
import psutil import os # Get the current Python process current_process = psutil.Process(os.getpid()) # Get the parent CMD process that launched the script parent_process = current_process.parent() # Terminate the parent CMD window parent_process.terminate()
Note: You’ll need to install psutil first with pip install psutil if you don’t already have it.
That said, adding exit to your batch file is still the cleaner, more reliable option—it avoids adding platform-specific code to your Python script and keeps the logic contained to the batch file where it belongs.
内容的提问来源于stack exchange,提问作者petek

