信号: 是 Unix 系统中常见的一种进程间通信方式(IPC)
2023/9/5大约 6 分钟
Python 高性能编程简述
Python 打包 rpm or wheel
Linux 下 Python 文件锁的使用
在并发情况下,多个线程/进程池 对同一文件进行读写,如 grpc 线程池收到多个请求同时改写一份文件的情况,
此时需要用到 fcntl 来对文件的读写加锁
在 Linux 中,flock 和 fcntl 都是系统调用,而 lockf 则是库函数, lockf 则是 fcntl 的封装,因此 lockf 和 fcntl 在底层实现是一样的,对文件加锁的效果也是一样的
Python aio 子进程集 及 队列集
####需求:
需要 ping 内网中的所有 ip 地址,是否都可以 pnig 通。
内网网段为:192.168.31.0/24
#!/usr/bin/env python3
# coding: utf-8
import time
import subprocess
import asyncio
import re
async def ping_call(num):
# 当前时间
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
ip = "192.168.31.%s" % num
# 超时时间为1秒,ping 1次
cmd = 'ping -c 1 -w 1 -W 1 %s' % ip
print(cmd)
# 执行命令
proc = await asyncio.create_subprocess_exec('ping', '-c', '1','-w','1','-W','1', ip,
stdout=asyncio.subprocess.PIPE)
# print("proc",proc,type(proc))
result = await proc.stdout.read()
# 通过正则匹配是否有100%关键字
regex = re.findall('100% packet loss', result.decode('utf-8'))
# 长度为0时,表示没有出现100% packet loss
if len(regex) == 0:
return current_time,ip,True
else:
return current_time,ip,False
async def main(): # 调用方
tasks = []
for i in range(1, 256):
# 把所有任务添加到task中
tasks.append(ping_call(i))
# 子生成器
done, pending = await asyncio.wait(tasks)
# done和pending都是一个任务,所以返回结果需要逐个调用result()
for r in done:
# print(r.result())
# 判断布尔值
if r.result()[2]:
# 颜色代码
color_code = 32
else:
color_code = 31
info = "\033[1;{};1m{}\033[0m".format(color_code, r.result())
print(info)
if __name__ == '__main__':
start = time.time()
# 创建一个事件循环对象loop
loop = asyncio.get_event_loop()
try:
# 完成事件循环,直到最后一个任务结束
loop.run_until_complete(main())
finally:
# 结束事件循环
loop.close()
print('所有IO任务总耗时%.5f秒' % float(time.time() - start))