擅长:python、mysql、java
<p>相对导入(如<code>from .. import mymodule</code>)只在包中工作。
要导入当前模块的父目录中的“mymodule”:</p>
<pre><code>import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import mymodule
</code></pre>
<p><strong>编辑</strong>:并非总是给出<code>__file__</code>属性。我现在建议使用inspect模块来检索当前文件的文件名(和路径),而不是使用<code>os.path.abspath(__file__)</code></p>