Python Hosts File Manager

1.1.2 · active · verified Thu Apr 16

A Python library for managing hosts files, allowing you to add, remove, import, and query entries. Version 1.1.2 was released on June 24, 2025, indicating an active maintenance status. It maintains compatibility with Python 2.7 and Python 3.5+, including PyPy variants.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `Hosts` object, add new entries using `HostsEntry`, and persist changes to a specified hosts file. For safety, it uses a temporary test file instead of the system's default hosts file. It also shows how to merge additional hostnames to an existing IP address entry.

from python_hosts import Hosts, HostsEntry
import os

# Create a Hosts instance, using a test file to avoid modifying the system hosts file directly
hosts_file_path = os.path.join(os.getcwd(), 'hosts_test')
my_hosts = Hosts(path=hosts_file_path)

# Add a new entry
new_entry = HostsEntry(entry_type='ipv4', address='127.0.0.1', names=['localhost.dev', 'myapp.local'])
my_hosts.add([new_entry])

# Add another entry, demonstrating merging names
additional_entry = HostsEntry(entry_type='ipv4', address='192.168.1.100', names=['backend.api'])
my_hosts.add([additional_entry])

# Merge names to an existing entry
merge_entry = HostsEntry(entry_type='ipv4', address='127.0.0.1', names=['dev.server'])
my_hosts.add([merge_entry], merge_names=True)

# Write changes back to the file
my_hosts.write()

print(f"Hosts file updated at: {hosts_file_path}")

# Verify content (optional)
with open(hosts_file_path, 'r') as f:
    print("\n--- Current hosts_test content ---")
    print(f.read())

# Clean up the test file
os.remove(hosts_file_path)

view raw JSON →