I am making a simple python code where main.py has a button where if you click it, it opens up main_newFile.py. However, I can't seem to figure out why it can't detect my second file. code from replit
I'm doing os.system("main_newFile.py") to launch the program and then use sys.exit() to close the main.py. However, the os.system states it can't find my file. If you look at the image, you can see the main_newFile should be in the same directory as the main.py. I can confirm its in the same directory as I even have some background images that I was able to load into my tkinter.
Does anyone know whats wrong or maybe another better way to launch the second python file? Thank you!
To fix your problem, use os.system('./main_newFile.py')
.
The reason why os.system('main_newFile.py')
doesn't work is that on Linux .
(current directory) is not on the program lookup path by default.
An even better solution, which avoids os.system
(which is insecure in general, because it goes through the shell):
import subprocess
import sys
def start_newFile():
subprocess.call((sys.executable, 'main_newFile.py'))
sys.exit()
sys.executable
is the current Python interpreter, e.g. /usr/bin/python
.
An even better solution, wich looks for main_newFile.py
in the same directory as main.py
:
import os
import os.path
import subprocess
import sys
def start_newFile():
subprocess.call((
sys.executable,
os.path.join(os.path.dirname(__file__), 'main_newFile.py')))
sys.exit()