将python包从本地目录导入解释器 [英] Import python package from local directory into interpreter

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

问题描述

我正在本地目录中开发/测试一个包.我想在解释器 (v2.5) 中导入它,但 sys.path 不包含当前目录.现在我输入 sys.path.insert(0,'.').有没有更好的办法?

I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in sys.path.insert(0,'.'). Is there a better way?

还有,

from . import mypackage

失败并出现此错误:

ValueError: Attempted relative import in non-package

推荐答案

您只能在作为包的一部分导入的模块中使用相对导入——您的脚本或交互式解释器不是,所以课程 from .import (这意味着从我从中导入的同一个包中导入")不起作用.一旦您确保 mypackage 的父目录在 sys.path(您如何设法获取当前目录 远离来自 sys.path 我不知道——你在 site.py 中有什么奇怪的东西,还是...?)

You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import (which means "import from the same package I got imported from") doesn't work. import mypackage will be fine once you ensure the parent directory of mypackage is in sys.path (how you managed to get your current directory away from sys.path I don't know -- do you have something strange in site.py, or...?)

要将当前目录放回 sys.path 实际上没有比将它放在那里更好的方法了.

To get your current directory back into sys.path there is in fact no better way than putting it there.

这篇关于将python包从本地目录导入解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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