返回列表 发帖

[原创代码] python多进程( 永远删除不完的文件 )

# 永远删不完的文件
# BY GIN
# 2020-7-31
#coding=utf-8
import os
from multiprocessing import Process, Queue
import time
import random
PH = r'D:\GIN\py\test\temp'
Q = Queue()
def random_del():
    # 随机删除一个文件
    os.chdir(PH)
    while True:
        time.sleep(0.5)
        file = str(random.Random.randint(random,1,10)) + '.txt'
        if os.path.isfile(file):
            print('随机删除一个文件:{}'.format(file))
            os.remove(file)
        
def supplement_t(Q):
    # 补充缺失文件
    os.chdir(PH)
    while True:
        time.sleep(0.5)
        # print('get {:>2}'.format(Q.qsize()))
        while not Q.empty():
            file = Q.get()
            print('正在补充缺失文件:{}'.format(file))
            with open(file, "w") as f:
                pass
def chec_txt(Q):
    # 检查文件是否缺失。
    # 如果文件缺失,向补充文件函数发送
    # 缺失文件。
    os.chdir(PH)
    while True:
        for i in (range(1,11)):
            time.sleep(0.3)
            file = str(i) + '.txt'
            if not os.path.isfile(file):
                Q.put(file)
                # print('put {:>2}'.format(Q.qsize()))
   
def generate_txt():
    # 创建所有文件。
    os.chdir(PH)
    for i in range(1,11):
        file = str(i) + '.txt'
        print('touch  {:>6}'.format(file))
        with open(file, "w") as f:
            pass
   
if __name__ == '__main__':
    gen_p = Process(target=generate_txt)
    che_p = Process(target=chec_txt, args=(Q,))     # 需要传入相同的对象
    get_p = Process(target=supplement_t, args=(Q,))   # 需要传入相同的对象
    rad_p = Process(target=random_del)
    gen_p.start()
    che_p.start()
    get_p.start()
    rad_p.start()
    # 主进程会等待所有进程结束COPY
result:
touch   1.txt
touch   2.txt
touch   3.txt
touch   4.txt
touch   5.txt
touch   6.txt
touch   7.txt
touch   8.txt
touch   9.txt
touch  10.txt
随机删除一个文件:5.txt
随机删除一个文件:6.txt
随机删除一个文件:1.txt
正在补充缺失文件:5.txt
正在补充缺失文件:6.txt
随机删除一个文件:3.txt
随机删除一个文件:9.txt
随机删除一个文件:4.txt
正在补充缺失文件:1.txt
随机删除一个文件:2.txt
正在补充缺失文件:3.txt
正在补充缺失文件:4.txt
随机删除一个文件:1.txtCOPY

返回列表