您可以执行此操作而无需在python本身中安装任何东西。
您不需要sudo或任何特权。
您无需查找virtualenvtar文件的最新版本
您无需在bash脚本中编辑版本信息即可保持最新状态。
你不需要curl/ wget或tar安装,也不pip或easy_install
这适用于2.7和3.X
将以下内容保存到/tmp/initvenv.py:
从将来导入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版本,这可能会给您InsecurePlatformWarnings¹。
获得virtualenv(例如名称venv)后,您可以使用virtualenv刚刚安装的虚拟环境来设置另一个virtualenv :
venv/bin/virtualenv venv2
虚拟环境包装器
我建议在一次设置后也查看一下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缓存了软件包,因此每次安装软件包时仅发出一次警告。
python distribute_setup.py其次是easy_install pip和virtualenv --distribute venv?(请参阅python-guide.readthedocs.org/en/latest/starting/install/…),如果是,为什么?