本文整理汇总了Python中asyncio.Future.set_result方法的典型用法代码示例。如果您正苦于以下问题:Python Future.set_result方法的具体用法?Python Future.set_result怎么用?Python Future.set_result使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio.Future
的用法示例。
在下文中一共展示了Future.set_result方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: filter_stderr
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def filter_stderr(popen:subprocess.Popen, future:asyncio.Future):
last_ex = None
while True:
data = popen.stderr.readline()
if data:
log.ffmpeg("Data from ffmpeg: {}".format(data))
try:
if check_stderr(data):
sys.stderr.buffer.write(data)
sys.stderr.buffer.flush()
except FFmpegError as e:
log.ffmpeg("Error from ffmpeg: %s", str(e).strip())
last_ex = e
except FFmpegWarning:
pass # useless message
else:
break
if last_ex:
future.set_exception(last_ex)
else:
future.set_result(True)
示例2: as_future
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def as_future(fun, *args, **kwargs):
"""
Executes a function with the given arguments
and wraps the result into a future.
:param fun: The function to be called.
:type fun: func
:param args: The argument list for the supplied function.
:type args: list
:param kwargs: The keyword argument dict for the supplied function.
:type kwargs: dict
:return: The functions result wrapped in a Future
:rtype: asyncio.Future
"""
try:
res = fun(*args, **kwargs)
except Exception as e:
f = Future()
f.set_exception(e)
return f
else:
if isinstance(res, Future):
return res
elif iscoroutine(res):
return asyncio.Task(res)
else:
f = Future()
f.set_result(res)
return f
示例3: filter_stderr
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def filter_stderr(popen:subprocess.Popen, future:asyncio.Future):
last_ex = None
while True:
data = popen.stderr.readline()
if data:
# print("FFmpeg says:", data, flush=True)
try:
if check_stderr(data):
sys.stderr.buffer.write(data)
sys.stderr.buffer.flush()
except FFmpegError as e:
print("Error from FFmpeg:", e)
last_ex = e
except FFmpegWarning:
pass # useless message
else:
break
if last_ex:
future.set_exception(last_ex)
else:
future.set_result(True)
示例4: __init__
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
class Tester:
def __init__(self):
self.end = Future()
def __call__(self, *args, **kwargs):
if not self.end.done():
self.end.set_result((args, kwargs))
示例5: test_json_with_async_string2
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def test_json_with_async_string2(self):
d = Future()
astr = wsgi.AsyncString(d)
response = wsgi.Json({'bla': astr})
self.assertEqual(len(response.children), 1)
result = response.render()
self.assertIsInstance(result, Future)
d.set_result('ciao')
result = yield result
self.assertEqual(result, json.dumps({'bla': 'ciao'}))
示例6: side_effect
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def side_effect(*args, **kwargs):
def _side_effect(*args, **kwargs):
fut = Future()
fut.set_result({'origin': '127.0.0.1'})
return fut
resp = Mock()
resp.json.side_effect = resp.release.side_effect = _side_effect
fut = Future()
fut.set_result(resp)
return fut
示例7: js_query
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def js_query(self, query) -> Future:
if self.connected:
self.js_exec(query, self._reqid)
fut = Future()
self._tasks[self._reqid] = fut
self._reqid += 1
return fut
else:
fut = Future()
fut.set_result(None)
return fut
示例8: CustomWSClientProtocol
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
class CustomWSClientProtocol(WebSocketClientProtocol):
"""Add auto-ping switch (dirty way) and let us start handshaking manually."""
# this framework mix camel and underline naming style, nice!
def __init__(self):
WebSocketClientProtocol.__init__(self)
self.customUriPath = '/'
self.customWsKey = None
self._delayedHandshake = Future()
def setAutoPing(self, interval, timeout):
"""Set auto-ping interval. Start it if it's not running."""
self.disableAutoPing()
self.autoPingInterval = interval
self.autoPingTimeout = timeout
self.autoPingPendingCall = loop.call_later(interval, self._sendAutoPing)
def disableAutoPing(self):
if self.autoPingPendingCall:
self.autoPingPendingCall.cancel()
self.autoPingPendingCall = None
def startHandshake(self):
"""Delay handshake because some states must be set right before handshake (so
they can't be set in factory)."""
self._delayedHandshake.set_result(None)
@coroutine
def restartHandshake(self):
"""Resume delayed handshake. It enable us to customize handshake HTTP header."""
yield from wait_for(self._delayedHandshake, None)
if config.compatible:
self.websocket_key = base64.b64encode(os.urandom(16))
else:
self.websocket_key = self.customWsKey
request = [
'GET %s HTTP/1.1' % self.customUriPath,
'Host: %s:%d' % (self.factory.host, self.factory.port),
'Sec-WebSocket-Key: %s' % self.websocket_key.decode(),
'Sec-WebSocket-Version: %d' % self.SPEC_TO_PROTOCOL_VERSION[self.version],
'Pragma: no-cache',
'Cache-Control: no-cache',
'Connection: Upgrade',
'Upgrade: WebSocket',
]
if config.compatible:
# store custom ws key in cookie to prevent it from being changed by ws proxy
request.append('Cookie: %s=%s' % (config.cookie_key, self.customWsKey.decode()))
if self.factory.useragent:
request.append('User-Agent: %s' % self.factory.useragent)
self.http_request_data = '\r\n'.join(request).encode('utf8') + b'\r\n\r\n'
self.sendData(self.http_request_data)
if self.debug:
self.log.debug(request)
示例9: go
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def go():
future = Future()
future.set_result(42)
source = Observable.from_future(future)
def on_next(x):
success[0] = 42 == x
def on_error(err):
success[1] = False
def on_completed():
success[2] = True
subscription = source.subscribe(on_next, on_error, on_completed)
示例10: _as_future
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def _as_future(fun, *args, **kwargs):
try:
res = fun(*args, **kwargs)
except Exception as e:
f = Future()
f.set_exception(e)
return f
else:
if isinstance(res, Future):
return res
elif iscoroutine(res):
return asyncio.Task(res)
else:
f = Future()
f.set_result(res)
return f
示例11: go
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def go():
future = Future()
future.set_result(42)
source = rx.from_future(future)
def on_next(x):
success[0] = x == 42
def on_error(err):
success[1] = False
def on_completed():
success[2] = True
source.subscribe(on_next, on_error, on_completed)
示例12: _uwsgi_entry_point
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
async def _uwsgi_entry_point(self, current_greenlet: greenlet.greenlet, future: asyncio.Future,
*args, **kwargs):
"""
uWSGI wrapper entry point.
"""
try:
# Call the underlying wrapped function.
result = await func(self, *args, **kwargs)
except Exception as e:
# Set the exception on the Future, allowing the web server to retrieve it.
future.set_exception(e)
else:
# Set the result of the function on the Future.
future.set_result(result)
finally:
# Switch back context.
current_greenlet.switch()
示例13: multi_future
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
def multi_future(children, quiet_exceptions=()):
"""
Wraps multiple futures in a single future.
:param quiet_exceptions:
:param children:
"""
if isinstance(children, dict):
keys = list(children.keys())
children = list(children.values())
else:
keys = None
unfinished_children = set(children)
future = Future()
if not children:
future.set_result({} if keys is not None else [])
def callback(ft):
unfinished_children.remove(ft)
if not unfinished_children:
result_list = []
for ft in children:
try:
result_list.append(ft.result())
except Exception as e:
if future.done():
if not isinstance(e, quiet_exceptions):
print("Multiple exceptions in yield list",
file=sys.stderr)
else:
future.set_exception(sys.exc_info())
if not future.done():
if keys is not None:
future.set_result(dict(list(zip(keys, result_list))))
else:
future.set_result(result_list)
listening = set()
for f in children:
if f not in listening:
listening.add(f)
f.add_done_callback(callback)
return future
示例14: test_ticks_pong
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
async def test_ticks_pong(make_transport, make_fut):
transp = make_transport()
pong = WSMessage(type=WSMsgType.PONG, data=b"", extra="")
close = WSMessage(type=WSMsgType.closing, data=b"", extra="")
future = Future()
future.set_result(pong)
future2 = Future()
future2.set_result(close)
ws = mock.Mock()
ws.receive.side_effect = [future, future2]
session = transp.session
await transp.client(ws, session)
assert session._tick.called
示例15: __init__
# 需要导入模块: from asyncio import Future [as 别名]
# 或者: from asyncio.Future import set_result [as 别名]
class MessageDialog:
def __init__(self, title, text):
self.future = Future()
def set_done():
self.future.set_result(None)
ok_button = Button(text='OK', handler=(lambda: set_done()))
self.dialog = Dialog(
title=title,
body=HSplit([
Label(text=text),
]),
buttons=[ok_button],
width=D(preferred=80),
modal=True)
def __pt_container__(self):
return self.dialog