django channel 如何实时 tail 某个文件

2018-09-19 17:23:53 +08:00
 yongzhong

我写了一个 consumer 在前端的 websocket 请求过来后就开始对某个日志实时输出

class LogConsumer(WebsocketConsumer):

    def disconnect(self, close_code):
        print('关闭')
        if getattr(self, 'f', None):
            self.f.terminate()

    def receive(self, text_data):
        print(text_data)
        log_file = 'xxxxx.log'

        if not os.path.exists(log_file):
            self.send(json.dumps({
                'key': 0,
                'data': '日志不存在'
            }))
            return
        self.f = subprocess.Popen(
            'tail -f -n 40 {}'.format(log_file),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,
        )
        p = select.poll()
        p.register(self.f.stdout)
        line_number = 1
        while True:
            if p.poll(1):
                msg = self.f.stdout.readline().decode("utf-8")
                if not msg:
                    raise Exception
                for m in str(msg).splitlines():
                    self.send(json.dumps({'key': line_number,
                                            'data': m + '\n'
                                            }))
                    line_number += 1

这样有一个问题就是会导致这个 consumer 处于 blocking 状态,导致 disconnect 无法被触发,进而无法释放进程

有什么好的解决办法吗?

2099 次点击
所在节点    Python
5 条回复
phithon
2018-09-19 21:35:37 +08:00
两个线程或进程,一个 websocket,一个 subprocess。中间用 channels layer 连接。
zengcul
2019-01-22 21:14:18 +08:00
同遇到这个问题 请问楼主如何解决
zengcul
2019-02-14 14:19:17 +08:00
@zengcul 想了了个歪招,后端不能使用 while True 一直占用进程,前端 ws 握手连接成功后,使用定时器向后端 send message,后端每收到一次 message 去 stdout.readline 下
yongzhong
2019-02-14 15:25:51 +08:00
@zengcul #3 我用了个比较丑陋的方法,见 append,没用到 channel
37Y37
2020-01-07 18:27:20 +08:00
可以看看这个,正好实现了一样的功能
https://ops-coffee.cn/s/r5SpyTjRl0jJeAuYE4Q_-Q

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/490900

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX