异常处理结构
1,try…except…
id=input('chengji:')
try:
id=int(id)
if(0<id<=100):
print('id=',id)
else:
print('输入的id超值了!')
except Exception as e:
print('输入错误')
2,try…except…else…
id=input('chengji:')
try:
id=int(id)
except Exception as e:
print('输入错误')
else:
if(0<id<=100):
print('id=',id)
else:
print('输入的id超值了!')
3,try…except…finally…
id=int(input('chengji:'))
a=int(input('a:'))
try:
b=id/a
print(b)
except Exception as e:
print('输入错误')
finally:
print('结束')
Socket网络编程
connect(address):连接远程计算机
send(bytes[,flags]):发送数据
recv(bufsize[,flags]):接收数据
bind(address):绑定地址
listen(backlog):开始监听,等待客户端连接
accept():响应客户端的一个请求,接受一个连接
服务器端:
#server
import socket
language={'what is your name':'i am tom','how old are you':'25','bye':'bye!'}
HOST="127.0.0.1"
PORT=6666
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
print("Listen at port 6666")
conn,addr=s.accept()
print('Connect by:',addr)
while True:
data=conn.recv(1024)
data=data.decode()
if not data:
break
print('Received message:',data)
conn.sendall(language.get(data,'Noting').encode())
conn.close()
s.close()
客户端代码:
#client
import socket,sys
HOST="127.0.0.1"
PORT=6666
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((HOST,PORT))
except Exception as e:
print("no found server!")
sys.exit()
while True:
c=input("you say:")
s.sendall(c.encode())
data=s.recv(1024)
data=data.decode()
print('Received:',data)
if c.close()=='byebye':
break
s.close()
在cmd’中先开启server.py 然后再用client.py跟他进行沟通。
可执行文件转换(.py 转.exe)
windows系统: pyinstall -F -i snail.ico xxx.py
linux系统: pyinstaller -F xxxx.py