简体   繁体   English

在Python中避免相对导入和sys.path

[英]Avoiding Relative Imports and sys.path in Python

Currently, I have a Python project I'm working on with a directory structure like this: 当前,我有一个Python项目正在处理这样的目录结构:

tests/
    corpus/
        __init__.py
        tests.py
monkey/
    corpus/
        corpus.py
setup.py

and I want tests.py (in tests/corpus) to import corpus.py (in monkey/corpus). 我想将tests.py(在测试/语料库中)导入corpus.py(在猴子/语料库中)。

I've seen many solutions that involve using relative imports and sys.path, but I've also seen people directly import using (for instance) 我已经看到了许多涉及使用相对导入和sys.path的解决方案,但是我也看到人们直接使用(例如)导入

import monkey.corpus

How can I set up my code to be able to import anything in the root folder like this? 如何设置代码,以便能够像这样导入根文件夹中的任何内容? I've seen glimpses of ideas that it might be possible through configuring setup.py. 我已经看到了一些想法,可以通过配置setup.py来实现。 Is this true? 这是真的?

Thanks a bunch. 谢谢你 My apologies for diluting this wonderful site with one more relative import-esque question. 抱歉,我用另一个相对类似导入的问题来稀释这个奇妙的网站。 :) :)

Sincerely, linuxuser 此致linuxuser

After doing some research, I found that I needed to add an empty __init__.py in the inner corpus directory and put a line in my .bashrc appending it to PYTHONPATH. 经过研究后,我发现我需要在内部语料库目录中添加一个空的__init__.py,并在.bashrc中添加一行以将其附加到PYTHONPATH。

This is what my .bashrc looks like now: 这就是我的.bashrc现在的样子:

...
export PYTHONPATH=$PYTHONPATH:/home/username/monkey/corpus
...

At first, it seemed unusual to have to append my .bashrc to access a library, but from what I've heard it is the typical way to edit your environment and therefore is a proper way to provide access to Python libraries. 最初,必须附加.bashrc来访问库似乎很不寻常,但是据我所知,这是编辑环境的典型方法,因此是提供对Python库的访问的适当方法。

A great resource to find info about PYTHONPATH is this blog post: http://www.stereoplex.com/blog/understanding-imports-and-pythonpath 此博客文章是查找有关PYTHONPATH信息的重要资源: http : //www.stereoplex.com/blog/understanding-imports-and-pythonpath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM