sh_cpl/src/cpl/utils/pip.py

44 lines
1.3 KiB
Python
Raw Normal View History

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:
@staticmethod
2021-03-14 10:31:45 +01:00
def get_package(package: str) -> Optional[str]:
result = None
with suppress(Exception):
result = subprocess.check_output([sys.executable, "-m", "pip", "show", package], stderr=subprocess.DEVNULL)
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}'
@staticmethod
def install(package: str, *args, source: str = None, stdout=None, stderr=None):
2021-03-14 11:33:29 +01:00
pip_args = [sys.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
@staticmethod
def uninstall(package: str, stdout=None, stderr=None):
subprocess.run([sys.executable, "-m", "pip", "uninstall", "--yes", package], stdout=stdout, stderr=stderr)