简体   繁体   中英

Avoiding Relative Imports and sys.path in Python

Currently, I have a Python project I'm working on with a directory structure like this:

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).

I've seen many solutions that involve using relative imports and sys.path, but I've also seen people directly import using (for instance)

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. Is this true?

Thanks a bunch. My apologies for diluting this wonderful site with one more relative import-esque question. :)

Sincerely, 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.

This is what my .bashrc looks like now:

...
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.

A great resource to find info about PYTHONPATH is this blog post: http://www.stereoplex.com/blog/understanding-imports-and-pythonpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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