100+ results for 'python asyncio wait_for'

Not the results you expected?

timeout.py (https://gitlab.com/llndhlov/journly) Python · 127 lines

17

18 Useful in cases when you want to apply timeout logic around block

19 of code or in cases when asyncio.wait_for is not suitable. For example:

20

21 >>> with timeout(0.001):

79 def _do_enter(self) -> "timeout":

80 # Support Tornado 5- without timeout

81 # Details: https://github.com/python/asyncio/issues/392

82 if self._timeout is None:

83 return self

114

115

116 def current_task(loop: asyncio.AbstractEventLoop) -> "Optional[asyncio.Task[Any]]":

117 if sys.version_info >= (3, 7):

118 task = asyncio.current_task(loop=loop)

matrix_sso_helper.py (https://github.com/poljar/weechat-matrix.git) Python · 137 lines

1 #!/usr/bin/env -S python3 -u

2 # Copyright 2019 The Matrix.org Foundation CIC

3 #

15

16

17 import asyncio

18 import argparse

19 import socket

37

38 async def shutdown():

39 await asyncio.sleep(1)

40 raise KeyboardInterrupt

41

53 to_weechat(message)

54 # Initiate a shutdown.

55 shutdown_task = asyncio.ensure_future(shutdown())

56 # Respond to the browser.

57 return web.Response(text="Continuing in Weechat.")

test_asgi.py (https://github.com/pgjones/quart.git) Python · 228 lines

87 request = connection._create_request_from_scope(lambda: None)

88

89 queue: asyncio.Queue = asyncio.Queue()

90 queue.put_nowait(request_message)

91

119 connection = ASGIWebsocketConnection(app, scope)

120

121 queue: asyncio.Queue = asyncio.Queue()

122 queue.put_nowait({"type": "websocket.connect"})

123

130

131 # This test fails if a timeout error is raised here

132 await asyncio.wait_for(connection(receive, send), timeout=1)

133

134

test_liquid_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 128 lines

1 #!/usr/bin/env python

2 from os.path import (

3 join,

11 TradeType

12 )

13 import asyncio

14 import logging

15 import math

41 @classmethod

42 def setUpClass(cls):

43 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

44 cls.order_book_tracker: LiquidOrderBookTracker = LiquidOrderBookTracker(cls.trading_pairs)

45

46 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

47 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

48

PeripheralDelegate.py (https://github.com/hbldh/bleak.git) Python · 436 lines

48

49 class PeripheralDelegate(NSObject):

50 """macOS conforming python class for managing the PeripheralDelegate for BLE"""

51

52 ___pyobjc_protocols__ = [CBPeripheralDelegate]

127 event = self._characteristic_read_events.get_cleared(cUUID)

128 self.peripheral.readValueForCharacteristic_(characteristic)

129 await asyncio.wait_for(event.wait(), timeout=5)

130 if characteristic.value():

131 return characteristic.value()

225 )

226

227 @objc.python_method

228 def did_discover_characteristics_for_service(

229 self, peripheral: CBPeripheral, service: CBService, error: NSError

iorw_to.py (https://github.com/peterhinch/micropython-async.git) Python · 143 lines

12

13 import io, pyb

14 import uasyncio as asyncio

15 import micropython

16 import sys

17 try:

18 print('Uasyncio version', asyncio.version)

19 if not isinstance(asyncio.version, tuple):

101 # Note that trapping the exception and returning is still mandatory.

102 async def receiver(myior):

103 sreader = asyncio.StreamReader(myior)

104 try:

105 while True:

123

124 async def run(coro, t):

125 await asyncio.wait_for_ms(coro, t)

126

127 async def do_test(loop, t):

test_cancel_token.py (https://github.com/QuarkChain/pyquarkchain.git) Python · 179 lines

110 )

111 token_wait_coroutine = token.wait()

112 done, pending = await asyncio.wait([token_wait_coroutine], timeout=0.1)

113 assert len(done) == 0

114 assert len(pending) == 1

140 async def test_cancellable_wait_cancels_subtasks_when_cancelled(event_loop):

141 token = CancelToken("")

142 future = asyncio.ensure_future(token.cancellable_wait(asyncio.sleep(2)))

143 with pytest.raises(asyncio.TimeoutError):

144 # asyncio.wait_for() will timeout and then cancel our cancellable_wait() future, but

145 # Task.cancel() doesn't immediately cancels the task

146 # (https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel), so we need

147 # the sleep below before we check that the task is actually cancelled.

148 await asyncio.wait_for(future, timeout=0.01)

170 async def assert_only_current_task_not_done():

171 # This sleep() is necessary because Task.cancel() doesn't immediately cancels the task:

172 # https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel

173 await asyncio.sleep(0.01)

client.py (https://github.com/kergoth/bitbake.git) Python · 172 lines

4

5 import abc

6 import asyncio

7 import json

8 import os

24 async def connect_tcp(self, address, port):

25 async def connect_sock():

26 return await asyncio.open_connection(address, port)

27

28 self._connect_sock = connect_sock

30 async def connect_unix(self, path):

31 async def connect_sock():

32 return await asyncio.open_unix_connection(path)

33

34 self._connect_sock = connect_sock

74 async def get_line():

75 try:

76 line = await asyncio.wait_for(self.reader.readline(), self.timeout)

77 except asyncio.TimeoutError:

staggered.py (https://gitlab.com/Alioth-Project/clang-r445002) Python · 149 lines

41 try:

42 # do work

43 except asyncio.CancelledError:

44 # undo partially completed work

45 raise

85 if previous_failed is not None:

86 with contextlib.suppress(exceptions_mod.TimeoutError):

87 # Use asyncio.wait_for() instead of asyncio.wait() here, so

88 # that if we get cancelled at this point, Event.wait() is also

89 # cancelled, otherwise there will be a "Task destroyed but it is

90 # pending" later.

91 await tasks.wait_for(previous_failed.wait(), delay)

92 # Get the next coroutine to run

93 try:

epochs_test.py (https://github.com/Conflux-Chain/conflux-rust.git) Python · 151 lines

1 #!/usr/bin/env python3

2

3 # allow imports from parent directory

6 sys.path.insert(1, os.path.join(sys.path[0], '..'))

7

8 import asyncio

9

10 from conflux.rpc import RpcClient

54

55 # wait for phase changes to complete

56 self.nodes[FULLNODE0].wait_for_phase(["NormalSyncPhase"])

57 self.nodes[FULLNODE1].wait_for_phase(["NormalSyncPhase"])

139 def run_test(self):

140 assert(SHORT_FORK_LEN < LONG_FORK_LEN)

141 asyncio.get_event_loop().run_until_complete(self.run_async())

142

143 def generate_chain(self, parent, len):

binance_api_user_stream_data_source.py (https://github.com/CoinAlpha/hummingbot.git) Python · 148 lines

71 while True:

72 try:

73 msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)

74 self._last_recv_time = time.time()

75 yield msg

77 try:

78 pong_waiter = await ws.ping()

79 await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)

80 self._last_recv_time = time.time()

81 except asyncio.TimeoutError:

101 return websockets.connect(stream_url)

102

103 async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):

104 try:

105 while True:

pexpect-4.8.0-py311.patch (https://gitlab.com/redcore/portage) Patch · 67 lines

2 From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= <miro@hroncok.cz>

3 Date: Thu, 24 Mar 2022 15:15:33 +0100

4 Subject: [PATCH] Convert @asyncio.coroutine to async def

5

6 This is required for Python 3.11+ support.

19 from pexpect import EOF

20

21 -@asyncio.coroutine

22 -def expect_async(expecter, timeout=None):

23 +async def expect_async(expecter, timeout=None):

29 pw = PatternWaiter()

30 pw.set_expecter(expecter)

31 - transport, pw = yield from asyncio.get_event_loop()\

32 + transport, pw = await asyncio.get_event_loop()\

38 transport.resume_reading()

39 try:

40 - return (yield from asyncio.wait_for(pw.fut, timeout))

41 + return (await asyncio.wait_for(pw.fut, timeout))

utilities.md (https://github.com/plone/guillotina.git) Markdown · 127 lines

2

3 An async utility is an object instantiation with an async function that is run

4 persistently on the asyncio event loop. It is useful for long running tasks.

5

6 For our training, we're going to use an async utility with a queue to send

55 while not self._closed:

56 try:

57 message, summary = await asyncio.wait_for(self._queue.get(), 0.2)

58 for user_id in message.__parent__.users:

59 for ws in self._webservices:

60 if ws.user_id == user_id:

61 await ws.send_str(orjson.dumps(summary))

62 except (RuntimeError, asyncio.CancelledError, asyncio.TimeoutError):

63 pass

64 except Exception:

test_generators.py (https://github.com/WoLpH/python-utils.git) Python · 67 lines

8 @pytest.mark.asyncio

9 async def test_abatcher():

10 async for batch in python_utils.abatcher(python_utils.acount(stop=9), 3):

11 assert len(batch) == 3

12

13 async for batch in python_utils.abatcher(python_utils.acount(stop=2), 3):

14 assert len(batch) == 2

15

41

42 # Test if exceptions are handled correctly

43 await asyncio.wait_for(asyncio.sleep(1), timeout=0.05)

44

45 # Test if StopAsyncIteration is handled correctly

test_radar_relay_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 119 lines

1 #!/usr/bin/env python

2 import math

3 from os.path import join, realpath

10 TradeType

11 )

12 import asyncio

13 import logging

14 import unittest

38 @classmethod

39 def setUpClass(cls):

40 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

41 cls.order_book_tracker: RadarRelayOrderBookTracker = RadarRelayOrderBookTracker(

42 trading_pairs=cls.trading_pairs

43 )

44 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

45 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

46

crypto_com_websocket.py (https://github.com/CoinAlpha/hummingbot.git) Python · 127 lines

1 #!/usr/bin/env python

2 import asyncio

45 await self._emit("public/auth", None)

46 # TODO: wait for response

47 await asyncio.sleep(1)

48

49 return self._client

63 while True:

64 try:

65 raw_msg_str: str = await asyncio.wait_for(self._client.recv(), timeout=self.MESSAGE_TIMEOUT)

66 raw_msg = ujson.loads(raw_msg_str)

67 if "method" in raw_msg and raw_msg["method"] == "public/heartbeat":

71 except asyncio.TimeoutError:

72 await asyncio.wait_for(self._client.ping(), timeout=self.PING_TIMEOUT)

73 except asyncio.TimeoutError:

protocol.pyx (https://github.com/edgedb/edgedb.git) Cython · 145 lines

18

19

20 import asyncio

21 import re

22 import time

23

24 from edgedb import con_utils

25 from edgedb.protocol.asyncio_proto cimport AsyncIOProtocol

26 from edgedb.protocol.protocol cimport ReadBuffer, WriteBuffer

27

134 before = time.monotonic()

135 try:

136 tr, pr = await asyncio.wait_for(connector, timeout=timeout)

137 finally:

138 timeout -= time.monotonic() - before

services.rst (https://github.com/ask/mode.git) ReStructuredText · 249 lines

88 1) Using ``add_dependency()`` in ``__post_init__``:

89

90 .. sourcecode:: python

91

92 class MyService(Service):

97 2) Using ``add_dependency()`` in ``on_start``:

98

99 .. sourcecode:: python

100

101 class MyService(Service):

109 of service instances:

110

111 .. sourcecode:: python

112

113 from typing import Iterable

test_mixed.py (https://github.com/aio-libs/janus.git) Python · 234 lines

1 import asyncio

2 import sys

3 import unittest

12 sys.version_info < (3, 7),

13 reason="forbidding implicit loop creation works on "

14 "Python 3.7 or higher only",

15 )

16 def test_ctor_noloop(self):

18 janus.Queue()

19

20 @pytest.mark.asyncio

21 async def test_maxsize(self):

22 q = janus.Queue(5)

23 self.assertIs(5, q.maxsize)

24

25 @pytest.mark.asyncio

26 async def test_maxsize_named_param(self):

27 q = janus.Queue(maxsize=7)

owner.py (https://github.com/Beefywhale/WeenieBot.git) Python · 181 lines

6 import sys

7 import discord

8 import asyncio

9

10 with open("database/adminweenie.json","r") as infile:

124

125

126 '''runs python code.'''

127 async def eval_logic(message, client):

128 if str(message.author.id) in client.bot_info.owner.id:

131 evalt = message.content.replace(message.content.split()[0] + ' ', '')

132 if len(str(eval(evalt))) >= 2000:

133 await client.send_message(message.channel, '```Python\n' + str(eval(evalt))[:1990] + '```' + '__Truncated!__')

134 else:

135 await client.send_message(message.channel, '```Python\n' + str(eval(evalt)) + '```')

rpc.py (https://github.com/primal100/pybitcointools.git) Python · 144 lines

1 #!/usr/bin/env python3

2 #

3 # Copyright (c) 2016, Neil Booth

11

12

13 import asyncio

14 import json

15 import random

28 self.result = {}

29

30 async def wait_for_response(self, id_):

31 from datetime import datetime

32 now = datetime.now()

116 coro = self.rpc_client.wait_for_response(id_)

117 coroutines.append(asyncio.wait_for(coro, self.timeout))

118 except asyncio.TimeoutError:

demo_await_object.py (https://github.com/mingz2013/study.python.git) Python · 136 lines

49 # Future 是一种特殊的低层级可等待对象,表示一个异步操作的最终结果。

50 # 当一个Future对象被等待,这意味着协程将保持等待直到该Future对象在其他地方操作完毕。

51 # 在asyncio中需要Future对象以便允许通过async/await使用基于回调的代码。

52 # 通常情况下 没有必要 在应用层级的代码中创建Future对象。

53

59 # await asyncio.gather(

60 # function_that_returns_a_future_obejct(),

61 # some_python_coroutine()

62 # )

63 pass

89 await asyncio.sleep(1)

90

91 asyncio.run(display_date())

92

93

110 async def main8():

111 try:

112 await asyncio.wait_for(asyncio.sleep(100), timeout=1.0)

113 except asyncio.TimeoutError:

test_snapshot.py (https://github.com/aio-libs/aioes.git) Python · 159 lines

2 import shutil

3 import random

4 import asyncio

5 import tempfile

6

41 '''

42 Sice elasticsearch may be launched under the other user,

43 tempfile.TemporaryDirectory can't be used, because python

44 can't cleanup it after elasticsearch user.

45 So we are just leaving it there.

74

75 @pytest.mark.xfail(reason="Elasticsearch setting repo.path must be configured")

76 @asyncio.coroutine

77 def test_repository(client, repo_path, repo_name):

78 ret = yield from client.snapshot.get_repository()

test_kucoin_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 128 lines

1 #!/usr/bin/env python

2 import math

3 from os.path import join, realpath

10 TradeType

11 )

12 import asyncio

13 import logging

14 from typing import (

38 @classmethod

39 def setUpClass(cls):

40 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

41 cls.order_book_tracker: KucoinOrderBookTracker = KucoinOrderBookTracker(

42 trading_pairs=cls.trading_pairs

43 )

44 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

45 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

46

clients.py (https://github.com/MailRuChamps/miniaicups.git) Python · 250 lines

1 import os

2 import asyncio

3 import datetime

4 import gzip

70

71

72 class SimplePythonClient(Client):

73 def __init__(self):

74 self.command = None

170

171 async def set_solution_id(self):

172 hello_json = await asyncio.wait_for(self.reader.readline(), timeout=CONSTS.REQUEST_MAX_TIME)

173 try:

174 self.solution_id = json.loads(hello_json.decode('utf-8')).get('solution_id')

189 try:

190 before = datetime.datetime.now()

191 z = await asyncio.wait_for(self.reader.readline(), timeout=CONSTS.REQUEST_MAX_TIME)

192 if not z:

193 raise ConnectionError('Connection closed')

notifier_test.py (https://github.com/hardbyte/python-can.git) Python · 58 lines

1 #!/usr/bin/env python

2 # coding: utf-8

3

4 import unittest

5 import time

6 import asyncio

7

8 import can

41

42 class AsyncNotifierTest(unittest.TestCase):

43 def test_asyncio_notifier(self):

44 loop = asyncio.get_event_loop()

48 msg = can.Message()

49 bus.send(msg)

50 future = asyncio.wait_for(reader.get_message(), 1.0)

51 recv_msg = loop.run_until_complete(future)

52 self.assertIsNotNone(recv_msg)

electrumx_rpc.py (https://bitbucket.org/arfonzo/electrumx4egc.git) Python · 93 lines

1 #!/usr/bin/env python3

2 #

3 # Copyright (c) 2016, Neil Booth

12

13 import argparse

14 import asyncio

15 import json

16 from functools import partial

28 self.max_buffer_size = 5*10**6

29

30 async def wait_for_response(self):

31 await self.items_event.wait()

32 await self.process_pending_items()

57 coro = rpc_client.wait_for_response()

58 loop.run_until_complete(asyncio.wait_for(coro, timeout))

59 except asyncio.TimeoutError:

multi_robot_independent.py (https://github.com/anki/cozmo-python-sdk.git) Python · 56 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

20 '''

21

22 import asyncio

23 import sys

24

28

29 async def turn_left(sdk_conn):

30 robot = await sdk_conn.wait_for_robot()

31 cozmo.logger.info("Turning robot 1")

32 await robot.turn_in_place(degrees(90)).wait_for_completed()

33

34 async def turn_right(sdk_conn):

35 robot = await sdk_conn.wait_for_robot()

36 cozmo.logger.info("Turning robot 2")

37 await robot.turn_in_place(degrees(-90)).wait_for_completed()

web_searcher.py (https://github.com/allenai/document-qa.git) Python · 93 lines

4

5 import ujson

6 import asyncio

7 from aiohttp import ClientSession

8 from os.path import exists

51 TriviaQA used boilerpipe (https://github.com/kohlschutter/boilerpipe) to extract the

52 "main" pieces of text from web documents. There is, far as I can tell, no complete

53 python re-implementation so far the moment we shell out to a jar file (boilerpipe.jar)

54 which downloads files from the given URLs and runs them through boilerpipe's extraction code

55 using multiple threads.

79

80 async def get_text(self, urls: List[str]) -> List[ExtractedWebDoc]:

81 process = await asyncio.create_subprocess_exec(

82 "java", "-jar", self.JAR, *urls, "-t", str(self.n_threads),

83 "-l", str(self.timeout),

84 stdout=asyncio.subprocess.PIPE)

85 stdout, stderr = await asyncio.wait_for(process.communicate(),

86 timeout=self.proc_timeout)

87 text = stdout.decode("utf-8")

README.rst (https://github.com/aio-libs/async-timeout.git) ReStructuredText · 99 lines

6 :target: https://codecov.io/gh/aio-libs/async-timeout

7 .. image:: https://img.shields.io/pypi/v/async-timeout.svg

8 :target: https://pypi.python.org/pypi/async-timeout

9 .. image:: https://badges.gitter.im/Join%20Chat.svg

10 :target: https://gitter.im/aio-libs/Lobby

11 :alt: Chat on Gitter

12

13 asyncio-compatible timeout context manager.

14

15

19

20 The context manager is useful in cases when you want to apply timeout

21 logic around block of code or in cases when ``asyncio.wait_for()`` is

22 not suitable. Also it's much faster than ``asyncio.wait_for()``

32 happens.

33 2. Otherwise ``inner()`` is cancelled internally by sending

34 ``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is

35 raised outside of context manager scope.

36

test_crypto_com_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 107 lines

1 #!/usr/bin/env python

2 from os.path import join, realpath

3 import sys; sys.path.insert(0, realpath(join(__file__, "../../../../../")))

4 import math

5 import time

6 import asyncio

7 import logging

8 import unittest

27 @classmethod

28 def setUpClass(cls):

29 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

30 cls.order_book_tracker: CryptoComOrderBookTracker = CryptoComOrderBookTracker(cls.trading_pairs)

31 cls.order_book_tracker.start()

41

42 async def run_parallel_async(self, *tasks, timeout=None):

43 future: asyncio.Future = asyncio.ensure_future(asyncio.gather(*tasks))

44 timer = 0

45 while not future.done():

test_aioh2.py (https://github.com/decentfox/aioh2.git) Python · 339 lines

112 else:

113 try:

114 yield from asyncio.wait_for(

115 self.server.read_stream(stream_id, -1), 0.1)

116 except asyncio.TimeoutError:

221

222 try:

223 yield from asyncio.wait_for(

224 self.server.send_data(stream_id, b'34'), 0.1)

225 except asyncio.TimeoutError:

234

235 try:

236 yield from asyncio.wait_for(

237 self.server.send_data(stream_id, b'5678'), 0.1)

238 except asyncio.TimeoutError:

__init__.py (https://github.com/wwqgtxx/wwqLyParse.git) Python · 115 lines

15

16 Useful in cases when you want to apply timeout logic around block

17 of code or in cases when asyncio.wait_for is not suitable. For example:

18

19 >>> with timeout(0.001):

68 def _do_enter(self) -> 'timeout':

69 # Support Tornado 5- without timeout

70 # Details: https://github.com/python/asyncio/issues/392

71 if self._timeout is None:

72 return self

103

104

105 def current_task(loop: asyncio.AbstractEventLoop) -> 'asyncio.Task[Any]':

106 if PY_37:

107 task = asyncio.current_task(loop=loop) # type: ignore

test_dispatcher.py (https://github.com/rmorshea/idom.git) Python · 178 lines

1 import asyncio

2 import sys

3 from typing import Any, Sequence

36 # received all the events, they might not have been sent since the two callbacks are

37 # executed in separate loops.

38 sem = asyncio.Semaphore(0)

39

40 async def send(patch):

94 events, expected_model = make_events_and_expected_model()

95 changes, send, recv = make_send_recv_callbacks(events)

96 await asyncio.wait_for(dispatch_single_view(Layout(Counter()), send, recv), 1)

97 assert_changes_produce_expected_model(changes, expected_model)

98

127 with pytest.raises(asyncio.TimeoutError):

128 await asyncio.wait_for(dispatch_future, timeout=1)

129

130 dispatch_future.cancel()

07_lookaround.py (https://github.com/anki/cozmo-python-sdk.git) Python · 74 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

20 '''

21

22 import asyncio

23

24 import cozmo

33

34 try:

35 cube = robot.world.wait_for_observed_light_cube(timeout=30)

36 print("Found cube", cube)

37

38 except asyncio.TimeoutError:

39 print("Didn't find a cube :-(")

40

pool.py (https://github.com/aiokitchen/aiomisc.git) Python · 225 lines

79 _tasks: Set[Any]

80 _used: Set[Any]

81 _instances: asyncio.Queue

82 _recycle_bin: asyncio.Queue

87 ), "recycle should be positive number or None"

88

89 self._loop = asyncio.get_event_loop()

90

91 self._instances = asyncio.Queue()

92 self._recycle_bin = asyncio.Queue()

93

94 self._semaphore = asyncio.Semaphore(maxsize)

210 log.exception("Exception when task execution")

211

212 await asyncio.wait_for(

213 asyncio.gather(

launchpad.py (https://github.com/fluentpython/concurrency.git) Python · 120 lines

1 #!/usr/bin/env python3

2

3 """

4 Brett Cannon's launchpad: concurrent countdowns driven by a custom event loop,

5 without `asyncio`. This example shows how `async/await` is independent of

6 `asyncio` or any specific asynchronous programming library.

7

8 Source: "How the heck does async/await work in Python 3.5?"

9 https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/

25 implement comparison methods, triggering an exception.

26

27 Think of this as being like asyncio.Task/curio.Task.

28 """

29

TCP_monitor.py (https://github.com/Dawnnnnnn/bilibili-live-tools.git) Python · 160 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3 # @Time : 2019/12/30 13:24

5 # @Contact: 1050596704@qq.com

6

7 import asyncio

8 import json

9 import traceback

36 while True:

37 try:

38 reader, writer = await asyncio.open_connection(host, port)

39 self._reader = reader

40 self._writer = writer

95 async def ReadSocketData(self):

96 try:

97 header = await asyncio.wait_for(self._reader.read(4), timeout=35.0)

98 except Exception:

99 Printer().printer("与服务器连接断开", "Error", "red")

condition.py (https://github.com/peterhinch/micropython-async.git) Python · 68 lines

5

6 try:

7 import uasyncio as asyncio

8 except ImportError:

9 import asyncio

14 class Condition():

15 def __init__(self, lock=None):

16 self.lock = asyncio.Lock() if lock is None else lock

17 self.events = []

18

53 if not self.lock.locked():

54 raise RuntimeError('Condition wait with lock not acquired.')

55 ev = asyncio.Event()

56 self.events.append(ev)

57 self.lock.release()

README.md (https://github.com/HDE/arsenic.git) Markdown · 43 lines

9

10

11 Asynchronous webdriver client built on asyncio.

12

13

17

18

19 ```python

20

21 from arsenic import get_session

30 await session.get('http://example.com')

31 # wait up to 5 seconds to get the h1 element from the page

32 h1 = await session.wait_for_element(5, 'h1')

33 # print the text of the h1 element

34 print(await h1.get_text())

test_huobi_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 126 lines

1 #!/usr/bin/env python

2 import math

3 from os.path import join, realpath

10 TradeType

11 )

12 import asyncio

13 import logging

14 from typing import (

38 @classmethod

39 def setUpClass(cls):

40 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

41 cls.order_book_tracker: HuobiOrderBookTracker = HuobiOrderBookTracker(

42 trading_pairs=cls.trading_pairs

43 )

44 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

45 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

46

01_light_when_face.py (https://github.com/anki/cozmo-python-sdk.git) Python · 55 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

21 '''

22

23 import asyncio

24 import time

25

32 # Move lift down and tilt the head up

33 robot.move_lift(-3)

34 robot.set_head_angle(cozmo.robot.MAX_HEAD_ANGLE).wait_for_completed()

35

36 face = None

45 # Wait until we we can see another face

46 try:

47 face = robot.world.wait_for_observed_face(timeout=30)

48 except asyncio.TimeoutError:

liquid_api_user_stream_data_source.py (https://github.com/CoinAlpha/hummingbot.git) Python · 140 lines

1 #!/usr/bin/env python

2

3 import asyncio

53 return self._last_recv_time

54

55 async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):

56 """

57 *required

99 elif not event_type:

100 raise ValueError(f"Liquid Websocket message does not contain an event type - {diff_msg}")

101 except asyncio.CancelledError:

102 raise

103 except Exception:

116 try:

117 while True:

118 msg: str = await asyncio.wait_for(ws.recv(), timeout=Constants.MESSAGE_TIMEOUT)

119 yield msg

120 except asyncio.TimeoutError:

shipyard_cascade.sh (https://github.com/Azure/batch-shipyard.git) Shell · 204 lines

151 log DEBUG "Starting Cascade Docker mode"

152 # shellcheck disable=SC2086

153 PYTHONASYNCIODEBUG=1 ./cascade.py --mode docker \

154 --concurrent "$concurrent_source_downloads" \

155 --prefix "$prefix" \

160 log DEBUG "Starting Cascade Singularity mode"

161 # shellcheck disable=SC2086

162 PYTHONASYNCIODEBUG=1 ./cascade.py --mode singularity \

163 --concurrent "$concurrent_source_downloads" \

164 --prefix "$prefix" \

197 block_for_container_images() {

198 # wait for images via cascade

199 "${AZ_BATCH_NODE_STARTUP_DIR}"/wd/wait_for_images.sh "$block"

200 }

201

test_knownservers.py (https://github.com/facebookexperimental/doh-proxy.git) Python · 115 lines

1 #!/usr/bin/env python3

2 #

3 # Copyright (c) 2018-present, Facebook, Inc.

8 #

9

10 import asyncio

11 import asynctest

12 import dns

103 qname=domain, qtype="A"))

104 try:

105 await asyncio.wait_for(fut, self.test_timeout)

106 except asyncio.TimeoutError:

test_bamboo_relay_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 117 lines

1 #!/usr/bin/env python

2 from os.path import join, realpath

3 import sys; sys.path.insert(0, realpath(join(__file__, "../../../")))

4

5 import math

6 import asyncio

7 import logging

8 import unittest

42 @classmethod

43 def setUpClass(cls):

44 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

45 cls.order_book_tracker: BambooRelayOrderBookTracker = BambooRelayOrderBookTracker(

46 trading_pairs=cls.trading_pairs

47 )

48 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

49 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

50

test_coroutines.py (https://github.com/ScatterHQ/eliot.git) Python · 105 lines

2 Tests for coroutines.

3

4 Imported into test_coroutine.py when running tests under Python 3.5 or later;

5 in earlier versions of Python this code is a syntax error.

6 """

7

8 import asyncio

9 from unittest import TestCase

10

18 Log a message inside a new coroutine.

19 """

20 await asyncio.sleep(0.1)

21 with start_action(action_type="standalone"):

22 pass

35 Run a coroutine until it finishes.

36 """

37 loop = asyncio.get_event_loop()

38 futures = [asyncio.ensure_future(f()) for f in async_functions]

streaming.py (https://github.com/prawn-cake/vk-requests.git) Python · 152 lines

3

4 if sys.version_info <= (3, 4):

5 raise RuntimeError('Streaming API requires python version >= 3.4')

6

7 import requests

43 raise ValueError('Consumer function is already defined for this '

44 'Stream instance')

45 if not any([asyncio.iscoroutine(fn), asyncio.iscoroutinefunction(fn)]):

46 raise ValueError('Consumer function must be a coroutine')

47 self._consumer_fn = fn

88 logger.info('Running task with timeout %s sec', timeout)

89 loop.run_until_complete(

90 asyncio.wait_for(task, timeout=timeout))

91 else:

92 loop.run_until_complete(task)

README.md (https://github.com/mossblaser/aiomqtt.git) Markdown · 88 lines

4 This library implements a minimal Python 3

5 [asyncio](https://docs.python.org/3/library/asyncio.html) wrapper around the

6 MQTT client in [paho-mqtt](https://github.com/eclipse/paho.mqtt.python).

15 This library is as thin as possible, exposing the exact same API as the

16 original paho-mqtt `Client` object with blocking calls replaced with coroutines

17 and all callbacks being scheduled into the asyncio main event loop. It does not

18 attempt to introduce a more idiomatic asyncio API.

25 ```python

26 import asyncio

27 import aiomqtt

28

42 print("Connected!")

43

44 subscribed = asyncio.Event(loop=loop)

45 def on_subscribe(client, userdata, mid, granted_qos):

46 subscribed.set()

02_cube_blinker.py (https://github.com/anki/cozmo-python-sdk.git) Python · 104 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

22 '''

23

24 import asyncio

25 import sys

26

45 cols[i] = cozmo.lights.green_light

46 self.set_light_corners(*cols)

47 await asyncio.sleep(0.1, loop=self._loop)

48 self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)

76

77 For more information, see

78 https://docs.python.org/3/library/asyncio-task.html

79 '''

80

gwss.py (https://github.com/skelsec/Responder3.git) Python · 190 lines

1 # Work with Python 3.6

2 """

3 Generic websocket based client-server framework

68 self.shutdown_evt = asyncio.Event() #to completely shutdown the client

69 self.shutdown_session_evt = asyncio.Event() #to disconnect from server, and try to connect back

70

71 self.ws_ping_interval = 5

77 try:

78 pong_waiter = await ws.ping()

79 await asyncio.sleep(self.ws_ping_interval)

80 except websockets.exceptions.ConnectionClosed:

81 await self.logger.debug('Server disconnected!')

101 #waiting to get a log from the log queue, timeout is introducted so we can check

102 #in the while loop above is the ws still exists

103 str_data = await asyncio.wait_for(self.out_queue.get(), 1)

104 except asyncio.TimeoutError:

perf_benchmark.py (https://github.com/ethereum/lahja.git) Python · 152 lines

5

6 from lahja import ConnectionConfig

7 from lahja.tools.benchmark.backends import AsyncioBackend, BaseBackend, TrioBackend

8 from lahja.tools.benchmark.constants import (

9 DRIVER_ENDPOINT,

122 driver.start()

123

124 await root.wait_for(ShutdownEvent)

125 driver.stop()

126

131 # WARNING: The `fork` method does not work well with asyncio yet.

132 # This might change with Python 3.8 (See https://bugs.python.org/issue22087#msg318140)

133 multiprocessing.set_start_method("spawn")

134

136 setup_stderr_lahja_logging()

137

138 for backend_str in args.backend or ["asyncio"]:

139 if backend_str == "asyncio":

test_worker_pool.py (https://github.com/aiokitchen/aiomisc.git) Python · 205 lines

27 @skipif

28 async def test_success(worker_pool):

29 results = await asyncio.gather(

30 *[

31 worker_pool.create_task(operator.mul, i, i)

51 with pytest.raises(asyncio.TimeoutError):

52 await asyncio.wait_for(

53 asyncio.gather(

74 pids_start = set(process.pid for process in worker_pool.processes)

75

76 await asyncio.gather(

77 *[

78 worker_pool.create_task(getpid)

83 with pytest.raises(asyncio.TimeoutError):

84 await asyncio.wait_for(

85 asyncio.gather(

clientwrap.py (https://github.com/nteract/papermill.git) Python · 110 lines

1 import sys

2 import asyncio

3

4 from nbclient import NotebookClient

39 # See https://bugs.python.org/issue37373 :(

40 if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'):

41 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

42

43 with self.setup_kernel(**kwargs):

44 self.log.info("Executing notebook with kernel: %s" % self.kernel_name)

45 self.papermill_execute_cells()

46 info_msg = self.wait_for_reply(self.kc.kernel_info())

47 self.nb.metadata['language_info'] = info_msg['content']['language_info']

48 self.set_widgets_metadata()

08_drive_to_charger_test.py (https://github.com/anki/cozmo-python-sdk.git) Python · 84 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

21 '''

22

23 import asyncio

24 import time

25

34 if robot.is_on_charger:

35 # drive off the charger

36 robot.drive_off_charger_contacts().wait_for_completed()

37 robot.drive_straight(distance_mm(100), speed_mmps(50)).wait_for_completed()

39 robot.move_lift(-3)

40 # turn around to look at the charger

41 robot.turn_in_place(degrees(180)).wait_for_completed()

42 # Tilt the head to be level

43 robot.set_head_angle(degrees(0)).wait_for_completed()

subscribe_async.html (https://github.com/nats-io/nats-site.git) HTML · 148 lines

23

24 <li class="api-lang" data-language="py">

25 <a data-toggle="tab" href="#subscribe_async-py">Python</a>

26 </li>

27

100

101

102 <pre class="tab-pane fade" id="subscribe_async-py"><a class="toolbar-icons pull-right" target="_blank" href="https://github.com/nats-io/asyncio-nats-examples/blob/master/subscribe_async.py#L6-24"><i class="icon icon-github js-tooltip" title="View on GitHub"></i></a><a class="toolbar-icons pull-right"><i class="icon icon-copy js-copy js-tooltip" title="Copy to Clipboard"></i></a><code class="language-python">nc = NATS()

103

104 await nc.connect(servers=[&#34;nats://demo.nats.io:4222&#34;])

115

116 # Wait for message to come in

117 msg = await asyncio.wait_for(future, 1)

118

119 </code></pre>

test_rwlock.py (https://github.com/aio-libs/aiorwlock.git) Python · 544 lines

1 import asyncio

2

3 import pytest

7

8 class Bunch(object):

9 """A bunch of Tasks. Port python threading tests"""

10

11 def __init__(self, f, n, wait_before_exit=False):

15 do_finish() is called.

16 """

17 self._loop = asyncio.get_event_loop()

18 self.f = f

19 self.n = n

32 self.finished.append(tid)

33 while not self._can_exit:

34 await asyncio.sleep(0.01)

35

36 for _ in range(n):

test_master_message_destination.py (https://github.com/blueset/efb-telegram-master.git) Python · 147 lines

7 """

8

9 import asyncio

10 import time

11 from contextlib import suppress

18 from .helper.filters import in_chats, has_button, edited, regex, text

19

20 pytestmark = mark.asyncio

21

22

29 await client.send_message(bot_id,

30 "test_master_master_quick_reply_no_cache this shall not be sent due to empty cache")

31 await helper.wait_for_message()

32 assert slave.messages.empty()

33

subprocess.py (https://github.com/wwqgtxx/wwqLyParse.git) Python · 96 lines

1 #!/usr/bin/env python3.5

2 # -*- coding: utf-8 -*-

3 # author wwqgtxx <wwqgtxx@gmail.com>

67

68

69 from . import asyncio

70

71

76 p = await asyncio.create_subprocess_exec(*args, stdout=pipe, stderr=pipe if need_stderr else None, **kwargs)

77 try:

78 stdout, stderr = await asyncio.wait_for(p.communicate(), timeout=timeout)

79 except asyncio.TimeoutError:

80 raise asyncio.CancelledError

81 else:

82 # try to decode

functional-tests.rst (https://github.com/electrumsv/electrumsv.git) ReStructuredText · 78 lines

31 1. Install pytest pre-requisites::

32

33 python3 -m pip install pytest pytest-cov pytest-asyncio pytest-timeout electrumsv_node openpyxl

34

35

49 Run the functional tests with pytest like this::

50

51 python3 -m pytest -v -v -v contrib/functional_tests/functional

52

53 Which should output something like (but with verbose logging output)::

56 contrib\functional_tests\functional\test_restapi.py::TestRestAPI::test_get_all_wallets PASSED [ 25%]

57 contrib\functional_tests\functional\test_restapi.py::TestRestAPI::test_load_wallet PASSED [ 33%]

58 contrib\functional_tests\functional\test_restapi.py::TestRestAPI::test_websocket_wait_for_mempool PASSED [ 41%]

59 contrib\functional_tests\functional\test_restapi.py::TestRestAPI::test_websocket_wait_for_confirmation PASSED [ 50%]

_asyncio_backend.py (git://github.com/rthalley/dnspython.git) Python · 149 lines

15 def _get_running_loop():

16 try:

17 return asyncio.get_running_loop()

18 except AttributeError: # pragma: no cover

19 return asyncio.get_event_loop()

48 if timeout:

49 try:

50 return await asyncio.wait_for(awaitable, timeout)

51 except asyncio.TimeoutError:

62

63 async def sendto(self, what, destination, timeout): # pragma: no cover

64 # no timeout for asyncio sendto

65 self.transport.sendto(what, destination)

66

91 async def sendall(self, what, timeout):

92 self.writer.write(what)

93 return await _maybe_wait_for(self.writer.drain(), timeout)

94

95 async def recv(self, size, timeout):

examples.ipynb (https://github.com/coady/multimethod.git) Jupyter · 241 lines

142 "outputs": [],

143 "source": [

144 "import asyncio\n",

145 "import time\n",

146 "from concurrent import futures\n",

156 "async def wait(timeout, func: asyncio.iscoroutinefunction, *args):\n",

157 " return await asyncio.wait_for(func(*args), timeout)\n",

158 "\n",

159 "\n",

167 "outputs": [],

168 "source": [

169 "wait(0.5, asyncio.sleep, 0.01)"

170 ],

171 "execution_count": null

226 "language_info": {

227 "codemirror_mode": {

228 "name": "ipython",

229 "version": 3

230 },

test_utils.py (https://github.com/conjure-up/conjure-up.git) Python · 116 lines

1 #!/usr/bin/env python

2 #

3 # tests test/utils.py

6

7

8 import asyncio

9 import logging

10 import unittest

47 def test_sentry_report(self, app, juju_version):

48 # test task schedule

49 flag = asyncio.Event()

50 with patch.object(utils, '_sentry_report',

51 lambda *a, **kw: flag.set()):

53 app.loop = loop

54 utils.sentry_report('m')

55 loop.run_until_complete(asyncio.wait_for(flag.wait(), 30))

56

57 # test implementation

server_protocol.py (https://github.com/facebookexperimental/doh-proxy.git) Python · 190 lines

1 #!/usr/bin/env python3

2 #

3 # Copyright (c) 2018-present, Facebook, Inc.

7 # LICENSE file in the root directory of this source tree.

8 #

9 import asyncio

10 import dns.edns

11 import dns.entropy

36

37 def __init__(self, upstream_resolver, upstream_port, logger=None):

38 self.loop = asyncio.get_event_loop()

39 self.upstream_resolver = upstream_resolver

40 self.upstream_port = upstream_port

84 async def _try_query(self, fut, qid, timeout, transport):

85 try:

86 await asyncio.wait_for(fut, timeout)

87 dnsr = fut.result()

88 dnsr.id = qid

test_pyppeteer.py (https://github.com/miyakogi/pyppeteer.git) Python · 80 lines

1 #!/usr/bin/env python

2 # -*- coding: utf-8 -*-

3

9 """

10

11 import asyncio

12 import logging

13 from pathlib import Path

74 options = {'path': str(self.target_path)}

75 self.assertFalse(self.target_path.exists())

76 await asyncio.wait_for(page.screenshot(options), 30)

77 self.assertTrue(self.target_path.exists())

78 with self.target_path.open('rb') as fh:

server.py (https://github.com/bui/taiko-web.git) Python · 399 lines

53 while True:

54 try:

55 message = await asyncio.wait_for(ws.recv(), timeout=10)

56 except asyncio.TimeoutError:

58 pong_waiter = await ws.ping()

59 try:

60 await asyncio.wait_for(pong_waiter, timeout=10)

61 except asyncio.TimeoutError:

235 sent_msg1 = msgobj("gameend")

236 sent_msg2 = status_event()

237 await asyncio.wait([

238 ws.send(sent_msg1),

239 ws.send(sent_msg2),

388 loop.default_exception_handler(context)

389 loop.set_exception_handler(shutdown_exception_handler)

390 tasks = asyncio.gather(*asyncio.all_tasks(loop=loop), loop=loop, return_exceptions=True)

391 tasks.add_done_callback(lambda t: loop.stop())

392 tasks.cancel()

asyncio_proto.pyx (https://github.com/edgedb/edgedb-python.git) Cython · 141 lines

18

19

20 import asyncio

21

22 from edgedb import errors

29

30

31 cdef class AsyncIOProtocol(protocol.SansIOProtocol):

32

33 def __init__(self, con_params, loop, tls_compat=False):

115

116 if self.transport is not None:

117 # With asyncio sslproto on CPython 3.10 or lower, a normal exit

118 # (connection closed by peer) cannot set the transport._closed

119 # properly, leading to false ResourceWarning. Let's fix that by

protocol.py (https://github.com/CityOfZion/neo-python.git) Python · 101 lines

1 import asyncio

2 import struct

3 from typing import Optional

4 from neo.Network.node import NeoNode

5 from neo.Network.message import Message

6 from asyncio.streams import StreamReader, StreamReaderProtocol, StreamWriter

7 from asyncio import events

27 super().__init__(self._stream_reader)

28

29 def connection_made(self, transport: asyncio.transports.BaseTransport) -> None:

30 super().connection_made(transport)

31 self._stream_writer = StreamWriter(transport, self, self._stream_reader, self._loop)

93 return m

94 try:

95 return await asyncio.wait_for(_read(), timeout)

96 except Exception:

97 return None

test_asyncio_client.py (https://github.com/miguelgrinberg/python-socketio.git) Python · 940 lines

36 await fake_wait_for._mock(timeout)

37

38 original_wait_for = asyncio.wait_for

39 asyncio.wait_for = fake_wait_for

40 fake_wait_for._mock = AsyncMock()

41 yield

42 asyncio.wait_for = original_wait_for

43

44

755

756 @mock.patch(

757 'asyncio.wait_for',

758 new_callable=AsyncMock,

759 side_effect=asyncio.TimeoutError,

831 assert wait_for.mock.call_count == 2

832 assert [x[0][1] for x in asyncio.wait_for.mock.call_args_list] == [

833 1.5,

834 1.5,

test_utils_test.py (https://github.com/dask/distributed.git) Python · 218 lines

1 import asyncio

2 from contextlib import contextmanager

3 import socket

17 inc,

18 gen_test,

19 wait_for_port,

20 new_config,

21 )

122 @gen_test()

123 async def test_gen_test():

124 await asyncio.sleep(0.01)

125

126

127 @gen_test()

128 def test_gen_test_legacy_implicit():

129 yield asyncio.sleep(0.01)

130

131

async_utils.py (https://github.com/Yelp/paasta.git) Python · 105 lines

1 import asyncio

2 import functools

3 import time

38 raise KeyError

39 except KeyError:

40 future = asyncio.ensure_future(async_func(*args, **kwargs))

41 # set the timestamp to +infinity so that we always wait on the in-flight request.

42 cache[key] = (future, float("Inf"))

99 @functools.wraps(wrapped)

100 async def inner(*args, **kwargs):

101 return await asyncio.wait_for(wrapped(*args, **kwargs), timeout=seconds)

102

103 return inner

timeout.py (https://github.com/django/asgiref.git) Python · 128 lines

19

20 Useful in cases when you want to apply timeout logic around block

21 of code or in cases when asyncio.wait_for is not suitable. For example:

22

23 >>> with timeout(0.001):

81 def _do_enter(self) -> "timeout":

82 # Support Tornado 5- without timeout

83 # Details: https://github.com/python/asyncio/issues/392

84 if self._timeout is None:

85 return self

116

117

118 def current_task(loop: asyncio.AbstractEventLoop) -> "asyncio.Task[Any]":

119 if PY_37:

120 task = asyncio.current_task(loop=loop) # type: ignore

manage.py (https://github.com/SFTtech/kevin.git) Python · 120 lines

1 #!/usr/bin/env python3

2

3 """

6

7 import argparse

8 import asyncio

9 import logging

10

36

37 logging.debug("VM launched, waiting for ssh...")

38 await vm.wait_for_ssh_port()

39

40 if manage:

52 wait_time = 30

53 logging.warning(f"waiting {wait_time}s for machine to shut down")

54 await vm.wait_for_shutdown(30)

55

56 await vm.terminate()

compat.py (https://github.com/MagicStack/asyncpg.git) Python · 108 lines

6

7

8 import asyncio

9 import functools

10 import os

75

76 if PY_37:

77 def current_asyncio_task(loop):

78 return asyncio.current_task(loop)

79 else:

80 def current_asyncio_task(loop):

81 return asyncio.Task.current_task(loop)

101

102 try:

103 return await asyncio.wait_for(fut, timeout)

104 except asyncio.CancelledError:

tools.py (https://github.com/mosquito/aiormq.git) Python · 100 lines

42 if hasattr(result, "__await__"):

43 return await result # type: ignore

44 if asyncio.iscoroutine(result) or asyncio.isfuture(result):

45 return await result # type: ignore

46

54

55 def __init__(self, timeout: TimeoutType = None):

56 self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()

57 self.deadline: TimeoutType = None

58

73 if self.deadline is None:

74 return coro

75 return asyncio.wait_for(coro, timeout=self.get_timeout())

76

77 def enter_context(

01_cube_blinker_sync.py (https://github.com/anki/cozmo-python-sdk.git) Python · 84 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

22 '''

23

24 import asyncio

25 import sys

26

45 cols[i] = cozmo.lights.green_light

46 self.set_light_corners(*cols)

47 await asyncio.sleep(0.1, loop=self._loop)

48 self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)

63

64 try:

65 cube = robot.world.wait_for_observed_light_cube(timeout=60)

66 except asyncio.TimeoutError:

multi_robot_unified.py (https://github.com/anki/cozmo-python-sdk.git) Python · 62 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

20 '''

21

22 import asyncio

23 import sys

24

28

29 async def run(sdk_conn1, sdk_conn2):

30 robot1 = await sdk_conn1.wait_for_robot()

31 robot2 = await sdk_conn2.wait_for_robot()

33 # First have one turn left and one turn right, one after the other

34 cozmo.logger.info("Turning robot 1")

35 await robot1.turn_in_place(degrees(90)).wait_for_completed()

36 cozmo.logger.info("Turning robot 2")

37 await robot2.turn_in_place(degrees(-90)).wait_for_completed()

tcp.py (https://github.com/pyrogram/pyrogram.git) Python · 120 lines

1 # Pyrogram - Telegram MTProto API Client Library for Python

2 # Copyright (C) 2017-2020 Dan <https://github.com/delivrance>

3 #

17 # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

18

19 import asyncio

20 import ipaddress

21 import logging

42 self.socket = None

43

44 self.reader = None # type: asyncio.StreamReader

45 self.writer = None # type: asyncio.StreamWriter

106 while len(data) < length:

107 try:

108 chunk = await asyncio.wait_for(

109 self.reader.read(length - len(data)),

110 TCP.TIMEOUT

test_binance_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 119 lines

1 #!/usr/bin/env python

2 import math

3 from os.path import join, realpath

7 from hummingbot.connector.exchange.binance.binance_order_book_tracker import BinanceOrderBookTracker

8 from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource

9 import asyncio

10 import logging

11 from typing import (

34 @classmethod

35 def setUpClass(cls):

36 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

37 cls.order_book_tracker: BinanceOrderBookTracker = BinanceOrderBookTracker(

38 trading_pairs=cls.trading_pairs)

39 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

40 cls.ev_loop.run_until_complete(cls.wait_til_tracker_ready())

41

util.py (https://github.com/ikalchev/HAP-python.git) Python · 149 lines

1 import asyncio

2 import base64

3 import socket

111

112 tohex = bytes.hex if sys.version_info >= (3, 5) else b2hex

113 """Python-version-agnostic tohex function. Equivalent to bytes.hex in python 3.5+.

114 """

115

116 fromhex = bytes.fromhex if sys.version_info >= (3, 5) else hex2b

117 """Python-version-agnostic fromhex function. Equivalent to bytes.fromhex in python 3.5+.

118 """

119

144 """

145 try:

146 await asyncio.wait_for(event.wait(), timeout, loop=loop)

147 except asyncio.TimeoutError:

beef.py (https://github.com/nocproject/noc.git) Python · 99 lines

6 # ----------------------------------------------------------------------

7

8 # Python modules

9 import asyncio

22 self.beef = None

23 self.read_buffer = []

24 self.read_event = asyncio.Event()

25

26 def close(self):

50 self.read_event.set()

51

52 async def wait_for_read(self):

53 pass

54

55 async def wait_for_write(self):

56 pass

57

subproc.py (https://github.com/ANLAB-KAIST/NBA.git) Python · 63 lines

1 #! /usr/bin/env python3

2 import sys, os

3 import asyncio

40 return ret

41

42 @asyncio.coroutine

43 def execute_async_simple(cmdargs, timeout=None):

44 proc = yield from asyncio.create_subprocess_exec(*cmdargs, stdout=sys.stdout)

45 if timeout:

46 try:

47 retcode = yield from asyncio.wait_for(proc.wait(), timeout + 1)

48 except asyncio.TimeoutError:

events.py (https://github.com/cheran-senthil/TLE.git) Python · 164 lines

1 import asyncio

2 import logging

3

55 raise ListenerNotRegistered(listener)

56

57 async def wait_for(self, event_cls, *, timeout=None):

58 future = asyncio.get_running_loop().create_future()

59 futures = self.futures_by_event.setdefault(event_cls, [])

60 futures.append(future)

61 return await asyncio.wait_for(future, timeout)

62

63 def dispatch(self, event_cls, *args, **kwargs):

75

76 def _ensure_coroutine_func(func):

77 if not asyncio.iscoroutinefunction(func):

78 raise TypeError('The listener function must be a coroutine function.')

79

async_pool.py (https://github.com/orleven/Tentacle.git) Python · 166 lines

12 self._kwargs = kwargs

13

14 self.future = asyncio.Future()

15

16

24

25 async def stop(self, timeout=None):

26 await asyncio.wait_for(self._fut, timeout)

27

28 async def run(self):

53 self._finish_left = num_workers

54

55 async def submit(self, _func, *args, **kwargs) -> asyncio.Future:

56 if self._closed:

57 raise RuntimeError('submit after shutdown')

async_tools.py (https://github.com/adamcharnock/lightbus.git) Python · 180 lines

1 import sys

2 import asyncio

3 import logging

4 import threading

18 logger = logging.getLogger(__name__)

19

20 PYTHON_VERSION = tuple(sys.version_info)

21

22

39 val = loop.run_until_complete(coroutine)

40 else:

41 val = loop.run_until_complete(asyncio.wait_for(coroutine, timeout=timeout))

42 except Exception as e:

43 # The intention here is to get sensible stack traces from exceptions within blocking calls

48 def get_event_loop():

49 try:

50 loop = asyncio.get_event_loop()

51 except RuntimeError:

52 loop = asyncio.new_event_loop()

port_scanner.py (https://github.com/socketry/async-await.git) Python · 36 lines

1 #!/usr/bin/env python

2

3 import os, resource

4 import asyncio

5

6 class PortScanner:

8 self.host = host

9 self.ports = ports

10 self.semaphore = asyncio.Semaphore(value=batch_size)

11 self.loop = asyncio.get_event_loop()

16 future = asyncio.open_connection(self.host, port, loop=self.loop)

17 reader, writer = await asyncio.wait_for(future, timeout=timeout)

18 print("{} open".format(port))

19 writer.close()

readuntil.py (https://github.com/pychess/pychess.git) Python · 146 lines

1 """ Monkey patching asyncio.StreamReader to add readuntil() from Python 3.5.2"""

2 import asyncio

28

29

30 async def _wait_for_data(self, func_name):

31 """Wait until feed_data() or feed_eof() is called.

32

41 'already waiting for incoming data' % func_name)

42

43 assert not self._eof, '_wait_for_data after EOF'

44

45 # Waiting for data while paused will make deadlock, so prevent it.

48 self._transport.resume_reading()

49

50 self._waiter = asyncio.futures.Future(loop=self._loop)

51 try:

52 await self._waiter

__init__.py (https://bitbucket.org/echarles5wits/kioskcommutility.git) Python · 104 lines

1 import asyncio

2 import sys

3

12

13 Useful in cases when you want to apply timeout logic around block

14 of code or in cases when asyncio.wait_for is not suitable. For example:

15

16 >>> with timeout(0.001):

20

21 timeout - value in seconds or None to disable timeout logic

22 loop - asyncio compatible event loop

23 """

24 def __init__(self, timeout, *, loop=None):

59 def _do_enter(self):

60 # Support Tornado 5- without timeout

61 # Details: https://github.com/python/asyncio/issues/392

62 if self._timeout is None:

63 return self

03_go_to_object_test.py (https://github.com/anki/cozmo-python-sdk.git) Python · 60 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

22 '''

23

24 import asyncio

25

26 import cozmo

33 # Move lift down and tilt the head up

34 robot.move_lift(-3)

35 robot.set_head_angle(degrees(0)).wait_for_completed()

36

37 # look around and try to find a cube

41

42 try:

43 cube = robot.world.wait_for_observed_light_cube(timeout=30)

44 print("Found cube: %s" % cube)

45 except asyncio.TimeoutError:

python3-async-timeout_3.0.1.bb (https://github.com/openbmc/openbmc.git) Bitbake · 19 lines

1 SUMMARY = "asyncio-compatible timeout context manager"

2 DESCRIPTION = "\

3 The context manager is useful in cases when you want to apply \

4 timeout logic around block of code or in cases when asyncio.wait_for() \

5 is not suitable. Also it's much faster than asyncio.wait_for() because \

16

17 RDEPENDS_${PN} = "\

18 ${PYTHON_PN}-asyncio \

19 "

20

roster_browser.py (https://github.com/poezio/slixmpp.git) Python · 133 lines

1 #!/usr/bin/env python3

2

3 # Slixmpp: The Slick XMPP Library

12 import slixmpp

13 from slixmpp.exceptions import IqError, IqTimeout

14 from slixmpp.xmlstream.asyncio import asyncio

15

16

30 # our roster.

31 self.add_event_handler("session_start", self.start)

32 self.add_event_handler("changed_status", self.wait_for_presences)

33

34 self.received = set()

35 self.presences_received = asyncio.Event()

36

37 async def start(self, event):

newHeads_test.py (https://github.com/Conflux-Chain/conflux-rust.git) Python · 91 lines

1 #!/usr/bin/env python3

2

3 # allow imports from parent directory

6 sys.path.insert(1, os.path.join(sys.path[0], '..'))

7

8 import asyncio

9

10 from conflux.rpc import RpcClient

48

49 # wait for phase changes to complete

50 self.nodes[FULLNODE0].wait_for_phase(["NormalSyncPhase"])

51 self.nodes[FULLNODE1].wait_for_phase(["NormalSyncPhase"])

86

87 def run_test(self):

88 asyncio.get_event_loop().run_until_complete(self.run_async())

89

90 if __name__ == "__main__":

event_logger.pyx (https://github.com/CoinAlpha/hummingbot.git) Cython · 57 lines

1 #!/usr/bin/env python

2

3 import asyncio

30 self._logged_events.clear()

31

32 async def wait_for(self, event_type, timeout_seconds: float = 180):

33 notifier = asyncio.Event()

demo_face.py (https://bitbucket.org/lilyzhang622/cozmo-demos.git) Python · 106 lines

1 #!/usr/bin/env python3

2 '''

3 Cozmo will recognize new faces and old faces and try to follow the faces.

8 import sys

9 import time

10 import asyncio

11

12 try:

45 # Move lift down and tilt the head up

46 robot.move_lift(-3)

47 robot.set_head_angle(cozmo.robot.MAX_HEAD_ANGLE).wait_for_completed()

48

49 faces = []

68 try:

69 face = None

70 face = robot.world.wait_for_observed_face(timeout=30)

71 if face in faces:

72 robot.say_text("Hello again!").wait_for_completed()

server_base.py (https://bitbucket.org/arfonzo/electrumx4egc.git) Python · 128 lines

6 # and warranty status of this software.

7

8 import asyncio

9 import os

10 import signal

21 Derived classes are expected to:

22

23 - set PYTHON_MIN_VERSION and SUPPRESS_MESSAGES as appropriate

24 - implement the start_servers() coroutine, called from the run() method.

25 Upon return the event loop runs until the shutdown signal is received.

32 ]

33

34 PYTHON_MIN_VERSION = (3, 6)

35

36 def __init__(self, env):

feed.py (https://github.com/Instagram/django-workload.git) Python · 215 lines

7 # Async can be introduced gradually. This file contains some async routines

8 # that are used from a synchronous endpoint.

9 import asyncio

10

11 from .models import FeedEntryModel, UserModel

13

14

15 def wait_for(coro):

16 loop = asyncio.get_event_loop()

119 ]

120 self.context.prepared = dict(

121 zip(self.steps, wait_for(self.async_prepare())))

122

123 async def async_prepare(self):

124 return await asyncio.gather(*(s.prepare() for s in self.steps))

125

126 def run(self):

syncer.py (https://github.com/pyrogram/pyrogram.git) Python · 88 lines

1 # Pyrogram - Telegram MTProto API Client Library for Python

2 # Copyright (C) 2017-2020 Dan <https://github.com/delivrance>

3 #

17 # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

18

19 import asyncio

20 import logging

21 import time

34 async def add(cls, client):

35 if cls.event is None:

36 cls.event = asyncio.Event()

37

38 if cls.lock is None:

70 while True:

71 try:

72 await asyncio.wait_for(cls.event.wait(), cls.INTERVAL)

73 except asyncio.TimeoutError:

02_face_follower.py (https://github.com/anki/cozmo-python-sdk.git) Python · 60 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2016 Anki, Inc.

21 '''

22

23 import asyncio

24 import time

25

32 # Move lift down and tilt the head up

33 robot.move_lift(-3)

34 robot.set_head_angle(cozmo.robot.MAX_HEAD_ANGLE).wait_for_completed()

35

36 face_to_follow = None

46 # find a visible face, timeout if nothing found after a short while

47 try:

48 face_to_follow = robot.world.wait_for_observed_face(timeout=30)

49 except asyncio.TimeoutError:

test_bittrex_order_book_tracker.py (https://github.com/CoinAlpha/hummingbot.git) Python · 105 lines

1 #!/usr/bin/env python

2 import math

3 import time

7 from hummingbot.core.event.events import OrderBookEvent, OrderBookTradeEvent, TradeType

8

9 import asyncio

10 import logging

11 from typing import Dict, Optional, List

33 @classmethod

34 def setUpClass(cls):

35 cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()

36 cls.order_book_tracker: BittrexOrderBookTracker = BittrexOrderBookTracker(trading_pairs=cls.trading_pairs)

37 cls.order_book_tracker_task: asyncio.Task = safe_ensure_future(cls.order_book_tracker.start())

47

48 async def run_parallel_async(self, *tasks, timeout=None):

49 future: asyncio.Future = asyncio.ensure_future(asyncio.gather(*tasks))

50 timer = 0

51 while not future.done():

pubsub.py (https://github.com/NoneGG/aredis.git) Python · 49 lines

1 #!/usr/bin/python

2 # -*- coding: utf-8 -*-

3

4 import aredis

5 import asyncio

6 import concurrent.futures

7 import time

9

10

11 async def wait_for_message(pubsub, timeout=2, ignore_subscribe_messages=False):

12 now = time.time()

13 timeout = now + timeout

19 if message is not None:

20 print(message)

21 await asyncio.sleep(0.01)

22 now = time.time()

23 return None

testing.py (https://github.com/sixty-north/cosmic-ray.git) Python · 79 lines

17

18 async def _run_tests(command, timeout):

19 # We want to avoid writing pyc files in case our changes happen too fast for Python to

20 # notice them. If the timestamps between two changes are too small, Python won't recompile

21 # the source.

22 env = dict(os.environ)

23 env['PYTHONDONTWRITEBYTECODE'] = '1'

24

25 try:

26 proc = await asyncio.create_subprocess_shell(

27 command,

28 stdout=asyncio.subprocess.PIPE,

29 stderr=asyncio.subprocess.STDOUT,

33

34 try:

35 outs, _errs = await asyncio.wait_for(proc.communicate(), timeout)

36

37 assert proc.returncode is not None

result_receiver.py (https://github.com/baidu-security/openrasp-iast.git) Python · 123 lines

1 #!/usr/bin/env python3

2 # -*- coding: UTF-8 -*-

3

19

20 import time

21 import asyncio

22 import collections

23

55 expire_time = time.time() + (self.timeout * 2)

56 self.rasp_result_collection[req_id] = [

57 asyncio.Event(), expire_time, None]

58

59 def add_result(self, rasp_result):

112 try:

113 Logger().debug("Start waiting rasp result, id: " + req_id)

114 await asyncio.wait_for(event.wait(), timeout=timeout)

115 except asyncio.TimeoutError:

timeout.py (https://github.com/h2non/paco.git) Python · 95 lines

34 @asyncio.coroutine

35 def _timeout(coro):

36 return (yield from asyncio.wait_for(coro, timeout, loop=loop))

37

38 @asyncio.coroutine

48

49 Useful in cases when you want to apply timeout logic around block

50 of code or in cases when asyncio.wait_for is not suitable.

51

52 Originally based on: https://github.com/aio-libs/async-timeout

54 Arguments:

55 timeout (int): value in seconds or None to disable timeout logic.

56 loop (asyncio.BaseEventLoop): asyncio compatible event loop.

57

58 Usage::

shell.py (https://github.com/hhstore/annotated-py-flask.git) Python · 70 lines

1 #!/usr/bin/env python

2 # -*- coding: utf-8 -*-

3

4 """Examples using create_subprocess_exec() and create_subprocess_shell()."""

5

6 import asyncio

7 import signal

8 from asyncio.subprocess import PIPE

12 # 执行 shell 命令:

13 #

14 @asyncio.coroutine

15 def cat(loop):

16

53 proc = yield from asyncio.create_subprocess_exec(*args)

54 try:

55 exitcode = yield from asyncio.wait_for(proc.wait(), timeout)

56 print("%s: exit code %s" % (' '.join(args), exitcode))

57 except asyncio.TimeoutError:

asyncio_generators.py (https://github.com/spatialaudio/python-sounddevice.git) Python · 108 lines

6 blocks but also output blocks where audio data can be written to.

7

8 You need Python 3.7 or newer to run this.

9

10 """

11 import asyncio

12 import queue

13 import sys

41 """

42 assert blocksize != 0

43 q_in = asyncio.Queue()

44 q_out = queue.Queue()

45 loop = asyncio.get_event_loop()

87 print('Some informations about the input signal:')

88 try:

89 await asyncio.wait_for(print_input_infos(), timeout=2)

90 except asyncio.TimeoutError:

stream.py (https://github.com/nocproject/noc.git) Python · 151 lines

64 loop = asyncio.get_running_loop()

65 try:

66 await asyncio.wait_for(

67 loop.sock_connect(self.socket, (address, port or self.default_port)), self._timeout

68 )

88 loop.add_reader(fileno, read_ev.set)

89 try:

90 await asyncio.wait_for(read_ev.wait(), self._timeout)

91 finally:

92 loop.remove_reader(fileno)

104 loop.add_writer(fileno, write_ev.set)

105 try:

106 await asyncio.wait_for(write_ev.wait(), self._timeout)

107 finally:

108 loop.remove_writer(fileno)

quickstart.rst (https://github.com/pipermerriam/py-evm.git) ReStructuredText · 89 lines

22 although it can fetch block bodies on demand. The easiest way to try it is by

23 running the lightchain_shell, which will run the LightPeerChain in the background

24 and let you use the python interpreter to interact with it:

25

26 .. code:: sh

27

28 $ python -i -m eth.lightchain_shell -db /tmp/testnet.db

29

30

31 That will immediately give you a python shell, with a chain variable that you

32 can use even before it has finished syncing:

33

connection_server.py (https://github.com/wwqgtxx/wwqLyParse.git) Python · 72 lines

1 #!/usr/bin/env python3.5

2 # -*- coding: utf-8 -*-

3 # author wwqgtxx <wwqgtxx@gmail.com>

4 import multiprocessing.connection

5 from . import asyncio

6 from .async_pool import *

7 from .async_pipe_connection import *

33 await conn.do_auth(self.authkey)

34 while True:

35 data = await asyncio.wait_for(conn.recv_bytes(), CONN_LRU_TIMEOUT)

36 if not data:

37 raise EOFError

44 else:

45 if result is not None:

46 await asyncio.wait_for(conn.send_bytes(result), CONN_LRU_TIMEOUT)

47 except asyncio.TimeoutError:

thrift_client.py (https://github.com/facebookincubator/FCR.git) Python · 101 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3

7 # LICENSE file in the root directory of this source tree.

8

9 import asyncio

10

11 from thrift.server.TAsyncioServer import ThriftClientProtocolFactory

16 class AsyncioThriftClient(ServiceObj):

17 """

18 util class to get asyncio client for different services using asyncio

19 get_hosts

20 """

70 port=port,

71 )

72 (transport, protocol) = await asyncio.wait_for(

73 conn_fut, self._open_timeout, loop=self.loop

74 )

bb8.py (https://github.com/undera/pylgbst.git) Python · 113 lines

1 import asyncio

2 import time

3

27

28 async def sleep(self, sleeptime, reset_inactivity_timeout=True, response_timeout_in_seconds=None):

29 # port from https://github.com/jchadwhite/SpheroBB8-python/blob/master/BB8_driver.py#L394

30 command = _ClientCommandPacket(device_id=_DEVICE_ID_CORE,

31 command_id=0x22,

32 sequence_number=self._get_and_increment_command_sequence_number(),

33 data=[(sleeptime >> 8), (sleeptime & 0xff), 0],

34 wait_for_response=False,

35 reset_inactivity_timeout=reset_inactivity_timeout)

36

39

40 async def set_rotation_rate(self, rate, reset_inactivity_timeout=True, response_timeout_in_seconds=None):

41 # port from https://github.com/jchadwhite/SpheroBB8-python/blob/master/BB8_driver.py

42 command = _ClientCommandPacket(device_id=_DEVICE_ID_SPHERO,

43 command_id=0x03,

helpers.py (https://github.com/aliasrobotics/aztarna.git) Python · 91 lines

1 #!/usr/bin/env python

2 # -*- coding: utf-8 -*-

3

4 import asyncio

5 from platform import system as system_name # Returns the system/OS name

6 from subprocess import call as system_call # Execute a shell command

54 conn = asyncio.open_connection(ip, port)

55 try:

56 reader, writer = await asyncio.wait_for(conn, timeout=3)

57 writer.close()

58 return port

83 :return:

84 """

85 sem = asyncio.Semaphore(max_conns)

86 ports = range(start_port, end_port)

87 tasks = [asyncio.ensure_future(PortScanner.check_port_sem(sem, address, port)) for port in ports]

receive_log.py (https://github.com/elastic-coders/aioamqp.git) Python · 45 lines

1 #!/usr/bin/env python

2 """

3 Rabbitmq.com pub/sub example

4

5 https://www.rabbitmq.com/tutorials/tutorial-three-python.html

6

7 """

34 yield from channel.exchange(exchange_name, 'fanout')

35

36 yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)

37

38 yield from asyncio.wait_for(channel.queue_bind(exchange_name=exchange_name, queue_name=queue_name, routing_key=''), timeout=10)

40 print(' [*] Waiting for logs. To exit press CTRL+C')

41

42 yield from asyncio.wait_for(channel.basic_consume(queue_name, callback=callback), timeout=10)

43

44

compat.py (https://github.com/edgedb/edgedb-python.git) Python · 55 lines

17 #

18

19 import asyncio

20 import sys

21

22

23 if sys.version_info < (3, 7):

24 # Workaround for https://bugs.python.org/issue37658

25 import functools

26

44

45 try:

46 return await asyncio.wait_for(fut, timeout)

47 except (asyncio.CancelledError, asyncio.TimeoutError):

53

54 else:

55 wait_for = asyncio.wait_for

56

image.py (https://bitbucket.org/btirelan86/chibibot.git) Python · 168 lines

3 import aiohttp

4 import functools

5 import asyncio

6

7 try:

42

43 try:

44 results = await asyncio.wait_for(task, timeout=10)

45 except asyncio.TimeoutError:

62

63 try:

64 results = await asyncio.wait_for(task, timeout=10)

65 except asyncio.TimeoutError:

102 task = self.bot.loop.run_in_executor(None, task)

103 try:

104 items = await asyncio.wait_for(task, timeout=10)

105 except asyncio.TimeoutError:

testutil.py (https://github.com/facebookincubator/FCR.git) Python · 67 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3

7 # LICENSE file in the root directory of this source tree.

8

9 import asyncio

10 import functools

11 import typing

15 from fbnet.command_runner.counters import Counters

16

17 # `asyncio.events.AbstractEventLoop` to have type `float` but is never initialized.

18 # pyre-fixme[13]: Attribute `slow_callback_duration` inherited from abstract class

19 class FcrTestEventLoop(asyncio.SelectorEventLoop):

41 def setUp(self) -> None:

42 self._loop = FcrTestEventLoop()

43 asyncio.set_event_loop(None)

44

45 def tearDown(self) -> None:

test_kernel.py (https://github.com/ipython/ipykernel.git) Python · 100 lines

1 # Copyright (c) IPython Development Team.

2 # Distributed under the terms of the Modified BSD License.

3

10 from ipykernel.inprocess.ipkernel import InProcessKernel

11 from ipykernel.tests.utils import assemble_output

12 from IPython.testing.decorators import skipif_not_matplotlib

13 from IPython.utils.io import capture_output

14

15

16 def _init_asyncio_patch():

17 """set default asyncio policy to be compatible with tornado

18

19 Tornado 6 (at least) is not compatible with the default

20 asyncio implementation on Windows

21

22 Pick the older SelectorEventLoopPolicy on Windows

conn.py (https://github.com/yjqiang/danmu.git) Python · 216 lines

42 return None

43

44 # 类似于 https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader.readexactly

45 # Read exactly n bytes.

46 @abstractmethod

48 return None

49

50 # 类似于 https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader.readexactly

51 # Read exactly n bytes.

52 @abstractmethod

111 return None

112 try:

113 bytes_data = await asyncio.wait_for(

114 self._reader.readexactly(n), timeout=self._receive_timeout)

115 except (OSError, asyncio.TimeoutError, asyncio.IncompleteReadError):

shell.py (https://github.com/Gorialis/jishaku.git) Python · 147 lines

12 """

13

14 import asyncio

15 import os

16 import pathlib

24

25

26 def background_reader(stream, loop: asyncio.AbstractEventLoop, callback):

27 """

28 Reads a stream and forwards each line to an async callback.

40 -------

41

42 .. code:: python3

43

44 # reader should be in a with statement to ensure it is properly closed

137 while not self.closed or not self.queue.empty():

138 try:

139 item = await asyncio.wait_for(self.queue.get(), timeout=1)

140 except asyncio.TimeoutError as exception:

sync_blocks_processor.py (https://github.com/Chia-Network/chia-blockchain.git) Python · 126 lines

1 import asyncio

2 import concurrent

3 import logging

63 future = asyncio.gather(*awaitables, return_exceptions=True)

64 try:

65 await asyncio.wait_for(future, timeout=self.SLEEP_INTERVAL)

66 break

67 # https://github.com/python/cpython/pull/13528

68 except (concurrent.futures.TimeoutError, asyncio.TimeoutError):

69 try:

70 await future

71 except asyncio.CancelledError:

72 pass

73 total_time_slept += self.SLEEP_INTERVAL

queue.py (https://github.com/nocproject/noc.git) Python · 123 lines

20 self.queue: deque = deque()

21 self.lock = Lock()

22 self.waiter: Optional[asyncio.Event] = None

23 self.drain_waiter: Optional[asyncio.Event] = None

27 self.to_shutdown: bool = False

28

29 def _notify_waiter(self, waiter: asyncio.Event) -> None:

30 if self.loop:

31 self.loop.call_soon_threadsafe(waiter.set)

67 if timeout:

68 try:

69 await asyncio.wait_for(self.waiter.wait(), timeout)

70 except asyncio.TimeoutError:

111 if timeout:

112 try:

113 await asyncio.wait_for(self.drain_waiter.wait(), timeout)

114 except asyncio.TimeoutError:

test_base_service.py (https://github.com/facebookincubator/FCR.git) Python · 152 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3

7 # LICENSE file in the root directory of this source tree.

8

9 import asyncio

10

11 import mock

37 service = DummyServiceTask(self._mock_service, "RunTest")

38

39 self.wait_for_tasks()

40 self.assertTrue(service._run_called)

41 self.assertTrue(service._cleanup_called)

52 async def run(self):

53 self._run_called = True

54 await asyncio.sleep(60, loop=self.service.loop)

55 self._run_complete = True

56

server_base.py (https://github.com/LIMXTEC/electrumx.git) Python · 126 lines

6 # and warranty status of this software.

7

8 import asyncio

9 import logging

10 import os

20 Derived classes are expected to:

21

22 - set PYTHON_MIN_VERSION and SUPPRESS_MESSAGES as appropriate

23 - implement the start_servers() coroutine, called from the run() method.

24 Upon return the event loop runs until the shutdown signal is received.

31 ]

32

33 PYTHON_MIN_VERSION = (3, 6)

34

35 def __init__(self, env):

11_play_song.py (https://github.com/anki/cozmo-python-sdk.git) Python · 62 lines

1 #!/usr/bin/env python3

2

3 # Copyright (c) 2018 Anki, Inc.

21 '''

22

23 import asyncio

24 import time

25

47

48 # Play the ascending notes

49 robot.play_song(notes, loop_count=1).wait_for_completed()

50

51 # Create an array of SongNote objects, consisting of the C3 pitch with varying durations

58

59 # Play the notes with varying durations

60 robot.play_song(notes, loop_count=1).wait_for_completed()

61

62 cozmo.run_program(cozmo_program)

exchange.py (https://github.com/mosquito/aio-pika.git) Python · 262 lines

79 self, timeout: TimeoutType = None

80 ) -> aiormq.spec.Exchange.DeclareOk:

81 return await asyncio.wait_for(

82 self.channel.exchange_declare(

83 self.name,

154 )

155

156 return await asyncio.wait_for(

157 self.channel.exchange_bind(

158 arguments=arguments,

191 )

192

193 return await asyncio.wait_for(

194 self.channel.exchange_unbind(

195 arguments=arguments,

smoke_test.py (https://github.com/piqueserver/piqueserver.git) Python · 87 lines

1 #!/usr/bin/python3

2 """

3 usage: smoke_test.py [-h] [--timeout TIMEOUT] [--config-dir CONFIG_DIR]

15

16

17 import asyncio

18 import sys

19 import argparse

42 async def smoketest(config_dir: str, timeout: int):

43 cmd = "piqueserver -d {}".format(config_dir)

44 proc = await asyncio.create_subprocess_exec(

45 "piqueserver",

46 "-d",

54 asyncio.ensure_future(_read_stream(proc.stderr, stderrprinter))

55 try:

56 await asyncio.wait_for(proc.wait(), timeout=timeout)

57 except asyncio.TimeoutError:

power_management.md (https://github.com/postlund/pyatv.git) Markdown · 53 lines

15 After connecting to a device, you get the power management via {% include api i="interface.AppleTV.power" %}:

16

17 ```python

18 atv = await pyatv.connect(config, ...)

19 pwrc = atv.power

22 You can then control via the available functions:

23

24 ```python

25 await pwrc.turn_on()

26 await pwrc.turn_off()

29 To get current power state use following property:

30

31 ```python

32 @property

33 def power_state(self) -> const.PowerState:

51 ```python

52 await asyncio.wait_for(pwrc.turn_off(await_new_state=True), timeout=5)

53 ```

54

receive_log_topic.py (https://github.com/elastic-coders/aioamqp.git) Python · 53 lines

34 yield from channel.exchange(exchange_name, 'topic')

35

36 yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)

37

38 binding_keys = sys.argv[1:]

42

43 for binding_key in binding_keys:

44 yield from asyncio.wait_for(channel.queue_bind(exchange_name='topic_logs',

45 queue_name=queue_name,

46 routing_key=binding_key), timeout=10)

48 print(' [*] Waiting for logs. To exit press CTRL+C')

49

50 yield from asyncio.wait_for(channel.basic_consume(queue_name, callback=callback), timeout=10)

51

52

command_server.py (https://github.com/facebookincubator/FCR.git) Python · 85 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3

7 # LICENSE file in the root directory of this source tree.

8

9 from fbnet.command_runner_asyncio.CommandRunner.Command import Processor

10 from thrift.server.TAsyncioServer import ThriftServerProtocolFactory

38

39 # Wait for FBNet to finish its run

40 await self.service.device_db.wait_for_data()

41

42 event_handler = self._create_thrift_event_handler()

uasyncio_micropython.py (https://github.com/mcauser/micropython.git) Python · 37 lines

1 # Test MicroPython extensions on CPython asyncio:

2 # - sleep_ms

3 # - wait_for_ms

4

5 try:

6 import utime, uasyncio

7 except ImportError:

8 print("SKIP")

24

25 # When task finished before the timeout

26 print(await uasyncio.wait_for_ms(task(1, 5), 50))

27

28 # When timeout passes and task is cancelled

29 try:

30 print(await uasyncio.wait_for_ms(task(2, 50), 5))

31 except uasyncio.TimeoutError:

roster_browser.py (https://github.com/louiz/SleekXMPP.git) Python · 142 lines

1 #!/usr/bin/env python3

2 # -*- coding: utf-8 -*-

3

16 import slixmpp

17 from slixmpp.exceptions import IqError, IqTimeout

18 from slixmpp.xmlstream.asyncio import asyncio

19

20

34 # our roster.

35 self.add_event_handler("session_start", self.start)

36 self.add_event_handler("changed_status", self.wait_for_presences)

37

38 self.received = set()

39 self.presences_received = asyncio.Event()

40

41 @asyncio.coroutine

time.py (https://github.com/vxgmichel/aiostream.git) Python · 65 lines

1 """Time-specific operators."""

2

3 import asyncio

4

5 from ..aiter_utils import anext

9

10

11 async def wait_for(aw, timeout):

12 task = asyncio.ensure_future(aw)

13 try:

14 return await asyncio.wait_for(task, timeout)

15 finally:

16 # Python 3.6 compatibility

19 try:

20 await task

21 except asyncio.CancelledError:

22 pass

23

entrypoint.rst (https://github.com/aiokitchen/aiomisc.git) ReStructuredText · 110 lines

8 :name: test_entrypoint_simple

9

10 import asyncio

11 import aiomisc

12

20 Complete example:

21

22 .. code-block:: python

23 :name: test_entrypoint_complex

24

48 :name: test_entrypoint_async

49

50 import asyncio

51 import aiomisc

52 import logging

67 async with aiomisc.entrypoint(service) as ep:

68 try:

69 await asyncio.wait_for(ep.closing(), timeout=1)

70 except asyncio.TimeoutError:

uasyncio_wait_for_fwd.py (https://github.com/mcauser/micropython.git) Python · 60 lines

1 # Test asyncio.wait_for, with forwarding cancellation

2

3 try:

4 import uasyncio as asyncio

5 except ImportError:

6 try:

17 except asyncio.CancelledError as er:

18 # CPython wait_for raises CancelledError inside task but TimeoutError in wait_for

19 print("awaiting canceled")

20 if return_if_fail:

32 async def wait():

33 try:

34 await asyncio.wait_for(awaiting(2, catch_inside), 1)

35 except asyncio.TimeoutError as er:

syl_automate.py (https://github.com/DOWRIGHTTV/DNX-FWALL-CMD.git) Python · 94 lines

1 #!/usr/bin/env python3

2

3 import os, sys

31 self.SyslogService = SyslogService

32

33 self.Initialize.wait_for_threads(count=1)

34 threading.Thread(target=self.get_settings).start()

35

73 # syslog_servers = deepcopy(self.SyslogService.syslog_servers)

74 # for server_ip in syslog_servers:

75 # reach = await asyncio.create_subprocess_shell(

76 # f'ping -c 2 {server_ip}',

77 # stdout=asyncio.subprocess.PIPE,

78 # stderr=asyncio.subprocess.PIPE)

79

80 # await reach.communicate()

pool.rst (https://github.com/aiokitchen/aiomisc.git) ReStructuredText · 47 lines

8 Example for ``aioredis``:

9

10 .. code-block:: python

11

12 import asyncio

29 async def _check_instance(self, instance: aioredis.Redis):

30 try:

31 await asyncio.wait_for(instance.ping(1), timeout=0.5)

32 except:

33 return False

45

46

47 asyncio.run(main())

48

receive_log_direct.py (https://github.com/elastic-coders/aioamqp.git) Python · 53 lines

1 #!/usr/bin/env python

2 """

3 Rabbitmq.com pub/sub example

33 yield from channel.exchange(exchange_name, 'direct')

34

35 yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)

36

37 severities = sys.argv[1:]

41

42 for severity in severities:

43 yield from asyncio.wait_for(channel.queue_bind(exchange_name='direct_logs',

44 queue_name=queue_name,

45 routing_key=severity), timeout=10)

47 print(' [*] Waiting for logs. To exit press CTRL+C')

48

49 yield from asyncio.wait_for(channel.basic_consume(queue_name, callback=callback), timeout=10)

50 yield from asyncio.Event().wait()