s12-20160227-day07
*:first-child {
margin-top: 0 !important;
}
body>*:last-child {
margin-bottom: 0 !important;
}
/* BLOCKS
=============================================================================*/
p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}
/* HEADERS
=============================================================================*/
h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}
h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}
h1 {
font-size: 28px;
color: #000;
}
h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
color: #777;
font-size: 14px;
}
body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}
a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}
h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}
/* LINKS
=============================================================================*/
a {
color: #4183C4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* LISTS
=============================================================================*/
ul, ol {
padding-left: 30px;
}
ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
dl {
padding: 0;
}
dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}
dl dt:first-child {
padding: 0;
}
dl dt>:first-child {
margin-top: 0px;
}
dl dt>:last-child {
margin-bottom: 0px;
}
dl dd {
margin: 0 0 15px;
padding: 0 15px;
}
dl dd>:first-child {
margin-top: 0px;
}
dl dd>:last-child {
margin-bottom: 0px;
}
/* CODE
=============================================================================*/
pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}
pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}
pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}
pre code, pre tt {
background-color: transparent;
border: none;
}
kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}
/* QUOTES
=============================================================================*/
blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}
blockquote>:first-child {
margin-top: 0px;
}
blockquote>:last-child {
margin-bottom: 0px;
}
/* HORIZONTAL RULES
=============================================================================*/
hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}
/* TABLES
=============================================================================*/
table th {
font-weight: bold;
}
table th, table td {
border: 1px solid #ccc;
padding: 6px 13px;
}
table tr {
border-top: 1px solid #ccc;
background-color: #fff;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
/* IMAGES
=============================================================================*/
img {
max-width: 100%
}
-->
pytho自动化开发 day07
Date:2016.02.27
@南非波波
课程大纲:
day06
http://www.cnblogs.com/alex3714/articles/5188179.html
day07
http://www.cnblogs.com/alex3714/articles/5213184.html
一、类的多态、继承
类的多态:统一接口调用
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
hobbie = ‘ddd‘
class Cat(Animal):
def talk(self):
return ‘Meow!‘
class Dog(Animal):
def talk(self):
return ‘Woof! Woof!‘
animals = [Cat(‘Missy‘),
Dog(‘Lassie‘)]
for animal in animals:
print(animal.name + ‘: ‘ + animal.talk())
类的方法:示例
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
class Animal(object):
‘‘‘
定义一个动物类
‘‘‘
def __init__(self,name):
self.name = name
self.__num = None #定义成私有变量,只能在类中访问
# def talk(self):
# print("%s is talking!" % self.name)
hobbie = "shen" #类变量,静态字段
@classmethod #类方法,不能访问实例变量
def talk(self):
print("%s is talking!" % self.hobbie)
# def work(self):
# print("%s is working!" % self.name)
@staticmethod #静态方法,不能访问类变量和实例变量
def work():
print("It is working!")
# def walk(self):
# print("%s is walking!" % self.name)
@property #把方法编程静态属性
def walk(self,num):
return self.__num
@walk.setter #传值
def walk(self,num):
self.__num = num
print(self.__num)
@walk.deleter #删值
def walk(self):
print("del num")
c = Animal("swht")
# c.talk()
# c.work()
c.walk = 3
del c.walk
print("OUT:",c._Animal__num) #特例情况下可以通过这种方式访问私有变量
经典类与新式类
经典类和新式类区别:
经典类:使用深度优先进行继承 新式类:使用广度优先进行继承
另外:经典类和新式类在python-3.X平台上会默认使用广度优先进行继承,而在python-2.X中则体现上述区别
示例代码:
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
class A:
print("A")
def f2(self):
print("f2 from A")
class B(A):
print("B")
def f1(self):
print("f1 from B")
def f2(self):
print("f2 from B")
class C(A):
print("C")
def f2(self):
print("f2 from C")
class D(B,C):
pass
d = D()
d.f1()
d.f2()
‘‘‘
广度优先算法继承。先将B类中的f2()注释掉,D自动继承C.f2(),如果再将C类中的f2(),D自动继承A.f2()
‘‘‘
类的特殊成员
__doc__:查看类的注释
__init__:构造方法,通过类创建对象时,自动触发执行。
__module__:表示当前操作的对象在那个模块
__class__:表示当前操作的对象的类是什么
__del__:析构方法,解释器进行垃圾回收时自动触发
__call__:对象加()执行call方法
__new__:实例化时new方法执行了__init__
__metaclass__:通过改写metaclass方法达到构建自己需要的类的目的
__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
__str__:如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
__iter__:用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__
示例:
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
class People(object):
‘‘‘
定义一个人类
‘‘‘
def __init__(self,name,age):
‘‘‘
定义属性
:param name: 人类的名字
:param age: 人类的年龄属性
:return:
‘‘‘
self.name = name
self.age = age
def china_man(self):
pass
chinese = People("swht",27)
#__doc__:查看类的注释
print(chinese.__doc__) # 定义一个人类
#__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
print(chinese.__dict__) #{‘age‘: 27, ‘name‘: ‘swht‘}
#__module__:表示当前操作的对象在那个模块
print(chinese.__module__) #__main__
#__class__:表示当前操作的对象的类是什么
print(chinese.__class__) #<class ‘__main__.People‘>
构造类的方法
http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
一句话构建一个类
Foo = type(‘Foo‘,(object,), {‘func‘: func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员
反射方法
hasattr:判断实例中是否存在指定输入的方法
hasattr(server,sys.argv[1]) 返回值是布尔型 True or False
getattr:获取实例中的方法
func = getattr(server,sys.argv[1]) 获取对象方法的内存地址
setattr:将自定义的某个方法设定到特定实例中去使用
setattr(server,‘run‘,test_run) 将特定方法test_run绑定给实例server,并重命名为run方法
server.run() 实例server可以指定调用方法run
delattr:删除实例的成员变量或者类的方法,不能删除实例的方法
#delattr可以删除类的方法、实例的成员变量
# delattr(server,‘start‘) #尝试删除实例的方法是错误的
# delattr(server,"host") #删除实例的变量
# delattr(Webserver,‘start‘)
# server.start() #AttributeError: ‘Webserver‘ object has no attribute ‘start‘
完整示例代码:
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import sys
class Webserver(object):
‘‘‘
定义一个web server启动、关闭类
‘‘‘
def __init__(self,host,port):
‘‘‘
初始化类
:param host: 主机地址
:param port: 主机端口号
:return:
‘‘‘
self.host = host
self.port = port
def start(self):
‘‘‘
服务启动方法
:return:
‘‘‘
print("service is starting...")
def stop(self):
‘‘‘
服务停止方法
:return:
‘‘‘
print("service is stopping ...")
def restart(self):
‘‘‘
服务重启方法
:return:
‘‘‘
self.stop()
self.start()
#定义一个特殊运行的函数,绑定到实例server上去
def test_run():
print("测试运行...")
server = Webserver("localhost",80)
if hasattr(server,sys.argv[1]):
func = getattr(server,sys.argv[1])
func()
#setattr主要作用是将一个单独定义的函数添加到实例中,对于类或者其他实例而言,该函数对其不生效
setattr(server,‘run‘,test_run)
server.run()
#delattr可以删除类的方法、实例的成员变量
# delattr(server,‘start‘) #尝试删除实例的方法是错误的
# delattr(server,"host") #删除实例的变量
# delattr(Webserver,‘start‘)
# server.start() #AttributeError: ‘Webserver‘ object has no attribute ‘start‘
二、socket网络编程
简单实现C/S交互实例:
示例代码:
实现简单的client与server端数据交互(一句话)
socket_server
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
print("南非波波server is Listening....")
conn,addr = sk.accept()
client_data = conn.recv(1024)
print(str(client_data,"utf8"))
conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
conn.close()
socket_client
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.connect(ip_port)
sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))
server_reply = sk.recv(1024)
print(str(server_reply,"utf8"))
sk.close()
改善代码1:
实现多个client与server进行串行交互
socket-server1
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
print("南非波波server is Listening....")
conn,addr = sk.accept()
client_data = conn.recv(1024)
print(str(client_data,"utf8"))
# conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
while True:
try:
client_data = conn.recv(1024)
if not client_data:
break
print("recv:",str(client_data,"utf8"))
conn.send(client_data)
except Exception:
print("客户端断开!")
break
conn.close()
socket-client1
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.connect(ip_port)
# sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))
server_reply = sk.recv(1024)
print(str(server_reply,"utf8"))
while True:
client_data = input(">>:").strip()
if not client_data:
continue
if client_data == ‘q‘:
break
sk.send(bytes(client_data,"utf8"))
print(client_data)
sk.close()
最终代码:
实现简单的ssh命令交互,获取Linux系统的相关信息
socket-server2
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
import subprocess
ip_port = ("127.0.0.1",5000) #定义服务监听的ip地址和端口
ssh = socket.socket()
ssh.bind(ip_port) #进行地址和端口绑定
ssh.listen(5) #设定做多5个并发连接
while True:
print("南非波波Server is waiting...")
conn,addr = ssh.accept()
while True:
client_data = conn.recv(1024) #介绍client发过来的数据,最大接收字节1024
if not client_data: #如果client_data为空,则跳出循环
break
cmd = str(client_data,"utf8") #获取client_data数据并进行类型和编码转换
print("server recv:",cmd)
cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) #以原生shell命令的形式指定client的强求指定,并将结果输出到cmd_result
cmd_result = cmd_call.stdout.read()
if len(cmd_result) == 0: #如果命令没有结果返回,则需要给client返回一个提示,否则控制台会阻塞
cmd_result = b"cmd execution has no output.."
#client不能一次性接收过多的数据包,需要server端先告知client端需要传输的数据多少。然后由client端分开接收
ack_msg = bytes("CMD_RESULT_SIZE|%s" % len(cmd_result),"utf8") #发送数据传输认证标志
conn.send(ack_msg)
client_ack = conn.recv(50)
if client_ack.decode() == ‘CLIENT_READY_TO_RECV‘:
conn.send(cmd_result) #数据传输
conn.close()
socket-client2
#!/usr/local/env python3
‘‘‘
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:[email protected]
‘‘‘
import socket
ip_port = ("127.0.0.1",5000)
ssh_client = socket.socket()
ssh_client.connect(ip_port)
while True:
user_input = input("ssh-client:").strip()
if len(user_input) == 0:
continue
if user_input == ‘q‘:
break
ssh_client.send(bytes(user_input,‘utf8‘))
#ack_msg = b"CMD_RESULT_SIZE|%s" % len(cmd_result)
server_ack_msg = ssh_client.recv(100)
cmd_res_msg = str(server_ack_msg.decode()).split("|")
if cmd_res_msg[0] == "CMD_RESULT_SIZE":
cmd_res_size = int(cmd_res_msg[1])
ssh_client.send(b"CLIENT_READY_TO_RECV")
res = ‘‘
received_size = 0
while received_size < cmd_res_size:
server_data = ssh_client.recv(500)
received_size += len(server_data)
res += str(server_data.decode())
else:
print(res)
print("-----------recv don----------")
ssh_client.close()