Solution: How do I check whether a module is installed in Python, and install it if needed?

Development | Programming languages
Description
PKGS=['selenium','ctypes','time',
'os','shutil','subprocess','unittest','urllib']

for p in PKGS:
    import imp
    m_repr = "'%s'"%p
    m_repr = m_repr.ljust(20,".")
    print("Module %s"%m_repr,)
    try:
        fp, pathname, description = imp.find_module(p)
        imp.load_module(p, fp, pathname, description)
    except:
        print("FAIL")
        continue
    finally:
        print("OK")
Attachments
No attachments.
Solutions
Code attached.
on March 19th, 2019 (9:27 pm)
What masters said
You must sign in to comment!!
All comments
When you need to install the python module:
# -*- coding: utf-8 -*-
# ver 2019.03.27

import imp
import os

packages=['selenium','ctypes','time','os','shutil','subprocess','unittest','urllib','cow']

for p in packages:
    not_installed = "'%s'"%p
    print("Module %s"%not_installed,)
    try:
        fp, pathname, description = imp.find_module(p)
        imp.load_module(p, fp, pathname, description)
    except:
        print("FAIL, RUNNING AUTOMATIC INSTALLATION")
        module_to_install = not_installed[1: -1]
        setup_module='python -m pip install ' + module_to_install
        print(setup_module)
        os.system(setup_module)
        continue
    finally:
        print("OK")


on March 20th, 2019 (9:19 pm)