python 每周一练
每周五发布 python 需求, 所有需求都来自或抽象于实际企业. 下周五发布参考答案.
python 测试工具开发自学每周一练 - 2018-06
2018-07-27 使用命令行自动化测试工具 pexpect 登录 ftp 服务器
使用命令行自动化测试工具 pexpect 登录 ftp 服务器 172.20.17.200, 并镜像 projects 目录.
参考
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319
- # 技术支持 钉钉群: 21745728(可以加钉钉 pythontesting 邀请加入)
- # qq 群: 144081101 591302926 567351477
- # CreateDate: 2018-07-27
- import pexpect
- class Lftp(object):
- client = None
- @classmethod
- def connect(cls, ip, username="andrew", password="654321_", prompt='~>',
- silent=False):
- child = pexpect.spawn('lftp {}:{}@{}'.format(username, password, ip),
- maxread=5000)
- i = 1
- # Enter password
- while i != 0:
- i = child.expect([prompt, pexpect.TIMEOUT])
- if not silent:
- print(child.before.decode('utf-8'), child.after.decode('utf-8'))
- if i == 0: # find prompt
- pass
- else:
- raise Exception('ERROR TIMEOUT! LFTP could not login.')
- Lftp.client = child
- @classmethod
- def command(cls, cmd, prompt='~>', silent=False):
- Lftp.client.buffer = b'' Lftp.client.send(cmd +"\r")
- # Lftp.client.setwinsize(400,400)
- Lftp.client.expect([prompt,])
- if not silent:
- print(Lftp.client.before.decode('utf-8'),
- Lftp.client.after.decode('utf-8'))
- return Lftp.client.before, Lftp.client.after
- @classmethod
- def close(cls):
- Lftp.client.close()
- c = Lftp()
- c.connect('172.20.17.200')
- c.command("ls -l")
- c.command("mirror projects")
- c.close()
最新代码地址
注意: 该例子用 ftplib 更快捷, 但是对于不支持网络协议的纯命令行交互, pexpect 则能大行其道. 另外对于网络设备, pexpect 能用几乎完全一样的代码支持 telnet,ftp,SSH, 且灵活性更好.
2018-07-20 用 flask 和 matplotlib 画出正弦曲线
用 flask 和 matplotlib 画出 1-10 的正弦曲线, 并用 flask 在 web 进行展示, 如下:
图片. PNG
参考答案:
- import matplotlib
- matplotlib.use('agg')
- import matplotlib.pyplot as plt
- from flask import Flask
- import numpy as np
- import io
- App = Flask(__name__)
- @App.route('/plot')
- def build_plot():
- # Generate the plot
- x = np.linspace(0, 10)
- line, = plt.plot(x, np.sin(x))
- f = io.BytesIO()
- plt.savefig(f, format='png')
- # Serve up the data
- header = {'Content-type': 'image/png'}
- f.seek(0)
- data = f.read()
- return data, 200, header
- if __name__ == '__main__':
- App.run(host='0.0.0.0',port=8000, debug=True)
最新代码地址
参考资料
https://gist.github.com/wilsaj/862153
2018-07-13 一些 pandas add 相关练习题
一, 条件:
- df1 = pd.DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcf'))
- df2 = pd.DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde'))
1, 求 df1 + df2 的计算结果:
参考答案:
- a b c d e f
- 0 0.0 2.0 4.0 NaN NaN NaN
- 1 9.0 11.0 13.0 NaN NaN NaN
- 2 18.0 20.0 22.0 NaN NaN NaN
- 3 NaN NaN NaN NaN NaN NaN
2, 求 df1.add(df2) 的计算结果:
参考答案:
- a b c d e f
- 0 0.0 2.0 4.0 NaN NaN NaN
- 1 9.0 11.0 13.0 NaN NaN NaN
- 2 18.0 20.0 22.0 NaN NaN NaN
- 3 NaN NaN NaN NaN NaN NaN
3, 求 df1.add(df2, fill_value=0) 的计算结果:
参考答案:
- a b c d e f
- 0 0.0 2.0 4.0 3.0 4.0 3.0
- 1 9.0 11.0 13.0 8.0 9.0 7.0
- 2 18.0 20.0 22.0 13.0 14.0 11.0
- 3 15.0 16.0 17.0 18.0 19.0 NaN
二, 条件:
- df1 = pd.DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcf'))
- df2 = pd.DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde'))
- df1.drop(0, inplace=True)
- df2.drop(2, inplace=True)
1, 求 df1 + df2 的计算结果:
参考答案:
- a b c d e f
- 0 NaN NaN NaN NaN NaN NaN
- 1 9.0 11.0 13.0 NaN NaN NaN
- 2 NaN NaN NaN NaN NaN NaN
- 3 NaN NaN NaN NaN NaN NaN
2, 求 df1.add(df2) 的计算结果:
参考答案:
- a b c d e f
- 0 NaN NaN NaN NaN NaN NaN
- 1 9.0 11.0 13.0 NaN NaN NaN
- 2 NaN NaN NaN NaN NaN NaN
- 3 NaN NaN NaN NaN NaN NaN
3, 求 df1.add(df2, fill_value=0) 的计算结果:
参考答案:
- a b c d e f
- 0 0.0 1.0 2.0 3.0 4.0 NaN
- 1 9.0 11.0 13.0 8.0 9.0 7.0
- 2 8.0 9.0 10.0 NaN NaN 11.0
- 3 15.0 16.0 17.0 18.0 19.0 NaN
参考资料
2018-07-06 使用 python3 smtplib 通过网易 126 邮箱发送带附件的邮件.
图片. PNG
参考代码:
- def send_mail(recipients, sub, content, from_name='比对测试',server="smtp.126.com",
- files=[]):
- EMAIL_SEND_USER = os.environ.get('EMAIL_SEND_USER')
- EMAIL_SEND_PASSPORT = os.environ.get('EMAIL_SEND_PASSPORT')
- msg = MIMEMultipart()
- msg.attach(MIMEText(content, 'plain'))
- msg['Subject'] = sub
- msg['From'] = "{}<{}>".format(from_name, EMAIL_SEND_USER)
- msg['To'] = ",".join(recipients)
- try:
- s = smtplib.SMTP()
- s.connect(server)
- s.login(EMAIL_SEND_USER, EMAIL_SEND_PASSPORT)
- for f in files or []:
- with open(f, "rb") as fil:
- part = MIMEApplication(
- fil.read(),
- Name=os.path.basename(f)
- )
- # After the file is closed
- part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(f)
- msg.attach(part)
- print("send email to {}".format(recipients))
- s.sendmail(EMAIL_SEND_USER, recipients, msg.as_string())
- s.close()
- return True
- except Exception as e:
- print(str(e))
- return False
- if __name__ == '__main__':
- if send_mail(['xurongzhong@sensetime.com'],"活体比对测试结果", "测试结果",
- files=[r'output.xls']):
- print("发送成功")
参考资料:
最新代码地址
http://naelshiab.com/tutorial-send-email-python/
https://gist.github.com/dtanham/11326557 要翻墙
参考资料
讨论 qq 群 144081101 591302926 567351477 钉钉免费群 21745728
本文最新版本地址
本文涉及的 python 测试开发库 https://github.com/china-testing/python-api-tesing 谢谢点赞!
本文相关海量书籍下载
2018-07-01 一些正则表达式练习题
1, 下面那些不是 python3 正则表达式的元字符:
A $ B - C * D ? E /
参考答案: B E
2,python3 正则表达式 r'\bfoo\b'匹配下面哪些字符串
A 'foo' B 'foo.' C '(foo)' D 'bar foo baz' E 'foobar' F 'foo3'
参考答案: A B C D
3,python3 正则表达式 r'\bfoo\b'匹配下面哪些字符串
A 'foo,' B 'foo.' C '(foo!' D 'bar foo baz' E 'foobar' F 'foo3'
参考答案: A B C D
4, 下面 python3 正则表达式元字符的描述哪些是错误的.
A. 默认 \ w 不能匹配汉字
B. 默认 \ w 能匹配汉字
C. 默认. 能匹配换行符
D. 默认. 不能匹配换行符
参考答案: A C
来源: http://www.jianshu.com/p/1872da4c9976