Python史上最全知识重点(超详细版)进阶篇

Python 进阶

  • 进程间通信:
    • Manager(内置了好多数据结构,可以实现多进程间内存共享)
from multiprocessing import Manager,Process
def add_data(p_dict, key, value):
    p_dict[key] = value

if __name__ == "__main__":
    progress_dict = Manager().dict()
    from queue import PriorityQueue

    first_progress = Process(target=add_data, args=(progress_dict, "bobby1", 22))
    second_progress = Process(target=add_data, args=(progress_dict, "bobby2", 23))

    first_progress.start()
    second_progress.start()
    first_progress.join()
    second_progress.join()

    print(progress_dict)
  • Pipe(适用于两个进程)
from multiprocessing import Pipe,Process
#pipe的性能高于queue
def producer(pipe):
    pipe.send("bobby")

def consumer(pipe):
    print(pipe.recv())

if __name__ == "__main__":
    recevie_pipe, send_pipe = Pipe()
    #pipe只能适用于两个进程
    my_producer= Process(target=producer, args=(send_pipe, ))
    my_consumer = Process(target=consumer, args=(recevie_pipe,))

    my_producer.start()
    my_consumer.start()
    my_producer.join()
    my_consumer.join()
  • Queue(不能用于进程池,进程池间通信需要使用Manager().Queue())
from multiprocessing import Queue,Process
def producer(queue):
    queue.put("a")
    time.sleep(2)

def consumer(queue):
    time.sleep(2)
    data = queue.get()
    print(data)

if __name__ == "__main__":
    queue = Queue(10)
    my_producer = Process(target=producer, args=(queue,))
    my_consumer = Process(target=consumer, args=(queue,))
    my_producer.start()
    my_consumer.start()
    my_producer.join()
    my_consumer.join()
  • 进程池
def producer(queue):
    queue.put("a")
    time.sleep(2)

def consumer(queue):
    time.sleep(2)
    data = queue.get()
    print(data)

if __name__ == "__main__":
    queue = Manager().Queue(10)
    pool = Pool(2)

    pool.apply_async(producer, args=(queue,))
    pool.apply_async(consumer, args=(queue,))

    pool.close()
    pool.join()
  • sys 模块几个常用方法

    • argv 命令行参数list,第一个是程序本身的路径
    • path 返回模块的搜索路径
    • modules.keys() 返回已经导入的所有模块的列表
    • exit(0) 退出程序
  • a in s or b in s or c in s简写

    • 采用any方式:all() 对于任何可迭代对象为空都会返回 True
# 方法一
True in [i in s for i in [a,b,c]]
# 方法二
any(i in s for i in [a,b,c])
# 方法三
list(filter(lambda x:x in s,[a,b,c]))
  • set集合运用

    • {1,2}.issubset({1,2,3})#判断是否是其子集
    • {1,2,3}.issuperset({1,2})
    • {}.isdisjoint({})#判断两个set交集是否为空,是空集则为T

你可能感兴趣的:(Python零基础入门,python,网络,java)