คู่มือติดตั้ง Python 3 บน macOS ด้วย Homebrew Package Manager รวมถึงการแก้ไข Permission Error ที่พบบ่อย
Prerequisites
- macOS (Intel หรือ Apple Silicon)
- Homebrew ติดตั้งแล้ว (
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)")
ติดตั้ง Python 3
# 1. เช็ค Homebrew Health
brew doctor
# 2. ติดตั้ง Python 3
brew install python3
# 3. Verify Installation
python3 --version
# Python 3.12.3
pip3 --version
# pip 24.0 from ...
แก้ไข Permission Error (ถ้าเกิด)
บางครั้งเจอ Error ตอน brew link:
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
วิธีแก้
# 1. เปลี่ยน Owner ของ Homebrew Prefix
sudo chown -R $(whoami) $(brew --prefix)/*
# 2. สร้าง Frameworks Directory ด้วย Permission ถูกต้อง
sudo install -d -o $(whoami) -g admin /usr/local/Frameworks
# 3. Link อีกครั้ง
brew link python3
💡 Apple Silicon (M1/M2/M3): Homebrew Path คือ
/opt/homebrewไม่ใช่/usr/localคำสั่ง$(brew --prefix)จะจัดการให้อัตโนมัติ
Post-Install Setup
Shell Configuration (zsh/bash)
# เพิ่มใน ~/.zshrc หรือ ~/.bash_profile
export PATH="$(brew --prefix)/bin:$PATH"
# Reload
source ~/.zshrc
Python Aliases (Optional)
# ใน ~/.zshrc
alias python=python3
alias pip=pip3
จัดการ Multiple Python Versions
pyenv (แนะนำสำหรับ Developer)
brew install pyenv
# เพิ่มใน ~/.zshrc
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
# ติดตั้ง Version เฉพาะ
pyenv install 3.11.9
pyenv global 3.11.9 # Set Global Default
pyenv local 3.10.12 # Set Per-Project
Virtual Environments
# Built-in venv
python3 -m venv myenv
source myenv/bin/activate
# หรือใช้ virtualenvwrapper
pip install virtualenvwrapper
Common Issues
| Issue | Solution |
|---|---|
| python3 command not found | Restart Terminal หรือ source ~/.zshrc |
| SSL Certificate Error | brew install openssl && brew reinstall python3 |
| pip install permission denied | ใช้ Virtual Environment หรือ pip install --user |
| ModuleNotFoundError: tkinter | brew install python-tk |