Popen 多行读取

Popen multi line read

我是新手 python 我一直在使用 popen 来执行命令,但我期待多行响应,我需要分别使用每一行。

我有以下从教程中获得的代码。

pipe = os.popen('dir')
        for line in pipe:
            print '--------------space---------------------'
            print pipe.readLine()

但我知道我不断收到以下错误:

AttributeError: 'file' 对象没有属性 'readLine'

有没有人对我有任何建议,或者关于如何改进它的想法。

感谢您的帮助

修正语法 readline 使用小写字母 l。

但是我想知道你想要完成什么。如果您只想打印每一行,那么您应该更改 print pipe.readline() --> print line.

import os
pipe = os.popen('dir')
for line in pipe:
    print '--------------space---------------------'
    print line

您的 for 循环已经在逐行读取 popen 的输出。事实上,如果您尝试在迭代中调用 pipe.readline(),这是非法的,您的代码将引发异常。

为了说明异常,您可以尝试 运行 这个:

import os
pipe = os.popen('dir')
for line in pipe:
    print '--------------space---------------------'
    print pipe.readline()

使用subprocess模块​​,它有很多有用的功能可以与其他进程交互。 check_output 或致电即可完成工作

import subprocess
output = subprocess.check_output('dir', universal_newlines=True)