Пример #1
0
    def test_bootstrapping_with_root(self):
        ensurepip.bootstrap(root="/foo/bar/")

        self.run_pip.assert_called_once_with(
            ["install", "--no-index", "--find-links", unittest.mock.ANY, "--root", "/foo/bar/", "setuptools", "pip"],
            unittest.mock.ANY,
        )
Пример #2
0
def update(git=True):
    try:
        print(_("Attempting to update.."))

        if git:
            import subprocess

            r_code = subprocess.call(["git", "pull"])
            if r_code:
                print(_("It looks like git failed to run - do you have it "
                        "installed?"))

        try:
            import pip
        except ImportError:
            try:
                import ensurepip
                ensurepip.bootstrap()
            except RuntimeError:
                print(_("It looks like ensurepip is disabled, continuing.."))

            import pip
            pip.main(["install", "-r", "requirements.txt", "--upgrade"])
        else:
            pip.main(["install", "-r", "requirements.txt", "--upgrade"])

        print(_("Done!"))
    except Exception as e:
        print(_("Error updating: %s") % e)
        raise e
Пример #3
0
    def test_bootstrapping_with_upgrade(self):
        ensurepip.bootstrap(upgrade=True)

        self.run_pip.assert_called_once_with(
            ["install", "--no-index", "--find-links", unittest.mock.ANY, "--upgrade", "setuptools", "pip"],
            unittest.mock.ANY,
        )
Пример #4
0
def main():
    parser = argparse.ArgumentParser(prog="python -m ensurepip")
    parser.add_argument(
        "--version",
        action="version",
        version="pip {}".format(ensurepip.version()),
        help="Show the version of pip that is bundled with this Python.",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="count",
        default=0,
        dest="verbosity",
        help=("Give more output. Option is additive, and can be used up to 3 "
              "times."),
    )
    parser.add_argument(
        "-U", "--upgrade",
        action="store_true",
        default=False,
        help="Upgrade pip and dependencies, even if already installed.",
    )
    parser.add_argument(
        "--user",
        action="store_true",
        default=False,
        help="Install using the user scheme.",
    )
    parser.add_argument(
        "--root",
        default=None,
        help="Install everything relative to this alternate root directory.",
    )
    parser.add_argument(
        "--altinstall",
        action="store_true",
        default=False,
        help=("Make an alternate install, installing only the X.Y versioned"
              "scripts (Default: pipX, pipX.Y, easy_install-X.Y)"),
    )
    parser.add_argument(
        "--default-pip",
        action="store_true",
        default=False,
        help=("Make a default pip install, installing the unqualified pip "
              "and easy_install in addition to the versioned scripts"),
    )

    args = parser.parse_args()

    ensurepip.bootstrap(
        root=args.root,
        upgrade=args.upgrade,
        user=args.user,
        verbosity=args.verbosity,
        altinstall=args.altinstall,
        default_pip=args.default_pip,
    )
Пример #5
0
    def test_basic_bootstrapping(self):
        ensurepip.bootstrap()

        self.run_pip.assert_called_once_with(
            ["install", "--no-index", "--find-links", unittest.mock.ANY, "setuptools", "pip"], unittest.mock.ANY
        )

        additional_paths = self.run_pip.call_args[0][1]
        self.assertEqual(len(additional_paths), 2)
Пример #6
0
    def test_bootstrapping_with_verbosity_3(self):
        ensurepip.bootstrap(verbosity=3)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
                unittest.mock.ANY, "-vvv", "setuptools", "pip",
            ],
            unittest.mock.ANY,
        )
    def test_bootstrapping_with_user(self):
        ensurepip.bootstrap(user=True)

        self.run_pip.assert_called_once_with(
            [
                "install", "--no-index", "--find-links",
                mock.ANY, "--user", "setuptools", "pip",
            ],
            mock.ANY,
        )
Пример #8
0
def installPythonPackages(packages:typing.List[str]) -> bool:
	"""
	Attempts to install the packages listed in ``packages`` and
	add them to the global scope.

	:param packages: A list of missing Python dependencies

	:return: a truthy value indicating success.
	"""
	logging.info("Attempting install of %s", ','.join(packages))

	# Ensure `pip` is installed
	try:
		import pip
	except ImportError as e:
		logging.info("`pip` package not installed. Attempting install with `ensurepip` module")
		logging.debug("%s", e, exc_info=True, stack_info=True)
		import ensurepip
		try:
			ensurepip.bootstrap(altinstall=True)
		except (EnvironmentError, PermissionError) as err:
			logging.info("Permission Denied, attempting user-level install")
			logging.debug("%s", err, exc_info=True, stack_info=True)
			ensurepip.bootstrap(altinstall=True, user=True)
		import pip

	# Get main pip function
	try:
		pipmain = pip.main
	except AttributeError as e: # This happens when using a version of pip >= 10.0
		from pip._internal import main as pipmain


	# Attempt package install
	ret = pipmain(["install"] + packages)
	if ret == 1:
		logging.info("Possible 'Permission Denied' error, attempting user-level install")
		ret = pipmain(["install", "--user"] + packages)

	logging.debug("Pip return code was %d", ret)
	if not ret:
		import importlib
		for package in packages:
			try:
				globals()[package] = importlib.import_module(package)
			except ImportError:
				logging.error("Failed to import %s", package)
				logging.warning("Install appeared succesful - subsequent run may succeed")
				logging.debug("%s", e, exc_info=True, stack_info=True)
				return False

		urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
		globals()["DISTRO"] = distro.LinuxDistribution().id()

	return not ret
Пример #9
0
def stage2(directory=_path):
    try:
        import pip
    except ImportError:
        try:
            import ensurepip
            ensurepip.bootstrap(upgrade=True, default_pip=True)
        except ImportError:
            get_pip()
    ensure_ui()
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-e', directory])
    for names in [('data',), ('data', 'static')]:
        path = os.path.join(directory, *names)
        if not os.path.exists(path):
            os.mkdir(path)
Пример #10
0
    def setup(self, data):
        if not data:
            # It's safe to use ensurepip.
            print("Installing pip...")
            try:
                import ensurepip
                ensurepip.bootstrap()
            except PermissionError:
                # panic and try and sudo it
                sudo_check_call("python3.5 -m ensurepip")
            return

        # Instead, we have to run get-pip.py.
        print("Installing pip...")
        try:
            sudo_check_call(["python3.5", "{}".format(data)])
        except FileNotFoundError:
            subprocess.check_call(["python3.5", "{}".format(data)])
Пример #11
0
def stage2(directory=_path, upgrade=False):
    try:
        import pip
    except ImportError:
        try:
            import ensurepip
            ensurepip.bootstrap(upgrade=True, default_pip=True)
        except ImportError:
            get_pip()
    ui_path = os.path.join(directory, 'lib', 'openeis-ui')
    args = [sys.executable, '-m', 'pip', 'install',
        '--global-option', '-q', '-e', ui_path, '-e', directory]
    if upgrade:
        args.insert(4, '--upgrade')
    subprocess.check_call(args)
    for names in [('data',), ('data', 'static')]:
        path = os.path.join(directory, *names)
        if not os.path.exists(path):
            os.mkdir(path)
Пример #12
0
 def test_bootstrapping_with_alt_install(self):
     ensurepip.bootstrap(altinstall=True)
     self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "altinstall")
Пример #13
0
 def test_bootstrapping_with_default_pip(self):
     ensurepip.bootstrap(default_pip=True)
     self.assertNotIn("ENSUREPIP_OPTIONS", self.os_environ)
def prepare_path():
    """Template code for zipapps entry point. Run with current PYTHONPATH"""
    # PYTHONPATH=./app.pyz
    zip_file_path = Path(__file__).parent.absolute()
    _zipapps_python_path_list = [str(zip_file_path)]
    unzip = os.environ.get('ZIPAPPS_UNZIP') or r'''{unzip}'''
    if unzip:
        _cache_folder = os.environ.get('ZIPAPPS_CACHE') or os.environ.get(
            'UNZIP_PATH') or r'''{unzip_path}'''

        _cache_folder_path = ensure_path(_cache_folder)
        _cache_folder_path = _cache_folder_path / zip_file_path.stem
        _cache_folder_path.mkdir(parents=True, exist_ok=True)
        _cache_folder_path_str = str(_cache_folder_path.absolute())
        _zipapps_python_path_list.insert(0, _cache_folder_path_str)
        ts_file_name = '_zip_time_{ts}'
        LAZY_PIP_DIR_NAME = r'''{LAZY_PIP_DIR_NAME}'''
        if not (_cache_folder_path / ts_file_name).is_file():
            # check timestamp difference by file name, need to refresh _cache_folder
            # rm the folder
            clear_old_cache(_cache_folder_path, LAZY_PIP_DIR_NAME)
            _need_unzip_names = unzip.split(',')
            _need_unzip_names.append(ts_file_name)
            with ZipFile(zip_file_path, "r") as zf:
                for member in zf.infolist():
                    file_dir_name = os.path.splitext(
                        member.filename.split('/')[0])[0]
                    if unzip == '*' or member.filename in _need_unzip_names or file_dir_name in _need_unzip_names:
                        zf.extract(member, path=_cache_folder_path_str)
        if LAZY_PIP_DIR_NAME:
            import platform

            pip_args = {pip_args_repr}
            pip_args_md5 = '{pip_args_md5}'
            lazy_pip_dir = _cache_folder_path / LAZY_PIP_DIR_NAME
            if lazy_pip_dir.is_dir():
                # pip target isolation with by python version and platform
                platform_name = (platform.system() or '-')
                py_version = '.'.join(
                    map(str, sys.version_info[:{python_version_slice}]))
                target_name = '%s_%s' % (py_version, platform_name)
                _pip_target = lazy_pip_dir / target_name
                _pip_target.mkdir(parents=True, exist_ok=True)
                lazy_pip_dir_str = str(_pip_target.absolute())
                _zipapps_python_path_list.insert(0, lazy_pip_dir_str)
                if not (_pip_target / pip_args_md5).is_file():
                    # rm old requirements
                    rm_dir_or_file(_pip_target)
                    _pip_target.mkdir(parents=True, exist_ok=True)
                    try:
                        import pip
                    except ImportError:
                        import ensurepip
                        ensurepip.bootstrap()
                    import subprocess
                    shell_args = [
                        sys.executable, '-m', 'pip', 'install', '--target',
                        lazy_pip_dir_str
                    ] + pip_args
                    with subprocess.Popen(shell_args,
                                          cwd=_cache_folder_path_str,
                                          stdout=sys.stderr) as proc:
                        proc.wait()
                    # avoid duplicated installation
                    (_pip_target / pip_args_md5).touch()
    sep = ';' if sys.platform == 'win32' else ':'
    ignore_system_python_path = {ignore_system_python_path}
    _new_sys_paths = r'''{sys_paths}'''.strip()
    if _new_sys_paths:
        new_sys_paths = [str(ensure_path(p)) for p in _new_sys_paths.split(',')]
    else:
        new_sys_paths = []
    if ignore_system_python_path:
        sys.path.clear()
        # env of Popen is not valid for win32 platform, use os.environ instead.
        _new_paths = _zipapps_python_path_list + new_sys_paths
    else:
        _old_path = os.environ.get('PYTHONPATH') or ''
        _new_paths = _zipapps_python_path_list + [_old_path] + new_sys_paths
    os.environ['PYTHONPATH'] = sep.join(_new_paths)
    # let the dir path first
    zipapps_paths = [
        path for path in _zipapps_python_path_list if path not in sys.path
    ]
    sys.path = zipapps_paths + sys.path + new_sys_paths
Пример #15
0
 def test_bootstrapping_with_regular_install(self):
     ensurepip.bootstrap()
     self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "install")
Пример #16
0
 def test_bootstrapping_with_default_pip(self):
     ensurepip.bootstrap(default_pip=True)
     self.assertNotIn("ENSUREPIP_OPTIONS", self.os_environ)
Пример #17
0
# parse CLI arguments
parser = ArgumentParser()
parser.add_argument('--branch', help='install dephell from git from given branch')
parser.add_argument('--version', help='install specified version')
parser.add_argument('--slug', default='dephell/dephell',
                    help='repository slug to use when installing from Github')
args = parser.parse_args()


# install pip
try:
    import pip  # noQA: F401
except ImportError:
    print('install pip')
    from ensurepip import bootstrap
    bootstrap()


# get dephell's jail path
def get_data_dir() -> Path:
    try:
        from appdirs import user_data_dir
    except ImportError:

        # linux
        path = Path.home() / '.local' / 'share'
        if path.exists():
            return path / 'dephell'

        # mac os
        path = Path.home() / 'Library' / 'Application Support'
Пример #18
0
 def test_pip_config_file_disabled(self):
     ensurepip.bootstrap()
     self.assertEqual(self.os_environ['PIP_CONFIG_FILE'], os.devnull)
Пример #19
0
 def test_pip_config_file_disabled(self):
     # ensurepip deliberately ignores the pip config file
     # See http://bugs.python.org/issue20053 for details
     ensurepip.bootstrap()
     self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
Пример #20
0
    def execute(self,
                context):  # execute() is called when running the operator.
        install_props = context.window_manager.install_props

        # pip in Blender:
        # https://blender.stackexchange.com/questions/139718/install-pip-and-packages-from-within-blender-os-independently/
        # pip 2.81 issues: https://developer.blender.org/T71856

        # no pip enabled by default version < 2.81
        install_props.install_status = "Preparing to enable pip..."
        self.report({'INFO'}, "Preparing to enable pip...")
        if bpy.app.version[0] == 2 and bpy.app.version[1] < 81:
            # find python binary OS independent (Windows: bin\python.exe; Linux: bin/python3.7m)
            py_path = Path(sys.prefix) / "bin"
            py_exec = str(
                next(py_path.glob("python*")
                     ))  # first file that starts with "python" in "bin" dir

            if subprocess.call([py_exec, "-m", "ensurepip"]) != 0:
                install_props.install_status += "\nCouldn't activate pip."
                self.report({'ERROR'}, "Couldn't activate pip.")
                return {'CANCELLED'}

        # from 2.81 pip is enabled by default
        else:
            try:
                # will likely fail the first time, but works after `ensurepip.bootstrap()` has been called once
                import pip
            except ModuleNotFoundError as e:
                # only first attempt will reach here
                print("Pip import failed with: ", e)
                install_props.install_status += "\nPip not activated, trying bootstrap()"
                self.report({'ERROR'}, "Pip not activated, trying bootstrap()")
                try:
                    import ensurepip
                    ensurepip.bootstrap()
                except:  # catch *all* exceptions
                    e = sys.exc_info()[0]
                    install_props.install_status += "\nPip not activated, trying bootstrap()"
                    self.report({'ERROR'},
                                "Pip not activated, trying bootstrap()")
                    print("bootstrap failed with: ", e)
            py_exec = bpy.app.binary_path_python

        # TODO check permission rights
        # TODO Windows ask for permission:
        #  https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script

        install_props.install_status += "\nPip activated! Updating pip..."
        self.report({'INFO'}, "Pip activated! Updating pip...")

        # pip update
        try:
            print("Trying pip upgrade")
            output = subprocess.check_output(
                [py_exec, '-m', 'pip', 'install', '--upgrade', 'pip'])
            print(output)
        except subprocess.CalledProcessError as e:
            install_props.install_status += "\nCouldn't update pip. Please restart Blender and try again."
            self.report(
                {'ERROR'},
                "Couldn't update pip. Please restart Blender and try again.")
            print(e.output)
            return {'CANCELLED'}
        install_props.install_status += "\nPip working! Installing pyzmq..."
        self.report({'INFO'}, "Pip working! Installing pyzmq...")

        # pyzmq pip install
        try:
            print("Trying pyzmq install")
            output = subprocess.check_output(
                [py_exec, '-m', 'pip', 'install', 'pyzmq'])
            print(output)
        except subprocess.CalledProcessError as e:
            install_props.install_status += "\nCouldn't install pyzmq."
            self.report({'ERROR'}, "Couldn't install pyzmq.")
            print(e.output)
            return {'CANCELLED'}

        install_props.install_status += "\npyzmq installed! READY!"
        self.report({'INFO'}, "pyzmq installed! READY!")

        return {'FINISHED'
                }  # Lets Blender know the operator finished successfully
Пример #21
0
print('Adafruit GPIO Library')
print('Works best with Python 2.7')
print('THIS INSTALL SCRIPT MAY REQUIRE ROOT/ADMIN PERMISSIONS')
print('Especially if you installed python for "all users" on Windows')
print('\ntry the following in your systems terminal if ensurepip is not sufficient:')
print('$ python -m ensurepip --upgrade')
print('$ python -m pip install --upgrade pip setuptools')

import sys
try:
    import pip
    from setuptools import setup, find_packages
except ImportError:
    import ensurepip
    ensurepip.version()
    ensurepip.bootstrap()
    from setuptools import setup, find_packages

# Define required packages.
requires = ['adafruit-pureio']

# Assume spidev is required on non-windows & non-mac platforms (i.e. linux).
if sys.platform != 'win32' and sys.platform != 'darwin':
    requires.append('spidev')

setup(name              = 'Adafruit_GPIO',
      version           = '1.0.4',
      author            = 'Tony DiCola',
      author_email      = '*****@*****.**',
      description       = 'Library to provide a cross-platform GPIO interface on the Raspberry Pi and Beaglebone Black using the RPi.GPIO and Adafruit_BBIO libraries.',
      license           = 'MIT',
Пример #22
0
 def test_pip_config_file_disabled(self):
     # ensurepip deliberately ignores the pip config file
     # See http://bugs.python.org/issue20053 for details
     ensurepip.bootstrap()
     self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
Пример #23
0
 def test_pip_environment_variables_removed(self):
     # ensurepip deliberately ignores all pip environment variables
     # See http://bugs.python.org/issue19734 for details
     self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
     ensurepip.bootstrap()
     self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
Пример #24
0
 def test_altinstall_default_pip_conflict(self):
     with self.assertRaises(ValueError):
         ensurepip.bootstrap(altinstall=True, default_pip=True)
     self.assertFalse(self.run_pip.called)
Пример #25
0
 def test_altinstall_default_pip_conflict(self):
     with self.assertRaises(ValueError):
         ensurepip.bootstrap(altinstall=True, default_pip=True)
     self.assertFalse(self.run_pip.called)
Пример #26
0
import sys

import ensurepip
try:
    ensurepip.bootstrap(upgrade=True)
except:
    sys.exit(1)
    
import pip
pip.main(['install', 'flask'])

from flask.testsuite import main
main()
Пример #27
0
 def test_pip_environment_variables_removed(self):
     # ensurepip deliberately ignores all pip environment variables
     # See http://bugs.python.org/issue19734 for details
     self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
     ensurepip.bootstrap()
     self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
Пример #28
0
 def test_bootstrapping_with_regular_install(self):
     ensurepip.bootstrap()
     self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "install")
Пример #29
0
 def test_bootstrapping_with_root(self):
     ensurepip.bootstrap(root='/foo/bar/')
     self.run_pip.assert_called_once_with([
         'install', '--no-index', '--find-links', unittest.mock.ANY,
         '--root', '/foo/bar/', 'setuptools', 'pip'
     ], unittest.mock.ANY)
Пример #30
0
 def test_bootstrapping_with_alt_install(self):
     ensurepip.bootstrap(altinstall=True)
     self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "altinstall")
Пример #31
0
bl_info = {
    "name": "BlenderMalt",
    "author": "Miguel Pozo",
    "description": "Extensible Python Render Engine",
    "blender": (2, 80, 0),
    "category": "Render"
}

import bpy

#ENSURE DEPENDENCIES ARE INSTALLED
try:
    import OpenGL, pcpp
except:
    import os, subprocess, ensurepip
    ensurepip.bootstrap()
    os.environ.pop("PIP_REQ_TRACKER",
                   None)  #https://developer.blender.org/T71856 :(
    dependencies = ['PyOpenGL', 'pcpp']
    for dependency in dependencies:
        subprocess.check_call(
            [bpy.app.binary_path_python, '-m', 'pip', 'install', dependency])

#Add Malt to the import path
import sys
from os import path
current_dir = path.join(path.dirname(path.realpath(__file__)), 'MaltPath')
if current_dir not in sys.path:
    sys.path.append(current_dir)

import Malt
Пример #32
0
 def test_bootstrapping_with_upgrade(self):
     ensurepip.bootstrap(upgrade=True)
     self.run_pip.assert_called_once_with([
         'install', '--no-index', '--find-links', unittest.mock.ANY,
         '--upgrade', 'setuptools', 'pip'
     ], unittest.mock.ANY)