Python: Dynamically importing a script in another folder from a string
<p>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.</p>

<p>main.py</p>

<pre><code>path = 'bin\TestScript'

module = __import__(path)

my_class = getattr(module, '__main__')

instance = my_class(3,16)

print(instance)
</code></pre>

<p>TestScript.py</p>

<pre><code>def __main__(a,b):

    return(a*b)
</code></pre>

<p>Get the errror:
ImportError: No module named 'bin\\TestScript'</p>

<p>on windows os</p>

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

<pre><code>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)
</code></pre>

<p>An alternative is to make the directory "bin" a package.</p>

python