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进行展示,如下:
参考答案:
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://stackoverflow.com/questions/35737116/runtimeerror-invalid-display-variable
http://www.fivecomputers.com/serving-dynamic-charts-with-flask.html
https://stackoverflow.com/questions/41459657/how-to-create-dynamic-plots-to-display-on-flask
http://hplgit.github.io/web4sciapps/doc/pub/._web4sa_flask013.html
http://dataviztalk.blogspot.com/2016/01/serving-matplotlib-plot-that-follows.html
https://github.com/realpython/flask-matplotlib/blob/master/app.py
https://gist.github.com/wilsaj/862153
https://www.hackster.io/mjrobot/from-data-to-graph-a-web-journey-with-flask-and-sqlite-4dba35
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
- 参考资料
pandas.DataFrame.add
2018-07-06 使用python3 smtplib通过网易126邮箱发送带附件的邮件。
参考代码:
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(['[email protected]'],"活体比对测试结果", "测试结果",
files=[r'output.xls']):
print("发送成功")
- 参考资料:
最新代码地址
http://naelshiab.com/tutorial-send-email-python/
https://gist.github.com/dtanham/11326557 要翻墙
http://code.activestate.com/recipes/578807-sending-email-from-a-python-program/
参考资料
- 讨论qq群144081101 591302926 567351477 钉钉免费群21745728
- 本文最新版本地址
- 本文涉及的python测试开发库 谢谢点赞!
- 本文相关海量书籍下载
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