def app_main(): args = docopt.docopt(__doc__, version=__version__) debug = args["-d"] if debug: log_level = logging.DEBUG else: log_level = [logging.ERROR, logging.INFO, logging.DEBUG][args["-v"]] try: import coloredlogs coloredlogs.install( level=log_level, stream=stderr, datefmt=DATEFMT, fmt=LOGFMT ) except ImportError: _LOGGER.debug("no colored logs. pip install coloredlogs?") logging.basicConfig( level=log_level, stream=stderr, datefmt=DATEFMT, format=LOGFMT ) logging.captureWarnings(debug) if debug: _LOGGER.info("Debug is on") try: asyncio.run(main(args), debug=debug) # pylint: disable=no-member except KeyboardInterrupt: exit()
def test_asyncio_run_debug(self): async def main(expected): loop = asyncio.get_event_loop() self.assertIs(loop.get_debug(), expected) asyncio.run(main(False)) asyncio.run(main(True), debug=True)
def test_asyncio_run_raises(self): async def main(): await asyncio.sleep(0) raise ValueError('spam') with self.assertRaisesRegex(ValueError, 'spam'): asyncio.run(main())
def generate_code(node_tree: code_structure.TranslationUnitDecl, src_paths: List[str], output_dir: str, compiler: Compiler): from .base2 import GeneratorHeader objects = [] for src_path in src_paths: folder = Folder(output_dir) Generator.generator_mapping = {} queue = collections.deque() for element in node_tree.children(): queue.append((element, folder, None)) def pop(): try: return queue.pop() except IndexError: return None, None, None async def generate_elements(): nonlocal objects, queue element, folder, parent = pop() while element is not None: if os.path.abspath(element.location) != os.path.abspath(src_path) or element.is_implicit: element, folder, parent = pop() continue with GeneratorHeader.generator(element=element, src_path=src_path, folder=folder, parent=parent) as header_generator: try: header_generator.generate() except: log.exception("Failed to generate for element %s and its children" % element.name) return with GeneratorBody.generator(element=element, src_path=src_path, folder=folder, parent=parent) as body_generator: try: body_generator.generate() except: import traceback traceback.print_exc() log.exception("Failed to generate body for element %s" % element.name) return try: obj = await compiler.compile_async(body_generator.body_file_path) objects.append(obj) for child in element.children(): queue.append((child, header_generator.folder, header_generator)) except: log.exception("Failed to compile %s" % body_generator.body_file_path) element, folder, parent = pop() GeneratorBody.common_stream().flush() async def main(): await asyncio.gather(*[generate_elements() for _ in range(multiprocessing.cpu_count())]) obj = await compiler.compile_async(GeneratorBody.common_stream().name); objects.append(obj) asyncio.run(main()) return objects
def __del__(self): if self.__our_session: loop = asyncio.get_event_loop() closer = self.session.close() if loop.is_running(): asyncio.ensure_future(closer) else: asyncio.run(closer)
def main(): if WINDOWS: asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) try: asyncio.run(amain()) except (KeyboardInterrupt, SystemExit) as e: rootlogger.info('Received %r', e)
def event_handler(self, data): rpt = Reporter(data) rpt.adorn(self._pepper) fmt = rpt.tidy() detail = rpt.detail() if fmt: asyncio.run(RealTimeMessage.send(fmt)) if detail: self._result.append(detail)
def anotherproc(path): async def lotsofwrites(path): os.remove(pathlib.Path(path).with_suffix('.opts.yaml')) async with await s_lmdbslab.Slab.anit(path, map_size=100000) as slab: foo = slab.initdb('foo', dupsort=True) mapsize = slab.mapsize count = 0 while mapsize == slab.mapsize: count += 1 slab.put(b'abcd', s_common.guid(count).encode('utf8') + byts, dupdata=True, db=foo) asyncio.run(lotsofwrites(path))
def render_html_to_png(html_data, filename): ws_url = get_ws_url() for i in range(0, 2): if i == 1: ws_url = get_ws_url(force=True) try: asyncio.run(render_html_async(html_data, filename, ws_url=ws_url)) return except: if i > 0: raise
def test_asyncio_run_from_running_loop(self): async def main(): coro = main() try: asyncio.run(coro) finally: coro.close() # Suppress ResourceWarning with self.assertRaisesRegex(RuntimeError, 'cannot be called from a running'): asyncio.run(main())
def run_async_test(self, func, jumpFrom, jumpTo, expected, error=None, event='line', decorated=False): tracer = JumpTracer(func, jumpFrom, jumpTo, event, decorated) sys.settrace(tracer.trace) output = [] if error is None: asyncio.run(func(output)) else: with self.assertRaisesRegex(*error): asyncio.run(func(output)) sys.settrace(None) self.compare_jump_output(expected, output)
def main() -> None: """ main method of application, expressed as a function so pylint won't complain about how I use the main namespace. Boots asynchronous main method inside default event loop. :return: """ if "LOGGING_LEVEL" in environ: getLogger(None).setLevel(environ["LOGGING_LEVEL"]) getLogger(None).addHandler(StreamHandler()) run(amain())
def test_proactor_win_policy(self): async def main(): self.assertIsInstance( asyncio.get_running_loop(), asyncio.ProactorEventLoop) old_policy = asyncio.get_event_loop_policy() try: asyncio.set_event_loop_policy( asyncio.WindowsProactorEventLoopPolicy()) asyncio.run(main()) finally: asyncio.set_event_loop_policy(old_policy)
def run( bot_constructor: BotConstructor, config_file: str = "bot.conf", ) -> None: async def _run() -> None: while True: # Load the config file config = configparser.ConfigParser(allow_no_value=True) config.read(config_file) bot = bot_constructor(config, config_file) await bot.run() asyncio.run(_run())
def status_handler(self, data, runner_config=None): status = data.get('status', '') if isinstance(data, dict) else data for item in self._drawer: if item.get('status', None) == status: raw = item.get('raw', lambda: {})() after = item.get('after', lambda: {})() # print('====>', raw, after) rpt = Reporter(raw) rpt.adorn({raw.get('event'): after}) fmt = rpt.tidy() detail = rpt.detail() if fmt: asyncio.run(RealTimeMessage.send(fmt)) # await RealTimeMessage.send(fmt) if detail: self._result.append(detail)
def get_master_list(name, *args, **kwargs): assert name in ('mounts', 'pets', 'achievements', 'realms') async def get(): async with BnetClient() as client: return (await getattr(client, name)(*args, **kwargs)) return asyncio.run(get())
def run_modulebot( modulebot_constructor: ModuleBotConstructor, module_constructors: Dict[str, ModuleConstructor], config_file: str = "bot.conf", ) -> None: async def _run() -> None: while True: # Load the config file config = configparser.ConfigParser(allow_no_value=True) config.read(config_file) modulebot = modulebot_constructor(config, config_file, module_constructors) await modulebot.run() asyncio.run(_run())
def test_asyncio_run_reports_hanging_tasks_errors(self): lo_task = None call_exc_handler_mock = mock.Mock() async def leftover(): try: await asyncio.sleep(0.1) except asyncio.CancelledError: 1 / 0 async def main(): loop = asyncio.get_running_loop() loop.call_exception_handler = call_exc_handler_mock nonlocal lo_task lo_task = asyncio.create_task(leftover()) return 123 self.assertEqual(asyncio.run(main()), 123) self.assertTrue(lo_task.done()) call_exc_handler_mock.assert_called_with({ 'message': test_utils.MockPattern(r'asyncio.run.*shutdown'), 'task': lo_task, 'exception': test_utils.MockInstanceOf(ZeroDivisionError) })
def detect(attack_context): payloads: List[Injection] = asyncio.run(get_injections(attack_context)) if not payloads: click.echo(click.style('Error: No injections detected', 'red'), err=True) exit(1) for payload in payloads: click.echo(click.style(payload.name, 'green')) click.echo('Example: ' + click.style(payload.example, 'yellow')) click.echo() features: List[Tuple[Feature, bool]] = asyncio.run(get_features(attack_context, payloads[0])) click.echo('Detected features:') for feature, available in features: click.echo(click.style(feature.name, 'blue') + ': ', nl=False) click.echo(click.style(str(available), 'green' if available else 'red'))
def block_processing(evt1): ''' Function to make a base and call main(). Used as a Process target. Args: evt1 (multiprocessing.Event): event to twiddle ''' async def main(): base = await s_base.Base.anit() await base.addSignalHandlers() evt1.set() await base.waitfini() asyncio.run(main()) sys.exit(137)
def test_wraps_async(): # from https://github.com/mahmoud/boltons/issues/194 import asyncio def delayed(func): @wraps(func) async def wrapped(*args, **kw): await asyncio.sleep(1.0) return await func(*args, **kw) return wrapped async def f(): await asyncio.sleep(0.1) assert asyncio.iscoroutinefunction(f) f2 = delayed(f) assert asyncio.iscoroutinefunction(f2) # from https://github.com/mahmoud/boltons/pull/195 def yolo(): def make_time_decorator(wrapped): @wraps(wrapped) async def decorator(*args, **kw): return (await wrapped(*args, **kw)) return decorator return make_time_decorator @yolo() async def foo(x): await asyncio.sleep(x) start_time = time.monotonic() asyncio.run(foo(0.3)) duration = time.monotonic() - start_time # lol windows py37 somehow completes this in under 0.3 # "assert 0.29700000000002547 > 0.3" https://ci.appveyor.com/project/mahmoud/boltons/builds/22261051/job/3jfq1tq2233csqp6 assert duration > 0.25
def test_ping_elsewhere(): """ The following is a private network that you probably aren't on. Unless you are! Should always fail to route because you can't route to this address via the public internet. :return: """ assert(not run(ping("10.254.254.254")))
def test_asyncio_run_cancels_hanging_tasks(self): lo_task = None async def leftover(): await asyncio.sleep(0.1) async def main(): nonlocal lo_task lo_task = asyncio.create_task(leftover()) return 123 self.assertEqual(asyncio.run(main()), 123) self.assertTrue(lo_task.done())
def test(): urls = ( 'http://lilydjwg.is-programmer.com/', 'http://www.baidu.com', 'https://zh.wikipedia.org', # redirection 'http://redis.io/', 'http://lilydjwg.is-programmer.com/2012/10/27/streaming-gzip-decompression-in-python.36130.html', # maybe timeout 'http://img.vim-cn.com/22/cd42b4c776c588b6e69051a22e42dabf28f436', # image with length 'https://github.com/m13253/titlebot/blob/master/titlebot.py_', # 404 'http://lilydjwg.is-programmer.com/admin', # redirection 'http://twitter.com', # connect timeout 'http://www.wordpress.com', # reset 'http://jquery-api-zh-cn.googlecode.com/svn/trunk/xml/jqueryapi.xml', # xml 'http://lilydjwg.is-programmer.com/user_files/lilydjwg/config/avatar.png', # PNG 'http://img01.taobaocdn.com/bao/uploaded/i1/110928240/T2okG7XaRbXXXXXXXX_!!110928240.jpg', # JPEG with Start Of Frame as the second block 'http://file3.u148.net/2013/1/images/1357536246993.jpg', # JPEG that failed previous code 'http://gouwu.hao123.com/', # HTML5 GBK encoding 'https://github.com/lilydjwg/winterpy', # github url finder 'http://github.com/lilydjwg/winterpy', # github url finder with redirect 'http://导航.中国/', # Punycode. This should not be redirected 'http://t.cn/zTOgr1n', # multiple redirections 'http://www.galago-project.org/specs/notification/0.9/x408.html', # </TITLE\n> 'http://x.co/dreamz', # redirection caused false ConnectionClosed error 'https://www.inoreader.com', # malformed start tag: <meta http-equiv="Content-Type" content="text/html" ; charset="UTF-8"> 'https://linuxtoy.org/archives/linux-deepin-2014-alpha-into-new-deepin-world.html', # charref outside ASCII 'http://74.125.235.191/search?site=&source=hp&q=%E6%9C%8D%E5%8A%A1%E5%99%A8+SSD&btnG=Google+%E6%90%9C%E7%B4%A2', # right charset in HTTP, wrong in HTML 'http://digital.sina.com.hk/news/-7-1514837/1.html', # mixed Big5 and non-Big5 escaped Unicode character 'http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece7631046893b4c4380147c808c5528888448e435061e5a27b9e867750d04d6c57f6102ad4b57f7fa3372340126bc9fcc825e98e6d27e20d77465671df65663a70edecb5124b137e65ffed86ef0bb8025e3ddc5a2de4352ba44757d97818d4d0164dd1efa034093b1e842022e60adec40728f2d6058e93430c6508ae5256f779686d94b3db3&p=882a9e41c0d25ffc57efdc394c52&newp=8a64865b85cc43ff57e6902c495f92695803ed603fd3d7&user=baidu&fm=sc&query=mac%CF%C2%D7%EE%BA%C3%B5%C4%C8%CB%C8%CB%BF%CD%BB%A7%B6%CB&qid=&p1=5', # HTML document inside another, correct charset is in outside one and title inside 'http://www.wooyun.org/bugs/wooyun-2014-069132?214&1780', # provide cookie or loop 'https://togetherjs.com/', # fail if no SNI 'https://forum.suse.org.cn/', # most Linux distributions seem not to trust this 'http://www.aosabook.org/en/posa/parsing-xml-at-the-speed-of-light.html', # <span> tag inside <title> tag 'http://github.com/contact', # redirect and should not use GitHub API 'http://caml.inria.fr/pub/docs/manual-ocaml/', 'http://localhost/', # should fail with ValueError 'https://friends.nico', ) asyncio.run(main(urls))
def main(argv=None): if argv is None: argv = sys.argv try: if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) return asyncio.run(amain( args=argv[1:], prog=argv[0] )) except KeyboardInterrupt: print(file=sys.stderr)
def test_asyncio_run_closes_gens_after_hanging_tasks_errors(self): spinner = None lazyboy = None class FancyExit(Exception): pass async def fidget(): while True: yield 1 await asyncio.sleep(1) async def spin(): nonlocal spinner spinner = fidget() try: async for the_meaning_of_life in spinner: # NoQA pass except asyncio.CancelledError: 1 / 0 async def main(): loop = asyncio.get_running_loop() loop.call_exception_handler = mock.Mock() nonlocal lazyboy lazyboy = asyncio.create_task(spin()) raise FancyExit with self.assertRaises(FancyExit): asyncio.run(main()) self.assertTrue(lazyboy.done()) self.assertIsNone(spinner.ag_frame) self.assertFalse(spinner.ag_running)
def main() -> None: parser = ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--debug', action='store_true', help='increase printed output for debugging') parser.add_argument('--version', action='version', version='%(prog)s ' + __version__) parser.add_argument('--set-uid', metavar='USER', type=_get_pwd, help='drop privileges to user name or uid') parser.add_argument('--set-gid', metavar='GROUP', type=_get_grp, help='drop privileges to group name or gid') parser.add_argument('--logging-cfg', metavar='PATH', help='config file for logging') parser.add_argument('--no-service', dest='skip_services', action='append', metavar='NAME', help='do not run the given service') subparsers = parser.add_subparsers(dest='backend', help='which pymap backend to use') backends: _Backends = _load_entry_points('pymap.backend') services: _Services = _load_entry_points('pymap.service') for backend_name, backend_cls in backends.items(): backend_cls.add_subparser(backend_name, subparsers) for service_cls in services.values(): service_cls.add_arguments(parser) parser.set_defaults(skip_services=[]) args = parser.parse_args() if args.logging_cfg: logging.config.fileConfig(args.logging_config) else: logging.basicConfig(level=logging.WARNING) if args.debug: logging.getLogger(__package__).setLevel(logging.DEBUG) if not args.backend: parser.error('Expected backend name') backend_type = backends[args.backend] service_types = [service for name, service in services.items() if name not in args.skip_services] try: return asyncio.run(run(args, backend_type, service_types), debug=False) except KeyboardInterrupt: pass
def main() -> int: parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s' + __version__) parser.add_argument('--outfile', metavar='PATH', type=FileType('w'), default=sys.stdout, help='the output file (default: stdout)') parser.add_argument('--socket', metavar='PATH', help='path to socket file') subparsers = parser.add_subparsers(dest='command', help='which admin command to run') commands = _load_entry_points('pymap.admin.client') for command_name, command_cls in commands.items(): command_cls.add_subparser(command_name, subparsers) args = parser.parse_args() if not args.command: parser.error('Expected command name.') command = commands[args.command] return asyncio.run(run(parser, args, command), debug=False)
def serial_request(self, command, args=None, timeout=None): """Send a request. For convenience use ``__call__`` to call this method. Args: command (str): The name of the endpoint to call. args (dict): Arguments to pass to the endpoint function. timeout (float): Override the default timeout (seconds). Raises: ClientTimeout: If a response takes longer than timeout to arrive. ClientError: Coverall for all other issues including failed auth. Returns: object: The data exactly as returned from the endpoint function, nothing more, nothing less. """ return asyncio.run( self.async_request(command, args, timeout))
def test_asyncio_task_decimal_context(self): async def fractions(t, precision, x, y): with decimal.localcontext() as ctx: ctx.prec = precision a = decimal.Decimal(x) / decimal.Decimal(y) await asyncio.sleep(t) b = decimal.Decimal(x) / decimal.Decimal(y ** 2) return a, b async def main(): r1, r2 = await asyncio.gather( fractions(0.1, 3, 1, 3), fractions(0.2, 6, 1, 3)) return r1, r2 r1, r2 = asyncio.run(main()) self.assertEqual(str(r1[0]), '0.333') self.assertEqual(str(r1[1]), '0.111') self.assertEqual(str(r2[0]), '0.333333') self.assertEqual(str(r2[1]), '0.111111')
class AsyncPiSysData: def __await__(self): return PiSystemData() async def get_data(): return AsyncPiSysData() async def send(): # This should work for creating the async verison of the PiSystemData class. task1 = asyncio.create_task(get_data()) task2 = asyncio.create_task(asyncio.sleep(0.01)) await task1 await task2 st = dt.datetime.now() asyncio.run(send()) print(f"time: {dt.datetime.now() - st} seconds") UNITS = {1: "B", 1024: "KB", 1024*1024: "MB", 1024*1024*1024: "GB", 1024*1024*1024*1024: "TB"} @dataclass class CpuData: logical: int = field(init=False) freq: Dict[str, float] = field(init=False, metadata={"unit": "MHz"}) load: Dict[str, float] = field(init=False, metadata={"unit": "percent"}) temp: float = field(init=False, metadata={"unit": "°C"}) def __post_init__(self): self.logical = ps.cpu_count() cpu_freq = ps.cpu_freq(percpu=True) self.freq = {"current": cpu_freq[0].current, "min": cpu_freq[0].min, "max": cpu_freq[0].max}
def run(self): asyncio.run(self._life_cycle())
writer.write("cisco\n") await reader.readuntil("#") writer.write("terminal length 0\n") await reader.readuntil("#") sleep_sec = choice([4, 1, 5]) print(f"Посплю {sleep_sec} секунд") await asyncio.sleep(sleep_sec) print(f'Отправляю команду {command} на {device["host"]}') writer.write(command + "\n") output = await reader.readuntil("#") ssh.close() print(f'Получили данные от {device["host"]}') return output async def send_command_to_devices(devices, command): task_1 = asyncio.create_task(connect_ssh(devices[0], command)) task_2 = asyncio.create_task(connect_ssh(devices[1], command)) task_3 = asyncio.create_task(connect_ssh(devices[2], command)) result1 = await task_1 result2 = await task_2 result3 = await task_3 return [result1, result2, result3] if __name__ == "__main__": with open("devices.yaml") as f: devices = yaml.safe_load(f) results = asyncio.run(send_command_to_devices(devices, "sh ip int br")) pprint(results, width=120)
def removetasks(loop: object) -> object: tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] for task in tasks: # skipping over shielded coro still does not help if task._coro.__name__ == "cant_stop_me": continue task.cancel() print("Cancelling outstanding tasks") # await asyncio.gather(*tasks, return_exceptions=True) loop.stop() async def shutdown_signal(signal, loop): print("Received exit signal {signal.name}...") await removetasks(loop) available() connect() sleep(0.5) Gamepad() loop = asyncio.get_event_loop() loop.run_until_complete(is_connected()) asyncio.run(read_gamepad_inputs()) loop.close() #
def main(): """ main CLI entry point parses commands and jumps into the subprogram's entry point """ cli = argparse.ArgumentParser() cli.add_argument( "-c", "--config-path", default="/etc/abrechnung/abrechnung.yaml", help="config file, default: %(default)s", ) cli.add_argument("-d", "--debug", action="store_true", help="enable asyncio debugging") cli.add_argument("-v", "--verbose", action="count", default=0, help="increase program verbosity") cli.add_argument("-q", "--quiet", action="count", default=0, help="decrease program verbosity") subparsers = cli.add_subparsers() def add_subcommand(name, subcommand_class): subparser = subparsers.add_parser(name) subparser.set_defaults(subcommand_class=subcommand_class) subcommand_class.argparse_register(subparser) # add all the subcommands here from . import mailer add_subcommand("mailer", mailer.Mailer) from . import http add_subcommand("api", http.HTTPService) from . import database add_subcommand("db", database.CLI) from . import admin add_subcommand("admin", admin.Admin) from . import demo add_subcommand("demo", demo.Demo) args = vars(cli.parse_args()) # set up log level log_setup(args["verbose"] - args["quiet"]) # enable asyncio debugging # loop = asyncio.get_event_loop() # loop.set_debug(args["debug"]) config_path = args.pop("config_path") config = Config.from_file(Path(config_path)) try: subcommand_class = args.pop("subcommand_class") except KeyError: cli.error("no subcommand was given") subcommand_class.argparse_validate(args, cli.error) subcommand_object = subcommand_class(config=config, **args) asyncio.run(subcommand_object.run())
print(f"Requesting test XPX for {alice.address.address}") reply = requests.get( f"https://bctestnetfaucet.xpxsirius.io/api/faucet/GetXpx/{alice.address.address}" ).json() print(f"{reply}\n") except: print("not available") # Print their account credentials print_account_info(alice) name = "sharmelen" #put any name you want # Register namespace tx = models.RegisterNamespaceTransaction.create_root_namespace( deadline=models.Deadline.create(), network_type=network_type, namespace_name=name, duration=10) # Sign the transaction with Alice's account signed_tx = tx.sign_with(account=alice, gen_hash=block_info.generation_hash) # We run announce() as an asynchronous function because it uses Listener that comes # only in async implementation result = asyncio.run(announce(signed_tx)) print_account_mosaics(alice) print("Namespace has been sucessfully registered")
def run(self): try: self.result = asyncio.run(self.func(*self.args, **self.kwargs)) except Exception as e: self.exception = e
def uasubscribe(): asyncio.run(_uasubscribe())
def uaclient(): asyncio.run(_uaclient())
def uawrite(): asyncio.run(_uawrite())
def uals(): asyncio.run(_uals())
def uaread(): asyncio.run(_uaread())
else: firstPos = R / total if G == 0: secondPos = 0 else: secondPos = G / total return [firstPos, secondPos] biglight = Bridge('192.168.86.26') biglight.connect() for l in biglight.lights: print(l.name) async def Biglight(brightness, R, G, B): light_name = 'Deckenlicht' biglight.set_light(light_name, 'on', True) biglight.set_light(light_name, 'bri', brightness) biglight.set_light(light_name, 'xy', convertColor(R, G, B)) while (True): R = random.randint(0, 15) G = random.randint(0, 15) B = random.randint(0, 15) asyncio.run(Biglight(254, R, G, B)) time.sleep(5)
class GBNServerProtocol(GBNProtocol): FilterError = int(c['server']['FilterError']) FilterLost = int(c['server']['FilterLost']) def connection_made(self, transport): self.transport = transport async def main(): print("Starting UDP server") # Get a reference to the event loop as we plan to use # low-level APIs. loop = asyncio.get_running_loop() # One protocol instance will be created to serve all # client requests. transport, _ = await loop.create_datagram_endpoint( lambda: GBNServerProtocol(loop, None, print_rx=True, print_tx=True), local_addr=('127.0.0.1', int(c['server']['UDPPort'])), remote_addr=('127.0.0.1', int(c['client']['UDPPort'])), allow_broadcast=True) try: await asyncio.sleep(3600) # Serve for 1 hour. finally: transport.close() asyncio.run(main())
def __main(): asyncio.run(RecognizeAndRespond().run()) pass
from Aviao_class import Aviao import asyncio aviao1 = Aviao('Boing777', 'PYTHON', 2020, 'TAM') aviao2 = Aviao('TitanicAereo', 'NODE-JS', 2020, 'GOL') asyncio.run(aviao1.decolar()) asyncio.run(aviao1.pousar()) asyncio.run(aviao2.decolar()) asyncio.run(aviao2.pousar())
while True: await asyncio.sleep(1) except KeyboardInterrupt: pass finally: controller.stop_websocket() await controller.session.close() if __name__ == "__main__": logging.basicConfig(format="%(message)s", level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("host", type=str) parser.add_argument("username", type=str) parser.add_argument("password", type=str) parser.add_argument("-p", "--port", type=int, default=8443) parser.add_argument("-s", "--site", type=str, default="default") args = parser.parse_args() LOGGER.info("%s %s %s %s %s", args.host, args.username, args.password, args.port, args.site) asyncio.run( main( host=args.host, username=args.username, password=args.password, port=args.port, site=args.site, ))
print(f"Client {address}: {item} from {manager.address}") except QUEUE.Empty: continue async def main(count: int): init_queue_manager_server() term_ev: threading.Event = threading.Event() # pylint: disable=consider-using-with executor: concurrent.futures.ThreadPoolExecutor = ( concurrent.futures.ThreadPoolExecutor() ) i: int for i in range(count): asyncio.ensure_future( asyncio.get_running_loop().run_in_executor(executor, serve, i, term_ev) ) # Gracefully shut down try: await asyncio.get_running_loop().create_future() except asyncio.CancelledError: term_ev.set() executor.shutdown() raise if __name__ == "__main__": asyncio.run(main(int(sys.argv[1])))
def get_title(html, episode): print(f"{Fore.GREEN} getting title from episode {episode}") grabbing_page = soup(html, "html.parser") title = grabbing_page.find("h1") return "No title" if not title else title.text async def main_coro(): tasks = [] for episode in range(100, 130): task = (episode, aio.create_task(get_page(episode))) tasks.append(task) for episode, task in tasks: html = await task title = get_title(html, episode) print(f"{title}\n") if __name__ == '__main__': start = time.time() print(f"Started at {time.strftime('%X')}") aio.run(main_coro()) print( f"Finished at {time.strftime('%X')}, overall time is {time.time() - start}" )
{Fore.CYAN}│ / ____/ / / / /_/ / __/ /_/ / /_/ (__ ) │ {Fore.CYAN}│/_/ /_/ /_/\____/\___/_.___/\__,_/____/ │ {Fore.CYAN}│ │ {Fore.CYAN}└─────────────────────────────nina🪴#6666───┘''' print(title) def loadconfig(): global bearer, refresh, headers config.read('config.ini') bearer = config['Account']['bearer'] refresh = config['Account']['refresh_token'] headers={"Content-type": "application/json", "Authorization": "Bearer " + bearer} async def bearercheck(bearer, refresh, headers): async with aiohttp.ClientSession(headers=headers) as session: async with session.post("https://api.minecraftservices.com/minecraft/profile") as response: if response.status == 400: print(f'{Fore.GREEN}[Success] {response.status} {Fore.RESET}| Bearer is valid') else: async with session.post(f"https://api.gosnipe.tech/api/refresh?code={refresh}") as r: res = r.json() bearer = (await res)['access_token'] config.set('Account', 'bearer', bearer) with open('config.ini', 'w') as cfg: config.write(cfg) print(f'{Fore.GREEN}[Success] {r.status} {Fore.RESET}| Updated bearer') if __name__ == "__main__": loadconfig() results = asyncio.run(bearercheck(bearer, refresh, headers))
if url.scheme == 'https': reader, writer = await asyncio.open_connection( url.hostname, 443, ssl=True) else: reader, writer = await asyncio.open_connection( url.hostname, 80) query = ( f"HEAD {url.path or '/'} HTTP/1.0\r\n" f"Host: {url.hostname}\r\n" f"\r\n" ) writer.write(query.encode('latin-1')) while True: line = await reader.readline() if not line: break line = line.decode('latin-1').rstrip() if line: print(f'HTTP header> {line}') # Ignore the body, close the socket writer.close() # コメント: http://example.com/ で十分 url = sys.argv[1] asyncio.run(print_http_headers(url))
def async_entry(message=None, server=None, port=None, N=1, queue=None, validate=False): """Start async execution in current process""" if queue: queue.put(asyncio.run(tcp_client(message, server=server, port=port, N=N, validate=validate))) else: asyncio.run(tcp_client(message, server=server, port=port, N=N, validate=validate))
# -*- coding:utf-8 -*- # @author: Crepuscule_v # @time : 2021/1/22 # @file : getYingXiaoHao.py ''' 给定关键词,自动生成一篇营销号文章 ''' import asyncio async def getPassage(obj : str, event : str, anotherWay : str) -> str: passage = "" passage += f"{obj}{event}是怎么回事呢?" passage += f"{obj}相信大家都很熟悉, 但是{obj}{event}是怎么回事呢?下面小编就来带大家一起了解吧。" passage += f"{obj}{event}其实就是{anotherWay},大家可能会很惊讶,{event}怎么会是{anotherWay}呢? 但事实就是这样。" passage += f"这就是关于{obj}{event}的事情。大家有什么想法呢? 欢迎在评论区告诉小编一起讨论哦!" print(passage) return passage # DEBUG if __name__ == "__main__": asyncio.run(getPassage("xxx", "高数挂了", "高数不及格"))
from kasa import Discover from kasa import SmartPlug from os import path device_name = 'light-1' def setup_device_info(): devices = asyncio.run(Discover.discover()) for addr, dev in devices.items(): asyncio.run(dev.update()) if dev.alias == device_name: print("Found device") f = open("device-ip.txt", "a") f.write(addr) f.close() async def get_device(): f = open("device-ip.txt", "r") device = SmartPlug(f.read()) await device.update() await device.turn_off() if not path.exists("device-ip.txt"): print("Device IP not known, discovering devices now") setup_device_info() asyncio.run(get_device())
# ANSI colors c = ( "\033[0m", "\033[36m", "\033[91m", "\033[35m", ) async def makerandom(idx: int, threshold: int = 6) -> int: print(c[idx + 1] + f"Initiated makerandom({idx}.") i = random.randint(0, 10) while i <= threshold: print(c[idx + 1] + f"makerandom({idx} == {i} too low; retrying.") await asyncio.sleep(idx + 1) i = random.randint(0, 10) print(c[idx + 1] + f"---> Finished: makerandom({idx}) == {i}" + c[0]) return i async def main(): res = await asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3))) return res if __name__ == "__main__": random.seed(444) r1, r2, r3 = asyncio.run(main()) print() print(f"r1: {r1}, r2: {r2}, r3: {r3}")
""" Services ---------------- An example showing how to fetch all services and print them. Updated on 2019-03-25 by hbldh <*****@*****.**> """ import sys import asyncio import platform from bleak import BleakClient ADDRESS = ("24:71:89:cc:09:05" if platform.system() != "Darwin" else "B9EA5233-37EF-4DD6-87A8-2A875E821C46") async def main(address: str): async with BleakClient(address) as client: svcs = await client.get_services() print("Services:") for service in svcs: print(service) if __name__ == "__main__": asyncio.run(main(sys.argv[1] if len(sys.argv) == 2 else ADDRESS))
def main(): asyncio.run(go()) print("DONE")
'adjust': False }, reload_quotes=True, news_titles_source=news_titles_source, verbose=True, base_option='for_merge', add_time_features=True, nlp_treator=embedding_pool, nlp_treator_signature=['sister'], nlp_treator_config=config, nlp_ductor='post', export_chunk=100_000) # base_option='without' # data = await loader.read() data = asyncio.run(loader.read()) """ data = data.dropna() d = './result.csv' data.to_csv(d, sep=';', index=False) """ """ # data.columns = [x.replace('_PCT1', '') for x in data.columns.values] data.dropna().sort_values(by=['title', 'lag']) d = './dataset_use_timed.csv' data.dropna().sort_values(by=['title', 'lag']).to_csv(d, index=False) """ """ g = 'E:/dataset_use_timed.csv'
print('consume time :{}'.format((timeit.default_timer() - start))) async def async_download(i): # async def는 해당 함수를 코루틴으로 만들어줍니다. # i: int 라는 부분은 type annotation입니다. 본 소스의 동작에는 일체의 영향을 주지 않습니다. async with aiohttp.ClientSession( ) as session: # requests의 Session 클래스 같은 역할입니다. # 실제 요청을 비동기적으로 발생시킵니다. async with session.get( f'http://www.randomtext.me/api/lorem/p-1/32') as resp: # Python의 기본 open 함수는 비동기 입출력을 지원하지 않습니다. 그렇기에 외부 의존성을 씁니다. # 파일명 부분의 f'{i}.txt' 는 formatted string 구문입니다. async with aiofiles.open(f'{i}.txt', 'w') as f: await f.write(await resp.text()) # 결과를 text로 불러와서 파일에 저장합니다. if __name__ == '__main__': # sync_download( 'sync' ) makedir("async") os.chdir("async") start = timeit.default_timer() # 요청 2048개를 준비합니다. # 만든 당시에는 아직 아무것도 일어나지 않고, 아랫줄의 asyncio.wait에 의해 동시에 실행됩니다. tasks = [async_download(x) for x in range(128)] asyncio.run(asyncio.wait(tasks)) print('consume time :{}'.format((timeit.default_timer() - start)))
目前无法实现的功能: 1、暂时无法对 Grid3D 设置 轴线和轴坐标的 style (非白色背景下有问题) """ async def get_json_data(url: str) -> dict: async with ClientSession(connector=TCPConnector(ssl=False)) as session: async with session.get(url=url) as response: return await response.json() # 获取官方的数据 data = asyncio.run( get_json_data( url="https://echarts.baidu.com/examples/data/asset/data/nutrients.json" )) # 列名映射 field_indices = { "calcium": 3, "calories": 12, "carbohydrate": 8, "fat": 10, "fiber": 5, "group": 1, "id": 16, "monounsat": 14, "name": 0, "polyunsat": 15, "potassium": 7,