Python readline 检索标准输出问题

Python readline retrieve stdout issues

我有一个文本,我打印了它的每一行。

我想停止(第一次只打印 "flag!",第二次停止)每次读取的行都是标志的文本

但它不会停止

代码部分:

    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")

正文部分

[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 !!!

我是 python 的新手,我尝试使用 subprocess 或将每一行附加到列表中并解析列表,但没有做任何事情。 有人可以减轻这个吗?

您的问题与 python 传递变量的方式有关。在你的函数 process(line) 结束时,你做

line = fileIN.readline()

但是,这个只修改了当前作用域内的line。退出该功能后,该更改将丢失。

解决方案是,不要在函数末尾赋值给 line,只需做

return fileIN.readline()

并在下面替换行

process(line)

line = process(line)

我不确定我是否理解问题和代码,您似乎在尝试多次读取文件中的行?

使用 "open" 函数您可以自由迭代结果,即逐行读取。

这是我按照您描述的方式做的

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