Skip to content

Instantly share code, notes, and snippets.

@denielchiang
Last active August 14, 2025 10:38
Show Gist options
  • Select an option

  • Save denielchiang/7724be6ee4c471611b122a5e5b5a14bc to your computer and use it in GitHub Desktop.

Select an option

Save denielchiang/7724be6ee4c471611b122a5e5b5a14bc to your computer and use it in GitHub Desktop.
🐍 Python 新專案建立流程(macOS + asdf + direnv + uv)

Python Project Environment Setup Guide

This guide explains how to set up isolated Python environments for each project, using asdf for Python version management, direnv for automatic .venv activation, and 1Password CLI for secure secret handling.

📦 Prerequisites

brew install asdf direnv uv 1password/tap/1password-cli
op account add && op signin

Ensure your ~/.zshrc has:

if command -v direnv >/dev/null 2>&1; then
  eval "$(direnv hook zsh)"
fi
alias oprun='op run --env-file .env --'

And your ~/.direnvrc contains:

usepy() {
  if [ -r /opt/homebrew/opt/asdf/libexec/asdf.sh ]; then
    . /opt/homebrew/opt/asdf/libexec/asdf.sh
  elif [ -r "$HOME/.asdf/asdf.sh" ]; then
    . "$HOME/.asdf/asdf.sh"
  fi
  VENV=".venv"; [ ! -d "$VENV" ] && python -m venv "$VENV"
  . "$VENV/bin/activate"
}

🆕 Creating a New Python Project

  1. Create project directory and move into it:
mkdir myproject && cd myproject
  1. Set Python version (change as needed):
asdf local python 3.12.5
  1. Enable direnv and .venv:
echo 'usepy' > .envrc
direnv allow
  1. Create .env and reference secrets from 1Password:
GOOGLE_KEY=op://<Vault>/<Item>/google_key.txt
  1. Install dependencies:
uv pip install <package>
  1. Run scripts with secrets loaded at runtime:
oprun uv run python script.py

🔑 Why This Approach?

  • Isolated: Each project has its own .venv
  • Reproducible: .tool-versions ensures consistent Python version
  • Secure: Secrets never stored in plain text — use op:// references
  • Automatic: direnv activates .venv when you cd into the folder

♻️ Rebuilding After Reinstall

  1. Reinstall prerequisites (see above)
  2. Restore ~/.direnvrc and ~/.zshrc from backup
  3. cd into project → direnv allow
  4. Install dependencies: uv pip install -r requirements.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment