Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Do something then sleep, repeat

I'm using a little app for Python called Pythonista which allows me to change text colour on things every few seconds. Here's an example of how I've been trying to go about doing this in an infinite loop;

while True:
    v['example'].text_color = 'red'
    time.sleep(0.5)
    v['example'].text_color = 'blue'
    time.sleep(0.5)
    # and so on..

The issue here is that this freezes my program because Python keeps sleeping over and over, and I never see any change. Is there a way of being able to see the change (the text changing to red/blue/etc) and then doing the next task x amount of time later, and so on?

like image 891
Lachlan Avatar asked Jul 19 '16 07:07

Lachlan


People also ask

How do you sleep while looping in Python?

sleep() is a method that causes Python to pause for a specified number of seconds. Give sleep() the number of seconds that you want it to pause for in its parenthesis, and it will stall the execution of your program. It's fairly common to see sleep() in loops, especially infinite ones.

How do I make Python sleep 2 seconds?

If you've got a Python program and you want to make it wait, you can use a simple function like this one: time. sleep(x) where x is the number of seconds that you want your program to wait.

Is there a wait function in Python?

The wait() function is defined in two separate modules in Python. The threading module's event class contains a wait() method that suspends the current thread's execution while the event is executed or completed.

What does sleep () do in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.


1 Answers

You will need to create a new thread that runs your code. Put your code in its own method some_function() and then start a new thread like this:

thread = Thread(target = some_function)
thread.start()
like image 105
AlexanderNajafi Avatar answered Oct 19 '22 05:10

AlexanderNajafi