本文整理汇总了Python中threading.Thread._Thread__stop方法的典型用法代码示例。如果您正苦于以下问题:Python Thread._Thread__stop方法的具体用法?Python Thread._Thread__stop怎么用?Python Thread._Thread__stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Thread
的用法示例。
在下文中一共展示了Thread._Thread__stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def main():
print "Launched."
if not os.path.exists("dataSaved.csv"):
try:
f = open("dataSaved.csv", "w")
except IOError:
print "Unable to create CSV file. Exiting."
return
else:
f.close()
v = Verarbeitung()
v.loadData()
v.saveDataCSV()
t = Thread(target=application.realmain)
t.start()
print "Web server launched!"
try:
print "About to launch local server..."
server.main(v)
except KeyboardInterrupt:
pass
finally:
print "Exiting. Saving data."
v.saveData()
t._Thread__stop()
示例2: _send_it
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def _send_it(subject, sender, recipients, text, html, tries):
import cStringIO, mimetools, MimeWriter
out = cStringIO.StringIO()
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
writer = MimeWriter.MimeWriter(out)
# headers
writer.addheader("From", sender)
writer.addheader("To", ','.join(recipients))
writer.addheader("Subject", subject)
writer.addheader("X-Mailer", "SmailiMail [version 1.0]")
writer.addheader("MIME-Version", "1.0")
writer.startmultipartbody("alternative")
writer.flushheaders()
# text
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'UTF-8')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
# html
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/html", [("charset", 'UTF-8')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
# to string
writer.lastpart()
msg = out.getvalue()
out.close()
class PostFixThread(Thread):
def __init__(self):
Thread.__init__(self)
self.result = False
def run(self):
self.result = _call_postfix(sender, recipients, msg)
thr = PostFixThread()
thr.start()
thr.join(MAIL_TIMEOUT)
if thr.isAlive():
Thread._Thread__stop(thr)
thr.result = False
if not thr.result and tries < 5:
_send_it(subject, sender, recipients, text, html, tries + 1)
示例3: worker
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def worker(self):
while True:
item = self.queue.get()
priority, time_sch, function, args, callback, deadline, fail_callback, fail_policy, time_policy = item
time_q = time.time()
thread = Thread(target=function, args=(time_q, ) + args)
thread.start()
# res = function(time_q, *args, **kwargs)
thread.join(deadline)
if thread.isAlive():
# overtime
thread._Thread__stop()
print("KILLED")
if fail_policy == "callback":
if fail_callback:
fail_callback(None)
elif fail_policy == "reschedule":
print("rescheduled")
self.schedule(*item[1:])
self.dropped_events += 1
self.log.write("{name} {time_s} {time_e} fail\n".format(name=function.func_name,
time_s=time_q - self.start,
time_e=time.time() - self.start))
self.log5.write("{name} {ctime} 1\n".format(name=function.func_name,
ctime=time.time() - self.start))
else:
time_end = time.time() - self.start
self.log.write("{name} {time_s} {time_e} ok\n".format(name=function.func_name,
time_s=time_q - self.start,
time_e=time_end))
if time_policy == "constant":
sleep_time = max((time_q + deadline) - time.time(), 0)
print("sleeping additionally %s for constant interval" % sleep_time)
time.sleep(sleep_time)
self.log.write("{name} {time_s} {time_e} placeholder\n".format(name=function.func_name,
time_s=time_end,
time_e=time_end + sleep_time))
if callback:
callback(None)
self.log3.write("{name} {ctime} {time}\n".format(name=function.func_name,
ctime=time.time() - self.start, time=time_end + self.start - time_q))
self.log4.write("{name} {ctime} 1\n".format(name=function.func_name,
ctime=time.time() - self.start))
self.log2.write("{name} {ctime} {time}\n".format(name=function.func_name,
ctime=time.time() - self.start, time=time_q - time_sch))
self.log.flush()
self.log2.flush()
self.log3.flush()
self.log4.flush()
self.log5.flush()
self.processed_events += 1
self.queue.task_done()
print("processed, dropped: ", self.processed_events, self.dropped_events)
示例4: __init__
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class Server:
def __init__(self, host, port, listener):
listenSocket = socket.socket(AF_INET, SOCK_STREAM)
listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
listenSocket.bind((host, port))
listenSocket.listen(10)
#print "SERVER: Listening"
self.sockets = {}
self.endpoints={}
self.socket = listenSocket
self.listener = listener
self.thread = Thread(target=self.AcceptConnections, args=[listenSocket])
self.thread.start()
def AcceptConnections(self, listenSocket):
while True:
self.AcceptEndpointConnections(listenSocket)
def AcceptEndpointConnections(self, listenSocket):
clientSocket, clientAddress = listenSocket.accept()
#print "SERVER: Accepted connection from", clientAddress
#print "SERVER: Client socket", id(clientSocket._sock)
EndPoint(self, clientSocket)
def send(self, msg):
addr = msg[TARGET]
data = cPickle.dumps(msg)
conn = None
if self.endpoints.has_key(addr):
end_point = self.endpoints[addr]
conn = end_point.socket
else:
conn = socket.socket(AF_INET, SOCK_STREAM)
(ip, port) = addr.split(':')
conn.connect((ip, int(port)))
self.endpoints[addr] = EndPoint(self, conn)
conn.send(struct.pack("!I", len(data)))
conn.send(data)
def close(self):
#print "SERVER: Shutting down the server"
try:
self.socket.shutdown(1)
except:
None
self.socket.close()
for endpoint in self.endpoints.values():
endpoint.Release()
self.thread._Thread__stop()
示例5: execute
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def execute(self, sql):
self.cursor.fetchall()
subproc = Thread(target=self.query, args=(sql,))
subproc.start()
subproc.join(3)
if subproc.isAlive():
subproc._Thread__stop()
self.connect()
self.query(sql)
self.out = self.cursor.fetchall()
return self.cursor.rowcount
示例6: get_comic
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def get_comic(self):
"""Run scrape_xkcd in a separate thread and kill it after a one second timeout if necessary.
Returns url, title, alt of the scraped comic
"""
t = Thread(target=self.scrape_xkcd)
t.start()
t.join(1)
if t.is_alive():
if self._valid:
t.join()
else:
t._Thread__stop()
return self._url, self._title, self._alt
示例7: main
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def main(argv):
(opts, args) = parser.parse_args()
if not check_arguments(opts, args):
print usage
sys.exit(0)
thread = Thread(target = start_pathway_tools_api_mode, args = (opts.pathway_tools, ))
thread.start()
sleep(10)
print "going to kill "
if thread.isAlive():
try:
thread._Thread__stop()
except:
print(str(thread.getName()) + ' could not be terminated')
示例8: __init__
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class IrisChannel:
def __init__(self):
self.stop_running = True
self.config = config.ConfigList(self.__class__, ());
def get_config_list(self):
return self.config
def start(self, wait = False):
self.thread = Thread(target=self.thread_run)
self.thread.start()
if wait:
self.thread.join()
def thread_run(self):
self.stop_running = False
self.loop_init()
while not self.stop_running:
self.loop()
self.loop_finish()
def thread_stop(self, cb = None):
if not self.stop_running:
self.stop_running = True
self.thread.join(5)
if self.thread.is_alive():
self.thread._Thread__stop()
if cb:
cb()
def stop(self, cb = None):
Thread(target=self.thread_stop, args=(cb,)).start()
def loop_init(self):
pass
def loop(self):
pass
def loop_finish(self):
pass
示例9: DotaLogWatcher
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class DotaLogWatcher():
path = ''
_thread = None
_dota_log = None
_overlayswitcher = None
_active = True
def __init__(self, path, overlayswitcher):
self.path = path
self._overlayswitcher = overlayswitcher
self._dota_log = open(self.path, 'r+')
self._thread = Thread(target=self._spin, name='thread-overlayswitcher.dotalogwatcher._spin')
self._thread.start()
def stop(self):
self._active = False
sleep(0.5)
if self._thread.is_alive:
self._thread._Thread__stop()
self._dota_log.close()
def _spin(self):
while self._active and not sleep(0.016): #frame at 60fps
new_content = self._dota_log.read()
if new_content:
prev_state_ = self._overlayswitcher.base_state
self._update_state(new_content)
if self._overlayswitcher.base_state != prev_state_:
self._overlayswitcher.work()
def _update_state(self, new_content):
for line in reversed(new_content.split('\n')):
if line.startswith('Start of Dota'):
self._overlayswitcher.base_state = 'MENU'
return
pos_rule = line.find('DOTA_GAMERULES_STATE_')
if pos_rule >= 0:
self._overlayswitcher.base_state = line[pos_rule+21:-1]
return
示例10: __init__
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class EndPoint:
packetSizeFmt = "!I"
packetSizeLength = struct.calcsize(packetSizeFmt)
def __init__(self, server, epSocket):
self.socket = epSocket
self.server = server
self.init = False
self.thread = Thread(target=self._ManageSocket)
self.thread.start()
def Release(self):
self.socket.close()
self.thread._Thread__stop()
def _ManageSocket(self):
try:
self._ReceivePackets()
except socket.error, e:
self.Release()
示例11: _stop
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def _stop(self):
if self.isAlive():
Thread._Thread__stop(self)
示例12: OBSRemoteSwitcher
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class OBSRemoteSwitcher():
"""Handler to talk to OBSRemote by websocket.
Handles authentication, SceneChanges and SceneUpdates
"""
def switch_to_scene(self, scene):
# Set the current scene
data = {"request-type":'SetCurrentScene', 'scene-name':scene}
self.send(data)
def update_scenes(self):
data = {"request-type":'GetSceneList'}
self.send(data)
def send(self, data):
if not type(data) == dict or not data:
return False
data = self.json_encoder.encode(data)
try:
self.ws.send(data)
except:
pass
def authenticate(self):
#TODO: Authentication
print 'authenticate not yet implemented'
def start(self):
self.ws = websocket.WebSocketApp("ws://{0}/".format(self.obsurl),
on_message=self.on_message,
on_error = self.on_error,
on_open = self.on_open,
header = ['Sec-WebSocket-Protocol: obsapi'])
websocket.setdefaulttimeout(5)
self.thread = Thread(target=self.ws.run_forever, name='thread-overlayswitcher.sceneswitcher.obsremote.ws.fun_forever')
self.thread.start()
def stop(self):
self.connected = False
self.ws.close()
self.thread._Thread__stop()
def on_message(self, ws, message):
""" Store new information for the overlayswitcher"""
data = self.json_decoder.decode(message)
if data.get('authRequired','False') == 'True':
self.authenticate()
if data.get('update-type','') == 'StreamStatus':
self.stats = data
if data.has_key('streaming'):
pass
if type(data.get('scenes',None)) == list:
pass
# print data.get('current-scene','')
# print '\n'.join(i['name'] for i in data['scenes'])
if data.has_key('current-scene'):
current_scene = data.get('current-scene')
self._overlayswitcher.active_scene = current_scene
def on_error(self, ws, error):
print "Error in the OBS Remote Handler:", error
self.stop()
def on_open(self, ws):
if ws is None or ws.sock is None:
print 'OBSRemote Socket Error!'
return
self.connected = ws.sock.connected
if not self.connected:
print 'Could not establish a connection to OBSRemote! Aborting'
return
else:
print 'Websocket created'
self.update_scenes()
data = {"request-type":'GetAuthRequired'}
self.send(data)
def __init__(self, settings, overlayswitcher):
self.json_encoder = json.JSONEncoder()
self.json_decoder = json.JSONDecoder()
self.password = settings.OBS_REMOTE_PASS
self.obsurl = settings.OBS_REMOTE_URL
self._overlayswitcher = overlayswitcher
self.obs_streaming = 0
self.connected = False #have we got a message yet?
#websocket.enableTrace(True)
self.start()
示例13: terminate
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
def terminate(self):
if self.is_alive():
Thread._Thread__stop(self)
示例14: ThingspeakSubscriber
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
class ThingspeakSubscriber (AbstractSubscriber):
def __init__ (self):
super(ThingspeakSubscriber, self).__init__(subscriberName, "", logLevel)
self.msgQueue = []
self.__lock = threading.Lock()
self.eventChannelMap = {}
self.timer = 15 # sleep due to thingspeak limitations
def mekeTopic(self, device, measureType):
return EventTopics.getSensorMeasurementEvent() + "/" + str(device) + "/" + str(measureType).lower()
def start (self):
# method overrided
resp, isOk = self.invokeWebService(self.homeWSUri)
while (not isOk):
self.logger.error ("Unable to find the home proxy. I will try again in a while...")
resp, isOk = self.invokeWebService(self.homeWSUri)
time.sleep(10) #sleep 10 seconds
myhome = json.loads(resp)
brokerUri = myhome["homeMessageBroker"]["address"]
brokerPort = myhome["homeMessageBroker"]["port"]
if (brokerUri != None and brokerUri != "") and (brokerPort != None and brokerPort != ""):
self.mqttc = MyMQTTClass(self.subscriberName, self.logger, self)
self.mqttc.connect(brokerUri,brokerPort)
for a, room in enumerate(myhome["rooms"]):
for b, device in enumerate(room["devices"]):
for c, channel in enumerate(device['thingspeakChannels']):
topic = self.mekeTopic(device["deviceID"], channel['measureType'])
self.eventChannelMap[topic] = channel['feed']
event = self.mqttc.subscribeEvent(None, topic)
self.subscribedEventList += event
else:
self.logger.error ("The message broker address is not valid")
self.uploadThread = Thread (target = self.upload)
self.uploadThread.start()
self.loop()
def stop (self):
if (hasattr(self, "uploadThread")):
if self.uploadThread.isAlive():
try:
self.uploadThread._Thread__stop()
except:
self.logger.error(str(self.uploadThread.getName()) + ' (upload value thread) could not terminated')
super(ThingspeakSubscriber, self).stop()
def upload(self):
while (True):
try:
if (len(self.msgQueue) > 0):
resp, isOk = self.invokeWebService(self.msgQueue[0])
if isOk and resp is not "0":
self.__lock.acquire()
deleted = self.msgQueue[0]
del self.msgQueue[0]
self.__lock.release()
time.sleep(self.timer) # sleep due to thingspeak limitations
else:
self.logger.error ("Unable to upload new value: %s" % (resp))
time.sleep(1)
except Exception, e:
self.logger.error("Error on ThingspeakSubscriber.upload() %s: " % e)
示例15: main
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import _Thread__stop [as 别名]
#.........这里部分代码省略.........
print (
term.render(
"Running regex search/replace on ${BOLD}REQUESTS${NORMAL} with regex: 's/%s/%s'"
% (sr_request[1], sr_request[2])
)
)
sr_request[0] = True
else:
print (
term.render(
"Running string search/replace on ${BOLD}REQUESTS${NORMAL} with search/replace: 's/%s/%s'"
% (sr_request[1], sr_request[2])
)
)
sr_request[0] = False
else:
sr_request = None
if options.search_response and options.replace_response:
sr_response = [
None,
options.search_response.decode("string-escape"),
options.replace_response.decode("string-escape"),
]
# Check if we want to use regex instead of string constants
if options.response_use_regex:
print (
term.render(
"Running regex search/replace on ${BOLD}RESPONSES${NORMAL} with regex: 's/%s/%s'"
% (sr_response[1], sr_response[2])
)
)
sr_response[0] = True
else:
print (
term.render(
"Running string search/replace on ${BOLD}RESPONSES${NORMAL} with search/replace: 's/%s/%s'"
% (sr_response[1], sr_response[2])
)
)
sr_response[0] = False
else:
sr_response = None
# Setup which to fuzz - request, response, neither, both?
if options.fuzz_request:
fuzz_request = options.fuzz_request
run_additional_info = "Fuzzing REQUESTS; " + run_additional_info
print (term.render("Fuzzing ${BOLD}REQUESTS${NORMAL}"))
else:
fuzz_request = False
if options.fuzz_response:
fuzz_response = options.fuzz_response
run_additional_info = "Fuzzing RESPONSES; " + run_additional_info
print (term.render("Fuzzing ${BOLD}RESPONSES${NORMAL}"))
else:
fuzz_response = False
if not (options.fuzz_response or options.fuzz_request):
run_additional_info = "Fuzzing NONE; " + run_additional_info
print (
term.render(
"Fuzzing ${BOLD}<NOTHING>${NORMAL} (Maybe you wanted ${BOLD}--fuzz-request or --fuzz-response${NORMAL}?)"
)
)
if fuzz_request and fuzz_response:
print (
term.render(
"${YELLOW}\nWARNING! WARNING!\n${BOLD}Fuzzing BOTH the request and response is probably a bad idea, ensure this is what you want to do!${NORMAL}${YELLOW}\nWARNING! WARNING!\n${NORMAL}"
)
)
# host, db, username, passwd
if logging_enabled:
logger = postgresLogger("postgreshost", "dbname", "dbuser", "dbpass")
logger.log_run_info("CompanyName", "ProjectName-v1.2.3", run_additional_info)
# create object that spawns reciever/sender pairs upon connection
fwdr = forwarder(options.local_addr, options.local_port, options.remote_addr, options.remote_port)
print ("Listener running...")
# asyncore.loop()
# A quick hack to be able to control fuzz on/off while running
# separate asyncore.loop into its own thread so we can have terminal control
asyncThread = Thread(target=asyncore.loop)
asyncThread.start()
# start a console (ipython)
from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell = TerminalInteractiveShell(user_ns=globals())
shell.mainloop()
# cleanup otherwise thread wont die and program hangs
fwdr.close()
# asyncore.close_all()
asyncThread._Thread__stop()