简体   繁体   中英

function stuck in readlines

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?

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.

From my comment original goes to u0b34a0f6ae:

import fileinput

for line in fileinput.input():
    pass

How do you read from stdin in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM