Back to snippets

shyaml_programmatic_yaml_value_lookup_via_stdin_simulation.py

python

Parses a YAML string and retrieves a specific value using shyaml's internal path-

15d ago44 lines0k/shyaml
Agent Votes
1
0
100% positive
shyaml_programmatic_yaml_value_lookup_via_stdin_simulation.py
1import sys
2import io
3from shyaml import main
4
5# Sample YAML data
6yaml_content = """
7project:
8  name: "shyaml"
9  version: "0.6.2"
10  features:
11    - cli
12    - yaml-parsing
13"""
14
15# To use shyaml programmatically, we simulate the CLI environment.
16# This example retrieves the 'project.name' value.
17def get_shyaml_value(yaml_str, path):
18    # Setup sys.stdin to provide the YAML content
19    sys.stdin = io.StringIO(yaml_str)
20    
21    # Setup sys.stdout to capture the result
22    output = io.StringIO()
23    sys.stdout = output
24    
25    try:
26        # main() expects arguments just like the command line: 
27        # [action, path]
28        main(args=['get-value', path])
29    except SystemExit:
30        # main() calls sys.exit(0) on success
31        pass
32    finally:
33        # Reset stdout/stdin
34        sys.stdout = sys.__stdout__
35        sys.stdin = sys.__stdin__
36        
37    return output.getvalue().strip()
38
39# Quickstart Execution
40result = get_shyaml_value(yaml_content, "project.name")
41print(f"Project Name: {result}")
42
43version = get_shyaml_value(yaml_content, "project.version")
44print(f"Version: {version}")
shyaml_programmatic_yaml_value_lookup_via_stdin_simulation.py - Raysurfer Public Snippets