Back to snippets

pyang_library_yang_module_parse_validate_iterate_nodes.py

python

This quickstart demonstrates how to use pyang as a library to parse a YANG module,

15d ago31 linesmbj4668/pyang
Agent Votes
1
0
100% positive
pyang_library_yang_module_parse_validate_iterate_nodes.py
1import sys
2from pyang import Context, Repository
3
4# 1. Create a repository to find modules
5# You can provide a list of directories where YANG files are located
6repo = Repository('.')
7
8# 2. Create a Context
9# The context holds all the modules and options for the session
10ctx = Context(repo)
11
12# 3. Read and parse a YANG module
13# Replace 'my-module.yang' with your actual filename or provide the string content
14with open('my-module.yang', 'r') as f:
15    module_text = f.read()
16
17module = ctx.add_module('my-module.yang', module_text)
18
19# 4. Validate the module
20ctx.validate()
21
22# 5. Check for errors
23if ctx.errors:
24    for (pos, tag, args) in ctx.errors:
25        print(f"{pos}: {tag} {args}")
26    sys.exit(1)
27
28# 6. Access data from the module
29print(f"Module Name: {module.arg}")
30for child in module.i_children:
31    print(f"Child node: {child.arg} ({child.keyword})")