本文整理汇总了Python中thread.interrupt_main函数的典型用法代码示例。如果您正苦于以下问题:Python interrupt_main函数的具体用法?Python interrupt_main怎么用?Python interrupt_main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了interrupt_main函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self):
""" Run the poll loop. This method never returns.
"""
from _subprocess import WAIT_OBJECT_0, INFINITE
# Build the list of handle to listen on.
handles = []
if self.interrupt_handle:
handles.append(self.interrupt_handle)
if self.parent_handle:
handles.append(self.parent_handle)
# Listen forever.
while True:
result = ctypes.windll.kernel32.WaitForMultipleObjects(
len(handles), # nCount
(ctypes.c_int * len(handles))(*handles), # lpHandles
False, # bWaitAll
INFINITE) # dwMilliseconds
if WAIT_OBJECT_0 <= result < len(handles):
handle = handles[result - WAIT_OBJECT_0]
if handle == self.interrupt_handle:
raw_print('Interrupted by parent poller!')
interrupt_main()
elif handle == self.parent_handle:
raw_print('Killed by parent poller!')
os._exit(1)
示例2: Pinging_Thread
def Pinging_Thread(self):
print "[+] Starting Ping thread"
#self.ptc=threading.Condition()
wait=True
p=0.1
while 1: #loop forever
if wait and (self.ping_delay > 0):
self.ptc.acquire()
self.ptc.wait(self.ping_delay+self.penalty) #send ping to server interval + penalty
self.ptc.release()
self.mutex_http_req.acquire() #Ensure that the other thread is not making a request at this time
try:
resp_data=self.http.HTTPreq(self.url,"") #Read response
if self.verbose: self.http.v_print(pings_n=1)
if self.penalty<60: self.penalty+=p #Don't wait more than a minute
if resp_data: #If response had data write them to socket
self.penalty=0
if self.verbose: self.http.v_print(received_d_pt=len(resp_data))
self.TunnaSocket.send(resp_data) #write to socket
resp_data="" #clear data
wait=False #If data received don't wait
else:
wait=True
except:
self.TunnaSocket.close()
thread.exit()
finally:
self.mutex_http_req.release()
print "[-] Pinging Thread Exited"
#Unrecoverable
thread.interrupt_main() #Interupt main thread -> exits
示例3: _test_main_thread
def _test_main_thread():
cherrypy.server.wait()
cherrypy._cputil._cpInitDefaultFilters()
try:
webtest.main()
finally:
thread.interrupt_main()
示例4: stop_code
def stop_code(self, quiet=False):
"""
Attempt to stop the running code by raising a keyboard interrupt in
the main thread.
If the optional quiet flag is True the engine will stop the code but not
print an error message or prompt again.
"""
if self.busy is False:
return
#set the stop flag to catch the error correctly
if quiet:
self._stop_quiet = True
else:
self._stop = True
#make sure we are not stuck in readline(s)
if self._isreading:
self._readevent.set()
#make sure the debugger is not paused.
if self.debug is True:
self.debugger.stop_code()
return
#try a keyboard interrupt - this will not work for the internal engine
# as the error is raised here instead of the running code, hence put in
#try clause.
try:
thread.interrupt_main()
except:
pass
示例5: receive_service
def receive_service(self):
# Receive data from server.
while True:
try:
# Recieve Message.
line = self.network_client_socket.recv(2048)
if (line != '\n'):
if((len(line.split(":")) >= 2) and
(line.split(":")[0].strip().startswith("LINE"))):
self.gui_send_service(line)
elif((len(line.split(":")) == 2) and
(line.split(":")[0].strip() == "JOINED")):
self.create_group_gui(line.split(":")[1].strip())
else:
print("\n %s" % line)
if not line:
print("Server closed connection, thread exiting.")
thread.interrupt_main()
self.quit()
break
except:
print("Recieve Error: Thread exiting.")
thread.interrupt_main()
self.quit()
break
示例6: listen
def listen(new_socket, filename, extension, part, size):
#listen on the random port
new_socket.listen(1)
#accept incoming connections
connection, address = new_socket.accept()
full_filename = filename + '.' + extension
#get username
username = os.getlogin()
#fully qualify path
file_path = '/home/' + username + '/p2p/files/' + full_filename
#open the file for reading
FILE = open(file_path, 'rb')
#read the desired parts
FILE.seek(part * 512000)
#set up data buffer for sending data
send_data = FILE.read(size)
#close up file
FILE.close()
#send out your data
connection.send(send_data)
#close up connection
connection.close()
#close up
new_socket.close()
#stop thread
thread.interrupt_main()
示例7: response
def response(context, flow):
"""========================================================================
"Called when a server response has been received"... łapię wyłącznie
odpowiedzi, bo interesują mnie zestawy (request/response). Przechwycony
response wraz z requestem wchodzą w skład transakcji, reprezentowanej przez
mitmproxy.models.HTTPFlow()
"HTTPFlow is collection of objects representing a single HTTP transaction".
Więcej info na WWW: http://docs.mitmproxy.org/en/stable/dev/models.html
==========================================================================="""
if flow.request.host.endswith('.thesettlersonline.pl'):
if "application/x-amf" in flow.response.headers.get("Content-Type", "_"):
with decoded(flow.response):
res = flow.response.content
req = flow.request.content
if search( 'defaultGame.Communication.VO.TradeWindow.dTradeWindowResultVO', res )\
and search( 'userAcceptedTradeIDs', res ) and search( 'tradeOffers', res )\
and search( 'GetAvailableOffers', req ):
log.debug("got trade REQ/RESP pair, feeding TDD thread...")
try:
t= Thread(target=ttd._incoming_traffic_handler, args=(context, flow,))
t.setDaemon(True)
t.start()
except (KeyboardInterrupt, SystemExit):
log.info('caught either KeyboardInterrupt or SystemExit, quitting threads')
t.__stop()
import thread
thread.interrupt_main()
示例8: parse_itemDetailView
def parse_itemDetailView(self, response):
if 'techerror' in response.url:
print 'somehow found tech error at url ', response.request.url
# logfun = logging.getLogger("logfun")
# time.sleep(0.10)
try:
hxs = HtmlXPathSelector(response)
page_title = hxs.select('//title/text()').extract()[0]
med_image = hxs.select('//input[@id="imageURL"]/@value')[0].extract() # 200x200 image
# Should probably do some form of exception, but lazy
large_image = ''
large_image_path = hxs.select('//input[@id="primaryImageURL"]/@value')
if len(large_image_path) > 0:
large_image = large_image_path[0].extract()
# large_image = hxs.select('//input[@id="primaryImageURL"]/@value')[0].extract() # 600x600 image
# Only take information in paragraphs, but preserve HTML & formatting: Combine all paragraphs for this entry
details_list = hxs.select('//div[@id="productDetails-details"]/p').extract()
details = ''.join(details_list)
cut_start = details.find('<a class="')
cut_end = details.rfind('</p>')
# Remove the disclaimer link at bottom
if cut_start > 0 and cut_end > 0:
details = details[0:cut_start] + details[cut_end:]
nutrition_path = hxs.select('//div[@id="productDetails-nutrition"]/table').extract()
nutrition = ''
if len(nutrition_path) > 0:
nutrition = nutrition_path[0]
ingredients = ''
if len(hxs.select('//div[@id="ingredients"]').extract()) > 0:
ingredients = hxs.select('//div[@id="ingredients"]')[0].extract()
#ingredients = hxs.select('//div[@id="ingredients"]')[0].extract()
detailed_item = DetailedShopItem(name = response.meta['name'], size =
response.meta['size'], unit_price = response.meta['unit_price'],
productId = response.meta['productId'], price =
response.meta['price'], cnid = response.meta['cnid'], small_image =
response.meta['thumb'], med_image = med_image, large_image =
large_image, details = details, nutrition = nutrition, ingredients = ingredients)
self.all_items_detail.append(detailed_item)
# except:
# e = sys.exc_info()[0]
# print e.print_stack()
# sys.exit("error has occurred")
except Exception, ex:
print 'gg exception'
print 'came from', response.request.url
raise
#raise KeyboardInterrupt
# logfun.exception("Bad gg")
# logfun.debug("figure this out")
thread.interrupt_main()
示例9: worker_thread
def worker_thread(work_queue,shutdown_flag):
while not shutdown_flag.is_set():
fileno, address, head, body = work_queue.get_request()
if fileno == 0:
thread.interrupt_main()
return
parser = Parser(head,body)
request = parser.parse()
if request == None:
response = Http400Response()
else:
request.remote_addr, request.remote_port = address
request._work_queue = work_queue
log("%s - %s" %( request.remote_addr, request.path ))
handler = config.HANDLER_CLASS(request)
try:
response = handler.response()
except:
exc = traceback.format_exc()
log(exc)
if config.DEBUG:
response = Http500Response(exc)
else:
response = Http500Response()
work_queue.submit_response(fileno,response)
示例10: _uoczer
def _uoczer(self):
""" "ten co czai" :) :: perform once-upon-a-time checks and cleanups ::
- sprawdza czas ostatnich odświerzeń rynków każdego z realmów
- dla przestarzałych emituje duplikaty, jeśli są dostępne
- planuje kolejne uruchomienie siebie przy pomocy threading.Timer
"""
self.uoczerIterCounter+=1
try: # performing timed checks and cleanups
if self.now()-self.c.lastupdatedTS > 3000 and self.uoczerIterCounter % 1000 == 0:
log.info('PINGING DATABASE')
self.db.ping()
if self._trade_refresh_needed() and self.c.treqs:
recent_key = self.c.treqs.keys()[0]
recent_request= self.c.treqs[recent_key]
raw_trade_response= recent_request.execute()
if raw_trade_response:
parsed_response_body= self._amf_raw_response_parser(raw_trade_response)
self._trade_update_market(parsed_response_body)
log.info('trade updated with duplicated treq (uID: %d)'%recent_key)
else:
log.info('trade requery failed, deleting treq (uID %d)'%recent_key)
del self.c.treqs[recent_key]
except (KeyboardInterrupt, SystemExit): # stop on interrupts
log.info('caught either KeyboardInterrupt or SystemExit, quitting thread')
import thread
thread.interrupt_main()
exit()
finally:
log.debug('scheduling run in %ds'%self.c.watchT)
self.uoczertimer = Timer(self.c.watchT, self._uoczer) # reschedule run
self.uoczertimer.setDaemon(True) # with abort at shutdown
self.uoczertimer.start()
示例11: process_stream
def process_stream(self):
"""Process lines using parseline() forever"""
# Catch-all so we know why the process died.
while True:
# Read the next line
try:
line = self.readline()
print line
except KeyboardInterrupt:
thread.interrupt_main()
except:
logging.error("%s failed with %s"
% (self.instrument, traceback.format_exc()))
continue
# Interpret the next line
try:
self.lock.acquire()
self.parseline(line)
except KeyboardInterrupt:
thread.interrupt_main()
except:
logging.error("%s failed with %s\nLine: %s"
% (self.instrument,
traceback.format_exc(),
self.lastline))
finally:
self.lock.release()
示例12: do_GET
def do_GET(self):
"""Serve a GET request."""
parsed_url = urlparse.urlparse(self.path)
params = urlparse.parse_qs(parsed_url.query)
path = parsed_url.path
if path.startswith('/stop'):
# stop children before we return a response
timeout = int((params.get("timeout", []) or ["30"])[0])
self.funkyserver.pre_stop(timeout=timeout)
t = self.get_response_text()
if self.send_head(t):
self.wfile.write(t)
#I preempt the finish operation here so that processing of this request is all done before we crash or whatever:
self.finish()
self.http_server.shutdown_request(self.connection)
if path.startswith('/crash'):
crash()
if path.startswith('/stop'):
self.funkyserver.stop()
if path.startswith('/interrupt_main'):
thread.interrupt_main()
if path.startswith('/exit'):
os._exit(1)
if path.startswith('/hold_gil'):
t = int((params.get("t", []) or ["100"])[0])
hold_gil(t)
示例13: __init__
def __init__(self, host, port, username, password):
self.origin = Location()
self.origin.set(130, 71, 83)
self.range = Location()
self.range.set(10, 10, 10)
self.X = 0
self.Y = 0
self.Z = 0
self.bot = Bot()
self.dispatch = PacketDispatch(self)
self.buff = Buffer()
self.packetSend = []
self.sendPacket = PacketSend(self)
self.printable = True
self.receiveSize = 1024
self.compressionThreshold = -1
self.username = username
self.HOST = host
self.PORT = port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.settimeout(None)
try:
self.s.connect((self.HOST, self.PORT))
except socket.error:
print("Connection refused")
thread.interrupt_main()
exit()
示例14: wait
def wait(secs):
for n in xrange(timeout_secs):
time.sleep(1)
if signal_finished:
break
else:
thread.interrupt_main()
示例15: _handle_test_status_file
def _handle_test_status_file(self, test_name, test_phase, success):
###########################################################################
#
# This complexity is due to sharing of TestStatus responsibilities
#
try:
if (test_phase != RUN_PHASE and
(not success or test_phase == BUILD_PHASE or test_phase == self._phases[-1])):
self._update_test_status_file(test_name)
# If we failed VERY early on in the run phase, it's possible that
# the CIME scripts never got a chance to set the state.
elif (test_phase == RUN_PHASE and not success):
test_status_file = os.path.join(self._get_test_dir(test_name), TEST_STATUS_FILENAME)
statuses = wait_for_tests.parse_test_status_file(test_status_file)[0]
if ( RUN_PHASE not in statuses or
statuses[RUN_PHASE] in [TEST_PASS_STATUS, TEST_PENDING_STATUS] ):
self._update_test_status_file(test_name)
except Exception as e:
# TODO: What to do here? This failure is very severe because the
# only way for test results to be communicated is by the TestStatus
# file.
warning("VERY BAD! Could not handle TestStatus file '%s': '%s'" % (test_status_file, str(e)))
thread.interrupt_main()