【问题标题】:Is there a way to make a loop that runs in the background while other code continues to run in python?有没有办法让一个循环在后台运行,而其他代码继续在 python 中运行?
【发布时间】:2019-03-13 14:19:02
【问题描述】:

我真的是编程新手,我想知道是否有办法在 Python 中已经运行的代码的后台运行 while 循环?

我在想类似的东西

While True: print("gibberish") print("pass")

输出类似:

'乱码 胡言乱语 经过 胡言乱语......'

(不一定要按这个顺序,只要我得到类似的结果)

【问题讨论】:

标签: python loops while-loop


【解决方案1】:

您可以使用multiprocessingthreading

def background_code():
    while some_condition:
        print("gibberish")

...
thread = threading.Thread(target=background_code, args=(), kwargs={})
thread.start()
print("pass")
...

multiprocessingthreading 都有非常相似的 API,使用哪一个取决于您的用例 - 进程和线程之间的区别不是这个问题的区别。您可能会想要 threading 来处理您当前的工作,但在不同的情况下,您更喜欢其中一种。

【讨论】:

  • 我认为这永远不会打印"pass"
  • 这是真的;但是,它最类似于问题中提出的代码,我认为这很明显
  • 我相信,如果您可以演示如何在另一个线程中运行while 循环,同时在主线程中执行其他操作(例如打印“pass”),那么这对未来的读者将是最有用的。
  • @Selcuk 好主意。相应地进行了编辑。
  • 协程是多处理和线程的替代方案(完全不同意这些选择)——只是提供第三种选择
【解决方案2】:

您可以参考以下代码。

import threading

def func1():
    for i in range(10):
        print("gibberish")

def func2():
    print("pass")

t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)


if __name__ == '__main__':
    t1.start()
    t2.start()

它的作用是同时运行func1func2 方法,以便提供的方法作为彼此的后台任务运行。

【讨论】:

    【解决方案3】:

    这是使用asyncio 的类似内容(需要python 3.7+):

    import asyncio
    
    async def loop():
        while True:
            print("gibberish")
            await asyncio.sleep(0.5)
    
    async def main():
        future = asyncio.ensure_future(loop())
        for i in range(100):
            print("pass")
            await asyncio.sleep(1)
        future.cancel()
    asyncio.get_event_loop().run_until_complete(main())    
    

    这将为每个pass 打印两个gibberish。您可以更改睡眠时间以更改比率。

    这里,mainloopcoroutines,一次只执行一个。 await ... 调用是可能让其他协程执行的点。

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多