在执行更多代码的同时保持一些代码运行 [英] Leave some code running while executing more

查看:100
本文介绍了在执行更多代码的同时保持一些代码运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中启动一个循环,在启动循环后,我希望在循环之后继续执行代码,同时循环保持循环(在背景"中).

I am starting a loop in python, and after I start the loop I want the execution of code after the loop to carry on, while the loop keeps looping (in the 'background').

x=True

while x:
  #do some output
  sleep(1)

#ask for input or something
if input()=='something':
  x=False

因此在该示例中,#do some output将在请求输入时不断发生.

So in that example, #do some output will keep happening while input is asked for.

这在python中可能吗?是否有任何变通办法可以实现这一目标?

Is this possible in python? Are there any work-arounds that could achieve this?

推荐答案

按照OP的要求,我发布了答案. :)有多个库可以实现您要尝试执行的操作.最知名的包括:

Following OP's wish I'm posting the answer. :) There are multiple libraries for achieving what you are trying to do. Most known include:

  • threading module
  • multiprocessing module

它们之间有细微的差别,但是我想您现在不必担心这一点.我鼓励您尽管阅读更多有关多线程处理和线程的一般信息.另外,绿色"线程是一个有趣的替代方法.

There are subtle differences between them, but I guess that you shouldn't worry about it at the moment. I encourage you though to read more about mutli-processing and threading in general. Also "green" threads is an interesting alternative.

这篇关于在执行更多代码的同时保持一些代码运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆