Search code examples
pythonmacospython-3.xpythonpathpyperclip

How to find the location of modules for python3 and debug an ImportError


I'm using Python 3.4.2 on a MacbookPro (10.9.5). The code is from Automate the Boring Stuff with Python by Al Sweigart I have a weird error when trying to run a script in python3. The code is below but I don't think it's the problem. It might be a module path issue but not 100% sure from my debugging.

I can run the code in Idle but I can't run the code from cmd line, running with either shebang or python3 "name of script".

We can see below, that pip3 and python3 are both in /usr/local/bin. We can also see the pyperclip module is installed. However, when running the script from cmd line, it says it can't find the module, even though it's installed.

I ran this from my terminal:

$ which pip3
/usr/local/bin/pip3
$ which python3
/usr/local/bin/python3
$ pip3 freeze | grep clip
pyperclip==1.5.24
$ python3 pw.py 
Traceback (most recent call last):
  File "pw.py", line 5, in <module>
    import pyperclip
ImportError: No module named 'pyperclip'

However, in Idle, the code runs fine w/o giving the error of module not found:

>>> ================================ RESTART ================================
>>> 
Password for email copied to clipboard
>>> 

Does anyone know what might be happening with my path or what other cmds I can run in my script or from the terminal to determine what's going on?

Test code below

#!/usr/local/bin/python3
# pw.py - an insecure password locker program

import sys
import pyperclip

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
      'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
      'luggage': '12345'}

account = "email"

if account in PASSWORDS:
   pyperclip.copy(PASSWORDS[account])
   print ('Password for ' + account + ' copied to clipboard')
else:
   print ('There is no account named ' + account)

Solution

  • Some of the solutions:

    export PYTHONPATH=//Library/Frameworks/Python.framework/Versions3.4/lib/python3.4/site-packages
    

    before you run your script in terminal

    OR Add this to your code (at the beginning) :

    import sys;
    sys.path.insert(0, "Library/Frameworks/Python.framework/Versions3.4/lib/python3.4/site-packages")
    

    OR (easiest and most effective since you only need to do this once)

    Link /usr/local/lib/python3.4/site-packages to /Library/Frameworks/Python.framework/Versions3.4/lib/python3.4/site-packages:

    sudo ln -s /Library/Frameworks/Python.framework/Versions3.4/lib/python3.4/site-packages /usr/local/lib/python3.4/site-packages