Skip to content

Instantly share code, notes, and snippets.

@jbcurtin
Last active June 15, 2019 13:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbcurtin/53e50232157c1f2899c1991e97e3b880 to your computer and use it in GitHub Desktop.
Save jbcurtin/53e50232157c1f2899c1991e97e3b880 to your computer and use it in GitHub Desktop.
A #microtutorial to show how to use asyncio and some other stdlib-tools, https://pugetsoundpython.slack.com/archives/C03LJKBPJ/p1530204386000485
#!/usr/bin/env python
'''
A #microtutorial to show how to use asyncio and some other stdlib-tools,
https://pugetsoundpython.slack.com/archives/C03LJKBPJ/p1530204386000485
Invoke with,
`python nhuntwalker-asyncio.py -m on`
`python nhuntwalker-asyncio.py -m awe`
`python nhuntwalker-asyncio.py`
For interesting results
'''
import argparse
import asyncio
import enum
import logging
import typing
# Always configure logging after std-lib and before pip/conda-installed libs.
# Sometimes when you import a module, it logs debug/info/error
logger = logging.getLogger('') # <--- Probable a good idea to name your logger. '' is the 'root' logger
sysHandler = logging.StreamHandler()
sysHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sysHandler)
logger.setLevel(logging.INFO)
import requests
EVENT_LOOP = None
class Mode(enum.Enum):
ON = 'on'
OFF = 'off'
def _obtain_event_loop():
"""
The native implementation of asyncio will return the same event loop.
uvloop will not.
"""
global EVENT_LOOP
if EVENT_LOOP is None:
EVENT_LOOP = asyncio.get_event_loop()
return EVENT_LOOP
def capture_options() -> typing.Any:
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', default=Mode.OFF, type=Mode)
return parser.parse_args()
async def main(options: typing.Any) -> None:
if options.mode is Mode.ON:
logger.info('ON')
else:
logger.info('OFF')
assert requests.get('https://jbcurtin.io/index.html').status_code is 200, 'jbcurtin.io seems to be down'
if __name__ in ['__main__']:
options = capture_options()
loop = _obtain_event_loop()
loop.run_until_complete(main(options))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment