2014-12-13 95 views
14

我正在使用Python 3.4,並創建了一個pyvenv,我正在從python進程中激活它。使用virtualenv,我曾經使用activate_this.py,但似乎在pyvenv中沒有了。如何從python中激活pyvenv vitrualenv? (activate_this.py被刪除?)

現在有一種簡單的方法可以將當前的解釋器有效地更改爲virtualenv解釋器嗎?我可能會弄亂PATH(這是activate_this.py做的),但我想要一個更簡單和更穩定的方法。

這是用在wsgi.py中的。

+0

是,激活腳本取決於您的平臺:https://docs.python.org/3/library/venv.html – 2014-12-13 19:13:19

+1

另外,在Python過程中激活並不完全合理。您只能激活virtualenv,然後使用屬於該virtualenv的Python解釋器。 – 2014-12-13 19:19:13

+0

我想如果你在這裏閱讀,你會明白爲什麼它是有道理的:http://virtualenv.readthedocs.org/en/latest/virtualenv.html#using-virtualenv-without-bin-python 這是功能我正在尋找這似乎已經消失在pyvenv。 – 2014-12-13 19:35:38

回答

6

pyvenvvenv模塊不支持開箱即用。第三方virtualenvdoes support this using activate_this.py,但that feature was not included in the built-in venv module

您可以嘗試從基於virtualenv的環境借用activate_this.py副本;它似乎工作,但我不能發誓它將是完美的(venv/pyvenv在啓動過程中使用了一些魔法;如果它全部通過activate_this.py複製,則不清楚)。

virtualenv文檔對於Python 3已過期(他們聲稱您使用的是execfile,它不存在)。 Python的3兼容的替代方案是:

activator = 'some/path/to/activate_this.py' # Looted from virtualenv; should not require modification, since it's defined relatively 
with open(activator) as f: 
    exec(f.read(), {'__file__': activator}) 

沒有activate_this.py確實是神奇的,所以你可以手動執行相同的變化,而不從virtualenv搶劫(調整PATHsys.pathsys.prefix等),但借款使得它更在這種情況下更簡單。

+0

謝謝,我從[這裏](https://github.com/pypa/virtualenv/blob/master/virtualenv_embedded/activate_this.py)將[[pyenv-virtualenv](https://github.com/pyenv/) pyenv-virtualenv)似乎沒有一個。 – cardamom 2017-07-03 17:35:41

1

我以前在virtualenv使用了不同的方法本身:

# the current Python interpreter is not from the virtual environment 
file = __file__ 
if file.endswith('.pyc'): 
    file = file[:-1] 
venv_executable = PROJECT_DIR/'venv'/'bin'/'python' 
popen = subprocess.Popen([venv_executable, file] + sys.argv[1:]) 
raise SystemExit(popen.wait())