【Python编程】运行前检测并安装脚本的依赖库

  python功能十分强大得益于其丰富的第三方库,也正因为此你写好的脚本在其他平台上运行的话,就坑能因为缺少所需要的这些库而报错无法运行。如下所示:

E:\project\python>python ./test.py
Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    import serial
ModuleNotFoundError: No module named 'serial'

  接下来我们以pyserial这个经产使用的第三方串口编程库为例

#!/usr/bin/env python
#-*-coding:utf-8 -*-
requirements = ["pyserial"]
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 os
import sys
import time
import string
import serial

if __name__ == "__main__":
    
    portx = 'COM1'
    bps = 115200
    mSerial = serial.Serial(portx, int(bps))
    if (mSerial.isOpen()):
        print("open success")
        mSerial.write("hello\n".encode())
        mSerial.flushInput()
    else:
        print("open failed")
        serial.close()

  演示效果如下截图:
【Python编程】运行前检测并安装脚本的依赖库


参考文章:

上一篇:week6 day3 并发编程之多进程 代码


下一篇:最近让我焦灼的四个问题