首页 > 解决方案 > 从另一个目录导入文件

问题描述

我有一个文件调用entryPoint.py

from .commonLib.deviceLib import *

我有一个名为deviceLib.py

import math
import sys
import logging
import requests
import this

class DeviceLib(object):
    def __init__(self, connectionDb):
        self.__db = connectionDb

树是这样的:

/test
    entryPoint.py
/commonLib
    __init__.py
    deviceLib.py

当我执行时,python entryPoint.py我得到错误:Attempted relative import in non-package。请帮我。

标签: pythonpython-2.7

解决方案


使用sys.path.append附加您的 python 文件(模块所在的目录)。例如,如果您的entryPoint.py地址目录中

import sys
sys.path.append('/path/to/your/module/address/')
import entryPoint

推荐阅读