【问题标题】:how to import a python module before installing it?如何在安装之前导入 python 模块?
【发布时间】:2014-02-09 06:58:07
【问题描述】:

所以我正在尝试创建一个setup.py 文件并在 python 中部署一个测试框架。 该库在pexpect 和easy_install 中有依赖项。所以,在安装easy_install 之后,我需要安装s3cmd,这是一个与亚马逊S3 配合使用的工具。 但是,要配置s3cmd,我使用pexpect,但是如果您想从新的VM 运行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 来安装easy_install 和pexpect,但我的问题是:在拥有它之前有没有办法import pexpect安装?库会在使用前安装,但是 Python 解释器会接受import pexpect 命令吗?

【问题讨论】:

    标签: python unix


    【解决方案1】:

    它不会接受这样的,但是 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 文件。你可以强制重新加载(找到here):

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

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

    【讨论】:

    • 第一次出现错误(我认为python没有发现模块已安装)。第二次起作用了。我怎么能避免呢?
    • 我收到以下错误:global name 'pkg_distribution' is not defined
    • @philippe,对不起,我的错。那应该是pkg_resources。您还需要导入它。已更新。
    • AttributeError: 'module' object has no attribute 'distribution' 你确定吗? :-(
    • 资本D在分配中
    猜你喜欢
    • 2019-05-08
    • 2016-05-12
    • 2018-01-21
    • 1970-01-01
    • 2013-06-18
    • 2023-04-05
    • 2023-02-22
    • 2017-07-08
    • 1970-01-01
    相关资源
    最近更新 更多