从另一个文件夹导入模块

时间:2019-09-24 06:34:22

标签: python import include

我想编写一个测试程序,为此,我需要包括我的DPS310.py文件。但是不知道怎么办

我尝试过:

• from myPackage import DPS310
• import ..DPS310
• import myPackage.DPS310

我的结构:

Projekt
├── myPackage
│   ├── __init__.py
│   └── DPS310.py
├── tests
│   ├── __init__.py
│   └── test_module1.py
├── README.md
├── LICENSE
└── setup.py

test_module1.py文件

import myPackage.DPS310


msg = "Hello World"
print(msg)

dps = DPS310()
#y = DPS310.getTemperature

print(dps.getTemperature())

DPS310.py文件(摘录。仅用于显示getTemperature方法在此处)

...
class DPS310():
    def __init__(self, *args):
        self.i2c = smbus2.SMBus(1)
        if len(args) > 0:
            self.addr = args[0]
            print("Man addr set")
        else:
            # default sensor's address
            self.addr = 0x77

    def getTemperature(self):
        r = self.i2c.read_i2c_block_data(self.addr, DPS310_TMP_B2, 3)
        # reads out the temperature that is stored in the register
        #       r[0]=TMP0-7    r[1]=TMP8-15  r[2]=TMP16-23
        temp = (r[2] << 16) | (r[1] << 8) | (r[0])  # r[0] << 0
        # deploys this function to 24 bits
        return self.twos_comp(temp, 24)
...

如果我运行test_module1.py文件:

Exception has occurred: ModuleNotFoundError
  No module named 'myPackage'
    File "C:\Julian\Projects\PhytonLib_Raspberry\DPS310_Library_RPi\tests\test_module1.py", line 1, in <module>
      import myPackage.DPS310

1 个答案:

答案 0 :(得分:0)

No module named 'myPackage' File

Python很可能不知道在哪里找到myPackage,因此您可以尝试将其设置为source root(可以为您的IDE查找相关信息)。另外,请查看this StackOverFlow帖子。

相关问题