Skip to content

Avoid sys.path pollution when switching interpreters #672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 7 additions & 22 deletions virtualenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,6 @@
import base64
import sys
import os

#
# RATIONALE:
# This script is both it's own "host" and "guest". If it's running in "guest
# mode" (inside the virtualenv interpreter), it's essentially invoked via:
# /path/to/python /path/to/this/script.py
#
# Which, by the nature of Python, will put `/path/to/this` on the system path
# as the first argument. Now this can cause many subtle bugs, because the
# rest of the script is now looking to import from the "host" Python version
# first. This has been especially troublesome when trying to create a Python
# 3 "guest" env using a Python 2 "host", but even with minor Python
# differences, there may been some bleeding between environments that doesn't
# stand out as obviously.
#
# This removes the first argument off the system path, to avoid any accidental
# usage of the "host" library directories.
#
if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
del sys.path[0]

import codecs
import optparse
import re
Expand Down Expand Up @@ -802,7 +781,13 @@ def main():
file = __file__
if file.endswith('.pyc'):
file = file[:-1]
popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
# use exec() instead of passing the script name directly to avoid
# sys.path pollution
popen = subprocess.Popen(
[interpreter,
'-c',
'import sys; del sys.argv[0]; s = sys.argv[0]; exec(open(s).read(), {"__file__": s, "__name__": "__main__"})',
file] + sys.argv[1:], env=env)
raise SystemExit(popen.wait())

if not args:
Expand Down