2021-03-13 22:53:28 +01:00
|
|
|
import subprocess
|
|
|
|
import sys
|
2021-03-14 10:31:45 +01:00
|
|
|
from contextlib import suppress
|
|
|
|
from typing import Optional
|
2021-03-13 22:53:28 +01:00
|
|
|
|
|
|
|
|
|
|
|
class Pip:
|
2021-03-14 13:22:10 +01:00
|
|
|
_executable = sys.executable
|
2021-03-13 22:53:28 +01:00
|
|
|
|
2021-03-14 13:22:10 +01:00
|
|
|
"""
|
|
|
|
Getter
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_executable(cls) -> str:
|
|
|
|
return cls._executable
|
|
|
|
|
|
|
|
"""
|
|
|
|
Setter
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def set_executable(cls, executable: str):
|
|
|
|
if executable is not None:
|
|
|
|
cls._executable = executable
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def reset_executable(cls):
|
|
|
|
cls._executable = sys.executable
|
|
|
|
|
|
|
|
"""
|
|
|
|
Public utils functions
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_package(cls, package: str) -> Optional[str]:
|
2021-03-14 10:31:45 +01:00
|
|
|
result = None
|
|
|
|
with suppress(Exception):
|
2021-03-14 13:22:10 +01:00
|
|
|
result = subprocess.check_output([cls._executable, "-m", "pip", "show", package], stderr=subprocess.DEVNULL)
|
2021-03-14 10:31:45 +01:00
|
|
|
|
|
|
|
if result is None:
|
|
|
|
return None
|
2021-03-13 22:53:28 +01:00
|
|
|
|
|
|
|
new_package: list[str] = str(result, 'utf-8').lower().split('\n')
|
|
|
|
new_version = ''
|
|
|
|
|
|
|
|
for atr in new_package:
|
|
|
|
if 'version' in atr:
|
|
|
|
new_version = atr.split(': ')[1]
|
|
|
|
|
|
|
|
return f'{package}=={new_version}'
|
|
|
|
|
2021-03-14 13:22:10 +01:00
|
|
|
@classmethod
|
|
|
|
def get_outdated(cls) -> bytes:
|
|
|
|
return subprocess.check_output([cls._executable, "-m", "pip", "list", "--outdated"])
|
|
|
|
|
|
|
|
@classmethod
|
2021-03-14 14:47:53 +01:00
|
|
|
def install(cls, package: str, *args, source: str = None, stdout=None, stderr=None):
|
2021-03-14 13:22:10 +01:00
|
|
|
pip_args = [cls._executable, "-m", "pip", "install"]
|
2021-03-13 22:53:28 +01:00
|
|
|
|
|
|
|
for arg in args:
|
|
|
|
pip_args.append(arg)
|
|
|
|
|
|
|
|
if source is not None:
|
|
|
|
pip_args.append(f'--extra-index-url')
|
|
|
|
pip_args.append(source)
|
|
|
|
|
|
|
|
pip_args.append(package)
|
|
|
|
subprocess.run(pip_args, stdout=stdout, stderr=stderr)
|
2021-03-14 10:58:59 +01:00
|
|
|
|
2021-03-14 13:22:10 +01:00
|
|
|
@classmethod
|
|
|
|
def uninstall(cls, package: str, stdout=None, stderr=None):
|
|
|
|
subprocess.run([cls._executable, "-m", "pip", "uninstall", "--yes", package], stdout=stdout, stderr=stderr)
|