day9-异常处理,网络编程(基于UDP),并发编程(多进程)
异常处理
#1 什么是异常:程序运行时发生错误的信号(一旦出错,就会产生一个异常,
# 如果该异常没有被应用程序处理,那么该异常才会抛出来,程序也随之终止)
# print('=====>')
# print('=====>')
# print('=====>')
# aaa
# print('=====>')
# print('=====>')
# print('=====>')
#2 异常分类
#分类一:针对语法上的异常,应该在程序执行前就解决掉
# try:
# print('asdfasdf'
# except Exception:
# pass
#分类二:逻辑异常,try...except
# xxx #NameError
# int('xxxxxxx') #valueError
# l=[]
# l[111111] #IndexError
# d={}
# d['a'] #keyError
# 1/0 #ZeroDivisionError:
# import os
# os.xxxxxxxxxxx #AttributeError:
#处理异常的方式:try 。。。except
# import os
# try:
# print('===>1')
# print('===>2')
# l=[]
# # l[123] #IndexError
# print('===>3')
# d={}
# d['a'] #KeyError
# # aaa
# # os.xxxx
# # except AttributeError as x:
# # # import os
# # # os.xxx
# # pass
# except IndexError as y:
# # print(x)
# # l[0]
# pass
# # except Exception as z:
# # print('Ex',z)
# else:
# print('被检测的代码块没有发生异常时执行else的代码')
#
# print('====>4')
#
# if 异常 == AttributeError:
# x=异常值
# elif 异常 == IndexError:
# x = 异常值
# try:
# print('===>1')
# print('===>2')
# cursor= connect(数据)
# cursor.excute(sql)
# cursor.excute(sql)
# cursor.excute(sql)
# cursor.excute(sql)
#
# print('===>3')
# d = {}
#
# except Exception:
# print('异常发生时执行的代码')
# # cursor.close()
# finally:
# #不管程序是否出错,都会执行finally的代码
# cursor.close()
#自定义异常
class MySQL_CONN_ERROR(BaseException):
def __init__(self,value):
self.value=value
def __str__(self):
return '出错啦老铁:%s' %self.value
# if 2 > 1:
# # raise TypeError('类型错误')
# # raise MyException('类型错误')
# raise MySQL_CONN_ERROR('数据库连接错误')
#断言
# assert 条1成立
# res=[]
# if len(res) > 0:
# res[0]
# res[1]
# else:
# # print('上一部分的代码有问题')
# raise PermissionError('xxxxx')
res=[]
assert len(res) > 0
res[0]
res[1]
基于udp协议的套接字通信
客户端
from socket import *
client=socket(AF_INET,SOCK_DGRAM)
# client.connect(('127.0.0.1',8080)) #udp没有连接
while True:
msg=input('>>: ').strip()
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
msg,server_addr=client.recvfrom(1024)
print(msg)
服务端
from socket import *
server=socket(AF_INET,SOCK_DGRAM)
server.bind(('127.0.0.1',8080))
# server.listen(5) #udp没有
# server.accept() #udp没有
# while True: #udp没有连接,更不可能有连接循环了
# server.accept() #udp没有
while True: #通信循环
msg,client_addr=server.recvfrom(1024)
print(msg)
server.sendto(msg.upper(),client_addr)
Udp不会粘包
客户端
from socket import *
client=socket(AF_INET,SOCK_DGRAM) #数据 报协议
client.sendto('hello'.encode('utf-8'),('127.0.0.1',8080))
client.sendto('world'.encode('utf-8'),('127.0.0.1',8080))
client.sendto('egon'.encode('utf-8'),('127.0.0.1',8080))
服务端
# from socket import *
#
# server=socket(AF_INET,SOCK_DGRAM)
# server.bind(('127.0.0.1',8080))
#
#
#
# msg1,client_addr=server.recvfrom(100000000)
# msg2,client_addr=server.recvfrom(1024)
# msg3,client_addr=server.recvfrom(1024)
#
# print(msg1)
# print(msg2)
# print(msg3)
# import os
# os.fork
开启子进程的两种方式
##开启进程的方式一:
# from multiprocessing import Process
# import time,random
#
# def piao(name):
# print('%s is piaoing' %name)
# time.sleep(random.randint(1,3))
# print('%s is over' % name)
#
#
# if __name__ == '__main__':
# # p=Process(target=piao,kwargs={'name':'alex'})
# p=Process(target=piao,args=('alex',))
# p.start() #仅仅只是向操作系统发送了一个创建子进程p的信号
# print('主')
##开启进程的方式二:
# from multiprocessing import Process
# import time,random
#
# class MyProcess(Process):
# def __init__(self,name):
# super(MyProcess,self).__init__()
# self.name=name
#
# def run(self):
# print('%s is piaoing' %self.name)
# time.sleep(random.randint(1,3))
# print('%s is over' % self.name)
#
#
# if __name__ == '__main__':
# p=MyProcess('P1')
# p.start() #仅仅只是向操作系统发送了一个创建子进程p的信号
# print('主')
Join方法
from multiprocessing import Process
import time,random
def piao(name):
print('%s is piaoing' %name)
time.sleep(random.randint(1,3))
print('%s is over' % name)
if __name__ == '__main__':
p1=Process(target=piao,args=('alex1',))
p2=Process(target=piao,args=('alex2',))
p3=Process(target=piao,args=('alex3',))
#串行执行
# p1.start()
# p1.join()
# p2.start()
# p2.join()
# p3.start()
# p3.join()
#并发执行
# p1.start()
# p2.start()
# p3.start()
# p3.join()
# p1.join()
# p2.join()
#简单写法
p_l=[p1,p2,p3]
for p in p_l:
p.start()
for p in p_l:
p.join()
print('主')
进程之间的内容空间是隔离的
from multiprocessing import Process
import time,random
n=100
def task():
global n
n=0
if __name__ == '__main__':
p=Process(target=task)
p.start()
p.join()
print('主',n)
进程对象的其他方法和属性
from multiprocessing import Process,Pool
import time,random
import os
def task():
print('%s is running parent[%s]' %(os.getpid(),os.getppid()))
if __name__ == '__main__':
p=Process(target=task)
p.start()
print(p.pid) #p这个进程的id
print('主',os.getpid()) #查看aaa.py的id号码
print(os.getppid()) #pycharm的进程id
time.sleep(1000)
#
# from multiprocessing import Process
# import time,random
# import os
#
# def task():
# print('%s is running ' %(os.getpid()))
# time.sleep(10)
#
# if __name__ == '__main__':
# p=Process(target=task,name='xxxxxxxxxxxxx')
# p.start()
# # p.terminate()
# # time.sleep(1)
# # print(p.is_alive())
# print(p.name)
# print('主')
Pool进程池的用法
from multiprocessing import Process,Pool
# Pool进程的用法
# p.apply_async() #p.submit()
# p.apply() #p.submit().result()
pool = Pool()
futrues = []
for i in range(10):
futrue = pool.apply_async(task, i) # 异步的方式提交任务
futrues.append(futrue)
pool.close()
pool.join()
for future in futrues:
print(futrue.get())
进程池
#程序的执行方式:
#一:串行执行
#二:并行执行
#同步调用:提交一个任务后,在原地等着,等到该任务运行完毕,拿到结果以后,再执行下一行代码
#异步调用:提交一个任务后,不用在原地等着,直接执行下一行代码,结果呢?
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor,Executor
import time,os,random
def task(i):
print('%s is running %s' %(os.getpid(),i))
time.sleep(random.randint(1,3))
return i**2
if __name__ == '__main__':
# print(os.cpu_count())
pool=ProcessPoolExecutor()
objs=[]
for i in range(10):
obj=pool.submit(task,i) #异步的方式提交任务
objs.append(obj)
# res=pool.submit(task,i).result() #同步方式提交任务
# print(res)
pool.shutdown(wait=True) #shutdown代表不允许再往进程池里提交任务,wait=True就是join的意思:等待任务都执行完毕
print('主')
for obj in objs:
print(obj.result())
Paramiko模块的使用
#基于用户名密码连接,远程执行命令
# import paramiko
#
# # 创建SSH对象
# ssh = paramiko.SSHClient()
# # 允许连接不在know_hosts文件中的主机
# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# # 连接服务器
# ssh.connect(hostname='123.56.157.199', port=22022, username='root', password='HLH199300.')
#
# # 执行命令
#
# while True:
# cmd=input('>>: ').strip()
# stdin, stdout, stderr = ssh.exec_command(cmd)
# # 获取命令结果
# result = stdout.read()
# print(result.decode('utf-8'))
# # 关闭连接
# ssh.close()
# 123.56.157.199:22022
# root
# HLH199300.
#基于密钥登录
# import paramiko
#
# private_key = paramiko.RSAKey.from_private_key_file(r'C:\\id_rsa')
#
# # 创建SSH对象
# ssh = paramiko.SSHClient()
# # 允许连接不在know_hosts文件中的主机
# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# # 连接服务器
# ssh.connect(hostname='123.56.157.199', port=22022, username='root', pkey=private_key)
#
# # 执行命令
# stdin, stdout, stderr = ssh.exec_command('df')
# # 获取命令结果
# result = stdout.read()
# print(result.decode('utf-8'))
# # 关闭连接
# ssh.close()
#上传下载
import paramiko
transport = paramiko.Transport(('123.56.157.199', 22022))
transport.connect(username='root', password='HLH199300.')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put(r'C:\\id_rsa', '/tmp/test.rsa')
# 将remove_path 下载到本地 local_path
# sftp.get('remove_path', 'local_path')
transport.close()