Search code examples
pythonloopsbackgroundexecution

Leave some code running while executing more


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?


Solution

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

    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.