2

I'm trying to run a Python script (A) from within another Python script (B), where the scripts are in different directories. The directory that script A is stored in is variable and is stored in a JSON file in script B's directory, something like this:

/documents
    /directory-a
        script-a.py
    /directory-b
        script-b.py
        script-info.json

To make matters more complicated, script A's filename is variable too. Currently my code for script-b.py is something like this:

import sys
import json


with open("script-info.json") as json_file:
    directory = json.load(json_file)["directory"]
    filename = json.load(json_file)["filename"]


sys.path.append(directory)
import filename

Using sys.path.append and import in the middle of my program feel like workarounds and import filename doensn't work since filename is stored as a string.

Thanks in advance for any help!

IkelosOne
  • 21
  • 3
  • 4
    i tink you will find the answer in this https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – Wahyu Hadinoto May 20 '20 at 10:57
  • @Melebius not exactly, the file's name is stored as a string and script B is in another directory. – IkelosOne May 20 '20 at 11:02
  • @WahyuHadinoto this works! Although I'm not entirely sure I understand it... – IkelosOne May 20 '20 at 11:11
  • @apet thats why I want to avoid the exec() command, people can make their own filenames... – IkelosOne May 20 '20 at 11:16
  • @WahyuHadinoto hey - it turns out this approach doesn't work when script-a.py uses a file from its local directory (import script-a-classes, for example, which is stored in directory-a). Any fix for this? – IkelosOne May 24 '20 at 18:28
  • just using module `importlib.util`. – Wahyu Hadinoto May 25 '20 at 02:58
  • @WahyuHadinoto but the whole point is that script-b.py doesn't know what dependencies script-a.py has... – IkelosOne May 29 '20 at 16:20
  • if 1 file separate randomly, you can scan all file on hard drive using `os` module (you can get the pathfile and filename automatically) and use `importlib.util` for load your file. – Wahyu Hadinoto May 30 '20 at 03:41

0 Answers0