Skip to main content
 首页 » 编程设计

Python readline 和 readlines 行为

2024年11月01日7dflying

我正在编写一小段代码,其中涉及使用子进程运行一个脚本来监听一些实时数据

这是我的代码:

def subscriber(): 
    try: 
        sub = subprocess.Popen('start listner',  
                               stdout=subprocess.PIPE,  
                               stderr=subprocess.Pipe) 
    except Exception as e: 
        print(e) 
    return sub 
 
def main(): 
    mysub = spark_subscriber() 
    while True: 
        # 1st version 
        try: 
            out = mysub.stdout.readline() 
            print(out) 
            sleep(1) 
        # 2ndversion 
        #try: 
        #    out = mysub.stdout.readlines()  #notice the s 
        #    print(out) 
        #    sleep(1) 
        # 3rd version 
        #try: 
        #    out = mysub.stdout.readlines()  #notice the s 
        #    print(out) 
        # 4th version 
        #try: 
        #    out = mysub.stdout.readline() 
        #    print(out) 
        except KeyboardInterrupt: 
            exit_program(0) 

第一个行为一次输出一行,休眠1秒,输出下一行,直到打印完所有内容。

因为我想一次打印所有行,所以我只是将 readline() 更改为 readlines() 并获得了第二个版本,我期望输出将是所有行。 - 结果无论我等多久都没有打印出来

编辑:第三版也没有输出

成功的是第 4 个

我现在对 readline()、readlines() 背后的整个机制有点困惑。

有人可以解释为什么 readlines() 不起作用吗?

此外,如果 readlines() 可以在这种情况下工作,有人可以提供一个使用 sleep() 和不使用 sleep() 的工作示例吗?

编辑:我在这里犯了一个大错误,第 4 版应该是有效的,第 3 版不起作用

请您参考如下方法:

readlines 直到没有东西可读时才会返回结果,因此它将继续等待数据,直到数据的生产者退出(程序中的 start_listner ).