本文整理汇总了Python中time.time.sleep方法的典型用法代码示例。如果您正苦于以下问题:Python time.sleep方法的具体用法?Python time.sleep怎么用?Python time.sleep使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类time.time
的用法示例。
在下文中一共展示了time.sleep方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_memory_base
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def _get_memory_base(gallery_conf):
"""Get the base amount of memory used by running a Python process."""
if not gallery_conf['plot_gallery']:
return 0.
# There might be a cleaner way to do this at some point
from memory_profiler import memory_usage
if sys.platform in ('win32', 'darwin'):
sleep, timeout = (1, 2)
else:
sleep, timeout = (0.5, 1)
proc = subprocess.Popen(
[sys.executable, '-c',
'import time, sys; time.sleep(%s); sys.exit(0)' % sleep],
close_fds=True)
memories = memory_usage(proc, interval=1e-3, timeout=timeout)
kwargs = dict(timeout=timeout) if sys.version_info >= (3, 5) else {}
proc.communicate(**kwargs)
# On OSX sometimes the last entry can be None
memories = [mem for mem in memories if mem is not None] + [0.]
memory_base = max(memories)
return memory_base
示例2: __init__
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def __init__(self, *args, **kwargs):
super(InterpreterInput, self).__init__(*args, **kwargs)
self.register_event_type('on_request_completions')
self.register_event_type('on_clear_completions')
self.register_event_type('on_get_completions')
if platform != 'android':
from pygments.lexers import PythonLexer
self.lexer = PythonLexer()
App.get_running_app().bind(on_pause=self.on_pause)
# self.text = '''for i in range(5):
# print(i)
# time.sleep(1)'''
示例3: parallel
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def parallel(function, argument_list, threads):
""" Based on: https://gist.github.com/admackin/003dd646e5fadee8b8d6 """
import multiprocessing as mp
import signal
import time
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
pool = mp.Pool(threads, init_worker)
try:
results = []
for arguments in argument_list:
p = pool.apply_async(function, args=arguments)
results.append(p)
pool.close()
while True:
if all(r.ready() for r in results):
for r in results: # catches errors in child process
r.get()
return
time.sleep(1)
except KeyboardInterrupt:
pool.terminate()
pool.join()
sys.exit("\nKeyboardInterrupt")
示例4: he_control_loop
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def he_control_loop(dummy,state):
from time import sleep
import RPi.GPIO as GPIO
import config as conf
GPIO.setmode(GPIO.BCM)
GPIO.setup(conf.he_pin, GPIO.OUT)
GPIO.output(conf.he_pin,0)
heating = False
try:
while True:
avgpid = state['avgpid']
if state['is_awake'] == False :
state['heating'] = False
GPIO.output(conf.he_pin,0)
sleep(1)
else:
if avgpid >= 100 :
state['heating'] = True
GPIO.output(conf.he_pin,1)
sleep(1)
elif avgpid > 0 and avgpid < 100:
state['heating'] = True
GPIO.output(conf.he_pin,1)
sleep(avgpid/100.)
GPIO.output(conf.he_pin,0)
sleep(1-(avgpid/100.))
state['heating'] = False
else:
GPIO.output(conf.he_pin,0)
state['heating'] = False
sleep(1)
finally:
GPIO.output(conf.he_pin,0)
GPIO.cleanup()
示例5: check_time
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def check_time(timer_id):
"""Add check points in a single line.
This method is suitable for running a task on a list of items. A timer will
be registered when the method is called for the first time.
:Example:
>>> import time
>>> import mmcv
>>> for i in range(1, 6):
>>> # simulate a code block
>>> time.sleep(i)
>>> mmcv.check_time('task1')
2.000
3.000
4.000
5.000
Args:
timer_id (str): Timer identifier.
"""
if timer_id not in _g_timers:
_g_timers[timer_id] = Timer()
return 0
else:
return _g_timers[timer_id].since_last_check()
示例6: wait
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def wait(i=10):
""" Wraps 'time.sleep()' with logger output """
logger.debug('Waiting %d sec... (%.2fmin)', i, i / 60.0)
sleep(i)
示例7: test_popen_streaming_output_timeout
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def test_popen_streaming_output_timeout():
start = time()
with pytest.raises(TimeoutError):
popen_streaming_output(
PYTHON + ' -c "import time; time.sleep(4)"',
lambda line: line, timeout=0.1,
)
assert (time() - start) < 3
示例8: patch_time
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def patch_time():
"""Replace :func:`time.sleep` with :func:`gevent.sleep`."""
from gevent.hub import sleep
import time
patch_item(time, 'sleep', sleep)
示例9: get_video
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def get_video(oversea, convert_m3u = False):
"""str->list
A full parser for getting video.
convert_m3u: [(URL, time_in_sec)]
else: [url,url]"""
rawurl = []
if oversea == '2':
raw_link = find_video_address_force_original(cid, BILIGRAB_HEADER)
rawurl = find_link_flvcd(raw_link)
elif oversea == '3':
rawurl = find_video_address_html5(vid, p, BILIGRAB_HEADER)
if rawurl == []: #As in #11
rawurl = find_video_address_html5(vid, p, FAKE_HEADER)
elif oversea == '4':
rawurl = find_link_flvcd(videourl)
elif oversea == '5':
rawurl = find_video_address_pr(cid, 1080, BILIGRAB_HEADER)
if '404' in rawurl[0]:
logging.info('Using lower quality...')
rawurl = find_video_address_pr(cid, 720, BILIGRAB_HEADER)
if '404' in rawurl[0]:
logging.error('Failed!')
rawurl = []
else:
pass
elif 'ERROR' in rawurl[0]:
logging.info('Wait a little bit...')
time.sleep(5)
rawurl = find_video_address_pr(cid, 1080, BILIGRAB_HEADER)
elif oversea == '6':
raw_link = find_video_address_force_original(cid, BILIGRAB_HEADER)
rawurl = find_link_you_get(raw_link)
else:
rawurl = find_video_address_normal_api(cid, BILIGRAB_HEADER, oversea, convert_m3u)
if 'API_BLOCKED' in rawurl[0]:
logging.warning('API header may be blocked! Using fake one instead...')
rawurl = find_video_address_normal_api(cid, FAKE_HEADER, oversea, convert_m3u)
return rawurl
#----------------------------------------------------------------------
示例10: _run_step
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def _run_step(self, test_id, index):
test = self.get_test(test_id)
if not test:
raise Exception("Unknown test")
cmd, selector, arg1, arg2 = test["steps"][index]
timeout = 5
if cmd == "wait":
return self.cli.wait(selector, timeout=timeout)
elif cmd == "wait_click":
self.cli.wait_click(selector, timeout=timeout)
return True
elif cmd == "wait_drag":
self.cli.wait_drag(
selector, target=arg1, duration=arg2, timeout=timeout)
return True
elif cmd == "assertExists":
return self.cli.wait(selector, timeout=timeout) is True
elif cmd == "assertNotExists":
return self.assertNotExists(self.cli, selector, timeout=timeout)
elif cmd == "assertAttributeValue":
attr_name = getarg(arg1)
attr_value = self.cli.getattr(selector, attr_name)
return bool(eval(arg1, {attr_name: attr_value}))
elif cmd == "setAttribute":
return self.cli.setattr(selector, arg1, eval(arg2))
elif cmd == "sendKeycode":
self.cli.send_keycode(selector)
return True
elif cmd == "sleep":
sleep(float(selector))
return True
elif cmd == "executeCode":
return self.cli.execute(selector)
示例11: assertNotExists
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def assertNotExists(self, cli, selector, timeout=-1):
start = time()
while True:
matches = cli.select(selector)
if not matches:
return True
if timeout == -1:
raise AssertionError("selector matched elements")
if timeout > 0 and time() - start > timeout:
raise Exception("Timeout")
sleep(0.1)
示例12: scheduler
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def scheduler(dummy,state):
import time
import sys
import schedule
from datetime import datetime
sys.stdout = open("scheduler.log", "a", buffering=0)
sys.stderr = open("scheduler.err.log", "a", buffering=0)
print "Starting scheduler thread ..."
last_wake = 0
last_sleep = 0
last_sched_switch = 0
while True:
if last_wake != state['wake_time'] or last_sleep != state['sleep_time'] or last_sched_switch != state['sched_enabled']:
schedule.clear()
if state['sched_enabled'] == True:
schedule.every().day.at(state['sleep_time']).do(gotosleep,1,state)
schedule.every().day.at(state['wake_time']).do(wakeup,1,state)
nowtm = float(datetime.now().hour) + float(datetime.now().minute)/60.
sleeptm = state['sleep_time'].split(":")
sleeptm = float(sleeptm[0]) + float(sleeptm[1])/60.
waketm = state['wake_time'].split(":")
waketm = float(waketm[0]) + float(waketm[1])/60.
if waketm < sleeptm:
if nowtm >= waketm and nowtm < sleeptm:
wakeup(1,state)
else:
gotosleep(1,state)
elif waketm > sleeptm:
if nowtm < waketm and nowtm >= sleeptm:
gotosleep(1,state)
else:
wakeup(1,state)
else:
wakeup(1,state)
last_wake = state['wake_time']
last_sleep = state['sleep_time']
last_sched_switch = state['sched_enabled']
schedule.run_pending()
time.sleep(1)
示例13: _do_query
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def _do_query(self, request_url, method, **kwargs):
tries = 0
max_tries = 2
lock_acquirer = False
resp = None
use_timeout = 30
# override default timeout
if 'timeout' in kwargs and isinstance(kwargs['timeout'], int):
use_timeout = kwargs['timeout']
kwargs.pop('timeout', None)
# remove un-needed kwargs
kwargs.pop('fetch_all_pages', None)
kwargs.pop('page_token_callback', None)
# do query
while tries < max_tries:
if self.token_refresh_lock.locked() and not lock_acquirer:
logger.debug("Token refresh lock is currently acquired. Trying again in 500ms...")
time.sleep(0.5)
continue
if method == 'POST':
resp = self.http.post(request_url, timeout=use_timeout, **kwargs)
elif method == 'PATCH':
resp = self.http.patch(request_url, timeout=use_timeout, **kwargs)
elif method == 'DELETE':
resp = self.http.delete(request_url, timeout=use_timeout, **kwargs)
else:
resp = self.http.get(request_url, timeout=use_timeout, **kwargs)
tries += 1
if resp.status_code == 401 and tries < max_tries:
# unauthorized error, lets refresh token and retry
self.token_refresh_lock.acquire(False)
lock_acquirer = True
logger.warning("Unauthorized Response (Attempts %d/%d)", tries, max_tries)
self.token['expires_at'] = time() - 10
self.http = self._new_http_object()
else:
break
return resp
示例14: handle
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def handle(self, *args, **options):
users = [line.strip() for line in file('/var/canvas/data/canvas_installed_users.csv')]
fb = facebook.GraphAPI(settings.FACEBOOK_APP_ACCESS_TOKEN)
def fb_call(fun, retries=0):
try:
return fun()
except (facebook.GraphAPIError, IOError):
if retries < 5:
time.sleep(retries + 0.01)
return fb_call(fun, retries + 1)
else:
raise
missing = 0
existing = 0
added = 0
try:
for n in range(0, len(users), 100):
fb_results = fb_call(lambda: fb.get_objects(users[n:n+100]))
for fbid, info in fb_results.items():
if "email" not in info:
print "no email", fbid
missing += 1
else:
try:
FacebookUser(
fb_uid=info['id'],
email=info['email'],
first_name=info['first_name'],
last_name=info['last_name'],
user=None
).save()
except IntegrityError:
existing += 1
else:
added += 1
print "Processed", n, "of", len(users)
finally:
print "Total", len(users)
print "Missing email", missing
print "Added", added
print "Existing", existing
示例15: start_process
# 需要导入模块: from time import time [as 别名]
# 或者: from time.time import sleep [as 别名]
def start_process(self):
url = "http://localhost:9901/jsonrpc"
process_start_timeout = 10
telenium_token = str(uuid4())
self.cli = cli = TeleniumHttpClient(url=url, timeout=10)
# entry no any previous telenium is running
try:
cli.app_quit()
sleep(2)
except:
pass
# prepare the application
entrypoint = self.session["settings"]["entrypoint"]
print(self.session)
args = shlex.split(self.session["settings"].get("args", ""))
cmd = [sys.executable, "-m", "telenium.execute", entrypoint] + args
cwd = dirname(entrypoint)
if not os.path.isabs(cwd):
cwd = os.getcwd()
env = os.environ.copy()
env.update(self.session["env"])
env["TELENIUM_TOKEN"] = telenium_token
# start the application
self.t_process = subprocess.Popen(cmd, env=env, cwd=cwd)
# wait for telenium server to be online
start = time()
while True:
try:
if cli.app_ready():
break
except Exception:
if time() - start > process_start_timeout:
raise Exception("timeout")
sleep(1)
# ensure the telenium we are connected are the same as the one we
# launched here
if cli.get_token() != telenium_token:
raise Exception("Connected to another telenium server")
self.send_object(["status", "running"])