note

Python Cheatsheet

Python essentials including HTTP servers, venv, pip, and debugging with pdb

Python Cheatsheet

HTTP Server

  • Simple HTTP server:
    • Python 2: python2 -m SimpleHTTPServer 8080
    • Python 3: python3 -m http.server 8080
    • Download from http server:
      • wget http://xxx.xxx.xxx.xxx:8080/path/to/file
      • If you don’t have permission to download a file try downloading to the /tmp folder.

Upgrading to more stable shell

python -c 'import pty; pty.spawn("/bin/bash")'

Python venv

  1. Create a virtual environment: python3 -m venv /path/to/new/virtual/environment
  2. Active virtual environment: source myenv/bin/activate
  3. Deactivate virtual environment: deactivate

Wheel files

Python wheel file or in abbreviation .whl file is a specially formatted zip archive as a Python built-package. It contains all the installation files and could be installed by only unpacking the file.

Installing a wheel file

pip install file.whl

Pip

Download wheel files for module and it’s dependencies. pip download $moduleName

ipdb

Using ipdb (built-in Python debugger)

  1. Navigate to the directory containing your script.
  2. Run your script with the Python debugger by typing: python -m pdb your_script.py
  3. The debugger will pause at the first line of your script. You can then use various pdb commands to step through the code, set breakpoints, inspect variables, etc.

Basic Commands

  • import pdb; pdb.set_trace() or breakpoint() - Set a breakpoint in your code
  • n (next) - Execute the current line and move to the next line
  • s (step) - Step into a function call
  • c (continue) - Continue execution until the next breakpoint
  • p variable_name - Print the value of a variable
  • l (list) - List the source code around the current line
  • q (quit) - Quit the debugger
  • u (up) - Move up one level in the call stack
  • d (down) - Move down one level in the call stack
  • w (where) - Print the call stack

Breakpoints

  • b file:line - Set a breakpoint at the specified line
  • b function - Set a breakpoint at the first line of the function
  • cl (clear) - Clear all breakpoints
  • break: List all breakpoints
  • disable bp_number: Disable breakpoint
  • enable breakpoint_number: Enable breakpoint
  • clear file:line: Remove breakpoint

Other Useful Commands

  • a (args) - Print the argument list of the current function
  • pp expression - Pretty-print the value of an expression
  • alias newname command - Create an alias for a command
  • !statement - Execute a Python statement
  • run - Restart the debugged script
  • r (return) - Continue execution until the current function returns

Poetry

See: Python Poetry

See: Using API Keys in Python

Binary in Python

Integer in Python using binary syntax using the 0b prefix:

print(0b0001)
# Prints 1

print(0b0101)
# Prints 5