Python readline 和 readlines 行为

标签 python io subprocess

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

这是我的代码:

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() 并得到了第二个版本,我期望的输出将是所有行。 - 结果无论我等多久都没有打印任何内容

编辑:第三个版本也没有输出

有效的是第四个

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

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

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

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

最佳答案

readlines 在没有任何内容可供读取之前不会返回结果,因此它将继续等待数据,直到数据的生产者退出(程序中的 start_listner )。

关于Python readline 和 readlines 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23685982/

相关文章:

python - 空饼图

python - 将子进程的标准输出重定向到 2 个或更多子进程的标准输入

python - 子进程.CalledProcessError : what *is* the error?

java - RMI传输文件

python - “输入”在 3.5 IDLE 中有效,但在终端中无效

Python监控子进程的stderr和stdout

python - Pandas 将时间序列数据重新采样为 15 分钟和 45 分钟 - 使用多索引或列

python - 如何从 asp.net Azure 应用服务调用 python 脚本?

python - gitpython中clone_from中的非值参数

c++ - 基本数组格式的二叉搜索树