bei*_*ei2 6 python linux macos terminal stdout
这是一个 python 问题,也是一个 linux/BSD 问题。
我有一个带有两个线程的 python 脚本,一个从 Web 下载数据,另一个通过串行端口将数据发送到设备。这两个线程都使用 python 的logging模块将大量状态信息打印到标准输出。
我想要的是并排打开两个终端窗口,并让每个终端窗口显示一个线程的输出,而不是将来自两个线程的消息交错在一个窗口中。
除了标准输入、标准输出和标准错误之外,还有其他文件描述符可以写入并连接到其他终端窗口吗?也许这个愿望最好用 GUI 来实现?
我不知道如何开始。
编辑:我尝试将状态消息写入两个不同的文件,而不是将它们打印到标准输出,然后tail -f在其他终端窗口中监视这两个文件,但这不适用于实时监视,因为文件直到你打电话close()给他们。
首先,自定义日志格式化程序以包含线程 id字段(https://docs.python.org/2/library/logging.html#logrecord-attributes)。然后将日志记录目标更改为某个文件而不是标准输出。
# A simple logger as print
import logging
import logging.handlers
hdr = logging.FileHandler(filename='output.log')
hdr.setFormatter(logging.Formatter('[%(asctime)s] thread=%(thread)s:%(levelname)s: %(message)s'))
logger = logging.getLogger(__name__)
logger.addHandler(hdr)
logger.setLevel(logging.DEBUG)
import threading
def func():
logger.info('test message')
for i in range(2):
threading.Thread(target=func).start()
Run Code Online (Sandbox Code Playgroud)
您的日志输出现在可能如下所示:
% tail -f output.log
[2015-09-28 15:14:49,782] thread=4344852480:INFO: test message
[2015-09-28 15:14:49,782] thread=4349059072:INFO: test message
Run Code Online (Sandbox Code Playgroud)
运行脚本,打开两个单独的终端,然后使用该命令tail -f output.log | grep thread=<THREAD_ID>按线程 ID 监视日志。
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |