MCPcopy Index your code
hub / github.com/ipython/ipython / init_virtualenv

Method init_virtualenv

IPython/core/interactiveshell.py:933–992  ·  view source on GitHub ↗

Add the current virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPyth

(self)

Source from the content-addressed store, hash-verified

931 return paths
932
933 def init_virtualenv(self):
934 """Add the current virtualenv to sys.path so the user can import modules from it.
935 This isn't perfect: it doesn't use the Python interpreter with which the
936 virtualenv was built, and it ignores the --no-site-packages option. A
937 warning will appear suggesting the user installs IPython in the
938 virtualenv, but for many cases, it probably works well enough.
939
940 Adapted from code snippets online.
941
942 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
943 """
944 if 'VIRTUAL_ENV' not in os.environ:
945 # Not in a virtualenv
946 return
947 elif os.environ["VIRTUAL_ENV"] == "":
948 warn("Virtual env path set to '', please check if this is intended.")
949 return
950
951 p = Path(sys.executable)
952 p_venv = Path(os.environ["VIRTUAL_ENV"]).resolve()
953
954 # fallback venv detection:
955 # stdlib venv may symlink sys.executable, so we can't use realpath.
956 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
957 # So we just check every item in the symlink tree (generally <= 3)
958 paths = self.get_path_links(p)
959
960 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
961 if len(p_venv.parts) > 2 and p_venv.parts[1] == "cygdrive":
962 drive_name = p_venv.parts[2]
963 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
964
965 if any(p_venv == p.parents[1].resolve() for p in paths):
966 # Our exe is inside or has access to the virtualenv, don't need to do anything.
967 return
968
969 if sys.platform == "win32":
970 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
971 else:
972 virtual_env_path = Path(
973 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
974 )
975 p_ver = sys.version_info[:2]
976
977 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
978 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
979 if re_m:
980 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
981 if predicted_path.exists():
982 p_ver = re_m.groups()
983
984 virtual_env = str(virtual_env_path).format(*p_ver)
985 if self.warn_venv:
986 warn(
987 "Attempting to work in a virtualenv. If you encounter problems, "
988 "please install IPython inside the virtualenv."
989 )
990 import site

Callers 1

__init__Method · 0.95

Calls 3

get_path_linksMethod · 0.95
searchMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected