代码之家  ›  专栏  ›  技术社区  ›  sjngm quinti

如何用python阻止读取文件

  •  0
  • sjngm quinti  · 技术社区  · 7 年前

    我在这个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() 在这种情况下是行不通的。

    1 回复  |  直到 7 年前
        1
  •  0
  •   sjngm quinti    7 年前

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

    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()
    

    换句话说,我正在打开管道 在里面 脚本而不是管道 剧本。缓冲似乎是在 tail 与…有关 Popen 的参数 bufsize . encoding universal_newlines 允许 readline() 读取字符串而不是字节数组(请参见 Python's documentation 更多信息)。

    系统 stdin 现在仍然可用,并且 curses 可以很好地处理键盘/鼠标事件。

    推荐文章