Python脚本检测并安装依赖的第三方库

Python第三方库非常丰富,使用第三方库可以减少代码量,使代码逻辑更加清晰。我写脚本分享给朋友的时候,经常要提醒他这个脚本依赖哪些第三方库。如果缺第三方库,新手很难从报错和源代码中,推测出缺哪个库。那么是否可以让脚本自己检测缺少哪个库,并询问用户,然后安装呢?

requirements = ["pandas", "matplotlib", "seaborn"]
def check_requirement(package):
    try:
        exec("import {0}".format(package))
    except ModuleNotFoundError:
        inquiry = input("This script requires {0}. Do you want to install {0}? [y/n]".format(package))
        while (inquiry != "y") and (inquiry != "n"):
            inquiry = input("This script requires {0}. Do you want to install {0}? [y/n]".format(package))
        if inquiry == "y":
            import os
            print("Execute commands: pip install {0}".format(package))
            os.system("pip install {0}".format(package))
        else:
            print("{0} is missing, so the program exits!".format(package))
            exit(-1)
for requirement in requirements:
    check_requirement(requirement)
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt