views:

1940

answers:

4

Hi,

I have a file called tester.py, located on /project.

/project has a subdirectory called lib, with has a file called BoxTime.py:

/project/tester.py
/project/lib/BoxTime.py

I want to import BoxTime from tester. I have tried this:

import lib.BoxTime

Which resulted:

Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime

Any ideas how to import BoxTime from the subdirectory?

EDIT

The init.py was the problem, but don't forget to refer to BoxTime is lib.BoxTome, or use:

import lib.BoxTime as BT
...
BT.bt_function()

Thanks,

Udi

+13  A: 

Take a look at the Packages documentation (Section 6.4) here: http://docs.python.org/tutorial/modules.html

In short, you need to put a blank file named

__init__.py

in the "lib" directory.

Greg
+1  A: 

Try import .lib.BoxTime. For more information read about relative import in PEP 328.

spatz
I don't think I've ever seen that syntax used before. Is there strong reason (not) to use this method?
tgray
+3  A: 

Does your lib directory contain a __init__.py file?

Python uses __init__.py to determine if a directory is a module.

Wade
+3  A: 
  • Create a subdirectory named lib.
  • Create an empty file named lib\__init__.py.
  • In lib\BoxTime.py, write a function foo() like this:

    def foo():
        print "foo!"
    
  • In your client code in the directory above lib, write:

    from lib import BoxTime
    BoxTime.foo()
    
  • Run your client code. You will get:

    foo!
    
hughdbrown