Python Hostlist
python-hostlist is a Python module designed for parsing and expanding hostlist strings (e.g., 'host[01-03],host[05,07]'). It can expand such strings into a list of individual hostnames and also compress a list of hostnames back into a compact hostlist string. The library is actively maintained, with releases typically driven by bug fixes or minor feature additions.
Common errors
-
ModuleNotFoundError: No module named 'python_hostlist'
cause Attempting to import the module using the package name (`python_hostlist`) instead of its internal module name (`hostlist`).fixChange `import python_hostlist` to `import hostlist`. -
hostlist.HostlistFormatException: Invalid Hostlist: host[1-a]
cause The input string provided to functions like `expand_hostlist` does not conform to the expected hostlist format.fixReview the hostlist string for syntax errors. Ensure ranges are numeric (e.g., `host[01-03]`) and separators are correct. Consider using `hostlist.is_hostlist()` to pre-validate inputs. -
The compressed hostlist string is not as compact or ordered as expected.
cause The input list of hostnames provided to `compress_hostlist` was not sorted, leading to sub-optimal compression or unusual ordering.fixSort the list of hostnames before passing it to the compression function: `hostlist.compress_hostlist(sorted(my_hostnames))`.
Warnings
- breaking Python 2 support was dropped in version 2.0.0. All versions >= 2.0.0 require Python 3 (specifically >=3.6).
- breaking The `hostlist.get_ranges()` and `hostlist.get_groups()` functions were removed in version 2.2.0.
- gotcha The `compress_hostlist` function expects a sorted list of hostnames for optimal and consistent compression. Providing an unsorted list may result in a less efficient or unexpectedly formatted hostlist string.
- gotcha Invalid hostlist string formats will raise a `hostlist.HostlistFormatException`.
Install
-
pip install python-hostlist
Imports
- hostlist
import python_hostlist
import hostlist
Quickstart
import hostlist
# Expand a hostlist string
expanded_hosts = hostlist.expand_hostlist('host[01-03,05],server[10-12]')
print(f"Expanded: {expanded_hosts}")
# Compress a list of hostnames
hostnames = ['node01', 'node02', 'node03', 'node05', 'node07']
compressed_string = hostlist.compress_hostlist(hostnames)
print(f"Compressed: {compressed_string}")
# Check if a string is a valid hostlist
is_valid = hostlist.is_hostlist('test[1-5]')
print(f"Is 'test[1-5]' a valid hostlist? {is_valid}")
is_invalid = hostlist.is_hostlist('test[1-a]')
print(f"Is 'test[1-a]' a valid hostlist? {is_invalid}")