Patrick
Patrick

Reputation: 11

Python: Dynamically importing a script in another folder from a string

I need to import and run a script from a string (path) which is located in another folder. The input needs to be completely dynamic. The code below works when the file is in the same folder but I can't seem to get it working when the file is located elsewhere.

main.py

path = 'bin\TestScript'

module = __import__(path)

my_class = getattr(module, '__main__')

instance = my_class(3,16)

print(instance)

TestScript.py

def __main__(a,b):

    return(a*b)

Get the errror: ImportError: No module named 'bin\\TestScript'

on windows os

Upvotes: 0

Views: 347

Answers (1)

cdarke
cdarke

Reputation: 44414

You need to separate the directory from the module name and add that to the module search path. For example:

import os.path
import sys

path = 'bin\\TestScript'
mdir = os.path.dirname(path)
modname = os.path.basename(path)
sys.path.append(mdir)

module = __import__(modname)

my_class = getattr(module, '__main__')

instance = my_class(3,16)

print(instance)

An alternative is to make the directory "bin" a package.

Upvotes: 2

Related Questions