如何在运行时安装和导入 Python 模块? [英] How to install and import Python modules at runtime?

查看:31
本文介绍了如何在运行时安装和导入 Python 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个脚本来自动设置一个全新的 ubuntu 安装并安装一个基于 django 的应用程序.由于脚本将在新服务器上运行,因此Python脚本需要自动安装一些必需的模块.

I want to write a script to automatically setup a brand new ubuntu installation and install a django-based app. Since the script will be run on a new server, the Python script needs to automatically install some required modules.

这是脚本.

#!/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...

pexpect安装成功,但下一行import pexpect失败.我认为这是因为在运行时代码不知道新安装的 pexpect.

The installation of pexpect is success, however the next line import pexpect is failed. I think its because at runtime the code doesn't aware about the newly installed pexpect.

如何在运行时安装和导入 Python 模块?我愿意接受其他方法.

How to install and import Python modules at runtime? I'm open to another approaches.

推荐答案

我使用 imp 模块.

I solved my problem using the imp module.

#!/usr/bin/env python

import pip
import imp

def install_and_load(package):
    pip.main(['install', package])

    path = '/usr/local/lib/python2.7/dist-packages'
    if path not in sys.path:
        sys.path.append(path)

    f, fname, desc = imp.find_module(package)
    return imp.load(package, f, fname, desc)

if __name__ == "__main__":
    try:
        import pexpect
    except:
        pexpect = install_and_load('pexpect')

    # More code...

实际上代码不太理想,因为我需要对 Python 模块目录进行硬编码.但由于脚本是针对已知目标系统设计的,我认为没问题.

Actually the code is less than ideal, since I need to hardcode the Python module directory. But since the script is intended for a known target system, I think that is ok.

这篇关于如何在运行时安装和导入 Python 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆