0

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

5
  • 1
    So what is exactly the problem? Do you get an error? Commented Oct 14, 2016 at 7:40
  • Which os are you using? Commented Oct 14, 2016 at 7:40
  • Get the errror: ImportError: No module named 'bin\\TestScript' Commented Oct 14, 2016 at 7:48
  • 1
    bin\TestScript is not a module name. The correct name would be something like bin.TestScript. Module names != file paths. Commented Oct 14, 2016 at 7:50
  • What is the input like? Could you give an example of that input? Commented Oct 14, 2016 at 7:55

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.