从另一个目录导入文件 [英] Import a file from another directory

查看:52
本文介绍了从另一个目录导入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件调用 entryPoint.py :

I have a file call entryPoint.py :

from .commonLib.deviceLib import *

我有一个名为 deviceLib.py 的文件:

And I have a file called 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.请帮帮我.

When I execute python entryPoint.py I get the error : Attempted relative import in non-package. Please help me.

推荐答案

使用 sys.path.append 附加您的 python 文件(模块所在的目录).例如,如果您的 entryPoint.pyaddress 目录内

use sys.path.append to append the directory where your python file (module is). E.g if your entryPoint.py is inside address directory

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

这篇关于从另一个目录导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆