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.
- Python 2:
Upgrading to more stable shell
python -c 'import pty; pty.spawn("/bin/bash")'
Python venv
- Create a virtual environment:
python3 -m venv /path/to/new/virtual/environment - Active virtual environment:
source myenv/bin/activate - 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)
- Navigate to the directory containing your script.
- Run your script with the Python debugger by typing:
python -m pdb your_script.py - 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()orbreakpoint()- Set a breakpoint in your coden(next) - Execute the current line and move to the next lines(step) - Step into a function callc(continue) - Continue execution until the next breakpointp variable_name- Print the value of a variablel(list) - List the source code around the current lineq(quit) - Quit the debugger
Navigation
u(up) - Move up one level in the call stackd(down) - Move down one level in the call stackw(where) - Print the call stack
Breakpoints
b file:line- Set a breakpoint at the specified lineb function- Set a breakpoint at the first line of the functioncl(clear) - Clear all breakpointsbreak: List all breakpointsdisable bp_number: Disable breakpointenable breakpoint_number: Enable breakpointclear file:line: Remove breakpoint
Other Useful Commands
a(args) - Print the argument list of the current functionpp expression- Pretty-print the value of an expressionalias newname command- Create an alias for a command!statement- Execute a Python statementrun- Restart the debugged scriptr(return) - Continue execution until the current function returns
Poetry
See: Python Poetry
Binary in Python
Integer in Python using binary syntax using the 0b prefix:
print(0b0001)
# Prints 1
print(0b0101)
# Prints 5