cybertextron
cybertextron

Reputation: 10961

importing a file as a package - Python

I have the following directory structure:

/testlib
    __init__.py
    ec2.py
    unit/
       __init__.py
       test_ec2.py
    utils/
       __init__.py

I'm trying to create a unittest class for ec2.py:

import ec2

class TestEC2(unittest.TestCase):

    def setUp(self):
        self.ec2obj = ec2.EC2(name="testlib_unittest")

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

However, when I execute test_ec2.py I'm getting the following error:

python unit/test_ec2.py 
Traceback (most recent call last):
  File "unit/test_ec2.py", line 4, in <module>
    import ec2
ImportError: No module named ec2

I still don't understand why I'm getting that, since I have the __init__.py properly set in the directory. The __init__.py files are completely empty: I've created them with touch __init__.py. Any clues?

**** Updates **** Here are some suggestions:

/testlib# python unit/test_ec2.py 
Traceback (most recent call last):
  File "unit/test_ec2.py", line 4, in <module>
    from ..ec2 import EC2
ValueError: Attempted relative import in non-package

testlib# python unit/test_ec2.py 
Traceback (most recent call last):
  File "unit/test_ec2.py", line 4, in <module>
    import testlib.ec2 as ec2
ImportError: No module named testlib.ec2

Upvotes: 0

Views: 90

Answers (2)

Ella Sharakanski
Ella Sharakanski

Reputation: 2773

Python is not looking for files in directories above yours. Ignacio's answer is correct, and see this for elaboration.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

It can't find the module because you're running the script incorrectly. Run the following in testlib/:

python -m unit.test_ec2

Upvotes: 2

Related Questions