简体   繁体   中英

What's the correct way to import a python package?

I have a python project structured as of now in the following way:

foo/
   __init__.py
   bar/
       __init__.py
       config.cfg
       README.md
       src/
          __init__.py
          myfile_a.py
          myfile_b.py
       tests/
          test_myfile_a.py
   README.md

and inside test_myfile_a.py I have:

 1 #!/usr/bin/python
  2 import unittest
  3 from foo.bar.src import myfile_a
  4 
  5 class TestToolsFunctions(unittest.TestCase):
  6 
  7     def setUp(self):
  8         file_a = MyFile_A()

  9   if __name__ == '__main__':
  10     unittest.main()

then i get:

Traceback (most recent call last):
  File "tests/test_myfile_a.py", line 3, in <module>
    from foo.bar.src import myfile_a
ImportError: No module named foo.bar.src

What is the correct way to set that path?

** EDIT ** The foo directory is a git repo, on my ~/home dir: /home/pribeiro/foo I also tried to do a import foo :

import foo
ImportError: No module named foo

Is foo in your PATH? Try

import sys
print sys.path

If you add foo to your path, foo.bar.src should be a valid module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM