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

cyb*_*ron 0 python unix

所以我正在尝试创建一个setup.py文件,在python中部署一个测试框架.该库具有依赖性pexpecteasy_install.因此,在安装之后easy_install,我需要安装s3cmd哪个是与Amazon S3一起使用的工具.但是,要配置s3cmd我使用pexpect,但如果你想setup.py从一个新的VM运行,那么我们遇到一个ImportError:

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()
Run Code Online (Sandbox Code Playgroud)

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

ber*_*eal 7

它不会接受它,但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
Run Code Online (Sandbox Code Playgroud)

编辑:这种方式使用setuptools有一个特点,因为在Python重新启动之前不会重新加载.pth文件.您可以执行重新加载(在此处找到):

import subprocess, pkg_resources
subprocess.call(['easy_install', 'pexpect'])
pkg_resources.get_distribution('pexpect').activate()
import pexpect  # Now works
Run Code Online (Sandbox Code Playgroud)

(不相关:我宁愿假设脚本本身是使用所需的权限调用的,而不是sudo在其中使用.这对virtualenv很有用.)