已安装Pillow仍报ImportError: No module named PIL的问题求助
Hey there, let's figure out why you're still hitting that ImportError even after installing Pillow!
What's Likely Going On
Your which python returns /opt/local/bin/python—that tells me your active Python 2.7 is installed via MacPorts, not Apple's default system Python. The problem almost certainly stems from a mismatch between the pip you used to install Pillow and the Python you're running your script with:
- When you ran
sudo pip install Pillow, that probably installed Pillow to Apple's default Python (at/usr/bin/python) instead of your MacPorts Python at/opt/local/bin/python. These are two separate environments, so your script can't find the installed module. - MacPorts often renames its pip binaries to
pip2orpip2.7to avoid conflicts with system tools, so using plainpipmight not target the right environment.
Fixes to Try
1. Install Pillow with the Correct Pip
The most reliable way to ensure Pillow goes into your active Python environment is to use python -m pip—this forces the use of the pip associated with whatever python you're calling:
sudo python -m pip install Pillow --upgrade
If you want to be extra explicit, you can use the full path to MacPorts' pip:
sudo /opt/local/bin/pip2.7 install Pillow --upgrade
2. Verify the Installation Works
After installing, test directly in your terminal to confirm the module is accessible:
# Open the Python shell python # Try importing import PIL from PIL import Image
If no errors pop up, you're good to go. If it still fails, check where your Python looks for packages to make sure Pillow's path is included:
import sys print(sys.path)
You should see a path like /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages—that's where MacPorts stores installed modules.
3. Ensure Your Script Uses the Right Python
Double-check your script's shebang line (the first line of the file). If it looks like #!/usr/bin/env python, it might be calling Apple's default Python instead of your MacPorts one. Update it to:
#!/opt/local/bin/python
Or run your script explicitly with the correct Python path:
/opt/local/bin/python your_script.py
内容的提问来源于stack exchange,提问作者Mithun

