2020系统综合实践 第5次实践作业

2020系统综合实践 第5次实践作业

本次作业为Python专题。Python是将练习使用docker容器运行Python程序。Python是很常用的程序设计语言,但是Python程序的运行依赖于提前的系统环境配置,为了降低系统配置的复杂度,同时减小资源开销,将系统环境容器化是一种解决方案。请根据Python官方镜像的镜像说明,自定义Python镜像文件,将Python程序运行起来。

项目结构

构造容器

1.Dockerfile

FROM python:3

MAINTAINER yzl


WORKDIR /py_file

# 依赖模块列表
COPY requirements.txt ./

# 修改源并安装依赖
RUN pip install -r requirements.txt -i https://pypi.douban.com/simple 

#挂在目录
VOLUME /py_file 

# 实现命令行式调用容器
ENTRYPOINT ["python"]

# 设置默认打开的文件
CMD ["hello.py"]

2.requirements.txt

opencv-python
PyMySQL

构建镜像

程序部署

代码一

hello.py

print("hello world")

执行

sudo docker run -it --rm -v /home/yang/python/py_file:/py_file mypython hello.py

代码二

date.py

# 引入日历模块
import calendar
 
# 输入指定年月
year = int(input("输入年份: "))
month = int(input("输入月份: "))
 
# 显示日历
print(calendar.month(year,month))

执行

sudo docker run -it --rm -v /home/yang/python/py_file:/py_file mypython date.py

代码三

sql.py

import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='yzl_mysql',port=3306,user='root',passwd='123456',db='student')   
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
try:
    cursor.execute("select * from grade1;")   #执行
    results = cursor.fetchall()
 
    for row in results:
          num = row[0]
          name = row[1]
           # 打印结果
          print ("num=%d , name=%s" % 
                 (num,name ))

except:
    print("Error: unable to fetch data")
# 关闭数据库连接
db.close()

手动创建一个数据库容器,并往里面添加数据(可参考实验二)

执行

sudo docker run -it --rm -v /home/yang/python/py_file:/py_file --link=yzl_mysql mypython sql.py

代码四

opencv.py

import cv2
# 转换为灰度图片
grayimage = cv2.imread("./test.jpg",cv2.IMREAD_GRAYSCALE)
# 保存图片
cv2.imwrite("./test_gray.jpg",grayimage)
print("success!!!")

执行

sudo docker run -it --rm -v /home/yang/python/py_file:/py_file mypython opencv.py

总结

这次实验比上一次简单了不少,问题也没有多少(就数据库这个,又重新学了一遍)

项目 时间
查看文档 1h
实验 2h
排错 0.5h
博客 0.5h
原文地址:https://www.cnblogs.com/cc1219032777/p/12924994.html