tinynetrc

1.3.1 · maintenance · verified Thu Apr 16

tinynetrc is a Python library designed to read and write .netrc files. It extends the standard library's `netrc` module by adding crucial write functionality, resolving a known bug with .netrc file formatting, and parsing entries into more accessible dictionary values instead of tuples. The library is currently at version 1.3.1 and is in a maintenance status, with infrequent but stable updates.

Common errors

Warnings

Install

Imports

Quickstart

The quickstart demonstrates reading, modifying, and saving a .netrc file using `tinynetrc`. It highlights the use of the context manager for automatic saving and direct dictionary-like access to machine entries. It also includes an example of explicit loading and saving.

import os
from tinynetrc import Netrc

# Define the path to the .netrc file (defaults to ~/.netrc)
netrc_path = os.path.expanduser('~/.netrc')

# Example: Read and modify a .netrc file using a context manager
# The file will be automatically saved on exit from the 'with' block
try:
    with Netrc(netrc_path) as netrc:
        # Add or update credentials for a machine
        netrc['api.example.com'] = {'login': 'myuser', 'password': os.environ.get('API_EXAMPLE_PASSWORD', 'default_password')}
        print(f"Credentials for api.example.com set to: {netrc['api.example.com']}")

        # Access credentials for an existing machine
        if 'api.heroku.com' in netrc:
            heroku_creds = netrc['api.heroku.com']
            print(f"Heroku credentials: {heroku_creds['login']} / {'*' * len(heroku_creds['password'])}")
        else:
            print("No credentials found for api.heroku.com")

        # Delete an entry
        if 'old.host.com' in netrc:
            del netrc['old.host.com']
            print("Removed old.host.com entry.")

except Exception as e:
    print(f"An error occurred: {e}")

# Example: Explicitly load and save
try:
    netrc = Netrc(netrc_path)
    netrc.load()
    if 'another.service.com' not in netrc:
        netrc['another.service.com'] = {'login': 'serviceuser', 'password': 'servicepass'}
        netrc.save()
        print("Added and saved credentials for another.service.com")
except Exception as e:
    print(f"An error occurred during explicit load/save: {e}")

view raw JSON →