Pythonic way to manage hosts file
Project description
pyhosts
Manage system hosts files (
/etc/hosts) the Pythonic way.
- Platform independent — Linux, macOS, Windows
- Zero dependencies — uses Python standard library only
- Type-safe — full type hints,
py.typed, strict mypy - Immutable models — frozen dataclasses for safety
- List-like API — implements
MutableSequenceprotocol - Lazy loading — file is read only when accessed
Installation
pip install pyhosts
Quick Start
from pyhosts import Hosts
# Load the system hosts file
hosts = Hosts()
# Iterate over entries
for host in hosts:
print(f"{host.ip_address} {host.hostname}")
# Attribute-style access
localhost = hosts.localhost
print(localhost.ip_address) # IPv4Address('127.0.0.1')
# Check membership
if "localhost" in hosts:
print("found!")
Usage
Search
# Find all entries matching IP, hostname, or alias
results = hosts.find("192.168.1.1")
results = hosts.find("localhost")
# Find first match
host = hosts.find_one("localhost")
Add and Remove
from pyhosts import Host
from ipaddress import ip_address
# Create a new entry
entry = Host(
ip_address=ip_address("192.168.1.100"),
hostname="myserver",
aliases=("server", "web"),
comment="Production server",
)
# Add it
hosts.add(entry)
# Remove by query
count = hosts.remove("myserver")
Save
# Save changes to disk
hosts.save()
# Save with automatic backup
hosts.save(backup=True)
List-style Access
# Index, slice, len, in — it's a MutableSequence
first = hosts[0]
total = len(hosts)
hosts[0] = new_entry
del hosts[2]
API Reference
Hosts
The main class for managing the hosts file.
| Method | Description |
|---|---|
load() |
Load entries from hosts file |
save(backup=False, write_header=True) |
Save entries to hosts file |
find(query) |
Find all entries matching query (IP, hostname, or alias) |
find_one(query) |
Find first matching entry |
add(host, allow_duplicates=False) |
Add a new entry |
remove(query) |
Remove all entries matching query, returns count |
Supports full MutableSequence interface: indexing, slicing, iteration, len(), in, del.
Note:
Hostsis not thread-safe. Use external synchronisation (e.g.threading.Lock) when sharing an instance across threads.
Host
Immutable (frozen) dataclass representing a single hosts file entry.
| Attribute | Type | Description |
|---|---|---|
ip_address |
IPv4Address | IPv6Address |
IP address |
hostname |
str |
Primary hostname |
aliases |
tuple[str, ...] |
Alias hostnames |
comment |
str | None |
Inline comment |
| Method | Description |
|---|---|
Host.from_line(line) |
Parse a hosts file line |
to_line() |
Format as hosts file line |
matches(query) |
Check if entry matches query |
all_names |
Property: hostname + aliases |
Exceptions
| Exception | Description |
|---|---|
DuplicateEntryError |
Raised when adding a duplicate entry |
PlatformNotSupportedError |
Raised on unsupported platforms |
Requirements
- Python 3.10+
- No external dependencies
Development
# Clone and install
git clone https://github.com/igormilovanovic/pyhosts.git
cd pyhosts
pip install -e .
pip install -r test-requirements.txt
# Run tests
pytest test/ -v
# Run tests with coverage
pytest test/ -v --cov=pyhosts
# Lint
pycodestyle pyhosts/ --max-line-length=120
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyhosts-0.3.1.tar.gz.
File metadata
- Download URL: pyhosts-0.3.1.tar.gz
- Upload date:
- Size: 17.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
25fdec2e4ba33ad52bc446749776dfa748be74e60f66c07bdef139e59d3e5c00
|
|
| MD5 |
8d9fd3e41bffc0ee8bba97286eac6263
|
|
| BLAKE2b-256 |
05a229ca6ff92fd7f0cd73a6aadf9bf306973b34b90c9dc980a1477b566fc277
|
Provenance
The following attestation bundles were made for pyhosts-0.3.1.tar.gz:
Publisher:
python-publish.yml on igormilovanovic/pyhosts
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyhosts-0.3.1.tar.gz -
Subject digest:
25fdec2e4ba33ad52bc446749776dfa748be74e60f66c07bdef139e59d3e5c00 - Sigstore transparency entry: 992674985
- Sigstore integration time:
-
Permalink:
igormilovanovic/pyhosts@812c2941d9996040ec68d319a87124f3df5638fe -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/igormilovanovic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@812c2941d9996040ec68d319a87124f3df5638fe -
Trigger Event:
release
-
Statement type:
File details
Details for the file pyhosts-0.3.1-py3-none-any.whl.
File metadata
- Download URL: pyhosts-0.3.1-py3-none-any.whl
- Upload date:
- Size: 11.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ae25dea7b111daab48201a85d06452f7b4f2399ed27aee4607defbf6c45e8caa
|
|
| MD5 |
359dd20b3e371e115e4659ca391db147
|
|
| BLAKE2b-256 |
37d3155e41793895c730fc4e30707da87d089baa431204d3abe64fcf16852422
|
Provenance
The following attestation bundles were made for pyhosts-0.3.1-py3-none-any.whl:
Publisher:
python-publish.yml on igormilovanovic/pyhosts
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyhosts-0.3.1-py3-none-any.whl -
Subject digest:
ae25dea7b111daab48201a85d06452f7b4f2399ed27aee4607defbf6c45e8caa - Sigstore transparency entry: 992674990
- Sigstore integration time:
-
Permalink:
igormilovanovic/pyhosts@812c2941d9996040ec68d319a87124f3df5638fe -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/igormilovanovic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@812c2941d9996040ec68d319a87124f3df5638fe -
Trigger Event:
release
-
Statement type: