def run(self): global m try: from pip._internal import main except ImportError: from pip import main try: main(['install', '--upgrade'] + m['install_requires']) except TypeError: # recent pip main.main(['install', '--upgrade'] + m['install_requires'])
def test_env_override_default_append(self): """ Test that environment variable overrides an append option default. """ os.environ['PIP_FIND_LINKS'] = 'F1' options, args = main(['fake']) assert options.find_links == ['F1'] os.environ['PIP_FIND_LINKS'] = 'F1 F2' options, args = main(['fake']) assert options.find_links == ['F1', 'F2']
def test_env_override_default_choice(self): """ Test that environment variable overrides a choice option default. """ os.environ['PIP_EXISTS_ACTION'] = 'w' options, args = main(['fake']) assert options.exists_action == ['w'] os.environ['PIP_EXISTS_ACTION'] = 's w' options, args = main(['fake']) assert options.exists_action == ['s', 'w']
def test_cache_dir__PIP_NO_CACHE_DIR_invalid__with_no_cache_dir( self, capsys, ): """ Test setting PIP_NO_CACHE_DIR to an invalid value while also passing --no-cache-dir. """ os.environ['PIP_NO_CACHE_DIR'] = 'maybe' expected_err = "--no-cache-dir error: invalid truth value 'maybe'" with assert_option_error(capsys, expected=expected_err): main(['--no-cache-dir', 'fake'])
def test_env_alias_override_default(self): """ When an option has multiple long forms, test that the technique of using the env variable, "PIP_<long form>" works for all cases. (e.g. PIP_LOG_FILE and PIP_LOCAL_LOG should all work) """ os.environ['PIP_LOG_FILE'] = 'override.log' options, args = main(['fake']) assert options.log == 'override.log' os.environ['PIP_LOCAL_LOG'] = 'override.log' options, args = main(['fake']) assert options.log == 'override.log'
def require(*packages): for package in packages: try: if not isinstance(package, str): import_name, install_name = package else: import_name = install_name = package __import__(import_name) except ImportError: cmd = ['install', install_name] if not hasattr(sys, 'real_prefix'): cmd.append('--user') main(cmd)
def _install_packages_local( requirements ): try: from pip._internal.main import main except: try: from pip._internal import main except: raise ValueError("could not find main method in pip." ) try: main( [ 'install', '--user', '--upgrade' ] + requirements + [ '--trusted-host', 'pypi.python.org' ] + [ '--trusted-host', 'pypi.org' ] + [ '--trusted-host', 'files.pythonhosted.org' ] ) except: main( [ 'install', '--user', '--upgrade' ] + requirements )
def _import_with_auto_install(package): package_name, version = _get_package_name_and_version(package) package_name = package_name.strip() import_name = PACKAGE_NAME_TO_IMPORT_NAME.get(package_name, package_name).replace( '-', '_') try: return __import__(import_name) except ImportError: try: pipmain.main(['install', package]) except: pipmain(['install', package]) return __import__(import_name)
def test_env_override_default_int(self): """ Test that environment variable overrides an int option default. """ os.environ['PIP_TIMEOUT'] = '-1' options, args = main(['fake']) assert options.timeout == -1
def read_config(config_yaml_file): """Read given yaml file and return dictionary with entries""" # if this results in an error, install the package with: pip install ruamel.yaml try: import ruamel.yaml as yaml # install the package with: pip install ruamel.yaml except ImportError: pip.main(['install', '--user', 'ruamel']) import ruamel.yaml as yaml # install the package with: pip install ruamel.yaml # TODO: add handling of file not found error yaml_config = yaml.YAML() with open(config_yaml_file, 'r') as file: config_dict = yaml_config.load(file) return config_dict
def test_cli_override_environment(self): """ Test the cli overrides and environment variable """ os.environ['PIP_TIMEOUT'] = '-1' options, args = main(['fake', '--timeout', '-2']) assert options.timeout == -2
def test_cache_dir__PIP_NO_CACHE_DIR(self, pip_no_cache_dir): """ Test setting the PIP_NO_CACHE_DIR environment variable without passing any command-line flags. """ os.environ['PIP_NO_CACHE_DIR'] = pip_no_cache_dir options, args = main(['fake']) assert options.cache_dir is False
def _pip_main(package, action, target=None): if action == ACTION_UNINSTALL: cmd = [action, package, '-y'] elif action == ACTION_INSTALL: cmd = [action, package, '--upgrade'] if target: cmd.append('--target=%s' % target) return main(cmd)
def test_cache_dir__PIP_NO_CACHE_DIR__with_cache_dir( self, pip_no_cache_dir): """ Test setting PIP_NO_CACHE_DIR while also passing an explicit --cache-dir value. """ os.environ['PIP_NO_CACHE_DIR'] = pip_no_cache_dir options, args = main(['--cache-dir', '/cache/dir', 'fake']) # The command-line flag takes precedence. assert options.cache_dir == '/cache/dir'
def test_cache_dir__PIP_NO_CACHE_DIR__with_no_cache_dir( self, pip_no_cache_dir): """ Test setting PIP_NO_CACHE_DIR while also passing --no-cache-dir. """ os.environ['PIP_NO_CACHE_DIR'] = pip_no_cache_dir options, args = main(['--no-cache-dir', 'fake']) # The command-line flag should take precedence (which has the same # value in this case). assert options.cache_dir is False
def pip_main(argv): # Extract the certificates from the PAR following the example of get-pip.py # https://github.com/pypa/get-pip/blob/430ba37776ae2ad89/template.py#L164-L168 cert_tmpdir = tempfile.mkdtemp() cert_path = os.path.join(cert_tmpdir, "cacert.pem") atexit.register(lambda: shutil.rmtree(cert_tmpdir, ignore_errors=True)) with open(cert_path, "wb") as cert: cert.write(pkgutil.get_data("pip._vendor.certifi", "cacert.pem")) argv = ["--isolated", "--disable-pip-version-check", "--cert", cert_path] + argv return _pip_main.main(argv)
def run(self): ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # download external programs required by package to install directory. cwd = os.getcwd() matches = glob(os.path.join(cwd, 'build/lib.*')) build_dir = cwd if len(matches) == 0 else matches[0] dest = Path(build_dir) / 'bq3d/.external' print('installing elastix') url = 'https://glams.bio.uci.edu/' + elastix_URL tmp = Path(url).name sink = dest / 'elastix-5.0.0' with request.urlopen(url, context=ctx) as response, open(tmp, 'wb') as out_file: shutil.copyfileobj(response, out_file) try: tar = tarfile.open(tmp, "r:bz2") # Linux except: tar = tarfile.open(tmp, "r:gz") # MacOS tar.extractall(sink) tar.close() print('installing ilastik') url = 'https://glams.bio.uci.edu/' + ilastik_URL tmp = Path(url).name sink = dest / 'ilastik-1.3.3' with request.urlopen(url, context=ctx) as response, open(tmp, 'wb') as out_file: shutil.copyfileobj(response, out_file) tar = tarfile.open(tmp, "r:bz2") tar.extractall(sink) tar.close() # Install ANTsPy print('installing ants') if sys.platform == 'linux': try: main(['install', '--user', "https://github.com/ANTsX/ANTsPy/releases/download/v0.1.4/antspy-0.1.4-cp36-cp36m-linux_x86_64.whl"]) except: main(['install', '--user', "https://github.com/ANTsX/ANTsPy/releases/download/v0.2.0/antspyx-0.2.0-cp37-cp37m-linux_x86_64.whl"]) if sys.platform == 'darwin': try: main(['install', '--user', "https://github.com/ANTsX/ANTsPy/releases/download/Weekly/antspy-0.1.4-cp36-cp36m-macosx_10_7_x86_64.whl"]) except: main(['install', '--user', "https://github.com/ANTsX/ANTsPy/releases/download/v0.1.8/antspyx-0.1.8-cp37-cp37m-macosx_10_14_x86_64.whl"]) _install.run(self)
def upgrade(current_version, version, path, migration_package): if current_version >= version: return False if os.path.exists(os.path.join(path, "requirements.txt")): pass pip.main(["install", "-r", os.path.join(path, "requirements.txt"), "--upgrade"]) migration_path = migration_package.__path__._path[0] migrations = [] for vers in os.listdir(migration_path): migration_version = packaging_version.parse(vers) if migration_version <= version and migration_version > current_version: migrations.append(migration_version) migrations = sorted(migrations) for migration in migrations: spec = importlib.util.spec_from_file_location( "migration", os.path.join(migration_path, migration.base_version, "migration.py"), ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) _logger.info("Executing migration for %s" % migration.base_version) module.migrate() return True
def uninstall(params): """ Uninstall third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.uninstall import UninstallCommand except ImportError: # be compatible with pip < 10.0 from pip import main as pip_main from pip.commands.uninstall import UninstallCommand params = [param for param in params] ##### modified here ##### a = 'test_1' b = 'test_2' options, mod_list = UninstallCommand(a, b).parse_args(params) params = ["uninstall"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Uninstall Mod uninstalled_result = pip_main.main(params) # Remove Mod Config from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") del user_conf['mod'][mod_name] dump_config(user_mod_conf_path(), user_conf) return uninstalled_result
def test_quiet(self): options1, args1 = main(['--quiet', 'fake']) options2, args2 = main(['fake', '--quiet']) assert options1.quiet == options2.quiet == 1 options3, args3 = main(['--quiet', '--quiet', 'fake']) options4, args4 = main(['fake', '--quiet', '--quiet']) assert options3.quiet == options4.quiet == 2 options5, args5 = main(['--quiet', '--quiet', '--quiet', 'fake']) options6, args6 = main(['fake', '--quiet', '--quiet', '--quiet']) assert options5.quiet == options6.quiet == 3
def install(package): main(['install', package])
# this file is for CI only. from sys import version_info # https://github.com/pypa/pip/issues/7498 try: from pip._internal.main import main if not callable(main): raise ImportError except ImportError: try: from pip._internal import main if not callable(main): raise ImportError except ImportError: from pip import main if not callable(main): raise ImportError requires = [] if (3, 4) <= version_info < (3, 5): pass else: requires = ['PyYAML'] if __name__ == '__main__': for package in requires: main(['install', package])
import logging import os import time import requests import yaml from pip._internal import main as pip from const import (CONFIGFILE, LOGFILE, KEYFILE, HOMEGRAPH_SCOPE, HOMEGRAPH_TOKEN_URL) try: import google.auth.crypt import google.auth.jwt except ImportError as e: pip.main(['install', 'google-auth']) import google.auth.crypt import google.auth.jwt FILE_PATH = os.path.abspath(__file__) FILE_DIR = os.path.split(FILE_PATH)[0] def readFile(filename): """Read file.""" try: file = open(filename, 'r+') readcontent = file.read() file.close() return readcontent except (ValueError, Exception):
def missing_module(module_name): print("Required module %s not detected, installing with pip..." % (module_name, )) main.main(["install", module_name])
def PrintInfo(text): # imprime info destacada, en amarillo. if (boring_user): print(text) else: print(color.Fore.YELLOW, text, color.Fore.RESET, sep="") def PrintGoodNews(text): # verde = bueno. if (boring_user): print(text) else: print(color.Fore.GREEN, text, color.Fore.RESET, sep="") if (__name__ == "__main__"): if (not boring_user): print(color.Fore.RED, "YOU ", sep="", end="") print(color.Fore.YELLOW, "HAVE ", sep="", end="") print(color.Fore.BLUE, "THE POWER ", sep="", end="") print(color.Fore.GREEN, "OF ", sep="", end="") print(color.Back.CYAN, color.Fore.WHITE, "COLORS\n", color.Back.RESET, color.Fore.RESET, sep="", end="") else: print("You do not have colorama library instlled. You have nothing.") print("Do you want me to install it for you? (y/n) ", end="") if (input().lower() not in ["y", "yes"]): print("...") exit(0) print("Trying to install...") try: # https://stackoverflow.com/questions/12937533/use-pip-install-uninstall-inside-a-python-script from pip._internal import main as pipmain pipmain.main(["install", "colorama"]) print(color.Back.CYAN, color.Fore.WHITE, " Yay! It worked. \n", color.Back.RESET, color.Fore.RESET, sep="", end="") except: print("I have failed to install it, probably because you have Python 2 or lower.")
if sys.prefix != sys.real_prefix: venv = True else: if sys.prefix != sys.base_prefix: venv = True import pip._internal pipargs = ['install'] if not venv: pipargs += ['--user'] pipargs += ['requests'] if hasattr(pip._internal, 'main'): pip._internal.main(pipargs) else: try: import pip._internal.main as pipmain pipmain.main(pipargs) except: print('The library could not be installed automatically.') print('Please install the \'requests\' library and re-run the ' + 'tool.') exit(1) print() # in older versions I tried to import the requests library after # installing it - this approach worked on Linux, but resulted in a # ModuleNotFoundError on Windows. (the program would work on the next run, # though.) oddly enough, removing the import fixed the problem: apparently # pip loads the module when installing it. I will need to fix the code # should this default behaviour ever change. version = '1.5'
def install_package(package): import pip from pip._internal import main main.main(['install', package])
User Name: fangod@cn Date Time: 2020-10-14 15:39:31 File Name: cbg.py @v1.0 """ import os import sys import platform try: import commentjson as json except ImportError: try: import pip pip.main(['install', 'commentjson', '--user']) except: from pip._internal import main main.main(['install', 'commentjson', '--user']) import commentjson as json config_list = [ "fontFace", "fontWeight", "antialiasingMode", "cursorShape", "cursorColor", "colorScheme", "useAcrylic", "acrylicOpacity", "scrollbarState", "historySize" ] class bcolors: HEADER = '\033[95m' RED = '\033[0;31m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m'
try: logger.info("Connecting to Domoticz on %s" % (DOMOTICZ_URL)) r = requests.get( DOMOTICZ_URL + '/json.htm?type=command¶m=addlogmessage&message=Connected to Google Assistant with DZGA v' + VERSION, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) except Exception as e: logger.error('Connection to Domoticz refused with error: %s' % (e)) try: import git except ImportError: logger.info('Installing package GitPython') pip.main(['install', 'gitpython']) import git repo = git.Repo(FILE_DIR) def checkupdate(): if 'CheckForUpdates' in configuration and configuration[ 'CheckForUpdates'] == True: try: r = requests.get( 'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/' + repo.active_branch.name + '/const.py') text = r.text if VERSION not in text: update = 1
sonarr2_url = '' sonarr2_api_key = '' deluge_url = '' deluge_password = '' days_to_seed = 4 #days to keep torrents even if they've been replaced. #### Script #### #install pandas & requests not found in Nerdpack's python... try: import pandas as pd except: try: pip.main(['install', 'pandas']) import pandas as pd except Exception as e: raise Exception( f'Error importing/installing Pandas. Ensure pip is installed from Nerdpack: {e}' ) try: import requests except: try: pip.main(['install', 'requests']) import requests except Exception as e: raise Exception( f'Error importing/installing Requests. Ensure pip is installed from Nerdpack: {e}'