Skip to content

Instantly share code, notes, and snippets.

@amcginlay
Last active June 7, 2023 22:28
Show Gist options
  • Save amcginlay/1d21af4354708e1a810dd907ff1c08b3 to your computer and use it in GitHub Desktop.
Save amcginlay/1d21af4354708e1a810dd907ff1c08b3 to your computer and use it in GitHub Desktop.
python-notes.md

Python Notes

Virtual Environments

Python virtual environments are used to create an isolated environment for Python projects. Each virtual environment has its own set of Python packages installed, separate from the global Python installation.

This helps provide:

  • Dependency management
  • Isolation
  • Reproducibility
  • A variety of test environments

Steps

Create a directory and change into it:

project=web-server
mkdir ${project} && cd $_

Create a virtual environment from global (pipenv is a more comprehensive alternative) :

python3 -m venv venv

Activate the virtual environment in the current shell:

source venv/bin/activate

Install the dependencies:

pip install flask

Write the code:

cat << EOF > main.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, world!'

if __name__ == '__main__':
    app.run()
EOF

Launch the app:

python main.py # ctrl+c to quit

Invoke the endpoint:

curl http://localhost:5000

Deactivate the virtual environment in the current shell:

deactivate

VSCode Interactive Mode (REPL)

The VSCode Interactive Mode is a feature that allows you to interact with Python code in a console-like environment within the editor. It provides a convenient way to experiment with and explore Python code without having to leave the editor.

Steps

As per this. If at any stage you are prompted to install dependencies or extensions, follow those prompts.

  • Open VSCode and create new Python file, for example, repl.py
  • On the first line, type the following
    # %%
    
    ... then press enter to enable Interactive Mode inside your file.
  • On the second line, type the following
    print('hello, world!')
    
    .. then press ctrl+enter or shift+enter, depending on the Run behaviour required
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment