本文整理汇总了Python中asyncio.set_event_loop_policy方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.set_event_loop_policy方法的具体用法?Python asyncio.set_event_loop_policy怎么用?Python asyncio.set_event_loop_policy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.set_event_loop_policy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_asyncio_patch
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def _init_asyncio_patch():
"""
Select compatible event loop for Tornado 5+.
As of Python 3.8, the default event loop on Windows is `proactor`,
however Tornado requires the old default "selector" event loop.
As Tornado has decided to leave this to users to set, MkDocs needs
to set it. See https://github.com/tornadoweb/tornado/issues/2608.
"""
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
import asyncio
try:
from asyncio import WindowsSelectorEventLoopPolicy
except ImportError:
pass # Can't assign a policy which doesn't exist.
else:
if not isinstance(asyncio.get_event_loop_policy(), WindowsSelectorEventLoopPolicy):
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
示例2: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def main():
args = parse_args()
if args.uvloop:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
task = loop.create_task(Benchmark(args).bench_simple())
task.add_done_callback(lambda _, loop=loop: loop.stop())
def signal_hndl(_task=task):
_task.cancel()
loop.add_signal_handler(signal.SIGTERM, signal_hndl)
loop.add_signal_handler(signal.SIGINT, signal_hndl)
try:
loop.run_forever()
finally:
loop.close()
if not task.cancelled():
task.result()
示例3: init
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def init(self, path_app_root, path_data):
log.initialize()
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
cfg = tp_cfg()
cfg.app_path = path_app_root
cfg.static_path = os.path.join(path_app_root, 'static')
cfg.template_path = os.path.join(path_app_root, 'view')
cfg.res_path = os.path.join(path_app_root, 'res')
cfg.data_path = path_data
cfg.cfg_path = os.path.join(path_data, 'etc')
cfg.log_path = os.path.join(path_data, 'log')
self._cfg_file = os.path.join(cfg.cfg_path, 'web.ini')
if not cfg.load(self._cfg_file):
return False
return True
示例4: asyncio_worker
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def asyncio_worker(
config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
) -> None:
app = load_application(config.application_path)
shutdown_trigger = None
if shutdown_event is not None:
shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)
if config.workers > 1 and platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # type: ignore
_run(
partial(worker_serve, app, config, sockets=sockets),
debug=config.debug,
shutdown_trigger=shutdown_trigger,
)
示例5: uvloop_worker
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def uvloop_worker(
config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
) -> None:
try:
import uvloop
except ImportError as error:
raise Exception("uvloop is not installed") from error
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
app = load_application(config.application_path)
shutdown_trigger = None
if shutdown_event is not None:
shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)
_run(
partial(worker_serve, app, config, sockets=sockets),
debug=config.debug,
shutdown_trigger=shutdown_trigger,
)
示例6: event_loop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def event_loop(request):
"""Overwrite `pytest_asyncio` eventloop to fix Windows issue.
Default implementation causes `NotImplementedError` on Windows with
Python 3.8, because they changed default eventloop in 3.8.
NOTE: We do the same thing in the `example/settings.py` because it
imports (and fails) before we have a chance to invoke this fixture.
So, we could avoid adding this fixture, but I feel it is better to
keep the proper solution here as well.
"""
if sys.platform == "win32" and sys.version_info.minor >= 8:
asyncio.set_event_loop_policy(
asyncio.WindowsSelectorEventLoopPolicy() # pylint: disable=no-member
)
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
示例7: test_it_logs_messages
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def test_it_logs_messages(self):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
async def test():
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader)
transport, _ = await loop.connect_read_pipe(
lambda: protocol, self.read_pipe
)
logger = Logger.with_default_handlers()
await logger.info("Xablau")
logged_content = await reader.readline()
self.assertEqual(logged_content, b"Xablau\n")
transport.close()
await logger.shutdown()
loop.run_until_complete(test())
示例8: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def main() -> int:
print("Hello, World!")
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(RedisProtocol, "127.0.0.1", 7878)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
return 0
示例9: _init_asyncio_patch
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def _init_asyncio_patch():
"""
Select compatible event loop for Tornado 5+.
As of Python 3.8, the default event loop on Windows is `proactor`,
however Tornado requires the old default "selector" event loop.
As Tornado has decided to leave this to users to set, MkDocs needs
to set it. See https://github.com/tornadoweb/tornado/issues/2608.
"""
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
import asyncio
try:
from asyncio import WindowsSelectorEventLoopPolicy
except ImportError:
pass # Can't assign a policy which doesn't exist.
else:
if not isinstance(asyncio.get_event_loop_policy(), WindowsSelectorEventLoopPolicy):
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
示例10: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def __init__(self,instance,host="localhost",port=None,autoreload=False):
super(WebServer, self).__init__()
self.app=None
self.instance=instance
self.host=host
self.autoreload=autoreload
if port is not None:
self.port = port
while not isFree("localhost", self.port):
self.port += 1
self.instance._webserver=(self.host,self.port)
try: # https://bugs.python.org/issue37373 FIX: tornado/py3.8 on windows
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
except:
pass
示例11: test_get_event_loop_returns_running_loop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def test_get_event_loop_returns_running_loop(self):
class Policy(asyncio.DefaultEventLoopPolicy):
def get_event_loop(self):
raise NotImplementedError
loop = None
old_policy = asyncio.get_event_loop_policy()
try:
asyncio.set_event_loop_policy(Policy())
loop = asyncio.new_event_loop()
self.assertIs(asyncio._get_running_loop(), None)
async def func():
self.assertIs(asyncio.get_event_loop(), loop)
self.assertIs(asyncio._get_running_loop(), loop)
loop.run_until_complete(func())
finally:
asyncio.set_event_loop_policy(old_policy)
if loop is not None:
loop.close()
self.assertIs(asyncio._get_running_loop(), None)
示例12: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def __init__(self, verbosity=0, max_tasks=512):
"""Constructor.
Args:
verbosity: set output verbosity: 0 (default) is none, 3 is debug
max_tasks: the maximum number of tasks asyncio will queue (default 512)
"""
self.tasks = []
self.errors = []
self.fqdn = []
self.ignore_hosts = []
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
self.loop = asyncio.get_event_loop()
self.resolver = aiodns.DNSResolver(loop=self.loop, rotate=True)
self.sem = asyncio.BoundedSemaphore(max_tasks)
self.max_tasks = max_tasks
self.verbosity = verbosity
self.logger = ConsoleLogger(verbosity)
示例13: check
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def check(self, src, value):
policy = asyncio.get_event_loop_policy()
loop = policy.new_event_loop()
asyncio.set_event_loop_policy(ForbiddenEventLoopPolicy())
try:
loop.run_until_complete(self._check(src, value, loop))
finally:
loop.close()
asyncio.set_event_loop_policy(policy)
示例14: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass
self.__started = False
self.__tasks = {}
self.__procs = {}
self.loop = asyncio.get_event_loop()
示例15: pytest_configure
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import set_event_loop_policy [as 别名]
def pytest_configure(config):
bins = config.getoption('--redis-server')[:]
cmd = 'which redis-server'
if not bins:
with os.popen(cmd) as pipe:
path = pipe.read().rstrip()
assert path, (
"There is no redis-server on your computer."
" Please install it first")
REDIS_SERVERS[:] = [path]
else:
REDIS_SERVERS[:] = bins
VERSIONS.update({srv: _read_server_version(srv)
for srv in REDIS_SERVERS})
assert VERSIONS, ("Expected to detect redis versions", REDIS_SERVERS)
class DynamicFixturePlugin:
@pytest.fixture(scope='session',
params=REDIS_SERVERS,
ids=format_version)
def server_bin(self, request):
"""Common for start_server and start_sentinel
server bin path parameter.
"""
return request.param
config.pluginmanager.register(DynamicFixturePlugin(), 'server-bin-fixture')
if config.getoption('--uvloop'):
try:
import uvloop
except ImportError:
raise RuntimeError(
"Can not import uvloop, make sure it is installed")
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())