1

I want to use importlib.import_module to import modules dynamically. My code like this:

import os
import importlib

os.chdir('D:\\Python27\\Lib\\bsddb')
m = importlib.import_module('db')
print dir(m)

I can to this successfully in the Python console. But if I run these code in a fileC:\Users\Administrator\Desktop>python test.py, it can't work:

Traceback (most recent call last):
File "test.py", line 5, in <module>
  m = importlib.import_module("db")
File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module
  __import__(name)
ImportError: No module named db

But if I copy the db.py file to the directory the same as the script file, it works. I can't figure out why.

Wayne Cui
  • 835
  • 7
  • 15
  • Can you show how your folder structure looks? And is db a python file or a folder? Please provide additional details. – Mahadeva Jul 16 '16 at 14:14
  • @SarvagyaPant Hi Sarvagya, the modules I am trying to load is in the Python Standard Lib. – Wayne Cui Jul 16 '16 at 14:18

1 Answers1

0

EDIT: I had tested the earlier code in console and it worked. However, I have modified the code again. I kept the bsddb module directly in D drive and changed the code again to:

import os
os.chdir("D:\\")
import importlib
m = importlib.import_module("bsddb.db")
print len(dir(m))
print dir(m)

This results in 319 and the list of functions and variables exponsed by the module. It seems you may need to import module using the dot (.) notation like above.

Pang
  • 9,564
  • 146
  • 81
  • 122
Mahadeva
  • 1,584
  • 4
  • 23
  • 56
  • Which path do you put the script file containing these code? I tried your code but still have no good luck. :-( – Wayne Cui Jul 16 '16 at 14:31
  • 1
    Yes, It works. But this line `os.chdir(..)` can be removed. I think `bsddb.db` should be the module's global name, isn't it? – Wayne Cui Jul 16 '16 at 15:44
  • If you go to this link https://docs.python.org/2/library/importlib.html#importlib.import_module it says that if the module exists in python path, it will import that module if not it will look into the location from which the python file was called. If you change the `bsddb` folder as `bsddb_your_sample` and use `m = importlib.import_module("bsddb_your_sample.db")`, it will look into the python path, however it doesn't exist there, so this will look into your current calling path and finds it there and returns the data. – Mahadeva Jul 16 '16 at 15:52
  • So either you keep the folder near your main python file or use os.chdir() to go to the location. Hope this helps. If it worked please mark the answer :) – Mahadeva Jul 16 '16 at 15:53
  • 1
    Could you explain that why my origin code works in the console but not the script file? – Wayne Cui Jul 16 '16 at 15:57