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.

4
  • Are you using threads? Commented Sep 3, 2015 at 7:39
  • Possible duplicate: stackoverflow.com/questions/14522923/… Commented Sep 3, 2015 at 7: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 Commented Sep 3, 2015 at 7:50
  • @ρss I think that post answers a different question. Calling raw_input() blocks the other function that i have to run Commented Sep 3, 2015 at 7:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.