Do I need PYTHONPATH

≡放荡痞女 提交于 2021-02-19 08:20:15

问题


There are many of similar questions about PYTHONPATH and imports but I didn't find exactly what I needed.

I have a git repository that contains a few python helper scripts. The scripts are naturally organized in a few packages. Something like:

scripts/main.py
scripts/other_main.py
scripts/__init__.py
a/foo.py
a/bar.py
a/__init__py
b/foo.py
b/bar.py
b/__init__.py
__init__.py

scripts depends on a and b. I'm using absolute import in all modules. I run python3 scripts/main.py. Everything works as long as I set up PYTHONPATH to the root of my project.

However, I'd like to avoid users the hassle of setting up an environment variable.

What would be the right way to go? I expected this to work like in java, where the current dir is in the classpath by default but it doesn't seem to be the case. I've also tried relative import without success.

EDIT: it seems to work if I remove the top-level __init__.py


回答1:


Firstly, you're right in that I don't think you need the top-level __init__.py. Removing it doesn't solve any import error for me though.

You won't need to set PYTHONPATH and there are a few alternatives that I can think of:

  1. Use a virtual environment (https://virtualenv.pypa.io/en/latest/). This would also require you to package up your code into an installable package (https://packaging.python.org/). I won't explain this option further since it's not directly related to your question.

  2. Move your modules under your scripts directory. Python automatically adds the script's directory into the Python path.

  3. Modify the sys.path variable in your scripts so they can find your local modules.

The second option is the most straightforward.

The third option would require you to add some python code to the top of your scripts, above your normal imports. In your main.py it would look like:

#!/usr/bin/env python
import os.path, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

import a
import b

What this does is:

  • Take the filename of the script

  • calculate the parent directory of the directory of the script

  • Prepend that directory to sys.path

  • Then do normal imports of your modules



来源:https://stackoverflow.com/questions/55656080/do-i-need-pythonpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!