如何在安装之前导入python模块?

问题描述:

所以我试图创建一个setup.py文件在python中部署一个测试框架。 该库依赖于pexpecteasy_install。所以,在安装easy_install后,我需要安装s3cmd这是一个与亚马逊S3一起工作的工具。 然而,配置s3cmd我用pexpect,但如果你想从一个新的虚拟机上运行setup.py,所以我们碰上ImportError如何在安装之前导入python模块?

import subprocess 
import sys 
import pexpect # pexpect is not installed ... it will be 

def install_s3cmd(): 
    subprocess.call(['sudo easy_install s3cmd']) 
    # now use pexpect to configure s3cdm 
    child = pexpect.spawn('s3cmd --configure') 
    child.expect ('(?i)Access Key') 
    # ... more code down there 

def main(): 
    subprocess.call(['sudo apt-get install python-setuptools']) # installs easy_install 
    subprocess.call(['sudo easy_install pexpect']) # installs pexpect 
    install_s3cmd() 
    # ... more code down here 

if __name__ == "__main__": 
    main() 

我当然知道,我可以创造一个又一个文件,initial_setup.pyeasy_installpexpect安装之前,使用setup.py,但我的问题是:有没有办法在安装之前import pexpect?该库将在使用之前安装,但Python解释器是否会接受命令import pexpect

它不会像这样接受它,但是Python允许你在任何地方导入东西,不仅在全局范围内。所以,你可以推迟进口,直到当你真正需要它的时候:

def install_s3cmd(): 
    subprocess.call(['easy_install', 's3cmd']) 

    # assuming that by now it's already been installed 
    import pexpect 

    # now use pexpect to configure s3cdm 
    child = pexpect.spawn('s3cmd --configure') 
    child.expect ('(?i)Access Key') 
    # ... more code down there 

编辑:有使用setuptools的这种方式,因为.pth文件不会被重新加载,直到重新登场的Python一个特点。您可以强制重装,但(发现here):

import subprocess, pkg_resources 
subprocess.call(['easy_install', 'pexpect']) 
pkg_resources.get_distribution('pexpect').activate() 
import pexpect # Now works 

(无关:我宁愿认为脚本本身被调用所需的特权,它不使用sudo这将是与virtualenv中有用)

+0

第一次出现错误(我认为python没有发现模块已经安装)。第二次运作。我怎么能避免这种情况? – cybertextron

+1

@philippe aha,找到它,看到更新。 – bereal

+0

我得到了以下错误:'全球名称'pkg_distribution'未定义' – cybertextron