簡體   English   中英

從 pipe 讀取 — 有狀態或無狀態

[英]reading from a pipe — stateful or stateless

我需要編寫一個 python 腳本來處理另一個程序的 output 。 即我必須這樣做:

./other_program | ./my_scripts.py 

我的問題是這個my_script.py是否是state-less 例如,我是否可以記住我處理的 output 的最后一行來自./other_program ,或者腳本只會處理當前行,完全不知道最后一行?

管道不知道“線”。 字節 go 在一端輸入,相同順序的相同字節在另一端輸出。 兩者之間有一點(可配置的)緩沖區,但是在使用它們時,請考慮它們是無緩沖的。

面向行的 I/O 發生在更高級別,例如,在 pipe 文件描述符上創建 C stdio FILE object 時,或使用類似的文件描述符,或使用readline庫。 或者 - 就像你的情況一樣 - Python stdio printwritelinesreadline

編輯1:

這里有兩個簡單的 python 程序


writer.py

#!/usr/bin/env python3
if '__main__' == __name__:
    import time
    i = 0;
    while True:
        print(f'This is writer.py, writing a line number {i} to stdout', flush=True)
        i += 1
        time.sleep(0.25)

reader.py

#!/usr/bin/env python3
if '__main__' == __name__:
    i = 0
    while True:
        l = input()
        print( f'This is reader.py, a line number {i} was read from stdin with the following content\n> {l}\n' )
        i += 1

使用./writer.py |./reader.py測試它們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM