Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run another Python script in different folder

Tags:

python

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])
like image 795
Avic Avatar asked Sep 30 '18 10:09

Avic


People also ask

How do I get the current working directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .


1 Answers

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. 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 called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: execfile('file.py'). Insecure, hacky, usually the wrong answer. Avoid where possible.
  3. 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
like image 178
Matthew Smith Avatar answered Sep 27 '22 21:09

Matthew Smith