繁体   English   中英

如何使用Python阻止读取文件

[英]How to Block-Read a File with Python

我是这个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 <module>
    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()在这种情况下不起作用。

似乎这种情况并不常见。 我现在正在做的是:

import subprocess

with subprocess.Popen([ "tail", "-10000f", FILENAME ], encoding = "utf-8", errors = "ignore", universal_newlines = True, bufsize = 1, stdout = subprocess.PIPE).stdout as log:
    line = log.readline()

换句话说,我剧本孔口的管子,而不是pipeing 东西的脚本。 缓冲似乎是在与Popen的参数bufsize tail完成的。 encodinguniversal_newlines允许readline()读取字符串而不是字节数组(有关此信息,请参阅Python文档 )。

System的stdin现在仍然可用,并且curses与键盘/鼠标事件配合得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM