888 commands · 53 cheat sheets · 7 subcategories
Python master quick reference — Page 4
Browse 197 commands from 12 focused cheat sheets on page 4 of 5. Each example opens its matching detailed section.
Files, OS, and CLI · 16 commands
Python subprocess and Command Execution Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Run an argument sequence | subprocess.run([program, '--flag', value], check=True) | View examples |
| Reuse this Python | subprocess.run([sys.executable, '-m', 'package'], check=True) | View examples |
| Capture both streams | result = subprocess.run(args, capture_output=True, text=True) | View examples |
| Choose text encoding | subprocess.run(args, capture_output=True, text=True, encoding='utf-8') | View examples |
| Merge stderr into stdout | subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) | View examples |
| Require success | result = subprocess.run(args, check=True) | View examples |
| Check after inspection | result.check_returncode() | View examples |
| Read the exit status | if result.returncode != 0: handle_failure(result.stderr) | View examples |
| Bound runtime | subprocess.run(args, timeout=10, check=True) | View examples |
| Handle expiration | except subprocess.TimeoutExpired as exc: report(exc.cmd, exc.timeout) | View examples |
| Send standard input | subprocess.run(args, input=payload, text=True, check=True) | View examples |
| Set child environment | subprocess.run(args, env={**os.environ, 'APP_MODE': 'test'}, check=True) | View examples |
| Set child directory | subprocess.run(args, cwd=workspace, check=True) | View examples |
| Start a managed process | with subprocess.Popen(args, stdout=subprocess.PIPE, text=True) as process: stdout, _ = process.communicate() | View examples |
| Drain process pipes | stdout, stderr = process.communicate(input=payload, timeout=10) | View examples |
| Discard a stream | subprocess.run(args, stdout=subprocess.DEVNULL, check=True) | View examples |
Files, OS, and CLI · 15 commands
Python zipfile, tarfile, and Compression Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a ZIP archive | with ZipFile(path, 'w', compression=ZIP_DEFLATED) as archive: archive.write(source, arcname='data.txt') | View examples |
| Write bytes to ZIP | archive.writestr('manifest.json', payload) | View examples |
| Read one ZIP member | with archive.open('manifest.json') as member: data = member.read(limit + 1) | View examples |
| Inspect ZIP metadata | for info in archive.infolist(): print(info.filename, info.file_size, info.compress_size) | View examples |
| Check ZIP CRC values | bad_member = archive.testzip() | View examples |
| Create a compressed tar | with tarfile.open(path, 'w:gz') as archive: archive.add(source, arcname='data') | View examples |
| Detect tar compression | with tarfile.open(path, 'r:*') as archive: members = archive.getmembers() | View examples |
| Add generated bytes to tar | archive.addfile(info, io.BytesIO(payload)) | View examples |
| Use the tar data filter | archive.extractall(destination, filter='data') | View examples |
| Validate ZIP destinations | target = (destination / info.filename).resolve() | View examples |
| Compress with gzip | compressed = gzip.compress(data, compresslevel=6, mtime=0) | View examples |
| Compress with bzip2 | compressed = bz2.compress(data, compresslevel=9) | View examples |
| Compress with XZ | compressed = lzma.compress(data, format=lzma.FORMAT_XZ) | View examples |
| Incremental zlib compression | compressor = zlib.compressobj(level=6) | View examples |
| Create an archive by format | archive_path = shutil.make_archive(base_name, 'zip', root_dir=source_dir) | View examples |
Packages, Testing, and Quality · 15 commands
Python importlib, Metadata, Resources, and Plugins Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Import by name | module = importlib.import_module('package.module') | View examples |
| Resolve a relative import | module = importlib.import_module('.codec', package='app.plugins') | View examples |
| Find a module specification | spec = importlib.util.find_spec('package.module') | View examples |
| Invalidate finder caches | importlib.invalidate_caches() | View examples |
| Read a distribution version | release = importlib.metadata.version('distribution-name') | View examples |
| Read core metadata | details = importlib.metadata.metadata('distribution-name') | View examples |
| Read declared requirements | requirements = importlib.metadata.requires('distribution-name') or [] | View examples |
| Map import to distributions | owners = importlib.metadata.packages_distributions().get('import_name', []) | View examples |
| Get a resource root | root = importlib.resources.files('package_name') | View examples |
| Read a text resource | text = root.joinpath('data/defaults.ini').read_text(encoding='utf-8') | View examples |
| Materialize a resource path | with importlib.resources.as_file(resource) as path: consume(path) | View examples |
| Discover a plugin group | plugins = importlib.metadata.entry_points(group='acme.plugins') | View examples |
| Select one entry point | matches = plugins.select(name='formatter') | View examples |
| Load a plugin object | plugin = entry_point.load() | View examples |
| Handle missing distribution metadata | except importlib.metadata.PackageNotFoundError: use_fallback() | View examples |
Packages, Testing, and Quality · 17 commands
Python Logging and Observability Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a module logger | logger = logging.getLogger(__name__) | View examples |
| Set a logger threshold | logger.setLevel(logging.INFO) | View examples |
| Defer message formatting | logger.info('processed %d records', count) | View examples |
| Guard expensive diagnostics | if logger.isEnabledFor(logging.DEBUG): logger.debug('state=%r', build_state()) | View examples |
| Configure a small application | logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s') | View examples |
| Apply dictionary configuration | logging.config.dictConfig({'version': 1, 'handlers': handlers, 'root': root}) | View examples |
| Preserve existing loggers | config = {'version': 1, 'disable_existing_loggers': False, 'root': root} | View examples |
| Add a stream destination | handler = logging.StreamHandler(sys.stdout) | View examples |
| Set a destination threshold | handler.setLevel(logging.ERROR) | View examples |
| Stop duplicate propagation | logger.propagate = False | View examples |
| Attach event context | logger.info('checkout accepted', extra={'order_id': order_id}) | View examples |
| Reuse stable context | request_log = logging.LoggerAdapter(logger, {'request_id': request_id}) | View examples |
| Record the active exception | except OSError: logger.exception('configuration load failed') | View examples |
| Include exception information | logger.error('operation failed', exc_info=True) | View examples |
| Attribute a helper's caller | logger.warning('deprecated call', stacklevel=2) | View examples |
| Filter one destination | handler.addFilter(lambda record: record.name != 'app.health') | View examples |
| Emit structured records | handler.setFormatter(JsonFormatter()) | View examples |
Packages, Testing, and Quality · 12 commands
Python Modules and Packages Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Import a module | import statistics | View examples |
| Import a name | from pathlib import Path | View examples |
| Alias an import | import collections.abc as cabc | View examples |
| Guard script entry | if __name__ == '__main__': main() | View examples |
| Run by module name | python -m package.module | View examples |
| Regular package marker | package/__init__.py | View examples |
| Relative import | from .formatting import render | View examples |
| Declare star-import names | __all__ = ['Client', 'connect'] | View examples |
| Inspect module identity | print(module.__name__) | View examples |
| Inspect source location | print(module.__file__) | View examples |
| Find without importing | spec = importlib.util.find_spec('package.module') | View examples |
| Read package data | text = resources.files('package').joinpath('defaults.json').read_text() | View examples |
Packages, Testing, and Quality · 19 commands
Python Packaging, Virtual Environments, and pyproject.toml Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a virtual environment | python -m venv .venv | View examples |
| Seed current packaging tools | python -m venv --upgrade-deps .venv | View examples |
| Invoke the environment directly | .venv/bin/python -m pip --version | View examples |
| Declare backend requirements | requires = ['hatchling>=1.26'] # in [build-system] | View examples |
| Select a build backend | build-backend = 'hatchling.build' | View examples |
| Declare Python compatibility | requires-python = '>=3.11' | View examples |
| Declare a runtime dependency | dependencies = ['httpx>=0.27,<1'] | View examples |
| Publish a console command | acme = 'acme.cli:main' # in [project.scripts] | View examples |
| Declare an optional feature | test = ['pytest>=8'] # in [project.optional-dependencies] | View examples |
| Apply deployment constraints | python -m pip install -c constraints.txt -r requirements.txt | View examples |
| Require artifact hashes | python -m pip install --require-hashes -r requirements.txt | View examples |
| Use a src package layout | src/acme/__init__.py | View examples |
| Open packaged text | text = resources.files('acme').joinpath('data.txt').read_text(encoding='utf-8') | View examples |
| Build sdist and wheel | python -m build | View examples |
| Build only a wheel | python -m build --wheel | View examples |
| Install the built wheel | python -m pip install --force-reinstall dist/acme_tools-1.2.0-py3-none-any.whl | View examples |
| Validate distribution metadata | python -m twine check dist/* | View examples |
| Upload to TestPyPI | python -m twine upload --repository testpypi dist/* | View examples |
| Read installed metadata | version = importlib.metadata.version('acme-tools') | View examples |
Packages, Testing, and Quality · 14 commands
Python unittest and Mocking Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a test case | class ParserTests(unittest.TestCase): ... | View examples |
| Declare a test | def test_rejects_empty_input(self): ... | View examples |
| Compare values | self.assertEqual(actual, expected) | View examples |
| Assert an exception | with self.assertRaises(ValueError): parse('') | View examples |
| Assert message text | with self.assertRaisesRegex(ValueError, 'positive'): validate(0) | View examples |
| Prepare each test | def setUp(self): self.client = Client() | View examples |
| Register cleanup | self.addCleanup(resource.close) | View examples |
| Name table cases | with self.subTest(value=value): self.assertTrue(valid(value)) | View examples |
| Create a specified mock | client = Mock(spec=ApiClient) | View examples |
| Patch with signature checks | @patch('module.ApiClient', autospec=True) | View examples |
| Configure a return | client.fetch.return_value = {'status': 'ok'} | View examples |
| Raise or vary calls | client.fetch.side_effect = TimeoutError('slow') | View examples |
| Verify one call | client.fetch.assert_called_once_with('/status') | View examples |
| Use a temporary directory | with tempfile.TemporaryDirectory() as directory: ... | View examples |
Concurrency, Networking, and Performance · 12 commands
Python asyncio and await Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Define a coroutine | async def fetch(): return await client.get('/') | View examples |
| Run an entry coroutine | asyncio.run(main()) | View examples |
| Await completion | result = await operation() | View examples |
| Schedule a task | task = asyncio.create_task(operation()) | View examples |
| Group child tasks | async with asyncio.TaskGroup() as group: group.create_task(operation()) | View examples |
| Collect ordered results | results = await asyncio.gather(*coroutines) | View examples |
| Bound a block by time | async with asyncio.timeout(5): result = await operation() | View examples |
| Request cancellation | task.cancel() | View examples |
| Yield to the loop | await asyncio.sleep(0) | View examples |
| Create a bounded queue | queue = asyncio.Queue(maxsize=100) | View examples |
| Bound concurrent access | async with asyncio.Semaphore(10): await operation() | View examples |
| Run blocking I/O in a thread | result = await asyncio.to_thread(blocking_function, argument) | View examples |
Concurrency, Networking, and Performance · 16 commands
Python concurrent.futures and Parallel Work Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a thread pool | with ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(fetch, urls)) | View examples |
| Create a process pool | with ProcessPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values)) | View examples |
| Create an interpreter pool | with InterpreterPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values)) | View examples |
| Submit one call | future = executor.submit(function, argument) | View examples |
| Retrieve a result | value = future.result(timeout=5) | View examples |
| Add a completion callback | future.add_done_callback(record_completion) | View examples |
| Map in input order | results = executor.map(function, items) | View examples |
| Bound submitted map work | results = executor.map(function, items, buffersize=16) | View examples |
| Batch process-pool items | results = executor.map(function, items, chunksize=64) | View examples |
| Consume completed futures | results = [future.result() for future in as_completed(futures)] | View examples |
| Wait for a condition | done, pending = wait(futures, timeout=5, return_when=FIRST_EXCEPTION) | View examples |
| Limit a result wait | future.result(timeout=2) | View examples |
| Cancel pending work | cancelled = future.cancel() | View examples |
| Shut down an executor | executor.shutdown(wait=True, cancel_futures=True) | View examples |
| Guard process entry | if __name__ == '__main__': main() | View examples |
| Choose a process context | ProcessPoolExecutor(mp_context=multiprocessing.get_context('spawn')) | View examples |
Concurrency, Networking, and Performance · 20 commands
Python Hashing, HMAC, and Secrets Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Hash bytes with SHA-256 | digest = hashlib.sha256(data).digest() | View examples |
| Render a hexadecimal digest | text = hashlib.sha256(data).hexdigest() | View examples |
| Hash data incrementally | hasher.update(chunk) | View examples |
| Hash an open binary file | with path.open('rb') as file: digest = hashlib.file_digest(file, 'sha256') | View examples |
| Branch a partial hash | branch = hasher.copy() | View examples |
| Construct an algorithm by name | hasher = hashlib.new('sha256', data) | View examples |
| Inspect portable algorithms | portable = hashlib.algorithms_guaranteed | View examples |
| Build an HMAC incrementally | mac = hmac.new(key, message, digestmod=hashlib.sha256) | View examples |
| Calculate an HMAC in one call | tag = hmac.digest(key, message, 'sha256') | View examples |
| Compare authenticators safely | valid = hmac.compare_digest(received_tag, expected_tag) | View examples |
| Generate random secret bytes | key = secrets.token_bytes(32) | View examples |
| Generate a hexadecimal token | token = secrets.token_hex(32) | View examples |
| Generate a URL-safe token | token = secrets.token_urlsafe(32) | View examples |
| Choose securely from a sequence | character = secrets.choice(alphabet) | View examples |
| Generate a bounded integer | index = secrets.randbelow(exclusive_upper_bound) | View examples |
| Derive a PBKDF2 verifier | derived = hashlib.pbkdf2_hmac('sha256', password, salt, iterations, dklen=32) | View examples |
| Derive a scrypt verifier | derived = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1, dklen=32) | View examples |
| Create a unique password salt | salt = secrets.token_bytes(16) | View examples |
| Authenticate with keyed BLAKE2 | tag = hashlib.blake2b(message, key=key, digest_size=32).digest() | View examples |
| Separate BLAKE2 domains | digest = hashlib.blake2b(data, person=b'cache-v1', digest_size=16).digest() | View examples |
Concurrency, Networking, and Performance · 15 commands
Python Memory, Garbage Collection, and Weak References Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Measure shallow size | shallow_bytes = sys.getsizeof(value) | View examples |
| Inspect CPython references | count_with_temporary = sys.getrefcount(value) | View examples |
| Run cyclic collection | unreachable = gc.collect() | View examples |
| Check collector state | collector_enabled = gc.isenabled() | View examples |
| Read GC thresholds | thresholds = gc.get_threshold() | View examples |
| Freeze tracked objects | gc.freeze() | View examples |
| Create a weak reference | reference = weakref.ref(instance) | View examples |
| Cache values weakly | cache = weakref.WeakValueDictionary() | View examples |
| Associate metadata weakly | metadata = weakref.WeakKeyDictionary() | View examples |
| Track instances weakly | instances = weakref.WeakSet() | View examples |
| Register a finalizer | cleanup = weakref.finalize(owner, close_resource, resource_id) | View examples |
| Start allocation tracing | tracemalloc.start(10) | View examples |
| Capture a snapshot | snapshot = tracemalloc.take_snapshot() | View examples |
| Compare snapshots | changes = after.compare_to(before, 'lineno') | View examples |
| Read traced current and peak | current, peak = tracemalloc.get_traced_memory() | View examples |



