0

My python script keeps getting stuck at this point when there is no input: else:

lines = sys.stdin.readlines()

My program has to support no input, so is there a way to figure it if there is no input, so that I just return out of the function. I tried seeing if lines was empty, but the control seems to be lost inside the readlines function (never exits it)

Here is the complete if statement

if len(args) != 0 and args[0] != '-':
           # print('B')
            input_file = args[0]
            try:
                f = open(input_file, 'r')
                lines = sys.stdin.readlines()
                lines = f.close()
            except:
                return
        else:
            #print('c')
            lines = sys.stdin.readlines()

is there a way to get around this?

SaiRam
  • 9
  • 1
  • If you give us a [mcve], including how you're running this, how you're feeding it input, etc., we can probably help. But without that, it's impossible to guess. – abarnert Apr 28 '18 at 21:43
  • Maybe related? https://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python#1454400 – What Apr 28 '18 at 21:45
  • I don't see anything particularly wrong with your code. It's fine for the user to be responsible for providing empty input with something like `python yourscript.py < /dev/null`. `readlines` is simply blocking until it reaches the end of the input "file", which you can simulate by using the correct control character for your terminal (typically Control-D in Unix or Control-Z in Windows, I believe.) – chepner Apr 28 '18 at 22:20

2 Answers2

1

From my comment original goes to u0b34a0f6ae:

import fileinput

for line in fileinput.input():
    pass

How do you read from stdin in Python?

What
  • 304
  • 1
  • 12
  • answers should be self-contained. you should include the link in your answer so people don't have to search through comments to know what you are talking about – avigil Apr 29 '18 at 00:41
0

You can’t use readlines, because that enforces a new line to be read, and depending on your input you can’t predict when that comes.

Instead, uses the select module to check (with a timeout) for new data. If there is some, read it’s with read() and stitch together the data yourself, then split lines & feed them to the rest of your program.

deets
  • 6,285
  • 29
  • 28