1 #!/bin/bash 2 # Copyright 2017 The Chromium OS Authors. All rights reserved. 3 # Use of this source code is governed by a BSD-style license that can be 4 # found in the LICENSE file. 5 # 6 # Starts a python interpreter in virtualenv. 7 # 8 # This script will set up a virtualenv when it has not been created yet and 9 # executes the Python interpreter. 10 # 11 # The canonical version of this script is in infra_virtualenv repository. 12 # See infra_virtualenv/README.md about how to adopt virtualenv to your project. 13 14 set -eu 15 16 # Change this constant to the path(s) to infra_virtualenv directory when you 17 # copy this script to other repos. 18 # A path can be a relative path from this script, or an absolute path. If this 19 # array contains multiple paths, they are searched in the listed order. 20 readonly -a infra_virtualenv_paths=( 21 "../../../../../../infra_virtualenv" 22 "/opt/infra_virtualenv" 23 ~chromeos-test/chromiumos/infra_virtualenv 24 ) 25 26 readonly bin_dir="$(readlink -e -- "$(dirname -- "$0")")" 27 if [[ ! -d "${bin_dir}" ]]; then 28 echo "python_venv: Cannot locate python_env!" >&2 29 exit 1 30 fi 31 32 realpath() { 33 pushd "${bin_dir}" > /dev/null 2>&1 34 readlink -e -- "$1" 35 popd > /dev/null 2>&1 36 } 37 38 find_create_venv() { 39 local p 40 for p in "${infra_virtualenv_paths[@]}"; do 41 local create_venv=$(realpath "${p}/bin/create_venv") 42 if [[ -f "${create_venv}" ]]; then 43 echo "${create_venv}" 44 break 45 fi 46 done 47 } 48 49 readonly create_venv=$(find_create_venv) 50 if [[ ! -f "${create_venv}" ]]; then 51 cat <<EOF >&2 52 python_venv: create_venv script could not be located 53 python_venv: Possible causes: python_venv configured incorrectly or 54 python_venv: incomplete repo checkout 55 EOF 56 exit 1 57 fi 58 59 readonly extra_imports_dir=$(realpath ../venv) 60 if [[ ! -d "${extra_imports_dir}" ]]; then 61 cat <<EOF >&2 62 python_venv: ${bin_dir}/../venv does not exist 63 python_venv: See infra_virtualenv/README.md for details 64 EOF 65 exit 1 66 fi 67 68 readonly venv_dir=$("${create_venv}" "${extra_imports_dir}/requirements.txt") 69 if [[ ! -d "${venv_dir}" ]]; then 70 echo "ERROR: Failed to set up a virtualenv." >&2 71 exit 1 72 fi 73 74 export PYTHONPATH="${extra_imports_dir}" 75 exec "${venv_dir}/bin/python" "$@" 76