找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 11603|回复: 0

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

[复制链接]
发表于 2020-7-31 15:31:33 | 显示全部楼层 |阅读模式
  1. # 永远删不完的文件
  2. # BY GIN
  3. # 2020-7-31

  4. #coding=utf-8

  5. import os
  6. from multiprocessing import Process, Queue
  7. import time
  8. import random

  9. PH = r'D:\GIN\py\test\temp'
  10. Q = Queue()

  11. def random_del():
  12.     # 随机删除一个文件
  13.     os.chdir(PH)
  14.     while True:
  15.         time.sleep(0.5)
  16.         file = str(random.Random.randint(random,1,10)) + '.txt'
  17.         if os.path.isfile(file):
  18.             print('随机删除一个文件:{}'.format(file))
  19.             os.remove(file)
  20.         

  21. def supplement_t(Q):
  22.     # 补充缺失文件
  23.     os.chdir(PH)
  24.     while True:
  25.         time.sleep(0.5)
  26.         # print('get {:>2}'.format(Q.qsize()))
  27.         while not Q.empty():
  28.             file = Q.get()
  29.             print('正在补充缺失文件:{}'.format(file))
  30.             with open(file, "w") as f:
  31.                 pass


  32. def chec_txt(Q):
  33.     # 检查文件是否缺失。
  34.     # 如果文件缺失,向补充文件函数发送
  35.     # 缺失文件。
  36.     os.chdir(PH)
  37.     while True:
  38.         for i in (range(1,11)):
  39.             time.sleep(0.3)
  40.             file = str(i) + '.txt'
  41.             if not os.path.isfile(file):
  42.                 Q.put(file)
  43.                 # print('put {:>2}'.format(Q.qsize()))
  44.    

  45. def generate_txt():
  46.     # 创建所有文件。
  47.     os.chdir(PH)
  48.     for i in range(1,11):
  49.         file = str(i) + '.txt'
  50.         print('touch  {:>6}'.format(file))
  51.         with open(file, "w") as f:
  52.             pass

  53.    
  54. if __name__ == '__main__':
  55.     gen_p = Process(target=generate_txt)
  56.     che_p = Process(target=chec_txt, args=(Q,))     # 需要传入相同的对象
  57.     get_p = Process(target=supplement_t, args=(Q,))   # 需要传入相同的对象
  58.     rad_p = Process(target=random_del)
  59.     gen_p.start()
  60.     che_p.start()
  61.     get_p.start()
  62.     rad_p.start()
  63.     # 主进程会等待所有进程结束
复制代码
result:
  1. touch   1.txt
  2. touch   2.txt
  3. touch   3.txt
  4. touch   4.txt
  5. touch   5.txt
  6. touch   6.txt
  7. touch   7.txt
  8. touch   8.txt
  9. touch   9.txt
  10. touch  10.txt
  11. 随机删除一个文件:5.txt
  12. 随机删除一个文件:6.txt
  13. 随机删除一个文件:1.txt
  14. 正在补充缺失文件:5.txt
  15. 正在补充缺失文件:6.txt
  16. 随机删除一个文件:3.txt
  17. 随机删除一个文件:9.txt
  18. 随机删除一个文件:4.txt
  19. 正在补充缺失文件:1.txt
  20. 随机删除一个文件:2.txt
  21. 正在补充缺失文件:3.txt
  22. 正在补充缺失文件:4.txt
  23. 随机删除一个文件:1.txt
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-16 22:21 , Processed in 0.016923 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表