本文整理汇总了Python中threading.Thread.isAlive方法的典型用法代码示例。如果您正苦于以下问题:Python Thread.isAlive方法的具体用法?Python Thread.isAlive怎么用?Python Thread.isAlive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Thread
的用法示例。
在下文中一共展示了Thread.isAlive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def run():
conf = get_config()
day = Thread(target=daily)
hour = Thread(target=hourly)
while True:
if not day.isAlive():
# Restart the VPN once per day
print("Daily restart of VPN at {}".format(datetime.now()))
restart_vpn(conf)
day = Thread(target=daily)
day.start()
if not hour.isAlive():
# do port_update every 10 min, unless connection problems, then try
# every 30 seconds.
try:
port_update(conf)
except URLError:
print("Port update failed: restarting "
"VPN at {}".format(datetime.now()))
restart_vpn(conf)
sleep(30)
else:
hour = Thread(target=hourly)
hour.start()
sleep(10)
if not check_running(conf):
restart_vpn(conf)
示例2: ssh_run
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def ssh_run(self, cmd, checkRC=True, waitForCompletion=True):
def target(p):
p.wait()
[t.join() for t in ts]
self.print_write("launching subprocess: %s" % cmd)
p = Popen(SSH_CMD + "%s %s" % (self.host, cmd), shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=self.preexec)
ts = [Thread(target=self.std_listen, args=(p.stdout, self.out))]
ts += [Thread(target=self.std_listen, args=(p.stderr, self.out))]
[t.start() for t in ts]
t = Thread(target=target, args=(p,))
t.start()
while waitForCompletion or self.goOnEvent.isSet():
t.join(1)
if not t.isAlive():
break
if t.isAlive():
os.kill(p.pid, signal.SIGTERM)
self.print_write("finished running subprocess: %s" % cmd)
if checkRC and self.goOnEvent.isSet():
rc = p.returncode
if rc is not 0:
c = SSH_CMD + "%s %s" % (self.host, cmd)
raise Exception(
"subprocess.CalledProcessError: Command '%s'" "returned non-zero exit status %s" % (c, rc)
)
示例3: SessionManager
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
class SessionManager(GenericSessionManager):
"""
In memory session manager implementation class
"""
def __init__(self, timeout, **kwargs):
GenericSessionManager.__init__(self, timeout)
self._sessions = {}
self._list = []
self._is_active = True
self._expire_thread = Thread(target=self._expire_sessions,
name='Session expriration thread')
def init_expiration_mechanism(self):
if not self._expire_thread.isAlive():
self._expire_thread.start()
def _expire_sessions(self):
from porcupine.core.runtime import logger
while self._is_active:
expire_threshold = time.time() - self.timeout - \
self.revive_threshold
for sessionid in self._list:
session = self.get_session(sessionid)
if session._last_accessed < expire_threshold:
logger.debug('Expiring Session: %s' % sessionid)
session.terminate()
logger.debug('Total active sessions: %s' % \
str(len(self._list)))
else:
break
time.sleep(3.0)
def create_session(self, userid):
session = Session(userid, {})
self._sessions[session.sessionid] = session
self._list.append(session.sessionid)
return session
def get_session(self, sessionid):
session = self._sessions.get(sessionid, None)
return session
def remove_session(self, sessionid):
self._list.remove(sessionid)
del self._sessions[sessionid]
def revive_session(self, session):
# move sessionid at the end of the list
self._list.append(session.sessionid)
self._list.remove(session.sessionid)
# update last access time
session._last_accessed = time.time()
def close(self):
self._is_active = False
if self._expire_thread.isAlive():
self._expire_thread.join()
# remove temporary files
for sessionid in self._list:
self._sessions.get(sessionid).remove_temp_files()
示例4: Cam
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
class Cam(object):
def __init__(self, url, bubbler, user=None, password=None, upload_interval_seconds=60):
self.user=user
self.password=password
self.bubbler=bubbler
self.upload_interval_seconds = upload_interval_seconds
if user is not None and password is not None:
self.stream = requests.get(url, auth=(self.user,self.password), stream=True)
else:
self.stream = requests.get(url, stream=True)
self.thread_cancelled = False
self.thread = Thread(target=self.run)
print "camera initialized"
def start(self):
self.thread.start()
print "camera stream started"
def run(self):
bytes=''
polling_start = time.time()
prev_img = None
diff_df = pd.DataFrame()
while not self.thread_cancelled:
try:
cur_time = time.time()
if cur_time - polling_start > self.upload_interval_seconds:
polling_start = cur_time
self.bubbler.process_buffer(diff_df)
diff_df = pd.DataFrame()
bytes+=self.stream.raw.read(1024)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_GRAYSCALE)
if prev_img is not None:
diff = self.bubbler.imgdiff(img, prev_img)
diff_df = diff_df.append(pd.Series({'t':time.time(), 'ctime':time.ctime(),
'diff':diff}), ignore_index=True)
prev_img = img
except ThreadError:
print 'Caught thread error...'
self.thread_cancelled = True
def is_running(self):
return self.thread.isAlive()
def shut_down(self):
self.thread_cancelled = True
print 'Shutting down'
#block while waiting for thread to terminate
while self.thread.isAlive():
time.sleep(100)
return True
示例5: testMainLoopStops
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def testMainLoopStops(self):
t = Thread(target = self.connection.main_loop)
t.start()
self.assertTrue(t.isAlive())
self.connection.sock.put("") # End of data signal
# Wait for the shutdown.
sleep(0.001)
self.assertFalse(t.isAlive())
示例6: main
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def main(args):
syslog.openlog("config-manager", syslog.LOG_PID)
pdlogs.STARTUP.log()
try:
arguments = docopt(__doc__, argv=args)
except DocoptExit:
pdlogs.EXITING_BAD_CONFIG.log()
raise
local_ip = arguments['--local-ip']
local_site = arguments['--local-site']
log_dir = arguments['--log-directory']
log_level = LOG_LEVELS.get(arguments['--log-level'], logging.DEBUG)
stdout_err_log = os.path.join(log_dir, "config-manager.output.log")
if not arguments['--foreground']:
utils.daemonize(stdout_err_log)
logging_config.configure_logging(log_level, log_dir, "config-manager", show_thread=True)
# urllib3 logs a WARNING log whenever it recreates a connection, but our
# etcd usage does this frequently (to allow watch timeouts), so deliberately
# ignore this log
urllib_logger = logging.getLogger('urllib3')
urllib_logger.setLevel(logging.ERROR)
utils.install_sigusr1_handler("config-manager")
# Drop a pidfile.
pid = os.getpid()
with open(arguments['--pidfile'], "w") as pidfile:
pidfile.write(str(pid) + "\n")
plugins_dir = "/usr/share/clearwater/clearwater-config-manager/plugins/"
plugins = load_plugins_in_dir(plugins_dir)
plugins.sort(key=lambda x: x.key())
threads = []
files = [p.file() for p in plugins]
alarm = ConfigAlarm(files)
for plugin in plugins:
syncer = EtcdSynchronizer(plugin, local_ip, local_site, alarm)
thread = Thread(target=syncer.main, name=plugin.__class__.__name__)
thread.start()
threads.append(thread)
_log.info("Loaded plugin %s" % plugin)
while any([thread.isAlive() for thread in threads]):
for thread in threads:
if thread.isAlive():
thread.join(1)
_log.info("Clearwater Configuration Manager shutting down")
pdlogs.EXITING.log()
syslog.closelog()
示例7: run
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def run():
t = Thread(target=test1)
t.start()
t.join(2)
print t.isAlive()
t.join()
print "over"
示例8: TimeoutProcess
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
class TimeoutProcess():
'''Runs an external command until timeout is reached
Assumes that Popen uses PIPE for stdin, stdout and stderr
Data for stdin may be supplied on instantiation, stdout and
stderr will be returned from the call.'''
def __init__(self):
self.argv = None
self.timeout = None
self.stdin = None
self.stdout = ''
self.stderr = ''
self.p = None
self.t = None
self.returncode = -127
def __call__(self, argv, timeout, stdin=None, **kwargs):
'''Run external command argv until timeout is reached
If stdin is not none the data will be supplied to the
processes stdin.
Remaining kwargs will be passed to Popen.
stderr and stdout are always strings, returncode is -1
if timeout occured'''
self.argv = argv
self.timeout = timeout
self.stdin = stdin
def target():
self.p = Popen(self.argv, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
(self.stdout, self.stderr) = self.p.communicate(self.stdin)
self.returncode = self.p.returncode
self.t = Thread(target=target)
self.t.start()
self.t.join(self.timeout)
if self.t.isAlive():
# In strange cases, there is no subprocess...
if self.p:
log.debug("Terminating process %d in thread %s" % (self.p.pid, self.t.name))
self.p.terminate()
self.t.join(THREADKILLTIMEOUT)
if self.t.isAlive():
log.debug("Killing process %d in thread %s" % (self.p.pid, self.t.name))
self.p.kill()
self.stderr += '\nTimeout occured\n'
self.returncode = -1
else:
log.warn('No subprocess found :-/')
return process(self.returncode, self.stdout, self.stderr)
示例9: test4_MaxConnections
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def test4_MaxConnections(self):
from DBUtils.PooledPg import TooManyConnections
pool = PooledPg(1, 2, 3)
self.assertEqual(pool._cache.qsize(), 1)
cache = []
for i in range(3):
cache.append(pool.connection())
self.assertEqual(pool._cache.qsize(), 0)
self.assertRaises(TooManyConnections, pool.connection)
pool = PooledPg(0, 1, 1, False)
self.assertEqual(pool._blocking, 0)
self.assertEqual(pool._cache.qsize(), 0)
db = pool.connection()
self.assertEqual(pool._cache.qsize(), 0)
self.assertRaises(TooManyConnections, pool.connection)
pool = PooledPg(1, 2, 1)
self.assertEqual(pool._cache.qsize(), 1)
cache = []
cache.append(pool.connection())
self.assertEqual(pool._cache.qsize(), 0)
cache.append(pool.connection())
self.assertEqual(pool._cache.qsize(), 0)
self.assertRaises(TooManyConnections, pool.connection)
pool = PooledPg(3, 2, 1, False)
self.assertEqual(pool._cache.qsize(), 3)
cache = []
for i in range(3):
cache.append(pool.connection())
self.assertEqual(pool._cache.qsize(), 0)
self.assertRaises(TooManyConnections, pool.connection)
pool = PooledPg(1, 1, 1, True)
self.assertEqual(pool._blocking, 1)
self.assertEqual(pool._cache.qsize(), 1)
db = pool.connection()
self.assertEqual(pool._cache.qsize(), 0)
def connection():
pool.connection().query('set thread')
from threading import Thread
thread = Thread(target=connection)
thread.start()
thread.join(0.1)
self.assert_(thread.isAlive())
self.assertEqual(pool._cache.qsize(), 0)
session = db._con.session
self.assertEqual(session, [])
del db
thread.join(0.1)
self.assert_(not thread.isAlive())
self.assertEqual(pool._cache.qsize(), 1)
db = pool.connection()
self.assertEqual(pool._cache.qsize(), 0)
self.assertEqual(session, ['thread'])
示例10: PSTracker
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
class PSTracker(object):
"""
Tracker module for PS
"""
def __init__(self, hostIP, cmd, port=9091, port_end=9999, envs=None):
"""
Starts the PS scheduler
"""
self.cmd = cmd
if cmd is None:
return
envs = {} if envs is None else envs
self.hostIP = hostIP
sock = socket.socket(get_family(hostIP), socket.SOCK_STREAM)
for port in range(port, port_end):
try:
sock.bind(('', port))
self.port = port
sock.close()
break
except socket.error:
continue
env = os.environ.copy()
env['DMLC_ROLE'] = 'scheduler'
env['DMLC_PS_ROOT_URI'] = str(self.hostIP)
env['DMLC_PS_ROOT_PORT'] = str(self.port)
for k, v in envs.items():
env[k] = str(v)
self.thread = Thread(
target=(lambda: subprocess.check_call(self.cmd, env=env, shell=True)), args=())
self.thread.setDaemon(True)
self.thread.start()
def join(self):
if self.cmd is not None:
while self.thread.isAlive():
self.thread.join(100)
def slave_envs(self):
if self.cmd is None:
return {}
else:
return {'DMLC_PS_ROOT_URI': self.hostIP,
'DMLC_PS_ROOT_PORT': self.port}
def alive(self):
if self.cmd is not None:
return self.thread.isAlive()
else:
return False
示例11: run
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def run(self, **kwargs):
super(MultiProcessingDependencyGraphRunner, self).run(**kwargs)
import multiprocessing
# Set up pool of evaluation workers.
self.evaluation_pool = multiprocessing.Pool(processes=self.pool_size)
# Set up a 'shared memory' dependency graph.
self.manager = multiprocessing.Manager()
self.execution_queue = self.manager.Queue()
self.result_queue = self.manager.Queue()
self.results_repo = self.manager.dict()
self.calls_dict = self.manager.dict()
self.calls_dict.update(self.dependency_graph.call_requirements)
self.dependencies = self.manager.dict()
self.dependencies.update(self.dependency_graph.dependencies)
self.dependents = self.manager.dict()
self.dependents.update(self.dependency_graph.dependents)
self.errors = []
# if 'all_market_prices' in self.run_kwds:
# all_market_prices = self.run_kwds.pop('all_market_prices')
# all_market_prices_dict = self.manager.dict()
# for market_name, market_prices in all_market_prices.items():
# all_market_prices_dict[market_name] = market_prices.copy()
# # market_prices_dict = self.manager.dict()
# # all_market_prices_dict[market_name] = market_prices_dict
# # for fixing_date, market_price in market_prices.items():
# # market_prices_dict[fixing_date] = market_price
# self.run_kwds['all_market_prices'] = all_market_prices_dict
evaluation_thread = Thread(target=self.evaluate_calls)
evaluation_thread.daemon = True
evaluation_thread.start()
results_thread = Thread(target=self.handle_results)
results_thread.daemon = True
results_thread.start()
# Put the leaves on the execution queue.
for call_requirement_id in self.dependency_graph.leaf_ids:
self.execution_queue.put(call_requirement_id)
while results_thread.isAlive() and evaluation_thread.isAlive():
sleep(1)
if evaluation_thread.isAlive():
self.execution_queue.put(None)
evaluation_thread.join()
if results_thread.isAlive():
self.result_queue.put(None)
results_thread.join()
if self.errors:
raise self.errors[0]
示例12: reindex_all
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def reindex_all(types = None, delete_all_first=False):
"""
Called from `paster run` to totally re-index everything in the
database. Spawns a thread to connect to Solr, and sends it
tokenised Things
"""
global indexed_types
start_t = datetime.now()
if not types:
types = indexed_types
# We don't want the default thread-local cache (which is just a
# dict) to grow un-bounded (normally, we'd use
# utils.set_emptying_cache, except that that preserves memcached,
# and we don't even want to get memcached for total indexing,
# because it would dump out more recent stuff)
g.cache.caches = (SelfEmptyingCache(),) # + g.cache.caches[1:]
count = 0
q=Queue(100)
indexer=Thread(target=indexer_worker,
args=(q,delete_all_first))
indexer.start()
try:
for cls in types:
for batch in fetch_batches(cls,1000,
timeago("50 years"),
start_t):
r = tokenize_things([ x for x in batch
if not x._spam and not x._deleted ])
count += len(r)
print ("Processing %s #%d(%s): %s"
% (cls.__name__, count, q.qsize(), r[0]['contents']))
if indexer.isAlive():
q.put(r)
else:
raise Exception("'tis a shame that I have but one thread to give")
q.put("done")
indexer.join()
except object,e:
if indexer.isAlive():
q.put(e,timeout=30)
raise e
示例13: controller
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def controller():
global kontroll
t1 = Thread(target=kaamerapilt)
t2 = Thread(target=loogika2)
katse = "STOP"
while True:
if katse == "START":
kontroll = True
if not t1.isAlive() and not t2.isAlive():
t2.start()
t1.start()
if katse == "STOP":
kontroll = False
print (t1.isAlive())
示例14: play
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def play(self, position, graph, goal, time):
startTime=clock()
self.timeout=False
# Search only on pertinent edges
interestingGraph=getInterestingGraph(position, graph, goal)
# At least, always try with a level 1 search
thread = Thread(target = self.blockerThread, args=(position,interestingGraph,goal))
thread.start()
thread.join(startTime-clock()+time)
self.move=self.blockerPlay(position,interestingGraph,goal, 0, -10000, 10000)
if thread.isAlive():
self.timeout=True
self.maxLevel-=1
writeIntoFile('timeout level 0')
r=RandomBlocker()
r.randomSearch(position,graph,interestingGraph,goal,time)
return
# Loop for trying differents depths
if clock()-startTime<time:
while self.move[0]!=10000 and self.maxLevel<10 and not self.timeout:
self.maxLevel+=1
thread = Thread(target = self.blockerThread, args=(position,interestingGraph,goal))
thread.start()
thread.join(startTime-clock()+time)
if thread.isAlive():
self.timeout=True
self.maxLevel-=1
writeIntoFile('timeout level '+str(self.maxLevel))
if self.move[0]==10000:
self.maxLevel-=2
else:
self.maxLevel-=1
# If not move is found, remove the first edge
if(self.move[1]==(-1,-1)):
for (a,b) in enumerate(interestingGraph):
for (c,d) in enumerate(b):
if d>0:
self.move=(-10000,(a,c))
writeIntoFile('removed'+str(self.move[1]))
graph[self.move[1][0]][self.move[1][1]]-=1
if self.move[0]>self.bestScore:
self.bestScore=self.move[0]
return graph[self.move[1][0]][self.move[1][1]]
示例15: test_monitor_log
# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import isAlive [as 别名]
def test_monitor_log(self):
"""Tests log monitoring by writing to a log in the background thread"""
node = self.account_service.nodes[0]
# Make sure we start the log with some data, including the value we're going to grep for
self.account_service.write_to_log("foo\nbar\nbaz")
# Background thread that simulates a process writing to the log
self.wrote_log_line = False
def background_logging_thread():
# This needs to be large enough that we can verify we've actually
# waited some time for the data to be written, but not too long that
# the test takes a long time
time.sleep(3)
self.wrote_log_line = True
self.account_service.write_to_log("foo\nbar\nbaz")
with node.account.monitor_log(self.account_service.log_file) as monitor:
logging_thread = Thread(target=background_logging_thread)
logging_thread.start()
monitor.wait_until('foo', timeout_sec=10, err_msg="Never saw expected log")
assert self.wrote_log_line
logging_thread.join(5.0)
if logging_thread.isAlive():
raise Exception("Timed out waiting for background thread.")