Hi,
I am testing out some stuff with threads and signals. This is just a prototype
of how I want to incorporate it into my main script.
I figured out how to "catch" signals for SIGUSR1 to output what all the thread
children are "working" on. The problem I have is if in terminalA I run my
script, and in terminalB I do `kill -SIGUSR1 $pid` the output from the script
shows up on terminalA. How can I get the output to show up in terminalB? The
reason I ask is because the script will be running in a loop forever doing
something, so I would like to be able to "query it".
I attached my test script in case that helps, so feel free to critique my code
at the same time, if you like as I just starting learning Python recently.
Thanks,
Andrew
# -*- coding: utf-8 -*-
#!/usr/bin/python
import threading
import Queue
import time
import random
import signal
queue = Queue.Queue()
ctlqueue = Queue.Queue()
class myt(threading.Thread):
def __init__(self, name, run_event, queue, ctlqueue):
threading.Thread.__init__(self, name = name)
self.run_event = run_event
self.queue = queue
self.ctlqueue = ctlqueue
def run(self):
msg = ""
while self.run_event:
st = int(str(random.random() * 5)[0]) + 1
try: msg = self.ctlqueue.get(False)
except Queue.Empty:
pass
if msg == "Shutdown" or self.queue.empty():
print "I see shutdowns"
self.run_event = False
continue
try: u = self.queue.get(True, 5)
except Queue.Empty : pass
self.username = u
time.sleep(st)
try: msg = self.queue.get(False)
except Queue.Empty:
pass
else:
print "Thread %s exiting..." % self.name
self._Thread__stop()
def printusers(signal, stack):
for x in range(threading.activeCount()):
try:
pt = threading.enumerate()[x]
print "Parent asks children for status: Child replies: I am %s and I have %s" % (pt.name, pt.username)
except: pass
def main():
users = ["kkanya", "Beatsascewsad", "manaligmd", "snotrastaeh", "rojskegalb", "autoluwix", "chopekwazi", "batemanfrg", "Gleddyea", "falcucciyk", "previnguiml", "Totenseekd", "Nawezinr", "cinematoriasj",]
for u in users:
queue.put(u)
run_event = threading.Event()
for x in range(2):
tname = "PThread-%s" % x
t = myt(tname, run_event, queue, ctlqueue)
t.daemon = True
t.start()
while threading.activeCount() > 1:
try:
time.sleep(1)
except KeyboardInterrupt as e:
print "\nExiting... Please wait for threads to clean up... "
for x in range(2):
ctlqueue.put("Shutdown")
if __name__ == '__main__':
signal.signal(signal.SIGUSR1, printusers)
try:
print "Starting PThread..."
main()
except KeyboardInterrupt as e:
print "later"
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor