【Python编程】运行前检测并安装脚本的依赖库
2021/10/24 17:41:18
本文主要是介绍【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脚本检测并安装依赖的第三方库
这篇关于【Python编程】运行前检测并安装脚本的依赖库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门
- 2024-11-14Python编程入门指南
- 2024-11-13Python基础教程
- 2024-11-12Python编程基础指南
- 2024-11-12Python基础编程教程
- 2024-11-08Python编程基础与实践示例
- 2024-11-07Python编程基础指南
- 2024-11-06Python编程基础入门指南
- 2024-11-06怎么使用python 计算两个GPS的距离功能-icode9专业技术文章分享