问题描述
我正在本地目录中开发/测试一个包.我想在解释器 (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包从本地目录导入解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!