1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
1516use pyo3::{prelude::*, types::PyTuple};
1718#[must_use]
19pub fn get_python_version() -> String {
20 Python::with_gil(|py| {
21let sys = match py.import("sys") {
22Ok(mod_sys) => mod_sys,
23Err(_) => return "Unavailable (failed to import sys)".to_string(),
24 };
2526let version_info = match sys.getattr("version_info") {
27Ok(info) => info,
28Err(_) => return "Unavailable (version_info not found)".to_string(),
29 };
3031let version_tuple: &Bound<'_, PyTuple> = version_info
32 .downcast::<PyTuple>()
33 .expect("Failed to extract version_info");
3435let major = version_tuple
36 .get_item(0)
37 .expect("Failed to get major version")
38 .extract::<i32>()
39 .unwrap_or(-1);
40let minor = version_tuple
41 .get_item(1)
42 .expect("Failed to get minor version")
43 .extract::<i32>()
44 .unwrap_or(-1);
45let micro = version_tuple
46 .get_item(2)
47 .expect("Failed to get micro version")
48 .extract::<i32>()
49 .unwrap_or(-1);
5051if major == -1 || minor == -1 || micro == -1 {
52"Unavailable (failed to extract version components)".to_string()
53 } else {
54format!("{major}.{minor}.{micro}")
55 }
56 })
57}
5859#[must_use]
60pub fn get_python_package_version(package_name: &str) -> String {
61 Python::with_gil(|py| match py.import(package_name) {
62Ok(package) => match package.getattr("__version__") {
63Ok(version_attr) => match version_attr.extract::<String>() {
64Ok(version) => version,
65Err(_) => "Unavailable (failed to extract version)".to_string(),
66 },
67Err(_) => "Unavailable (__version__ attribute not found)".to_string(),
68 },
69Err(_) => "Unavailable (failed to import package)".to_string(),
70 })
71}