0

I am trying to do multi threading to check the network connection. My code is:

exitFlag = 0
lst_doxygen=[]
lst_sphinx=[]
class myThread (threading.Thread):
    def __init__(self, counter):
        threading.Thread.__init__(self)
    self.counter=counter
    def run(self):
    print "Starting thread"
        link_urls(self.counter)

def link_urls(delay):
    global lst_doxygen
    global lst_sphinx
    global exitFlag

    while exitFlag==0:
        try:
            if network_connection() is True:
                try:
                    links = lxml.html.parse(gr.prefs().get_string('grc', 'doxygen_base_uri', '').split(',')[1]+"annotated.html").xpath("//a/@href")
                    for url in links: 
                        lst_doxygen.append(url)
                    links = lxml.html.parse(gr.prefs().get_string('grc', 'sphinx_base_uri', '').split(',')[1]+"genindex.html").xpath("//a/@href")
                    for url in links: 
                        lst_sphinx.append(url)
                    exitFlag=1
                except IOError, AttributeError:
                    pass
            time.sleep(delay)
            print "my"
        except KeyboardInterrupt:
            exitFlag=1


def network_connection():

    network=False
    try:
        response = urllib2.urlopen("http://google.com", None, 2.5)
        network=True

    except urllib2.URLError, e:
           pass
    return network

I have set a flag to stop the thread inside while loop. I also want to exit the thread by pressing Ctrl-C. So I have used try-except but thread is still working and does not exit. If I try to use

if KeyboardInterrupt:
    exitFlag=1

instead of try-except, thread just works for first time execution of while loop and then exist. p.s. I have created the instance of myThread class in another module.

2
  • can you show the code where you create the instances of the threads? By the way, "if KeyboardInterrupt" will always return True, this is not the way you catch an exception. To catch the CTRL-C, it is better to use signal, see docs.python.org/2/library/signal.html Commented Jul 27, 2013 at 1:59
  • That module is very long one that runs a software application. I just use these two lines to create instances:thread1 = myThread(2) thread1.start() Commented Jul 27, 2013 at 2:03

3 Answers 3

1

Finally, I got the answer of my question. I need to flag my thread as Daemon. So when I will create the instance if myThread class, I will add one more line:

thread1.myThread(2)
thread1.setDaemon(True)
thread1.start()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing! I'm happy to report this still works like a charm 8 years later
0

You only get signals or KeyboardInterrupt on the main thread. There are various ways to handle it, but perhaps you could make exitFlag a global and move the exception handler to your main thread.

Comments

0

Here is how I catch a CTRL-C in general.

import time
import signal
import sys

stop = False

def run():
    while not stop:
        print 'I am alive'
        time.sleep(3)

def signal_handler(signal, frame):
    global stop
    print 'You pressed Ctrl+C!'
    stop = True

t1 = threading.Thread(target=run)
t1.start()

signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C'
signal.pause()

output:

python threads.py
Press Ctrl+C
I am alive
I am alive
^CYou pressed Ctrl+C!

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.