Python脚本切换问题:启动新脚本时终止旧脚本
Hey there! As a fellow Python learner, I totally get why this feels confusing—let's break this down and fix it for you.
The problem with using execfile() (or exec(open('script.py').read()) in Python 3) is that it runs the new script inside the same process and context as your original script. That means your old code keeps running alongside the new one, which is why you're seeing them run in parallel.
The Fix: Replace the Current Process with the New Script
The cleanest way to stop your original script and start the new one is to use Python's os.exec* family of functions. These functions completely replace the current running process with the new script—your original code stops immediately, and the new script takes over the entire process.
Here's a concrete example, using a Tkinter button (since you mentioned clicking a button to switch):
import sys import os import tkinter as tk def switch_to_new_script(): # First, close any open windows from the original script root.destroy() # Replace the current process with the new script # sys.executable gives the path to your Python interpreter os.execv(sys.executable, [sys.executable, "new_script.py"]) # Original script setup root = tk.Tk() switch_btn = tk.Button(root, text="Launch New Script", command=switch_to_new_script) switch_btn.pack(pady=20) root.mainloop()
Why This Works:
root.destroy()closes the original Tkinter window and exits its event loop (so the original script's UI stops immediately).os.execv()replaces the entire current process with the new script. Once this line runs, none of the original script's code will execute anymore—your new script starts fresh as if you ran it directly from the command line.
What If You Can't Use os.exec*?
If for some reason you need to stay in the same process (though this is rare for your use case), you'd have to explicitly stop all running parts of your original script first:
- If you're using an event loop (like Tkinter's
mainloop), you need to exit it. - If you have any background threads, you need to stop them gracefully.
- Then you can run the new script's code. But this is error-prone and not recommended—using
os.exec*is the cleaner, more reliable approach.
A quick note: execfile() was removed in Python 3, so if you're using a newer version, you'd use exec(open("script.py").read()) instead—but again, this runs the code in the same process, so it doesn't solve your parallel execution problem.
内容的提问来源于stack exchange,提问作者lukhubert

