在代码运行时导入package
- 起初goole到的方法是
pip.main(['insatll', packagename]), 但是会提示Warning,根据提示信息:pip与python对应的版本不一样。从link找到的方法没有解决问题。
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
- 查阅文档后,得到
pip的推荐方法: pip官方文档,和import的推荐方法:importlib,不建议用imp
import importlib, subprocess, sys
subprocess.check_call([sys.executable, "-m", "pip", "install", packagename])
package = importlib.import_module(packagename)
print("{} package: test auto install and import package complete!".format(package))
封装代码
传入package和目标版本(可选),直接返回module
import subprocess, importlib
import sys, re
from logging import log
def pkg_install_import(package, required_version=None):
"""
Check the version of given package whether the version is matched after
getting the version info of the package by pip show.
If the package is installed and it equals to the required version, just import it.
If the package is not installed, install and import the required pkg.
*Args*:
package(str): the package name to be checked and imported
*Optional Args*:
required_version(str): specific version of the package
*Returns*:
module: the target package
"""
try:
ret = subprocess.check_output([sys.executable, "-m", "pip", "show", package])
ret = ret.decode('utf-8')
ret = ret.split('\n')
pattern = re.compile('version', re.IGNORECASE)
for word in ret:
if re.findall(pattern, word):
old_version = word.split(' ')[1]
log.info("{0}_old_version = {1}\n".format(package, old_version))
except:
log.info("{} is not existed\n".format(package))
old_version = None
if old_version == None or old_version != required_version:
if required_version == None:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
else:
subprocess.check_call([sys.executable, "-m", "pip", "install", package + '==' + required_version])
return importlib.import_module(package)
测试代码
def testFunc1():
package_imgio_ffmpeg = pkg_install_import("imageio_ffmpeg")
def testFunc2():
u2 = pkg_install_import('uiautomator2', '2.9.6')
log.info("uiautomator2_new_version = {}".format(u2.version.__version__))