我需要在我的脚本中直接从PyPi安装一个包.也许有一些模块或distutils(distribute,pip等)功能,它允许我只是执行像pypi.install('requests')和请求将被安装到我的virtualenv.
我跑的时候
import sys
print sys.path
Run Code Online (Sandbox Code Playgroud)
在我的Mac(Mac OS X 10.6.5,Python 2.6.1)上,我得到以下结果.
/Library/Python/2.6/site-packages/ply-3.3-py2.6.egg ... /Library/Python/2.6/site-packages/ipython-0.10.1-py2.6.egg /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload /Library/Python/2.6/site-packages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode
它们分为5类.
我可以使用代码添加更多路径
sys.path.insert(0, MORE_PATH)
Run Code Online (Sandbox Code Playgroud)
根据Michael的回答,我调查了site.py,并得到了以下代码.
def addsitepackages(known_paths):
"""Add site-packages (and possibly site-python) to sys.path"""
sitedirs = []
seen = []
for prefix in PREFIXES:
if not prefix or prefix in seen:
continue
seen.append(prefix)
if sys.platform …Run Code Online (Sandbox Code Playgroud) 我想编写一个脚本来自动设置一个全新的ubuntu安装并安装一个基于django的应用程序.由于脚本将在新服务器上运行,因此Python脚本需要自动安装一些必需的模块.
这是脚本.
#!/usr/bin/env python
import subprocess
import os
import sys
def pip_install(mod):
print subprocess.check_output("pip install %s" % mod, shell=True)
if __name__ == "__main__":
if os.getuid() != 0:
print "Sorry, you need to run the script as root."
sys.exit()
try:
import pexpect
except:
pip_install('pexpect')
import pexpect
# More code here...
Run Code Online (Sandbox Code Playgroud)
安装pexpect成功,但下一行import pexpect失败.我认为这是因为在运行时代码不知道新安装的pexpect.
如何在运行时安装和导入Python模块?我对其他方法持开放态度.