go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/vpython/python/interpreter.go (about)

     1  // Copyright 2017 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package python
    16  
    17  import (
    18  	"go.chromium.org/luci/common/system/environ"
    19  	"go.chromium.org/luci/common/system/filesystem"
    20  )
    21  
    22  // Interpreter represents a system Python interpreter. It exposes the ability
    23  // to use common functionality of that interpreter.
    24  type Interpreter struct {
    25  	// Python is the path to the system Python interpreter.
    26  	Python string
    27  }
    28  
    29  // Normalize normalizes the Interpreter configuration by resolving relative
    30  // paths into absolute paths.
    31  func (i *Interpreter) Normalize() error {
    32  	return filesystem.AbsPath(&i.Python)
    33  }
    34  
    35  // IsolateEnvironment mutates e to remove any environmental influence over
    36  // the Python interpreter.
    37  //
    38  // If e is nil, no operation will be performed.
    39  func IsolateEnvironment(e *environ.Env) {
    40  	if e == nil {
    41  		return
    42  	}
    43  
    44  	// Remove PYTHONHOME from the environment. PYTHONHOME is used to set the
    45  	// location of standard Python libraries, which we make a point of overriding.
    46  	//
    47  	// https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME
    48  	e.Remove("PYTHONHOME")
    49  
    50  	// set PYTHONNOUSERSITE, which prevents a user's "site" configuration
    51  	// from influencing Python startup. The system "site" should already be
    52  	// ignored b/c we're using the VirtualEnv Python interpreter.
    53  	e.Set("PYTHONNOUSERSITE", "1")
    54  }