Python Virtual Environment

Ref: Chloe's TIL

Purpose of Python virtual environment

  • To create an isolated environment for different Python projects

    • You can install a specific version of the module on each project without worrying that it will affect your other Python projects.

Create Virtual Environment for Python 3

  1. Check your python version

    • $ python --version
      Python 3.6.9
    • Python 2 ๊นŒ์ง€๋Š” ์™ธ๋ถ€ํŒจํ‚ค์ง€๋ฅผ ํ†ตํ•ด ์„ค์น˜ํ–ˆ์ง€๋งŒ Python 3 ๋ถ€ํ„ฐ๋Š” venv ๋ชจ๋“ˆ์ด ๋‚ด์žฅ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ์„ค์น˜ํ•  ํ•„์š” ์—†์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ Python 2 ๋ผ๋ฉด ์•„๋ž˜ ๋ช…๋ น์„ ํ†ตํ•ด ํŒจํ‚ค์ง€๋ฅผ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค.

      • $ pip install virtualenv
  2. Create a virtual environment

    • $ cd < ํ”„๋กœ์ ํŠธ ๋””๋ ‰ํ† ๋ฆฌ >
      $ python -m venv .venv
  3. git ignore

    ๊ฐ€์ƒ ํ™˜๊ฒฝ์„ ๊ตณ์ด Git๊ณผ ๊ฐ™์€ ์†Œ์Šค ๋ฒ„์ „ ๊ด€๋ฆฌ ์‹œ์Šคํ…œ์— ์˜ฌ๋ฆด ํ•„์š”๋Š” ์—†์œผ๋ฏ€๋กœ .venv ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ .gitignore ํŒŒ์ผ์— ์ถ”๊ฐ€

    • $ echo '.venv' >> .gitignore
  4. activate your virtual environment

    • # mac
      $ source .venv/bin/activate
    • # mac
      $ source .venv/Script/activate
  5. set up command alias in .bashrc

    • alias va="source venv/bin/activate"

Caution

  1. ํŒŒ์ด์ฌ๋ฒ„์ „์— ๋”ฐ๋ผ์„œ ์ƒ์„ฑ๋œ activate ํŒŒ์ผ์˜ ํ™•์žฅ์ž๊ฐ€ .bat ์ผ ์ˆ˜ ์žˆ๋‹ค.

    • .bat ํŒŒ์ผ์€ powershell ์ด๋‚˜ bash ์—์„œ ์‹คํ–‰๋˜์ง€ ์•Š๊ณ  cmd์—์„œ๋งŒ ์ž‘๋™ํ•œ๋‹ค.

    • $ source .venv/bin/activate.bat

Last updated