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

Open full cheat sheet
UseSyntaxExamples
Run an argument sequencesubprocess.run([program, '--flag', value], check=True)View examples
Reuse this Pythonsubprocess.run([sys.executable, '-m', 'package'], check=True)View examples
Capture both streamsresult = subprocess.run(args, capture_output=True, text=True)View examples
Choose text encodingsubprocess.run(args, capture_output=True, text=True, encoding='utf-8')View examples
Merge stderr into stdoutsubprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)View examples
Require successresult = subprocess.run(args, check=True)View examples
Check after inspectionresult.check_returncode()View examples
Read the exit statusif result.returncode != 0: handle_failure(result.stderr)View examples
Bound runtimesubprocess.run(args, timeout=10, check=True)View examples
Handle expirationexcept subprocess.TimeoutExpired as exc: report(exc.cmd, exc.timeout)View examples
Send standard inputsubprocess.run(args, input=payload, text=True, check=True)View examples
Set child environmentsubprocess.run(args, env={**os.environ, 'APP_MODE': 'test'}, check=True)View examples
Set child directorysubprocess.run(args, cwd=workspace, check=True)View examples
Start a managed processwith subprocess.Popen(args, stdout=subprocess.PIPE, text=True) as process: stdout, _ = process.communicate()View examples
Drain process pipesstdout, stderr = process.communicate(input=payload, timeout=10)View examples
Discard a streamsubprocess.run(args, stdout=subprocess.DEVNULL, check=True)View examples

Files, OS, and CLI · 15 commands

Python zipfile, tarfile, and Compression Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a ZIP archivewith ZipFile(path, 'w', compression=ZIP_DEFLATED) as archive: archive.write(source, arcname='data.txt')View examples
Write bytes to ZIParchive.writestr('manifest.json', payload)View examples
Read one ZIP memberwith archive.open('manifest.json') as member: data = member.read(limit + 1)View examples
Inspect ZIP metadatafor info in archive.infolist(): print(info.filename, info.file_size, info.compress_size)View examples
Check ZIP CRC valuesbad_member = archive.testzip()View examples
Create a compressed tarwith tarfile.open(path, 'w:gz') as archive: archive.add(source, arcname='data')View examples
Detect tar compressionwith tarfile.open(path, 'r:*') as archive: members = archive.getmembers()View examples
Add generated bytes to tararchive.addfile(info, io.BytesIO(payload))View examples
Use the tar data filterarchive.extractall(destination, filter='data')View examples
Validate ZIP destinationstarget = (destination / info.filename).resolve()View examples
Compress with gzipcompressed = gzip.compress(data, compresslevel=6, mtime=0)View examples
Compress with bzip2compressed = bz2.compress(data, compresslevel=9)View examples
Compress with XZcompressed = lzma.compress(data, format=lzma.FORMAT_XZ)View examples
Incremental zlib compressioncompressor = zlib.compressobj(level=6)View examples
Create an archive by formatarchive_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

Open full cheat sheet
UseSyntaxExamples
Import by namemodule = importlib.import_module('package.module')View examples
Resolve a relative importmodule = importlib.import_module('.codec', package='app.plugins')View examples
Find a module specificationspec = importlib.util.find_spec('package.module')View examples
Invalidate finder cachesimportlib.invalidate_caches()View examples
Read a distribution versionrelease = importlib.metadata.version('distribution-name')View examples
Read core metadatadetails = importlib.metadata.metadata('distribution-name')View examples
Read declared requirementsrequirements = importlib.metadata.requires('distribution-name') or []View examples
Map import to distributionsowners = importlib.metadata.packages_distributions().get('import_name', [])View examples
Get a resource rootroot = importlib.resources.files('package_name')View examples
Read a text resourcetext = root.joinpath('data/defaults.ini').read_text(encoding='utf-8')View examples
Materialize a resource pathwith importlib.resources.as_file(resource) as path: consume(path)View examples
Discover a plugin groupplugins = importlib.metadata.entry_points(group='acme.plugins')View examples
Select one entry pointmatches = plugins.select(name='formatter')View examples
Load a plugin objectplugin = entry_point.load()View examples
Handle missing distribution metadataexcept importlib.metadata.PackageNotFoundError: use_fallback()View examples

Packages, Testing, and Quality · 17 commands

Python Logging and Observability Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a module loggerlogger = logging.getLogger(__name__)View examples
Set a logger thresholdlogger.setLevel(logging.INFO)View examples
Defer message formattinglogger.info('processed %d records', count)View examples
Guard expensive diagnosticsif logger.isEnabledFor(logging.DEBUG): logger.debug('state=%r', build_state())View examples
Configure a small applicationlogging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s')View examples
Apply dictionary configurationlogging.config.dictConfig({'version': 1, 'handlers': handlers, 'root': root})View examples
Preserve existing loggersconfig = {'version': 1, 'disable_existing_loggers': False, 'root': root}View examples
Add a stream destinationhandler = logging.StreamHandler(sys.stdout)View examples
Set a destination thresholdhandler.setLevel(logging.ERROR)View examples
Stop duplicate propagationlogger.propagate = FalseView examples
Attach event contextlogger.info('checkout accepted', extra={'order_id': order_id})View examples
Reuse stable contextrequest_log = logging.LoggerAdapter(logger, {'request_id': request_id})View examples
Record the active exceptionexcept OSError: logger.exception('configuration load failed')View examples
Include exception informationlogger.error('operation failed', exc_info=True)View examples
Attribute a helper's callerlogger.warning('deprecated call', stacklevel=2)View examples
Filter one destinationhandler.addFilter(lambda record: record.name != 'app.health')View examples
Emit structured recordshandler.setFormatter(JsonFormatter())View examples

Packages, Testing, and Quality · 12 commands

Python Modules and Packages Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Import a moduleimport statisticsView examples
Import a namefrom pathlib import PathView examples
Alias an importimport collections.abc as cabcView examples
Guard script entryif __name__ == '__main__': main()View examples
Run by module namepython -m package.moduleView examples
Regular package markerpackage/__init__.pyView examples
Relative importfrom .formatting import renderView examples
Declare star-import names__all__ = ['Client', 'connect']View examples
Inspect module identityprint(module.__name__)View examples
Inspect source locationprint(module.__file__)View examples
Find without importingspec = importlib.util.find_spec('package.module')View examples
Read package datatext = 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

Open full cheat sheet
UseSyntaxExamples
Create a virtual environmentpython -m venv .venvView examples
Seed current packaging toolspython -m venv --upgrade-deps .venvView examples
Invoke the environment directly.venv/bin/python -m pip --versionView examples
Declare backend requirementsrequires = ['hatchling>=1.26'] # in [build-system]View examples
Select a build backendbuild-backend = 'hatchling.build'View examples
Declare Python compatibilityrequires-python = '>=3.11'View examples
Declare a runtime dependencydependencies = ['httpx>=0.27,<1']View examples
Publish a console commandacme = 'acme.cli:main' # in [project.scripts]View examples
Declare an optional featuretest = ['pytest>=8'] # in [project.optional-dependencies]View examples
Apply deployment constraintspython -m pip install -c constraints.txt -r requirements.txtView examples
Require artifact hashespython -m pip install --require-hashes -r requirements.txtView examples
Use a src package layoutsrc/acme/__init__.pyView examples
Open packaged texttext = resources.files('acme').joinpath('data.txt').read_text(encoding='utf-8')View examples
Build sdist and wheelpython -m buildView examples
Build only a wheelpython -m build --wheelView examples
Install the built wheelpython -m pip install --force-reinstall dist/acme_tools-1.2.0-py3-none-any.whlView examples
Validate distribution metadatapython -m twine check dist/*View examples
Upload to TestPyPIpython -m twine upload --repository testpypi dist/*View examples
Read installed metadataversion = importlib.metadata.version('acme-tools')View examples

Packages, Testing, and Quality · 14 commands

Python unittest and Mocking Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a test caseclass ParserTests(unittest.TestCase): ...View examples
Declare a testdef test_rejects_empty_input(self): ...View examples
Compare valuesself.assertEqual(actual, expected)View examples
Assert an exceptionwith self.assertRaises(ValueError): parse('')View examples
Assert message textwith self.assertRaisesRegex(ValueError, 'positive'): validate(0)View examples
Prepare each testdef setUp(self): self.client = Client()View examples
Register cleanupself.addCleanup(resource.close)View examples
Name table caseswith self.subTest(value=value): self.assertTrue(valid(value))View examples
Create a specified mockclient = Mock(spec=ApiClient)View examples
Patch with signature checks@patch('module.ApiClient', autospec=True)View examples
Configure a returnclient.fetch.return_value = {'status': 'ok'}View examples
Raise or vary callsclient.fetch.side_effect = TimeoutError('slow')View examples
Verify one callclient.fetch.assert_called_once_with('/status')View examples
Use a temporary directorywith tempfile.TemporaryDirectory() as directory: ...View examples

Concurrency, Networking, and Performance · 12 commands

Python asyncio and await Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Define a coroutineasync def fetch(): return await client.get('/')View examples
Run an entry coroutineasyncio.run(main())View examples
Await completionresult = await operation()View examples
Schedule a tasktask = asyncio.create_task(operation())View examples
Group child tasksasync with asyncio.TaskGroup() as group: group.create_task(operation())View examples
Collect ordered resultsresults = await asyncio.gather(*coroutines)View examples
Bound a block by timeasync with asyncio.timeout(5): result = await operation()View examples
Request cancellationtask.cancel()View examples
Yield to the loopawait asyncio.sleep(0)View examples
Create a bounded queuequeue = asyncio.Queue(maxsize=100)View examples
Bound concurrent accessasync with asyncio.Semaphore(10): await operation()View examples
Run blocking I/O in a threadresult = await asyncio.to_thread(blocking_function, argument)View examples

Concurrency, Networking, and Performance · 16 commands

Python concurrent.futures and Parallel Work Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a thread poolwith ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(fetch, urls))View examples
Create a process poolwith ProcessPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values))View examples
Create an interpreter poolwith InterpreterPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values))View examples
Submit one callfuture = executor.submit(function, argument)View examples
Retrieve a resultvalue = future.result(timeout=5)View examples
Add a completion callbackfuture.add_done_callback(record_completion)View examples
Map in input orderresults = executor.map(function, items)View examples
Bound submitted map workresults = executor.map(function, items, buffersize=16)View examples
Batch process-pool itemsresults = executor.map(function, items, chunksize=64)View examples
Consume completed futuresresults = [future.result() for future in as_completed(futures)]View examples
Wait for a conditiondone, pending = wait(futures, timeout=5, return_when=FIRST_EXCEPTION)View examples
Limit a result waitfuture.result(timeout=2)View examples
Cancel pending workcancelled = future.cancel()View examples
Shut down an executorexecutor.shutdown(wait=True, cancel_futures=True)View examples
Guard process entryif __name__ == '__main__': main()View examples
Choose a process contextProcessPoolExecutor(mp_context=multiprocessing.get_context('spawn'))View examples

Concurrency, Networking, and Performance · 20 commands

Python Hashing, HMAC, and Secrets Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Hash bytes with SHA-256digest = hashlib.sha256(data).digest()View examples
Render a hexadecimal digesttext = hashlib.sha256(data).hexdigest()View examples
Hash data incrementallyhasher.update(chunk)View examples
Hash an open binary filewith path.open('rb') as file: digest = hashlib.file_digest(file, 'sha256')View examples
Branch a partial hashbranch = hasher.copy()View examples
Construct an algorithm by namehasher = hashlib.new('sha256', data)View examples
Inspect portable algorithmsportable = hashlib.algorithms_guaranteedView examples
Build an HMAC incrementallymac = hmac.new(key, message, digestmod=hashlib.sha256)View examples
Calculate an HMAC in one calltag = hmac.digest(key, message, 'sha256')View examples
Compare authenticators safelyvalid = hmac.compare_digest(received_tag, expected_tag)View examples
Generate random secret byteskey = secrets.token_bytes(32)View examples
Generate a hexadecimal tokentoken = secrets.token_hex(32)View examples
Generate a URL-safe tokentoken = secrets.token_urlsafe(32)View examples
Choose securely from a sequencecharacter = secrets.choice(alphabet)View examples
Generate a bounded integerindex = secrets.randbelow(exclusive_upper_bound)View examples
Derive a PBKDF2 verifierderived = hashlib.pbkdf2_hmac('sha256', password, salt, iterations, dklen=32)View examples
Derive a scrypt verifierderived = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1, dklen=32)View examples
Create a unique password saltsalt = secrets.token_bytes(16)View examples
Authenticate with keyed BLAKE2tag = hashlib.blake2b(message, key=key, digest_size=32).digest()View examples
Separate BLAKE2 domainsdigest = 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

Open full cheat sheet
UseSyntaxExamples
Measure shallow sizeshallow_bytes = sys.getsizeof(value)View examples
Inspect CPython referencescount_with_temporary = sys.getrefcount(value)View examples
Run cyclic collectionunreachable = gc.collect()View examples
Check collector statecollector_enabled = gc.isenabled()View examples
Read GC thresholdsthresholds = gc.get_threshold()View examples
Freeze tracked objectsgc.freeze()View examples
Create a weak referencereference = weakref.ref(instance)View examples
Cache values weaklycache = weakref.WeakValueDictionary()View examples
Associate metadata weaklymetadata = weakref.WeakKeyDictionary()View examples
Track instances weaklyinstances = weakref.WeakSet()View examples
Register a finalizercleanup = weakref.finalize(owner, close_resource, resource_id)View examples
Start allocation tracingtracemalloc.start(10)View examples
Capture a snapshotsnapshot = tracemalloc.take_snapshot()View examples
Compare snapshotschanges = after.compare_to(before, 'lineno')View examples
Read traced current and peakcurrent, peak = tracemalloc.get_traced_memory()View examples

Concurrency, Networking, and Performance · 26 commands

Python multiprocessing and Shared Memory Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List available start methodsmethods = multiprocessing.get_all_start_methods()View examples
Create an explicit contextctx = multiprocessing.get_context('spawn')View examples
Set the global start methodmultiprocessing.set_start_method('spawn')View examples
Guard application startupif __name__ == '__main__': main()View examples
Start one processprocess = ctx.Process(target=worker, args=(input_value,)); process.start()View examples
Wait for process completionprocess.join(timeout=5)View examples
Release a Process handleprocess.close()View examples
Map work through a poolwith ctx.Pool(processes=4) as pool: results = pool.map(transform, items, chunksize=32)View examples
Submit an asynchronous pool callpending = pool.apply_async(transform, (item,)); result = pending.get(timeout=5)View examples
Drain and close a poolpool.close(); pool.join()View examples
Send a queued messagequeue.put(message); received = queue.get(timeout=5)View examples
Create a one-way pipereceiver, sender = ctx.Pipe(duplex=False)View examples
Wait for ready connectionsready = multiprocessing.connection.wait(connections, timeout=5)View examples
Signal workers with an Eventready.set(); ready.wait(timeout=5)View examples
Protect a critical sectionwith lock: shared_value.value += 1View examples
Create a synchronized scalarcounter = ctx.Value('i', 0)View examples
Create a shared-memory blockblock = SharedMemory(create=True, size=byte_count)View examples
Attach by shared-memory nameblock = SharedMemory(name=block_name)View examples
Close and unlink shared memoryblock.close(); block.unlink()View examples
Opt out of resource trackingblock = SharedMemory(name=block_name, track=False)View examples
Run a manager serverwith ctx.Manager() as manager: shared = manager.dict()View examples
Create a managed listshared_items = manager.list(initial_items)View examples
Receive only trusted objectsmessage = connection.recv()View examples
Use an importable workerdef worker(payload): return process_payload(payload)View examples
Request cooperative shutdownstop_event.set(); process.join(timeout=5)View examples
Terminate an unresponsive processif process.is_alive(): process.terminate(); process.join()View examples
CMDMEMO TERMINALREAD ONLY