Leave some code running while executing more

ぃ、小莉子 提交于 2019-12-12 00:32:35

问题


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

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

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


回答1:


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.




回答2:


From what I understand, what you want is to create a Thread that keeps executing some tasks in the background.

http://docs.python.org/library/threading.html

Threading is a moderately complex issue, so giving you a recipe here wouldn't amount to much. I suggest you take a look at the documentation to understand what's involved.

Update your question or create a new one if you then have troubles with something specific to the implementation.

EDIT: I agree with the comment made by Tim Hoffman, the correct solution depends on what you're trying to achieve. From my understanding, threading should work for you, but if you give us more details, it might be easier to give a more precise answer.



来源:https://stackoverflow.com/questions/11756802/leave-some-code-running-while-executing-more

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!