Norfeldt
Norfeldt

Reputation: 9638

mac: using python 3 via pyenv throws import errors

What does not work

Have been trying to setup python 3.8.5 on mac using pyenv as described by Matthew Broberg

$ brew install pyenv && pyenv install 3.8.5

.zshrc

# Python
# https://opensource.com/article/19/5/python-3-default-mac#what-we-should-do
if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"
fi

# Pip - https://gist.github.com/haircut/14705555d58432a5f01f9188006a04ed
PATH="$PATH:~/Library/Python/2.7/bin"
PATH="$PATH:~/Library/Python/3.8.5/bin"

doing

$ python --version
Python 3.8.5

but running scripts like

$ python utils/search.py 'something' 'somewhere'
Traceback (most recent call last):
__file__=utils/search.py                     | __name__=__main__             | __package__=None                
  File "utils/search.py", line 9, in <module>
    import utils.constants as CONSTANTS
ModuleNotFoundError: No module named 'utils'

What works

removing pyenv by brew uninstall pyenv && rm -Rf ~/.pyenv and completely restarting the terminal (sourcing .zshrc does not seem to be enough).

$ python --version
Python 2.7.16
$ python3 --version
Python 3.8.5
$ python3 utils/search.py 'something' 'somewhere'
Found what you are looking for. It's working!
$

What I don't understand

It's the same python version, but I'm getting import errors in one of them - how does that makes sense?

And more importantly: Can I fix it so python 3 is the default for terminal python and not having to use python3

BTW: alias python to python3 is not an option - tried it and recall it was a failure.

Upvotes: 1

Views: 785

Answers (1)

Simba
Simba

Reputation: 27568

Seems you didn't describe your problem correctly. Not related to pyenv but the way how another package is imported.

Explanation about the how the import works in Python: Python Not Finding Module

Python depends the sys.path to import packages. It searches the path in sys.path and try to find the package you want.

In my understanding, when you call python utils/search.py, $PWD/utils is added into sys.path but not $PWD. There's no way to get the command working cause module utils is not covered by $PWD/utils but $PWD.

Solution: touch utils/__init__.py and call python -m utils.search 'something' 'somewhere'.

Upvotes: 1

Related Questions