On this page
  1. netrc
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Graceful Fallback When .netrc Is Missing
  7. Gotchas & Boundaries
  8. Classes & Objects

netrc

Prev: multiprocessing | Up: stdlib_module | Next: nt
Rel: csv, configparser, tomllib, plistlib
Ref: docs.python.org โ€” netrc
Tags: #public #python3 #stdlib


Import

import netrc

Overview

Parser for Unix .netrc configuration files (machine, login, account, password, default). Use netrc when writing CLI tools or HTTP/FTP clients that honor a user's existing .netrc entries instead of prompting interactively or hardcoding configuration values.

Quick Start

import netrc
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    rc = Path(tmp) / "sample_netrc"
    rc.write_text("machine api.example.com login demo_user password demo_val\n", encoding="utf-8")
    rc.chmod(0o600)

    auth = netrc.netrc(rc).authenticators("api.example.com")
    assert auth == ("demo_user", None, "demo_val")

Implementation Walkthrough

1. Graceful Fallback When .netrc Is Missing

Wrap netrc.netrc() to handle missing files or permission errors cleanly before falling back to environment variables or getpass:

import netrc

def lookup_creds(host: str) -> tuple[str, str] | None:
    try:
        auth = netrc.netrc().authenticators(host)
    except (FileNotFoundError, netrc.NetrcParseError):
        return None
    if auth is None:
        return None
    login, _account, value = auth
    return (login, value)

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes