Reputation: 469
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])
Upvotes: 6
Views: 23702
Reputation: 508
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.
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
Upvotes: 10