• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4Copyright (c) 2024 Huawei Device Co., Ltd.
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9    http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16
17Description: Python package install.
18"""
19
20import subprocess
21import sys
22from pathlib import Path
23
24python_path = Path(sys.executable)
25python_path = (python_path.parent / python_path.stem) if sys.platform == 'win32' else python_path
26pip_list = subprocess.check_output(str(python_path) + ' -m pip list'.decode('utf-8'))
27
28
29def install(pkg_name=None):
30    if not pkg_name: # 按照requirements.txt安装
31        install_by_requirements(python_path, pip_list)
32    else: # 安装单个package
33        install_by_pkg_name(pkg_name)
34
35
36def install_by_requirements():
37    require_file_path = Path.cwd().parent / 'requirements.txt'
38    with open(require_file_path, "r") as require:
39        pkgs = require.readlines()
40        for pkg in pkgs:
41            if pkg in pip_list:
42                continue
43            install_cmd = (f'{python_path} -m pip install {pkg.strip()}')
44            res = subprocess.call(install_cmd)
45            assert res == 0, "Install packages from requirements.txt failed!"
46
47
48def install_by_pkg_name(pkg_name):
49    if pkg_name in pip_list:
50        return
51    install_cmd = (f'{python_path} -m pip install {pkg_name}')
52    res = subprocess.call(install_cmd)
53    assert res == 0, f"Install packages '{pkg_name}' failed!"
54