Skip to content

Commit 2330f4a

Browse files
fholgerarmintaenzertng
authored andcommitted
Add example for parsing and using an existing SPDX2 document
Signed-off-by: Holger Frydrych <holger.frydrych@tngtech.com>
1 parent 5c99b5c commit 2330f4a

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

examples/spdx2_parse_file.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# SPDX-FileCopyrightText: 2023 spdx contributors
2+
#
3+
# SPDX-License-Identifier: Apache-2.0
4+
import logging
5+
from os import path
6+
7+
from spdx_tools.spdx.model.document import Document
8+
from spdx_tools.spdx.parser.error import SPDXParsingError
9+
from spdx_tools.spdx.parser.parse_anything import parse_file
10+
11+
# This example demonstrates how to parse an existing spdx file.
12+
13+
# Provide a path to the input file
14+
input_path = path.join(path.dirname(__file__), "..", "tests", "spdx", "data", "SPDXLite.spdx")
15+
document: Document
16+
try:
17+
# Try to parse the input file. If successful, returns a Document, otherwise raises an SPDXParsingError
18+
document = parse_file(input_path)
19+
except SPDXParsingError:
20+
logging.exception("Failed to parse spdx file")
21+
22+
# We can now access attributes from the parsed document
23+
print(f"Parsed document name: {document.creation_info.name}")
24+
creators_as_str = ", ".join([creator.to_serialized_string() for creator in document.creation_info.creators])
25+
print(f"Created on {document.creation_info.created} by {creators_as_str}")

0 commit comments

Comments
 (0)