2

I need to print a message every x seconds, at the same time, I need to listen to the user's input. If 'q' is pressed, it should kill the program.

For example

some message
.
. # after specified interval
. 
some message
q # program should end

The current problem I face now is that raw_input is blocking which stops the my function from repeating the message. How do I get input reading and my function to run in parallel?

EDIT: It turns out that raw_input was not blocking. I misunderstood how multi-threading works. I'll leave this here in case any one stumbles upon it.

Gerald
  • 567
  • 1
  • 10
  • 17
  • Are you using threads? – CIsForCookies Sep 03 '15 at 07:39
  • Possible duplicate: https://stackoverflow.com/questions/14522923/how-to-break-a-python-while-loop-from-a-function-within-the-loop – ρss Sep 03 '15 at 07:42
  • @CIsForCoocckies yes I am using threads. But there is no requirement to be a thread. as long as the intended effect can be achieved – Gerald Sep 03 '15 at 07:50
  • @ρss I think that post answers a different question. Calling `raw_input()` blocks the other function that i have to run – Gerald Sep 03 '15 at 07:56

2 Answers2

4

You can use threading to print your message in a different thread.

import threading

t = threading.Timer(30,func,args=[])
t.start()

Where 30 is how often to call func.

func is the function to call in a different thread.

And args is an array of the arguments to call the function with

If you want just one call to a different function you can do

t = threading. Thread(target=func, args=[]) 
t.start() 

This will make func run in parallel

DorElias
  • 2,243
  • 15
  • 18
  • Timer works in a slightly unexpected way. The interval specified is not actually interval but rather delay. It wait for 30 secs before calling the func and period, it will not fire again after 30 sec – Gerald Sep 03 '15 at 18:18
2
import threading
import time as t

value = 0

def takeInput():
    """This function will be executed via thread"""
    global value
    while True:
        value = raw_input("Enter value: ")
        if value == 'q':
            exit()  # kills thread
        print value
    return

if __name__ == '__main__':
    x = int(raw_input('time interval: '))
    thread = threading.Thread(target=takeInput)
    thread.start()
    while True:
        if value == 'q':
            exit()  # kills program
        print 'some message'
        t.sleep(x)
Anvesh Arrabochu
  • 165
  • 1
  • 2
  • 11