import tkinter as tk
import subprocess
import sys
def start_newFile():
subprocess.call((sys.executable, 'testing2.py'))
sys.exit()
root = tk.Tk()
root.title("First Script")
# Button to start a new file
start_button = tk.Button(root, text="Start New File", command=start_newFile)
start_button.pack()
root.mainloop()
I'm a newbie CS student and I have this simple code that I am creating for a smaller part of a much larger college project but I running into some issue. One of the project requirements needs me to demonstrate how to open a second python file and to close the first one. From what I've learned, there are three ways to open a second python file, subprocess.call() subprocess.run() and subprocess.Popen()
I've fiddled around with this call by simply changing the call() to either run() or Popen() and I've found that the Popen() function is the only one working, allowing the sys.exit() to actually close it. call() and run() opens the second file but the first file is still there and it dosen't close. In my end, it looks to be freezing up.
Why is this?
subprocess.Popen() indeed gives you more flexibility compared to subprocess.call() or subprocess.run(). When you use Popen(), it spawns a new process, allowing your main script to continue running without waiting for the subprocess to complete. when you use call() or run(), your main script waits for the subprocess to finish execution before proceeding. In your case, sys.exit() isn't being called until the subprocess completes. This might cause your main script to appear frozen because it's waiting for the subprocess to finish, which it never does because it's waiting for the main script to exit.
import all necessary libraries
def function_name:
subprocess.Popen([sys.executable, 'testing2.py'])
root.destroy() # Close the Tkinter window immediately
root = tk.Tk()
root.title("First Script")
start_button = tk.Button(root, text="Start New File", command=start_new_file)
start_button.pack()
root.mainloop()
Here's the modified version, you can try this.