stdout get previous more than 1 lines from shell

Viewed 68

I am using a subproccess like this to get output from shell.

 with subprocess.Popen(['bash', '-c', '. /root/myFile.sh;',
                       ' func ' ], stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       bufsize=1,universal_newlines=True) as proc_launch:

        for line in proc_launch.stdout:
            print(line, end='')

It's giving line by line output, while I want to get output in a way like last 3 or 4 lines plus current line. Is there any method to do that in a clean way?

2 Answers

If I understand problem: you have to remember previous lines in some list and use slice [-3:] to display last 3 lines from this list.

previous_lines = list()

for line in proc_launch.stdout:
    #remeber previous lines
    previous_lines.append(line)

    # get last 3 lines with current
    text = ''.join(previous_lines[-3:])

    # display it
    print(text, end='')

BTW: you can use variable to easily change how many lines to display [-count:]

# before `for`-loop

count = 3

# inside `for`-loop

text = ''.join(previous_lines[-count:])

Probably the cleanest method would be to use a collections.deque.

The maxlen parameter is specifically designed for your use-case:

Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. ... They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

A deque will be much more efficient than a perpetually increasing list, or even a fixed size list.

So:

from collections import deque

last_lines = deque(4)
with subprocess.Popen(...) as proc_launch:
    for line in proc_launch.stdout:
        last_lines.append(line)
        print(''.join(last_lines), end='')
Related