How to stop reading from sys.stdin in Python 3 after reaching a bounded number of lines?

Asked

Viewed 101 times

1

I am trying to receive command from sys.stdin until it reaches a limit n lines, and then finish the execution automatically.

My code is as follows:

import sys

A = [] 
n = int(input("number of nodes: "))
for line in sys.stdin:
    if len(line.split()) == 2:
        A.append(line.split())    
    else:
        print("Requires two integers, ie: 1 2. You typed:", line)
print(A)

This code will ask for an initial value, which will be assigned to n. After that you’ll be adding number pairs to lista A. I wanted you to stop requesting command after the lista have a size equal to n

Example of input would be:

> 2

> 1 2

> 2 3

and the output would be:

[['1','2'], ['2','3']]

But the way it is now it keeps adding to the list in an undetermined way, until the user of the sign they have finished typing. How do I make it automatic to end the execution once the len(A) == n?

  • if I put at the end of the code, after the else but before the print(A), one if len(A) == n: break, works as I would like, but I believe there is a more appropriate way to achieve this

1 answer

2


The way you described in the comments is a valid alternative yes (the difference is that I only need to test the size of the list if any element is inserted - that is, within the if, because there is no reason to test in else, nor outside the if, since in such cases the list has not been modified):

for line in sys.stdin:
    v = line.split()
    if len(v) == 2:
        A.append(v)
        if len(A) == n:
            break
    else:
        print("Requires two integers, ie: 1 2. You typed:", line)

I also changed the code to do the split once.


Although input also reads from stdin, then another alternative is to use a loop infinity and keep reading until the list has the desired size:

while True:
    v = input().split()
    if len(v) == 2:
        A.append(v)    
        if len(A) == n:
            break
    else:
        print("Requires two integers, ie: 1 2. You typed:", v)

If the idea is only to stop when the list has n elements, and a new element is only added under certain conditions (i.e., not all lines will be inserted in the list), so there is no way: you have to keep reading indefinitely, and every time the list is modified, has to test if it already has the desired size to know if the loop must be stopped.

  • 1

    Much more understandable reading your code. Thank you very much for the information, I didn’t know that input() can work like sys.stdin

Browser other questions tagged

You are not signed in. Login or sign up in order to post.