繁体   English   中英

从另一个文件夹导入模块

[英]Module imports from another folder

我想编写一个测试程序,为此我需要包含我的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
No module named 'myPackage' File

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

暂无
暂无

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

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