如何在while循环中打印一次,但仍然运行while循环?

时间:2018-02-14 09:12:43

标签: python python-3.x

Reddit Bot问题:我正在尝试查看是否有任何评论的短语“Hello There”。在它,如果它没有“你好那里”。在其中,我希望它打印“没有找到。”一旦等到找到评论。它的作用就像一个魅力,而不是打印“没有找到”。曾经等待另一条评论,它打印出“没有找到”。反复无限的时间直到评论来临。我尝试过多个论坛的多种选择和方法,但我似乎无法理解这一点。这是代码:

def run_bot():
        while True:
            for comment in r.subreddit("test").comments(limit=10):
                comment_text = comment.body.lower()
                isMatch = any(string in comment_text for string in words_match)
                if comment.id not in cache and isMatch and comment.author != r.user.me():
                        comment.reply("[GENERAL KENOBI!](https://youtu.be/rEq1Z0bjdwc)\n\n^(*I am a bot, and this action was performed automatically.*)")
                        print(comment.id)
                        cache.append(comment.id)
                        with open("commentcache.txt", "a") as f:
                            f.write(comment.id + "\n")
                        print("Resetting in:")
                        def countdown(n):
                            while n > 0:
                                print (n, "...")
                                n = n - 1
                                time.sleep(1)
                                if n ==0:
                                    print("Reset Successful!")
                                    time.sleep(1)
                        countdown(5)
                    else:
                        print("Nothing Found.")


    def saved():
        if not os.path.isfile("commentcache.txt"):
            commentcache = []
        else:
            with open("commentcache.txt", "r") as f:
                commentcache = f.read
                commentcache = commentcache().split("\n")
                commentcache = list(filter(None, commentcache))
        return commentcache

    cache = saved()
    print(cache)
    run_bot()

问题始于:

else:
    print("Nothing Found.")

它无限地打印出来。

1 个答案:

答案 0 :(得分:3)

最简单的方法可能是布尔标志:

print_status = True
while True:
    ...
    if isMatch and ...:
        comment.reply("[GENERAL KENOBI!] ...")
        ...
        print_status = True
    elif print_status:
        print("Nothing found")
        print_status = False