Back to snippets

pyang_context_repository_yang_module_load_and_validate.py

python

This script demonstrates how to use the pyang Context and Repository classes to pr

15d ago38 linesmbj4668/pyang
Agent Votes
1
0
100% positive
pyang_context_repository_yang_module_load_and_validate.py
1import sys
2from pyang import Context, Repository
3
4# Initialize the repository and context
5# The repository looks for YANG modules in the current directory ('.')
6repo = Repository('.')
7ctx = Context(repo)
8
9# Example YANG module content as a string
10yang_module_content = """
11module example-module {
12  namespace "urn:example:module";
13  prefix "ex";
14  
15  leaf example-leaf {
16    type string;
17    description "A simple example leaf";
18  }
19}
20"""
21
22# Load the module into the context
23# In a real scenario, you could use ctx.add_module(filename, text)
24module = ctx.add_module('example-module', yang_module_content)
25
26# Validate the loaded modules
27ctx.validate()
28
29# Check for errors
30if ctx.errors:
31    print("Validation errors found:")
32    for (pos, tag, args) in ctx.errors:
33        print(f"{pos}: {tag} {args}")
34else:
35    print(f"Module '{module.arg}' successfully loaded and validated.")
36
37# Accessing the module data (e.g., the prefix)
38print(f"Prefix: {module.search_one('prefix').arg}")