Search code examples
python-3.xmacospippyyaml

I installed pyyaml via pip, but when I run my Python3 script, I'm not it can't find the module


I’m on Mac OS X Big Sur. I installed python3 via brew, and have this version

$ python3 --version
Python 3.9.13

Pip verison is

$ pip3 --version
pip 22.1.1 from /Users/davea/Library/Python/3.8/lib/python/site-packages/pip (python 3.8)

I want to write a program use the pyyaml module. I’m told I already installed it

$ pip3 install pyyaml
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pyyaml in /Users/david.alvarado/Library/Python/3.8/lib/python/site-packages (6.0)

I have this script

import pyyaml

arg = sys.argv[0]
with open(arg) as f:
    document = f.readlines()
    print(yaml.load(document))

But when I run my program, I’m told pyyaml cannot be found

$ python3 convert_yaml_to_json.py ~/Downloads/myfile.yml 
Traceback (most recent call last):
  File "/Users/davea/scripts/convert_yaml_to_json.py", line 1, in <module>
    import pyyaml

Edit: added some output in response to suggestion given

I tried using the full path of Python and I’m told the requirement is already satisfied

$ /usr/local/bin/python3 -m pip install pyyaml
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
Requirement already satisfied: pyyaml in /usr/local/lib/python3.9/site-packages (6.0)
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621

I even tried pip3

$ /usr/local/bin/python3 -m pip3 install pyyaml
/usr/local/opt/python@3.9/bin/python3.9: No module named pip3

However, when running with the full path it says it can’t find the YAML module

$ /usr/local/bin/python3 convert_yaml_to_json.py 
Traceback (most recent call last):
  File "/Users/davea/scripts/convert_yaml_to_json.py", line 1, in <module>
    import pyyaml
ModuleNotFoundError: No module named 'pyyaml'

Solution

  • The installation is correct and the module is also in the right directory. The only problem is that in your code you have to change the command import pyyaml to import yaml

    Here is the example; (using your code)

    import yaml
    arg = sys.argv[0]
    with open(argv) as f:
         document = f.readlines()
         print(yaml.load(document))
    

    It should work correctly now