简体   繁体   中英

Python readline retrieve stdout issues

i have a text and i print each line of it.

i want to stop (for a first time just print "flag!" and in a second time to stop) the text every time the readed line is the flag

but it dont stop

code part:

    import sys
    path = "/somepath/story_line"
    flag = "010001"

    def process(line):
        sys.stdout.write(line)
        sys.stdout.flush()
        time.sleep(2.4)
        line = fileIN.readline()


    with open(path, "r") as content:
        if line != flag:
            for line in content:
                process(line)
                if line == path:
                    print ("flag")

text part

[START]
010001 
welcome traveler,
This story begins in a dark era where Evil took over the weak... Many times ago a dark force came from beyond the sky and over*** the balance of this land.
You are the hope and new strengh of this world, please choose wisely
....


....
Let the story begin










[END]
010001
GAME OVER !!!

im new to python and i tried with subprocess or to append every line into a list an parse the list but nothing do. can someone maybe lighten this up?

Your issue is with the way python passes variables. At the end of your function process(line) , you do

line = fileIN.readline()

However, this only modifies the line within the current scope . Once you exit the function, that change is lost.

The solution is, instead of assigning to line at the end of the function, simply do

return fileIN.readline()

and, below, replace the line

process(line)

with

line = process(line)

I'm not sure I understood the question and the code, it looks like you are attempting to read lines from the file multiple times?

Using the "open" function you can freely iterate over the result, ie read line by line.

Here's how I'd do what you describe

import sys
import time
path = "/path/to/my/file"
flag = "010001"


def process(line):
    if line.strip() == flag:
        process.flagcount += 1
        if process.flagcount == 1:
            sys.stdout.write("flag!\n")
        return process.flagcount
    sys.stdout.write(line)
    time.sleep(2.4)
    return 0

process.flagcount = 0 #initialise a static counting attribute inside process()

#open the file
with open(path, "r") as content:
    #read each line
    for line in content:
        #process it and if it tells us it's counted more than one flag then stop reading.
        if process(line) > 1:
            break

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