Python-day8

1.跨目录调用模块

#!/usr/bin/env python3
# this is CR7 scripts!

import importlib

aa = importlib.import_module('lib.aa')
obj = aa.C('123')
print(obj.NAME)

2.断言

#!/usr/bin/env python3
# this is CR7 scripts!

a = "123"
assert type(a) is str
print("yes")
########################
yes

注:相当于程度比较重的”if”,在用于一些绝对不可以出错的判断场景,比如一些重要应用有很多关联和关系的判断,如果不符合条件那么程序出错,不允许往下走

3.传文件(server)

#!/usr/bin/env python3
# this is CR7 scripts!

import socket,subprocess,os,hashlib

server = socket.socket()
server.bind(('localhost',9999))
server.listen()

while True:
    conn,addr = server.accept()
    print("new connection:",addr)
    while True:
        data = conn.recv(1024).decode()
        if not data:
            print("client is disconnect!")
            break
        cmd,filename = data.split()# 命令接受分组 get filename  写死了格式必须是get xxx
        if cmd == "get":
            if os.path.isfile(filename):
                file_size = os.stat(filename)
                m = hashlib.sha1()
                conn.send(str(file_size.st_size).encode()) # 发送文件大小,单位字节
                conn.recv(1024).decode() # wait client ack infomation...
                with open(filename,'rb') as f:
                    for line in f:
                        m.update(line)
                        conn.send(line) # 传文件本身
                print("file sha1:",m.hexdigest())
                conn.send(m.hexdigest().encode())

server.close()

4.传文件(client)

#!/usr/bin/env python3
# this is CR7 scripts!

import socket,subprocess,os,hashlib
subprocess.getstatusoutput("rm -rf newfile")
client = socket.socket()
client.connect(('localhost',9999))
print(subprocess.getstatusoutput('ls -l')[1])

while True:
    cmd = input("q[quit],:").strip()
    if len(cmd) == 0:
        continue
    elif cmd == "q":
        exit()
    if cmd.startswith('get'):
        client.send(cmd.encode())
        server_responce_size = client.recv(1024).decode() # 收到文件的大小
        client.send(b'ready to recv file...') # 确认收到,发送给服务端信息
        file_total_size = int(server_responce_size)
        received_size = 0
        filename = cmd.split()[1]
        f = open('newfile','wb')
        m = hashlib.sha1()
        while received_size < file_total_size:
            if file_total_size - received_size > 1024:
                size = 1024
            else:
                size = file_total_size - received_size
                print("the last data size:",size)
            data = client.recv(size)
            received_size+=len(data)
            m.update(data)
            f.write(data)
            print("size1:%s    size2:%s"%(received_size,file_total_size))
        else:
            new_file_sha1 = m.hexdigest()
            f.close()
            server_file_sha1 = client.recv(1024).decode()
            print("server:",server_file_sha1)
            print("client:",new_file_sha1)

client.close()

5.多线程传消息(server)

#!/usr/bin/env python3
# this is CR7 scripts!

import socketserver,subprocess,os,hashlib

class MyTCPHandler(socketserver.BaseRequestHandler):

    # 和客户端所有的交互都是在handler里处理的,每过来一个请求都会生成一个实例
    def handle(self):
        while True:
            try:
                print("from %s is connect..." %(HOST,PORT))
                self.data = self.request.recv(1024).strip()
                self.request.send(self.data.upper())
            except ConnectionResetError:
                print("It disconnect...",HOST)
                break

if __name__ == "__main__":
    HOST,PORT = 'localhost',9999
    server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()

6.多线程传消息(client)

#!/usr/bin/env python3
# this is CR7 scripts!

import socket

client = socket.socket()
client.connect(('localhost',9999))

while True:
    msg = input(":".strip())
    if len(msg) == 0:
        continue
    client.send(msg.encode())
    data = client.recv(1024).decode()
    print(data)

client.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,异常处理是非常重要的一部分。当程序运行时如果出现错误,如果没有异常处理,程序就会崩溃。为了避免这种情况,Python提供了异常处理机制。 在Python中,异常处理语句使用 `try` 和 `except` 关键字来实现。`try` 语句块中包含可能会发生异常的代码,如果这段代码出现了异常,则会跳转到 `except` 语句块中执行异常处理代码。 下面是一个简单的例子: ```python try: num = int(input("请输入一个整数:")) print(10/num) except ZeroDivisionError: print("除数不能为0") except ValueError: print("输入的不是整数") ``` 在上面的代码中,我们尝试将用户输入的字符串转换为整数,并将其用作除数计算 10/num。如果用户输入的是 0,则会触发 ZeroDivisionError 异常。如果用户输入的不是整数,则会触发 ValueError 异常。如果发生异常,则会跳转到对应的 except 语句块中执行处理代码。 除了可以指定具体的异常类型,也可以使用 `except Exception` 来捕获所有异常。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) ``` 在上面的代码中,如果发生任何异常,都会跳转到 `except` 语句块中执行处理代码,并将异常信息打印出来。 除了 `try` 和 `except`,还有 `finally` 关键字,它指定的代码块无论是否发生异常都会执行。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) finally: print("程序执行完毕") ``` 在上面的代码中,无论是否发生异常,都会执行 `finally` 中的代码,即输出“程序执行完毕”。 总之,在Python中,异常处理是非常重要的一部分,它可以有效避免程序崩溃,提高程序的健壮性和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值