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])
-
1Are you sure you don't want to import the module?henrycjc– henrycjc2018年09月30日 10:33:45 +00:00Commented Sep 30, 2018 at 10:33
-
how to import from different folder ? , and i have calculation.py in several folder . and they have same variable and function. will it be a problem if i import all calculation.py to calculation_control.py ?Avic– Avic2018年09月30日 10:40:46 +00:00Commented Sep 30, 2018 at 10:40
-
stackoverflow.com/questions/7974849/…iamklaus– iamklaus2018年09月30日 10:41:29 +00:00Commented Sep 30, 2018 at 10:41
-
1Possible duplicate of How can I make one python file run another?Matthew Smith– Matthew Smith2018年09月30日 10:50:06 +00:00Commented Sep 30, 2018 at 10:50
-
1i think it is not duplicate , my problem is the another program in different folderAvic– Avic2018年09月30日 11:21:58 +00:00Commented Sep 30, 2018 at 11:21
1 Answer 1
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, yourimportshould not include the.pyextension 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