鱼C论坛

 找回密码
 立即注册
查看: 2177|回复: 3

[技术交流] 实时检查文本追加的新内容

[复制链接]
发表于 2020-6-2 16:33:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #!/usr/bin/env python3
  2. #coding:utf-8

  3. import threading
  4. import os
  5. from time import sleep

  6. def writefile(file):
  7.     os.system('for /l %i in (1,1,20) do (@timeout /t 1 >nul&echo 正在写入新的一行:%i >> '+ file + ')') #调用批处理写入文件
  8.    
  9. def readfile(filestream):
  10.     filestream.seek(0,2) #移到文件末尾
  11.     while True:
  12.         line = filestream.readline()
  13.         if line:
  14.             yield line
  15.         else:
  16.             sleep(0.5)
  17.    
  18. def threa(f):
  19.     count = 1
  20.     with open(f) as fs:
  21.         for i in readfile(fs):
  22.             print('\n文件写入了新的内容:',i)
  23.             if count == 20:
  24.                 os.system('taskkill /f /pid ' + str(os.getpid()))
  25.             count += 1

  26. f = r'd:\test.txt'
  27. if not os.path.exists(f): #文件不存在,创建空文件
  28.     with open(f, 'w') as f:
  29.         pass

  30. th = []
  31. th.append(threading.Thread(target = writefile, args = (f,)))
  32. th.append(threading.Thread(target = threa, args = (f,)))

  33. for i in range(len(th)):
  34.     th[i].start()
  35.    
  36. for i in range(len(th)):
  37.     th[i].join()
复制代码

  1. 文件写入了新的内容: 正在写入新的一行:18


  2. D:\GIN\py>()

  3. 文件写入了新的内容: 正在写入新的一行:19


  4. 文件写入了新的内容: 正在写入新的一行:20

  5. 成功: 已终止 PID 为 7924 的进程。

  6. 请按任意键继续. . .
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-2 18:45:29 | 显示全部楼层
本帖最后由 赚小钱 于 2020-6-2 18:48 编辑

很有想法,不过,是 fsnotify 不好用吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-6-2 21:18:15 | 显示全部楼层
赚小钱 发表于 2020-6-2 18:45
很有想法,不过,是 fsnotify 不好用吗

不会。感觉要学的东西好多啊!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-2 21:45:47 From FishC Mobile | 显示全部楼层
每次看楼主的代码都觉得有点新奇
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 00:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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