Skip to content

Commit f1d77cc

Browse files
committed
Fix activate_this.py does not exist, python-mode#406
1 parent fd70ac2 commit f1d77cc

File tree

1 file changed

+43
-10
lines changed

1 file changed

+43
-10
lines changed

pymode/virtualenv.py

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
""" Support virtualenv in pymode. """
22

3-
import os.path
3+
import os
4+
import sys
5+
import site
46

57
from .environment import env
68

@@ -25,13 +27,44 @@ def enable_virtualenv():
2527
activate_this = os.path.join(
2628
os.path.join(path, 'Scripts'), 'activate_this.py')
2729

28-
f = open(activate_this)
2930
try:
30-
source = f.read()
31-
exec(compile( # noqa
32-
source, activate_this, 'exec'), dict(__file__=activate_this))
33-
env.message('Activate virtualenv: ' + path)
34-
env.let('g:pymode_virtualenv_enabled', path)
35-
return True
36-
finally:
37-
f.close()
31+
with open(activate_this) as f:
32+
source = f.read()
33+
exec(compile( # noqa
34+
source, activate_this, 'exec'), dict(__file__=activate_this))
35+
except IOError:
36+
_activate_env_from_path(path)
37+
38+
env.message('Activate virtualenv: ' + path)
39+
env.let('g:pymode_virtualenv_enabled', path)
40+
return True
41+
42+
43+
def _activate_env_from_path(env_path):
44+
""" Fix when `activate_this.py` does not exist.
45+
46+
For Python 3.3 and newer, a new command-line tool `pyvenv` create venv
47+
will not provide 'activate_this.py'.
48+
"""
49+
prev_sys_path = list(sys.path)
50+
51+
if sys.platform == 'win32':
52+
site_packages_paths = [os.path.join(env_path, 'Lib', 'site-packages')]
53+
else:
54+
lib_path = os.path.join(env_path, 'lib')
55+
site_packages_paths = [os.path.join(lib_path, lib, 'site-packages')
56+
for lib in os.listdir(lib_path)]
57+
for site_packages_path in site_packages_paths:
58+
site.addsitedir(site_packages_path)
59+
60+
sys.real_prefix = sys.prefix
61+
sys.prefix = env_path
62+
sys.exec_prefix = env_path
63+
64+
# Move the added items to the front of the path:
65+
new_sys_path = []
66+
for item in list(sys.path):
67+
if item not in prev_sys_path:
68+
new_sys_path.append(item)
69+
sys.path.remove(item)
70+
sys.path[:0] = new_sys_path

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy