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

2024-05-16 01:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试创建一个setup.py文件,在python中部署一个测试框架。 库在pexpecteasy_install中有依赖关系。因此,在安装easy_install之后,我需要安装s3cmd,这是一个与Amazon的S3一起工作的工具。 但是,要配置s3cmd,我使用pexpect,但是如果您想从新的虚拟机运行setup.py,那么我们将遇到一个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()

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


Tags: install文件pyimportchildmainconfiguredef
1条回答
网友
1楼 · 发布于 2024-05-16 01:52:30

它不会这样接受它,但是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有一个特点,因为在Python重新启动之前,.pth文件不会被重新加载。您可以强制重新加载(found here):

^{pr2}$

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

相关问题 更多 >