我在这个Python领域是个新手,我想从另一个程序在运行时编写的文件中读取数据。所以我的剧本一被另一个节目写下来就应该读一行。
以下是我的资料:
#!/usr/bin/env python
import datetime
import os
import select
import sys
FILENAME = "/home/sjngm/coding/source/python/text.log"
with open(FILENAME, "r", encoding = "utf-8", errors = "ignore") as log:
print("blocks: " + str(os.get_blocking(log.fileno())) + " / fd: " + str(log.fileno()) + " / " + str(log))
while True:
os.pread(log.fileno(), 1, 0)
sel = select.select([log], [], [], 60000.0) #[0]
line = log.readline().replace("\n", "")
if line:
print(line)
else:
print("-" + str(datetime.datetime.now()), end = "\r")
# do something interesting with line...
text.log(目前它只是一个普通的文本文件,没有其他进程访问它):
line 1
line 2
line 3
如果有一个
\n
是否在最后一行的末尾
输出:
[sjngm@runlikehell ~]$ python ~/coding/source/python/test.py
blocks: True / fd: 3 / <_io.textiowrapper name="/home/sjngm/coding/source/python/text.log" mode="r" encoding="utf-8">
line 1
line 2
line 3
^CTraceback (most recent call last):
File "/home/sjngm/coding/source/python/test.py", line 16, in
line = log.readline().replace("\n", "")
File "/usr/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
KeyboardInterrupt
[sjngm@runlikehell ~]$ uname -a
Linux runlikehell 4.14.53-1-MANJARO #1 SMP PREEMPT Tue Jul 3 17:59:17 UTC 2018 x86_64 GNU/Linux
[sjngm@runlikehell ~]$
所以说阻塞被启用了。打印完这三行后,脚本继续运行,不停地打印当前时间。
它应该停在
pread()
,
select()
或
readline()
. 或者事实上,在我不知道的任何其他命令下。
我该怎么做?
请注意,我不想将文件通过管道传输到脚本,因为稍后我想使用curses及其
getch()
在这种情况下是行不通的。