import socket, urllib2, threading, time g_host = 'localhost' g_post = 8000 g_timeout_wait = 5 def background_func(): global g_success for i in range(g_timeout_wait - 1): time.sleep(1) print i g_success = True for scheme in ['http', 'https']: print 'testing '+scheme g_success = False background_thread = threading.Thread(target=background_func) background_thread.start() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((g_host, g_post)) s.listen(1) try: f = urllib2.urlopen('%s://%s:%d'%(scheme, g_host, g_post), timeout=g_timeout_wait) print f.read() except Exception as e: print e else: assert 0, 'expected exception' print 'g_success =', g_success