本文整理汇总了Python中thread.interrupt_main函数的典型用法代码示例。如果您正苦于以下问题:Python interrupt_main函数的具体用法?Python interrupt_main怎么用?Python interrupt_main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了interrupt_main函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:08saikiranreddy,项目名称:ipython,代码行数:30,代码来源:parentpoller.py
示例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
开发者ID:AmesianX,项目名称:Tunna,代码行数:33,代码来源:TunnaClient.py
示例3: _test_main_thread
def _test_main_thread():
cherrypy.server.wait()
cherrypy._cputil._cpInitDefaultFilters()
try:
webtest.main()
finally:
thread.interrupt_main()
开发者ID:bieschke,项目名称:nuffle,代码行数:7,代码来源:helper.py
示例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
开发者ID:tito2016,项目名称:Python-Project,代码行数:33,代码来源:engine.py
示例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
开发者ID:kakkoyun,项目名称:cmpe322,代码行数:26,代码来源:GroupScribbleClient.py
示例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()
开发者ID:evangipson,项目名称:PP2P,代码行数:26,代码来源:p2p2_0.py
示例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()
开发者ID:internety,项目名称:smarTSO,代码行数:27,代码来源:TradeDumper.py
示例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()
开发者ID:einstein7th,项目名称:SnapShopWeb,代码行数:60,代码来源:peapod_spider.py
示例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)
开发者ID:gattis,项目名称:magnum-py,代码行数:27,代码来源:serve.py
示例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()
开发者ID:internety,项目名称:smarTSO,代码行数:35,代码来源:TradeDumper.py
示例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()
开发者ID:reflectometry,项目名称:WRed,代码行数:28,代码来源:xpeek.py
示例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)
开发者ID:j5int,项目名称:processfamily,代码行数:27,代码来源:FunkyWebServer.py
示例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()
开发者ID:natruiz3555,项目名称:dennis,代码行数:29,代码来源:networkManager.py
示例14: wait
def wait(secs):
for n in xrange(timeout_secs):
time.sleep(1)
if signal_finished:
break
else:
thread.interrupt_main()
开发者ID:TianlaiProject,项目名称:tlpipe,代码行数:7,代码来源:safeeval.py
示例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()
开发者ID:rljacob,项目名称:cime,代码行数:27,代码来源:create_test_impl.py
示例16: update_config
def update_config(self):
if self._restart:
print >>sys.stderr, "[hosted.py] restarting service (restart_on_update set)"
import thread, time
thread.interrupt_main()
time.sleep(100)
return
def parse_recursive(options, config, target):
# print 'parsing', config
for option in options:
if not 'name' in option:
continue
if option['type'] == 'list':
items = []
for item in config[option['name']]:
parsed = {}
parse_recursive(option['items'], item, parsed)
items.append(parsed)
target[option['name']] = items
continue
target[option['name']] = types[option['type']](config[option['name']])
parsed = {}
parse_recursive(self._options, self._config, parsed)
print >>sys.stderr, "[hosted.py] updated config"
self._parsed = parsed
开发者ID:cfra,项目名称:package-weather-hand-drawn,代码行数:27,代码来源:hosted.py
示例17: callback
def callback():
global thread, s, peersData, my_ip, host, port
if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
s.sendto("exit", (host, port))
s.close()
root.destroy()
thread.interrupt_main()
开发者ID:dae-eklen,项目名称:Shared-whiteboard,代码行数:7,代码来源:whiteboardUDP.py
示例18: run
def run(self):
"""Start event listener"""
try_interval = 1
while self.stop_event.is_set() is False:
try:
try_interval *= 2
with self._celery_app.connection() as conn:
handlers = {
"task-succeeded": (self._engine._task_success_handler),
"task-failed": (self._engine._task_failure_handler),
}
recv = events.EventReceiver(conn, handlers=handlers, app=self._celery_app)
while self.stop_event.is_set() is False:
recv.capture(limit=None, timeout=None)
self._running = True
try_interval = 1
except (KeyboardInterrupt, SystemExit):
thread.interrupt_main()
except Exception as e:
self._running = False
LOG.error("Failed to capture events: '%s', " "trying again in %s seconds." % (e, try_interval))
LOG.debug(e, exc_info=True)
time.sleep(try_interval)
开发者ID:jessicalucci,项目名称:TaskManagement,代码行数:25,代码来源:distributed_engine.py
示例19: decompte
def decompte(self, sec=90., dt=.1):
endTime = time.time() + sec
while True:
novTime = time.time()
if novTime >= endTime:
break
if self.tirette.armee():
self.printLog( "sortie du programme sur remise de la tirette apres %.2fs"%(sec-(endTime-novTime)) )
import sys
sys.exit(1)
#raise KeyboardInterrupt(message)
time.sleep(dt)
self.disableActuators()
self.disableActuators()
self.disablePower()
self.disablePower()
time.sleep(0.5)
self.disableActuators()
self.disableActuators()
self.disablePower()
self.disablePower()
self.printLog( "fin du temps imparti: %.2fs"%sec )
thread.interrupt_main()
开发者ID:RoseTeam,项目名称:Software,代码行数:28,代码来源:robot.py
示例20: worker
def worker():
try:
workerRun()
except Exception, e:
print sys.exc_info()
M6Item.status = 'STOPPED'
thread.interrupt_main()
开发者ID:fbturk,项目名称:Scripts,代码行数:7,代码来源:AdobeHDS.py
注:本文中的thread.interrupt_main函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论