0

I need to print the value of a variable every second or couple of seconds, while "at the same time" this variable is being modified. So I would be modifying this variable in my main function and I want something to print its value every second. Something like:

'''This is my main program'''

for i in range(very large number):

'''do something which modifies the value of 'var' '''

And somewhere else in the code:

'''Every second'''

print var

I took a look at this but I'm not sure if it's what I'm looking for, or how I should use it.

What I need is reaaaly simple, there are no other threads, and I don't care about syncing anything, or when in the main function the value is printed.

Community
  • 1
  • 1
Chrischpo
  • 145
  • 1
  • 11
  • If you have no threads that paralelize the work (Modify var and print it's value) why you need to wait 1 second to print? – Mr. E Nov 23 '15 at 13:45
  • You can't do such things without using multithreading or multiprocessing or asynchronous (like gevent or tornado) approaches. – Sergeev Andrew Nov 23 '15 at 13:46

2 Answers2

3

You can use threading to print var each second.

try this example:

import threading

var = 5


def printit():
  global var
  threading.Timer(5.0, printit).start()
  print "Hello, World!", var

printit()

import time

for i in range(1000000):
    time.sleep(2)
    var = i
Kenly
  • 24,317
  • 7
  • 44
  • 60
  • Both answers work, but this is the easiest. I just had to add a flag "done" so that when the other part finishes, this function stops. Otherwise it keeps running forever! – Chrischpo Nov 23 '15 at 14:23
2

Basically, the question/answer you pointed to is what you need:

import threading import time

interesting = 0

class MonitorThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global interesting
        while(1):
            print interesting
            time.sleep(1)

MonitorThread().start()

for interesting in range(2000000):
    time.sleep(1)
GreenAsJade
  • 14,459
  • 11
  • 63
  • 98