2

thank you all, this problem was solved

but I don't know What is the different between them

wrong script :

def func(module) :
    cwd = os.getcwd()
    os.chdir(module['path'])
    tmp = __import__(module['name'])
    os.chdir(cwd)

working well script :

def func(module) :
    sys.path.append(module['path'])
    tmp = __import__(module['name'])

...

happy new year :)

============================================================

Hello I need to import dynamically in python script

when I try __import__() outside of a function

ex)

__import__('myModule')

it does work, but when I try it within a function

ex )

def func() :
    __import__('myModule')


func()

I get an ImportError: ImportError: No module named myModule

How can I use __import__() in function??

4
  • no import() I wrote __import__() Commented Jan 4, 2018 at 4:40
  • Fix your formatting Commented Jan 4, 2018 at 4:41
  • You're welcome :-D :-D Commented Jan 4, 2018 at 4:52
  • Is func in a different module from the one where it worked? Commented Jan 4, 2018 at 4:56

2 Answers 2

2

I think what you want to use here is the following:

from importlib import import_module

def func():
    import_module('myModule')
Sign up to request clarification or add additional context in comments.

Comments

0

When Python starts, the script’s directory is put at the front of sys.path, so that import finds things in it. In some cases (not, for example, python foo/bar.py), what is put there is an empty string, which means “search the current working directory”. Only in that case will os.chdir affect import in the way you expected.

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.