How to run another python scripts in a different folder?
I have main program:
calculation_control.py
In the folder calculation_folder
, there is calculation.py
How do I run calculation_folder/calculation.py
from within calculation_control.py
?
So far I have tried the following code:
calculation_file = folder_path + "calculation.py"
if not os.path.isfile(parser_file) :
continue
subprocess.Popen([sys.executable, parser_file])
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):
- Treat it like a module:
import file
. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is calledfile.py
, yourimport
should not include the.py
extension at the end.- The infamous (and unsafe) exec command:
execfile('file.py')
. Insecure, hacky, usually the wrong answer. Avoid where possible.- Spawn a shell process:
os.system('python file.py')
. Use when desperate.Source: How can I make one python file run another?
Solution
Python only searches the current directory for the file(s) to import. However, you can work around this by adding the following code snippet to calculation_control.py
...
import sys
sys.path.insert(0, 'calculation_folder') # Note: if this relavtive path doesn't work or produces errors try replacing it with an absolute path
import calculation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With