<p>首先将<code>from config import DEFAULT_DATA_PATH</code>更改为<code>from ..config import DEFAULT_DATA_PATH</code>,然后在<code>SEC-Edgar</code>目录中添加空的<code>__init__.py</code>。</p>
<p>然后,尝试从SEC Edgar所在的位置(目录)执行模块<code>python -m SEC-Edgar.SECEdgar.test</code>,或者对正在运行的任何模块执行类似的操作。</p>
<p>这里有三件事要注意。</p>
<ol>
<li>您的<code>config.py</code>和<code>crawler.py</code>模块不共享同一父目录。所以,当您尝试从<code>crawler.py</code>中<code>from config import DEFAULT_DATA_PATH</code>时,Python无法为您导入它。</li>
<li>只有当python中的其他目录是一个包时,我们才能从该目录导入模块(.py文件)。只需在该目录中添加一个空的<code>__init__.py</code>文件就可以完成。</li>
<li>我们现在可以使用相对进口。但是,在相对导入期间,Python根据<a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a>使用模块的<code>__name__</code>属性:</li>
</ol>
<blockquote>
<p>Relative imports use a module's <strong>name</strong> attribute to determine that
module's position in the package hierarchy. If the module's name does
not contain any package information (e.g. it is set to '<strong>main</strong>')
then relative imports are resolved as if the module were a top level
module, regardless of where the module is actually located on the file
system.</p>
</blockquote>
<p>因此,我们使用<code>-m</code>选项运行它,为Python执行相关导入提供包信息。</p>
<p>[回应评论]
这是对我有用的东西</p>
<pre><code>SEC-Edgar
├── SECEdgar
│ ├── __init__.py
│ ├── crawler.py
│ └── test.py
├── __init__.py
└── config.py
</code></pre>
<p>我在SEC Edgar目录外</p>
<pre><code>C:\Users\username\Documents> ls
SEC-EDGAR OTHERS
C:\Users\username\Documents> python -m SEC-Edgar.SECEdgar.test
Lets assume I'm an SecCrawler
</code></pre>
<p><strong>配置py</strong></p>
<pre><code>DEFAULT_DATA_PATH = "some/path"
</code></pre>
<p><strong>爬虫程序.py</strong></p>
<pre><code>from ..config import DEFAULT_DATA_PATH
SecCrawler = "Lets assume I'm an SecCrawler"
</code></pre>
<p><strong>测试.py</strong></p>
<pre><code>from crawler import SecCrawler
print(SecCrawler)
</code></pre>