Coverage for /opt/cloud/slavespace/usr1/096471637100f3de0fcfc01072822a80/dttest/api/python/ge/ge/_capi/_lib_loader.py: 100%

14 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-07-27 10:02 +0800

1#!/usr/bin/env python3 

2# -*- coding: utf-8 -*- 

3# ------------------------------------------------------------------- 

4# ----------------------------------------------------------------------------------------------------------- 

5# Copyright (c) 2025 Huawei Technologies Co., Ltd. 

6# This program is free software, you can redistribute it and/or modify it under the terms and conditions of 

7# CANN Open Software License Agreement Version 2.0 (the "License"). 

8# Please refer to the License for details. You may not use this file except in compliance with the License. 

9# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, 

10# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. 

11# See LICENSE in the root of the software repository for the full text of the License. 

12# ----------------------------------------------------------------------------------------------------------- 

13 

14"""Internal utility for loading shared libraries with fallback paths.""" 

15 

16import ctypes 

17import os 

18from typing import Optional 

19 

20 

21def load_lib_from_path(lib_name: str, lib_dir: str, mode: Optional[int] = None) -> ctypes.CDLL: 

22 """Load library from file system with fallback search paths. 

23 

24 Args: 

25 lib_name: Library name or absolute path. 

26 lib_dir: Directory to search for the library if lib_name is not absolute. 

27 mode: Optional dlopen mode flags (e.g., os.RTLD_GLOBAL | os.RTLD_NOW). 

28 

29 Returns: 

30 Loaded ctypes.CDLL object. 

31 

32 Raises: 

33 OSError: If library cannot be loaded from any candidate path. 

34 """ 

35 candidates = [lib_name] if os.path.isabs(lib_name) else [os.path.join(lib_dir, lib_name), lib_name] 

36 

37 errors = [] 

38 for path in candidates: 

39 try: 

40 if mode is None: 

41 return ctypes.CDLL(path) 

42 return ctypes.CDLL(path, mode=mode) 

43 except OSError as exc: 

44 errors.append(f"try to load {path} failed: {exc}") 

45 

46 raise OSError("\n".join(errors))