# Python

{% hint style="warning" %}
While `pyenv` and `pipx` can still be used, `uv` is quickly becoming the standard/favorite for many.

I've kept the guides for these tools below, but strongly suggest checking out `uv` instead!
{% endhint %}

## Overview

* As Python gets updated, older code will cease to run due to changes in Python syntax and functionality
* To resolve this, we can run code in containers, but that adds a level of complexity&#x20;
* Another solution is to use `uv` (or [pyenv](#pyenv) and [pipx](#pipx)) and run the code in virtualized environments with the required version of Python

{% hint style="danger" %}
`uv` only supports Python v3+ so use `pyenv` if you need Python v2.x
{% endhint %}

### Installation

{% code overflow="wrap" %}

```bash
brew install uv
```

{% endcode %}

### View Available Python Versions

#### **List all available python versions (both installed and not)**

{% code overflow="wrap" %}

```bash
uv python list 
```

{% endcode %}

#### **List only installed python versions**

{% code overflow="wrap" %}

```bash
uv python list --only-installed
```

{% endcode %}

#### **List only python versions not already installed**

{% code overflow="wrap" %}

```bash
uv python list --only-downloads
```

{% endcode %}

### Using Specific Python Versions

#### **Install one or more versions of python**

{% code overflow="wrap" %}

```bash
uv python install 3.8.5
uv python install 3.8.5 3.14.0
```

{% endcode %}

#### **Install a tool with a specific python version**

{% code overflow="wrap" %}

```bash
uv tool install principalmapper --python 3.9.21
```

{% endcode %}

### Set up a Virtual Environment

#### **Creates a virtual environment with python v3.14.0**

{% code overflow="wrap" %}

```bash
uv venv tmp-py3-14 --python 3.14.0
source tmp-py3-14/bin/activate
```

{% endcode %}

### Installing Required Modules

{% code overflow="wrap" %}

```zsh
## script doesn't execute because of missing module
python3 ./my-script.py
# output
ModuleNotFoundError: No module named 'colorama'
```

{% endcode %}

{% code overflow="wrap" %}

```zsh
## install the module(s) via a req file or individually
uv pip install -r requirements.txt
uv pip install colorama
```

{% endcode %}

### Managing Tools Installed with `uv`

**List installed tools**

```
uv tool list 
```

**Install tools**

* This works just like `pipx` or `pip`

{% code overflow="wrap" %}

```bash
uv tool install <tool>
```

{% endcode %}

**Uninstall tools**

{% code overflow="wrap" %}

```bash
uv tool uninstall <tool>
```

{% endcode %}

***

***

## Old — Examples

### Old — Install and Run a Python App with a Specific Python Version

* [PrincipalMapper](https://github.com/nccgroup/PMapper) (pmapper) is a tool that requires Python version 3.9 to run (it errors out otherwise)

{% code overflow="wrap" %}

```bash
# list available versions of python to install
pyenv install --list

# install python 3.9.21
pyenv install 3.9.21

# set version of python that pyenv will use
pyenv global 3.9.21

# validate version is set (should match 3.9.21 for this example)
python --version 

# install the tool, principalmapper (aka pmapper)
pipx install --python $(pyenv which python) principalmapper
```

{% endcode %}

### Old — Set up a Python Virtual Environment&#x20;

* We can set up a virtual environment to run any version of Python we want
* This is useful for isolating your Python code/packages without impacting your system configuration

{% code overflow="wrap" %}

```bash
# install python 2.7.18
pyenv install 2.7.18

# make a directory to work in 
mkdir venv-tyler-python-2-7-18

# create virtualenv for python 2.7.18
pyenv virtualenv 2.7.18 venv-tyler-python-2-7-18

# change into the directory
cd venv-tyler-python-2-7-18

# set directory for virtualenv
pyenv local venv-tyler-python-2-7-18

# validate python version (should match 2.7.18)
python --version
```

{% endcode %}

### Parsing JSON

{% code overflow="wrap" %}

```bash
"ffuf -w /opt/useful/SecLists/Discovery/DNS/namelist.txt -u http://<target IP> -H HOST: FUZZ.<target domain> -o possible-subdomains.json"
```

{% endcode %}

{% code overflow="wrap" %}

```python
import json

json_dump = "./possible-subdomains.json"

with open(json_dump) as f:
    data = json.load(f)

for host in data["results"]:
    print(host["host"], host["url"]) # print out the host & URL
```

{% endcode %}

### View installed modules

{% code overflow="wrap" %}

```python
python3 -c 'help("modules")'

[SNIP]
Cryptodome          cairo               ldb                 retrying
Cython              calendar            lib2to3             rfc3986
IPy                 catfish             libfuturize         rfc3987
IPython             catfish_lib         libpasteurize       rich
[SNIP]
```

{% endcode %}

### View pip modules

```python
pip list

Package    Version
---------- -------
pip        20.3.4
setuptools 44.1.1
wheel      0.37.1
xlrd       2.0.1
```

***

## Old — Pyenv

### Installation

* [pyenv](https://github.com/pyenv/pyenv?ref=playfulpython.com) is a useful tool for letting us quickly download and switch between multiple versions of Python
* Full installation instructions can be [found here](https://github.com/pyenv/pyenv?tab=readme-ov-file#installation)

{% code overflow="wrap" %}

```bash
# install on linux
curl https://pyenv.run | bash

# add to ~/.zshrc
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init - zsh)"' >> ~/.zshrc

# restart shell for PATH changes to take effect
exec "$SHELL"

# install python build dependencies (see install instructions as this is specific to your OS)
# this is for Debian-based systems (Ubuntu, Kali, Parrot, etc.)
sudo apt update; sudo apt install build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev curl git \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
```

{% endcode %}

### Useful commands

{% code overflow="wrap" %}

```bash
# view all python versions installed with pyenv
pyenv versions

# set global (default) python version for pyenv
pyenv global 3.x.x

# set local (directory) python version for pyenv (trumps global). Adds `.python-version` to directory. All pyenv commands in this directory will use this python version
pyenv local 3.x.x

# view available python versions
pyenv install --list
```

{% endcode %}

***

## Old — Pipx

### Installation

* [pipx](https://github.com/pypa/pipx) is a useful tool for installing and running python code and apps in isolated virtual environments
* Full installation instructions can be [found here](https://github.com/pypa/pipx?tab=readme-ov-file#install-pipx)

{% code overflow="wrap" %}

```bash
# install on linux
sudo apt update
sudo apt install pipx
pipx ensurepath
sudo pipx ensurepath --global # optional to allow pipx actions with --global argument
```

{% endcode %}

### Useful commands

{% code overflow="wrap" %}

```bash
# install package for user (~/.local/bin)
pipx install trufflehog

# install package for all users (/usr/local/bin/)
sudo pipx install trufflehog --global

# view installed packages
pipx list
sudo pipx list  

# uninstall packages
pipx uninstall trufflehog
sudo pipx uninstall trufflehog --global
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.techwithtyler.dev/coding-and-cli-tooling/coding-and-scripting/python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
