0

I made some code in python to read stdin. When I execute it and input all the data I want I press Ctrl-D, which should send EOF macro but in reality nothing happens. Im on arch-linux using alacritty terminal and zsh shell if thats relevant.

from sys import stdin, stdout


bl = False
res = ""
for line in stdin:
    while line:
        if bl:
            bl = False
            arr = list(map(int, line.strip().split(" ")))
            dicc = {arr.index(x) : x for x in arr}
            for key, value in dicc.items():
                res += "{}:{} ".format(key, value)
        else:
            bl = True
stdout.write(res)
dahko37
  • 131
  • 4
  • 11
  • 3
    Looks like the program has an infinite loop because of `while line`, since `line` does not change within the while loop. It therefore, does not process the next line in stdin via the for loop. – mew Jan 28 '22 at 12:24
  • i think [this](https://stackoverflow.com/a/22257270/4751700) might be of help. – fanta fles Jan 28 '22 at 12:26
  • `ctrl-d` does not "send EOF macro". EOF is not a thing that is "sent". It is a convenient way of talking about the end of file. `ctrl-d` closes the input stream (under certain conditions). – William Pursell Jan 28 '22 at 12:51

1 Answers1

1
from sys import stdin, stdout

res = ''

while True:
    line =  stdin.readline()
    if line:
        res += line #do calculations
    else:
        break

stdout.write(res)

or using the walrus operator from python 3.8:

while True:
    if line := stdin.readline():
        pass # do calculations with line
    else:
        break

This will keep getting values from stdin until ctrl+d is pressed

fanta fles
  • 149
  • 8