简体   繁体   English

将文件作为包导入-Python

[英]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 : 我正在尝试为ec2.py创建一个unittest类:

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: 但是,当我执行test_ec2.py时,出现以下错误:

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. 我仍然不明白为什么会这样,因为我已经在目录中正确设置了__init__.py The __init__.py files are completely empty: I've created them with touch __init__.py . __init__.py文件完全为空:我已经使用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

It can't find the module because you're running the script incorrectly. 它找不到模块,因为您运行的脚本不正确。 Run the following in testlib/ : testlib/运行以下testlib/

python -m unit.test_ec2

Python is not looking for files in directories above yours. Python不在您上面的目录中查找文件。 Ignacio's answer is correct, and see this for elaboration. 伊格纳西奥(Ignacio)的答案是正确的,请参阅此内容进行详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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