本文整理汇总了Python中threading.Thread类的典型用法代码示例。如果您正苦于以下问题:Python Thread类的具体用法?Python Thread怎么用?Python Thread使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Thread类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_windows_service
def run_windows_service(config):
""" Initialize the web application and run it in the background, while
displaying a small system tray icon to interact with the it.
"""
import webbrowser
from winservice import SysTrayIcon
app = WebApplication(config)
server_thread = Thread(target=app.run_server)
server_thread.start()
def on_quit(systray):
""" Callback that stops the application. """
IOLoop.instance().stop()
server_thread.join()
listening_port = config['web']['port'].get(int)
open_browser = (
lambda x: webbrowser.open_new_tab("http://127.0.0.1:{0}"
.format(listening_port)))
menu_options = (('Open in browser', None, open_browser),)
SysTrayIcon(
icon=os.path.join(os.path.dirname(sys.argv[0]), 'spreads.ico'),
hover_text="Spreads Web Service",
menu_options=menu_options,
on_quit=on_quit,
default_menu_index=1,
on_click=open_browser)
示例2: __init__
def __init__(self, req, proxy, logger, task, exit_check=None, ignored_errors=[]):
Thread.__init__(self, name = "monitor%s" % task.guid)
Thread.setDaemon(self, True)
# the count of votes per error code
self.vote_result = {}
# the error code to be ignored
self.vote_cleared = set().union(ignored_errors)
self.thread_last_seen = {}
self.dctlock = RLock()
self.votelock = RLock()
self.thread_ref = {}
self.thread_zombie = set()
# HttpReq instance
self.req = req
# proxy.Pool instance
self.proxy = proxy
self.logger = logger
self.task = task
self._exit = exit_check if exit_check else lambda x: False
self._cleaning_up = False
if os.name == "nt":
self.set_title = lambda s:os.system("TITLE %s" % (
s if PY3K else s.encode(CODEPAGE, 'replace')))
elif os.name == 'posix':
import sys
self.set_title = lambda s:sys.stdout.write("\033]2;%s\007" % (
s if PY3K else s.encode(CODEPAGE, 'replace')))
示例3: __init__
def __init__(self, newJobsQueue, updatedJobsQueue, boss):
Thread.__init__(self)
self.newJobsQueue = newJobsQueue
self.updatedJobsQueue = updatedJobsQueue
self.currentjobs = list()
self.runningjobs = set()
self.boss = boss
示例4: __init__
def __init__(self, interval_sec, get_connection_holders):
Thread.__init__(self, name="Connection heartbeat")
self._interval = interval_sec
self._get_connection_holders = get_connection_holders
self._shutdown_event = Event()
self.daemon = True
self.start()
示例5: __init__
def __init__(self):
self.title = self.empty_title
# we are listening to i3 events in a separate thread
t = Thread(target=self._loop)
t.daemon = True
t.start()
示例6: run
def run(data, d=None):
global timer
print(data)
if data == "ring":
if int(d) == 1:
if timer:
timer.cancel()
timer = Timer(60, genugdavon)
timer.start()
check = Thread(target=check_locks)
check.start()
putfile('/sys/class/gpio/gpio11/value', '0')
playsound("/root/ring-bb.wav")
else:
playsound("/root/ring-fis.wav")
if data == "open":
# if not locked_oben:
playsound("/root/open.wav")
if data == "summ":
if timer:
timer.cancel()
# if not locked_oben:
putfile('/sys/class/gpio/gpio11/value', '1')
playsound("/root/summ.wav")
示例7: AntiFlapping
class AntiFlapping(object):
"""
AntiFlapping class to process event in a timely maneer
"""
def __init__(self, window):
self.window = window
self.tasks = Queue(maxsize=1)
self._window_ended = True
self._thread = Thread(name="AntiFlapping", target=self._run)
self._thread.start()
def newEvent(self, func, kwargs={}):
"""
newEvent Triggered.
"""
if not self.tasks.full() and self._window_ended:
self.tasks.put({'func': func, 'args':kwargs})
def _run(self):
"""
internal runloop that will fire tasks in order.
"""
while True:
task = self.tasks.get()
self._window_ended = False
sleep(self.window)
self._window_ended = True
if task['args']:
task['func'](**task['args'])
else:
task['func']()
示例8: get_stock
def get_stock(self):
self.sku = self.sku_input.get().strip()
self.client_id = self.client_id_input.get().strip()
self.cycle = 1
region = self.region_input.get()
if self.refresh_var.get():
validity = self.refresh_is_valid()
if not validity[0]:
self.update_status(validity[1])
return
else:
amt = int(self.refresh_amt_input.get())
dly = float(self.refresh_dly_input.get())
if amt <= 0:
self.update_status('Please enter a non-zero/negative amount.')
return
if dly < 0:
self.update_status('Please enter a non-negative delay.')
return
else:
amt = 1
dly = 1
thread = Thread(name=self.sku+'_'+region, target=self.check_stock, args=[region, amt, dly])
thread.daemon = True
thread.start()
self.disable_submit()
示例9: __init__
def __init__(self, log = None):
from threading import Event
Thread.__init__(self)
self.__mytid = P.mytid()
try:
## get process ID of parent
self.__parent = P.parent()
except:
self.__parent = None
self.__bindings = {}
self.__stop = 0
self.__tasks = {}
self.setMessageLoopDelay(0.1)
self.__loopEvent = Event()
if log: self.__log = Logfile()
else: self.__log = None
## add ping-mechanism
self.setPingTimeout(5.)
self.bind(MSG_PING, -1, self._ping)
示例10: looped
def looped(window, *args, **kwargs):
if hasattr(linux_native_dialog, 'native_failed'):
import importlib
m = importlib.import_module('calibre.gui2.qt_file_dialogs')
qfunc = getattr(m, 'choose_' + name)
return qfunc(window, *args, **kwargs)
try:
if window is None:
return func(window, *args, **kwargs)
ret = [None, None]
loop = QEventLoop(window)
def r():
try:
ret[0] = func(window, *args, **kwargs)
except:
ret[1] = sys.exc_info()
sys.exc_clear()
while not loop.isRunning():
time.sleep(0.001) # yield so that loop starts
loop.quit()
t = Thread(name='FileDialogHelper', target=r)
t.daemon = True
t.start()
loop.exec_(QEventLoop.ExcludeUserInputEvents)
if ret[1] is not None:
raise ret[1][0], ret[1][1], ret[1][2]
return ret[0]
except Exception:
linux_native_dialog.native_failed = True
import traceback
traceback.print_exc()
return looped(window, *args, **kwargs)
示例11: __init__
def __init__(self, config, pipe_name=PIPE):
"""@param pipe_name: Cuckoo PIPE server name."""
Thread.__init__(self)
self.pipe_name = pipe_name
self.config = config
self.options = config.get_options()
self.do_run = True
示例12: start
def start(self, *args):
""" Creates a subprocess of nping and invokes it
with the given arguments."""
cline = [BotConfig.NPING_PATH]
cline = cline + args[0]
t = Thread(target=self.__run, args=[cline])
t.start()
示例13: __init__
def __init__(self, stationBase):
Thread.__init__(self)
self.stationBase = stationBase
self.imageVirtuelle = None
self.anciennePosRobot = []
self.police = cv2.FONT_HERSHEY_SIMPLEX
self.chargerImageVirtuelle()
示例14: __init__
def __init__(self, server):
"""
constructor
@param server to run
"""
Thread.__init__(self)
self.server = server
示例15: __init__
class NonBlockingStreamReader:
def __init__(self, stream):
'''
stream: the stream to read from.
Usually a process' stdout or stderr.
'''
self._s = stream
self._q = Queue()
def _populateQueue(stream, queue):
'''
Collect lines from 'stream' and put them in 'quque'.
'''
while True:
line = stream.readline()
if line:
queue.put(line)
else:
break
self._t = Thread(target = _populateQueue,
args = (self._s, self._q))
self._t.daemon = True
self._t.start() #start collecting lines from the stream
def readline(self, timeout = None):
try:
return self._q.get(block = timeout is not None,
timeout = timeout)
except Empty:
return None