How to use virtualenv - 10 common examples

To help you get started, we’ve selected a few virtualenv examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pypa / virtualenv / tests / unit / interpreters / boostrap / test_boostrap_link_via_app_data.py View on Github external
def test_base_bootstrap_link_via_app_data(tmp_path, coverage_env):
    bundle_ver = BUNDLE_SUPPORT[CURRENT.version_release_str]
    create_cmd = [
        str(tmp_path / "env"),
        "--seeder",
        "link-app-data",
        "--download",
        "--pip",
        bundle_ver["pip"].split("-")[1],
        "--setuptools",
        bundle_ver["setuptools"].split("-")[1],
    ]
    result = run_via_cli(create_cmd)
    coverage_env()
    assert result

    # uninstalling pip/setuptools now should leave us with a clean env
    site_package = result.creator.site_packages[0]
    pip = site_package / "pip"
    setuptools = site_package / "setuptools"

    files_post_first_create = list(site_package.iterdir())
    assert pip in files_post_first_create
    assert setuptools in files_post_first_create

    env_exe = result.creator.exe
    for pip_exe in [
        env_exe.with_name("pip{}{}".format(suffix, env_exe.suffix))
        for suffix in (
github pypa / virtualenv / tests / test_virtualenv.py View on Github external
def test_create_environment_with_exec_prefix_pointing_to_prefix(tmpdir):
    """Create virtual environment for Python with ``sys.exec_prefix`` pointing
    to ``sys.prefix`` or ``sys.base_prefix`` or ``sys.real_prefix`` under a
    different name
    """
    venvdir = str(tmpdir / "venv")
    python_dir = tmpdir / "python"
    python_dir.mkdir()
    path_key = str("PATH")
    old_path = os.environ[path_key]
    if hasattr(sys, "real_prefix"):
        os.environ[path_key] = os.pathsep.join(
            p for p in os.environ[path_key].split(os.pathsep) if not p.startswith(sys.prefix)
        )
    python = virtualenv.resolve_interpreter(os.path.basename(sys.executable))
    try:
        subprocess.check_call([sys.executable, "-m", "virtualenv", "-p", python, venvdir])
        home_dir, lib_dir, inc_dir, bin_dir = virtualenv.path_locations(venvdir)
        assert not os.path.islink(os.path.join(lib_dir, "distutils"))
    finally:
        os.environ[path_key] = old_path
github pytest-dev / pytest-cov / tests / test_pytest_cov.py View on Github external
def test_dist_missing_data(testdir):
    """Test failure when using a worker without pytest-cov installed."""
    venv_path = os.path.join(str(testdir.tmpdir), 'venv')
    virtualenv.create_environment(venv_path)
    if sys.platform == 'win32':
        if platform.python_implementation() == "PyPy":
            exe = os.path.join(venv_path, 'bin', 'python.exe')
        else:
            exe = os.path.join(venv_path, 'Scripts', 'python.exe')
    else:
        exe = os.path.join(venv_path, 'bin', 'python')
    subprocess.check_call([
        exe,
        '-mpip',
        'install',
        'py==%s' % py.__version__,
        'pytest==%s' % pytest.__version__,
        'pytest_xdist==%s' % xdist.__version__

    ])
github playpauseandstop / kikola / testproject / bootstrap.py View on Github external
# Create new virtual environment
    print('Step 1. Create new virtual environment')

    if not os.path.isdir(dest_dir) or CONFIG['virtualenv']['clear']:
        kwargs = copy.copy(CONFIG['virtualenv'])
        kwargs['home_dir'] = kwargs['dest_dir']

        verbosity = int(kwargs['verbose']) - int(kwargs['quiet'])
        logger = virtualenv.Logger([
            (virtualenv.Logger.level_for_integer(2 - verbosity), sys.stdout),
        ])

        del kwargs['dest_dir'], kwargs['quiet'], kwargs['verbose']

        virtualenv.logger = logger
        virtualenv.create_environment(**kwargs)
    else:
        print('Virtual environment %r already exists.' % \
              CONFIG['virtualenv']['dest_dir'])
github prezi / snakebasket / tests / test_pip.py View on Github external
def create_virtualenv(where, distribute=False):
    import virtualenv
    if sys.version_info[0] > 2:
        distribute = True
    virtualenv.create_environment(
        where, use_distribute=distribute, unzip_setuptools=True)

    return virtualenv.path_locations(where)
github pypa / virtualenv / tests / test_zipapp.py View on Github external
def version_exe(venv, exe_name):
    _, _, _, bin_dir = virtualenv.path_locations(str(venv))
    exe = os.path.join(bin_dir, exe_name)
    script = "import sys; import json; print(json.dumps(dict(v=list(sys.version_info), e=sys.executable)))"
    cmd = [exe, "-c", script]
    out = json.loads(subprocess.check_output(cmd, universal_newlines=True))
    return out["v"], out["e"]
github pypa / pip / tests / test_pip.py View on Github external
def create_virtualenv(where, distribute=False):
    save_argv = sys.argv

    try:
        import virtualenv
        distribute_opt = distribute and ['--distribute'] or []
        sys.argv = ['virtualenv', '--quiet'] + distribute_opt + ['--no-site-packages', '--unzip-setuptools', where]
        virtualenv.main()
    finally:
        sys.argv = save_argv

    return virtualenv.path_locations(where)
github pypa / virtualenv / tests / test_cmdline.py View on Github external
def test_commandline_basic(tmpdir):
    """Simple command line usage should work and files should be generated"""
    home_dir, lib_dir, inc_dir, bin_dir = virtualenv.path_locations(str(tmpdir.join("venv")))
    subprocess.check_call([sys.executable, "-m", "virtualenv", "-vvv", home_dir, "--no-download"])

    assert os.path.exists(home_dir)
    assert os.path.exists(bin_dir)

    assert os.path.exists(os.path.join(bin_dir, "activate"))
    assert os.path.exists(os.path.join(bin_dir, "activate_this.py"))
    assert os.path.exists(os.path.join(bin_dir, "activate.ps1"))

    exe = os.path.join(bin_dir, os.path.basename(sys.executable))
    assert os.path.exists(exe)

    def _check_no_warnings(module):
        subprocess.check_call((exe, "-Werror", "-c", "import {}".format(module)))

    _check_no_warnings("distutils")
github arangodb / arangodb / tests / js / common / test-data / modules / commonjs / bootstrap.py View on Github external
def install_setuptools(py_executable, unzip=False):
    setup_fn = 'setuptools-0.6c9-py%s.egg' % sys.version[:3]
    search_dirs = ['.', os.path.dirname(__file__), join(os.path.dirname(__file__), 'support-files')]
    if os.path.splitext(os.path.dirname(__file__))[0] != 'virtualenv':
        # Probably some boot script; just in case virtualenv is installed...
        try:
            import virtualenv
        except ImportError:
            pass
        else:
            search_dirs.append(os.path.join(os.path.dirname(virtualenv.__file__), 'support-files'))
    for dir in search_dirs:
        if os.path.exists(join(dir, setup_fn)):
            setup_fn = join(dir, setup_fn)
            break
    if is_jython and os._name == 'nt':
        # Jython's .bat sys.executable can't handle a command line
        # argument with newlines
        import tempfile
        fd, ez_setup = tempfile.mkstemp('.py')
        os.write(fd, EZ_SETUP_PY)
        os.close(fd)
        cmd = [py_executable, ez_setup]
    else:
        cmd = [py_executable, '-c', EZ_SETUP_PY]
    if unzip:
        cmd.append('--always-unzip')
github playpauseandstop / kikola / testproject / bootstrap.py View on Github external
def create_environment():
    dest_dir = os.path.join(DIRNAME, CONFIG['virtualenv']['dest_dir'])
    dest_dir = os.path.abspath(dest_dir)

    # Create new virtual environment
    print('Step 1. Create new virtual environment')

    if not os.path.isdir(dest_dir) or CONFIG['virtualenv']['clear']:
        kwargs = copy.copy(CONFIG['virtualenv'])
        kwargs['home_dir'] = kwargs['dest_dir']

        verbosity = int(kwargs['verbose']) - int(kwargs['quiet'])
        logger = virtualenv.Logger([
            (virtualenv.Logger.level_for_integer(2 - verbosity), sys.stdout),
        ])

        del kwargs['dest_dir'], kwargs['quiet'], kwargs['verbose']

        virtualenv.logger = logger
        virtualenv.create_environment(**kwargs)
    else:
        print('Virtual environment %r already exists.' % \
              CONFIG['virtualenv']['dest_dir'])