Unit 6 — Modules — Organizing Your Network Scripts
What Is a Module?
A module is a Python file you can import into another script. It lets you split your code into reusable pieces instead of writing everything in one long file.
You have already used a module — sys in Unit 2. Python ships with hundreds of built-in modules. You can also write your own.
Importing Built-in Modules
import os
import sys
import json
import re
Once imported, you access the module's functions with a dot:
import os
print(os.getcwd()) # current working directory
print(os.path.exists("devices.txt")) # does this file exist?
Import just what you need with from ... import:
from os.path import exists, basename
print(exists("devices.txt"))
print(basename("/home/emmy/scripts/check.py")) # check.py
Creating Your Own Module
Any .py file is a module. Create device_utils.py:
# device_utils.py
def format_hostname(name):
return name.strip().lower()
def get_device_type(hostname):
if hostname.startswith("sw"):
return "switch"
elif hostname.startswith("rtr"):
return "router"
elif hostname.startswith("fw"):
return "firewall"
else:
return "unknown"
Import it in another script in the same directory:
import device_utils
print(device_utils.format_hostname(" SW-CORE-01 "))
print(device_utils.get_device_type("rtr-edge-01"))
Output:
sw-core-01
router
Exploring a Module with dir()
dir() lists everything available in a module. Useful when you want to know what tools a module has:
import json
print(dir(json))
To filter out private internals (names starting with _):
public = [x for x in dir(json) if not x.startswith("_")]
print(public)
Check if a specific function is in a module:
import os
print("getcwd" in dir(os)) # True
print("path" in dir(os)) # True
Running a Module as a Script
Sometimes you want a module to do something when run directly but behave as a normal import when used by another script. Use __name__:
# device_utils.py
def format_hostname(name):
return name.strip().lower()
if __name__ == "__main__":
# This block only runs when the file is executed directly
print(format_hostname(" SW-CORE-01 "))
When you run python3 device_utils.py — the block runs. When another script imports it — the block is skipped.
Summary
- A module is any
.pyfile — import it withimport module_name - Built-in modules like
os,sys,json,regive you powerful tools with zero setup - Your own modules let you share functions across multiple scripts
from module import funcimports just one function — no need to prefix it with the module namedir(module)shows everything a module containsif __name__ == "__main__"lets a file work both as a module and a standalone script