你可以做到这一点,而无需在 python 本身中安装任何东西。
您不需要 sudo 或任何特权。
您无需查找最新版本的virtualenv
tar 文件
您无需在 bash 脚本中编辑版本信息来保持最新状态。
您不需要curl
/wget
或tar
安装,也不需要pip
或easy_install
这适用于 2.7 和 3.X
将以下内容保存到/tmp/initvenv.py
:
from __future__ import print_function
import os, sys, shutil, tempfile, subprocess, tarfile, hashlib
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
tmp_dir = tempfile.mkdtemp(prefix='initvenv_')
try:
# read the latest version from PyPI
f = urlopen("https://pypi.python.org/pypi/virtualenv/")
# retrieve the .tar.gz file
tar_found = False
url = None
sha256 = None
for line in f.read().splitlines():
if isinstance(line, bytes):
line = line.decode('utf-8')
if tar_found:
if 'sha256' in line:
sha256 = line.split('data-clipboard-text')[1].split('"')[1]
break
continue
if not tar_found and 'tar.gz">' not in line:
continue
tar_found = True
for url in line.split('"'):
if url.startswith('https'):
break
else:
print('tar.gz not found')
sys.exit(1)
file_name = url.rsplit('/', 1)[1]
print(file_name)
os.chdir(tmp_dir)
data = urlopen(url).read()
data_sha256 = hashlib.sha256(data).hexdigest()
if sha256 != data_sha256:
print('sha256 not correct')
print(sha256)
print(data_sha256)
sys.exit(1)
with open(file_name, 'wb') as fp:
fp.write(data)
tar = tarfile.open(file_name)
tar.extractall()
tar.close()
os.chdir(file_name.replace('.tar.gz', ''))
print(subprocess.check_output([sys.executable, 'virtualenv.py'] +
[sys.argv[1]]).decode('utf-8'), end='')
if len(sys.argv) > 2:
print(subprocess.check_output([
os.path.join(sys.argv[1], 'bin', 'pip'), 'install', 'virtualenv'] +
sys.argv[2:]).decode('utf-8'), end='')
except:
raise
finally:
shutil.rmtree(tmp_dir) # always clean up
并将其用作
python_binary_to_use_in_venv /tmp/initvenv.py your_venv_name [optional packages]
例如(如果你真的需要distribute
兼容层setuptools
)
python /tmp/initvenv.py venv distribute
请注意,对于较旧的 python 版本,这可能会给你InsecurePlatformWarning
s¹。
一旦你有了你的 virtualenv(名字 eg venv
),你可以使用virtualenv
刚刚安装的来设置另一个 virtualenv:
venv/bin/virtualenv venv2
###virtualenvwrapper
我建议在一次设置后也看看virtualenvwrapper :
% /opt/python/2.7.10/bin/python /tmp/initvenv.py venv virtualenvwrapper
和激活(可以从您的登录脚本完成):
% source venv/bin/virtualenvwrapper.sh
您可以执行以下操作:
% mktmpenv
New python executable in tmp-17bdc3054a46b2b/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-17bdc3054a46b2b)%
¹我还没有找到抑制警告的方法。它可以在pip
和/或中解决request
,但开发人员互相指出原因。我得到了通常不切实际的建议,将我正在使用的 python 版本升级到最新版本。我确信这会破坏我的 Linux Mint 17 安装。幸运的是pip
缓存包,因此每次安装包时只会发出一次警告。