"""Activate virtualenv for current interpreter: Use exec(open(this_file).read(), {'__file__': this_file}). This can be used when you must use an existing Python interpreter, not the virtualenv bin/python. """ import os import site import sys try: abs_file = os.path.abspath(__file__) except NameError: raise AssertionError("You must use exec(open(this_file).read(), {'__file__': this_file}))") bin_dir = os.path.dirname(abs_file) base = bin_dir[: -len("Scripts") - 1] # strip away the bin part from the __file__, plus the path separator # prepend bin to PATH (this file is inside the bin directory) os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep)) os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory # add the virtual environments libraries to the host python import mechanism prev_length = len(sys.path) for lib in "..\Lib\site-packages".split(os.pathsep): path = os.path.realpath(os.path.join(bin_dir, lib)) site.addsitedir(path.decode("utf-8") if "" else path) sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length] sys.real_prefix = sys.prefix sys.prefix = base
时间: 2023-05-17 21:03:04 浏览: 267
python虚拟环境 virtualenv的简单使用
这段代码是用来激活当前解释器的虚拟环境的。当你必须使用现有的Python解释器而不是虚拟环境中的bin/python时,可以使用这个方法。代码中使用了os、site和sys模块。首先,通过os模块获取当前文件的绝对路径,然后通过切片操作获取虚拟环境的根目录。最后,可以使用这个根目录来激活虚拟环境。
阅读全文