I have a file called tester.py, located on /project.
/project has a subdirectory called lib, with 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 as lib.BoxTime, or use:
import lib.BoxTime as BT ... BT.bt_function()
The PYTHONPATH is the environment variable that contains the path of the directories that Python searches to import the packages. Therefore, if we add the subdirectory to the PYTHONPATH , Python will first look at the directories in PYTHONPATH and import it from there.
A subdirectory is a type of website hierarchy under a root domain that uses folders to organize content on a website. A subdirectory is the same as a subfolder and the names can be used interchangeably.
Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a subdirectory.
Take a look at the Packages documentation (Section 6.4).
In short, you need to put a blank file named
__init__.py in the lib directory.
lib.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! Much later -- in linux, it would look like this:
% cd ~/tmp % mkdir lib % touch lib/__init__.py % cat > lib/BoxTime.py << EOF heredoc> def foo(): heredoc> print "foo!" heredoc> EOF % tree lib lib ├── BoxTime.py └── __init__.py 0 directories, 2 files % python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from lib import BoxTime >>> BoxTime.foo() foo!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With