def main(): parser = get_parser() args = parser.parse_args() curio.run(curio.tcp_server(args.host, args.port, yosser_handler))
def main(): parser = argparse.ArgumentParser() parser.add_argument('--gallery', nargs='*', default=['.', '../gallery']) parser.add_argument( '--snowy', action='store_true', help='random cat pictures') parser.add_argument( '--name', default='tree', help='what to show') args = parser.parse_args() farm = pigfarm.PigFarm() from karmapi.mclock2 import GuidoClock farm.add(GuidoClock) name = args.name if args.snowy: name = 'cat' farm.add(BeanField, dict(gallery=args.gallery, name=name)) curio.run(farm.run(), with_monitor=True)
def test_remove(tmp): p = tmp subpaths = [] m = Monitor(error_empty=True) for i in '1234': subpath = p/i subpath.touch() m.add_watch(subpath, EVENTS.DELETE_SELF) subpaths.append(subpath) assert(len(m._watches) == len(subpaths) == len(m.active_watches())) wd = m.add_watch(p, EVENTS.DELETE_SELF) it = iter(subpaths) def delpath(): try: next(it).unlink() except StopIteration: m.remove_watch(wd) async def do_watch(): try: async for event in m: delpath() except NoMoreWatches: return async def main(): t = await curio.spawn(curio.timeout_after(2, do_watch())) delpath() await t.join() curio.run(main()) with pytest.raises(ValueError): m.remove_watch(wd) assert not m._watches
def main(args=None): """ Retrieve images currently available There are usually six images available from the last half hour. """ parser = argparse.ArgumentParser() parser.add_argument('--pig', action='store_false', default=True) parser.add_argument('--minutes', type=int, default=30) parser.add_argument('path', nargs='?', default='~/karmapi/tankrain') parser.add_argument('--version', default='') args = parser.parse_args() if args.pig: farm = pigfarm.PigFarm() farm.add(TankRain, dict(path=args.path, version=args.version)) from karmapi.mclock2 import GuidoClock farm.add(GuidoClock) pigfarm.run(farm) sys.exit() else: curio.run(fetch(args.minutes))
def run(app): # add qt event loop to the curio tasks selector = win_curio_fix() selector = None curio.run(app.pig.run(), with_monitor=True, selector=selector)
def curio_test(x): async def main(): for n in range(COUNT): r = await curio.run_in_process(fib, x) start = time.time() curio.run(main()) end = time.time() print('Curio:', end-start)
def curio_test(): async def main(): for n in range(COUNT): await curio.run_in_thread(time.sleep, 0) start = time.time() curio.run(main()) end = time.time() print('Curio:', end-start)
def test_activation_base(): async def main(): await sleep(0.01) await sleep(0.01) await sleep(0.01) a = _TestActivation() run(main, activations=[a]) assert a.events == ['activate', 'created', 'running', 'suspended', 'running', 'suspended', 'running', 'suspended', 'running', 'suspended', 'terminated']
def test_several(tmpdir): m = Monitor() m.add_watch(tmpdir, (EVENTS.ACCESS, EVENTS.CREATE)) async def main(): tmpdir.mkdir('xxx') async for event in m.next_events(): assert event.name == 'xxx' assert event.is_dir assert str(event) in ('CREATE: xxx', 'ACCESS: xxx') curio.run(main())
def main(): parser = argparse.ArgumentParser(description=__description__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', dest='verbose', action='count', default=0, help='print verbose output') parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}') parser.add_argument('--pdb', dest='pdb', action='store_true') parser.add_argument('server', nargs='+', type=get_server) args = parser.parse_args() global verbose verbose = args.verbose try: run(multi_server(*args.server), pdb=args.pdb) except KeyboardInterrupt: pass
def test_context(tmpdir): async def do_watch(): monitor = watch(str(tmpdir), EVENTS.DELETE, oneshot=True) async with monitor as event: assert event.tp == EVENTS.DELETE with pytest.raises(OSError): os.fstat(monitor._fd) async def main(): t = await curio.spawn(do_watch()) np = await touch(tmpdir) Path(np).unlink() await t.join() curio.run(main())
def _curio_runner(coroutine): """ handler for curio autoawait """ import curio return curio.run(coroutine)
def test_iter(tmpdir): p = Path(tmpdir) async def do_watch(): count = 0 async for event in watch(p, EVENTS.CLOSE): count += 1 (p / str(count)).touch() if count == 5: break assert count == 5 async def main(): t = await curio.spawn(do_watch()) await touch(p) await t.join() curio.run(main())
def main(args=None): import argparse parser = argparse.ArgumentParser() parser.add_argument('--outfile', default='out.hush') parser.add_argument('--record', action='store_true') parser.add_argument('--infile') parser.add_argument('--nomick', action='store_true') args = parser.parse_args(args) if args.record: curio.run(arecord(open(args.outfile, 'wb'))) return from karmapi import sonogram from karmapi import pigfarm
def test_filters(tmp): p = tmp m = watch(p, EVENTS.ALL_EVENTS, filter="abc*d") async def do_watch(): async for event in m.next_events(): assert event.name == "abcXXd" async def main(): t = await curio.spawn(curio.timeout_after(1,do_watch())) (p/"xyz").touch() (p/"abcXXd").touch() await t.join() (p/"xyz").touch() #Cover the case where all the first events are filtered out t = await curio.spawn(do_watch()) (p/'XXX').touch() await curio.sleep(0) (p/"abcXXd").touch() await t.join() curio.run(main())
def test_symlinks(tmpdir): m1 = Monitor() m2 = Monitor() root_path = Path(tmpdir) watch_path = root_path / 'dir' watch_path.mkdir() f = watch_path / 'file' f.touch() link = watch_path / 'link' link.symlink_to(f) m1.add_watch(link, EVENTS.ALL_EVENTS, follow_symlinks=False) m2.add_watch(link, EVENTS.ALL_EVENTS) async def do_watch_m1(): async with m1: # pragma: no cover raise RuntimeError() async def do_watch_m2(t): async with m2: await t.cancel() async def main(): t1 = await curio.spawn(curio.timeout_after(2, do_watch_m1())) t2 = await curio.spawn(curio.timeout_after(2, do_watch_m2(t1))) with link.open('a') as wr: wr.write("Hello") await t2.join() with pytest.raises(curio.TaskError): await t1.join() curio.run(main(), with_monitor=True)
def test_interface(tmpdir): m = Monitor() with pytest.raises(TypeError): m.add_watch(tmpdir, "xxxx") with pytest.raises(TypeError): m.add_watch(1234, 0) p = Path(tmpdir) m.add_watch(p, 1) m.add_watch(tmpdir, EVENTS.CREATE) m.add_watch(tmpdir, EVENTS.DELETE_SELF, replace_existing=True) async def do_watch(): async for event in m.next_events(): assert event.tp != EVENTS.CREATE async def main(): t = await curio.spawn(do_watch()) with (p/'xxx').open('a'): pass (p/'xxx').unlink() p.rmdir() await t.join() curio.run(main())
def __getitem__(self, key): '''Get the search result for an address. This function may block long time when the address has not been searched. If an asynchronous version is needed, use ``get`` method. Parameters ---------- key: Address-like An address to get the search result. Returns ------- result: AWAState An state containing the search result. ''' key = Address(key) return curio.run(self.get(key))
# Example of making an SSL connection and downloading data import curio async def main(): sock = await curio.open_connection('www.python.org', 443, ssl=True, server_hostname='www.python.org') async with sock: await sock.sendall(b'GET / HTTP/1.0\r\nHost: www.python.org\r\n\r\n') chunks = [] while True: chunk = await sock.recv(10000) if not chunk: break chunks.append(chunk) response = b''.join(chunks) print(response.decode('latin-1')) if __name__ == '__main__': try: curio.run(main()) except KeyboardInterrupt: pass
# CPU-intensive work out to a separate process. from curio import run, run_in_process, tcp_server def fib(n): if n <= 2: return 1 else: return fib(n-1) + fib(n-2) async def fib_handler(client, addr): print('Connection from', addr) s = client.as_stream() async for line in s: try: n = int(line) result = await run_in_process(fib, n) resp = str(result) + '\n' await s.write(resp.encode('ascii')) except ValueError: await s.write(b'Bad input\n') print('Connection closed') await client.close() if __name__ == '__main__': run(tcp_server('', 25000, fib_handler))
""" stream_id = event.stream_id if stream_id and stream_id in self.flow_control_events: evt = self.flow_control_events.pop(stream_id) await evt.set() elif not stream_id: # Need to keep a real list here to use only the events present at # this time. blocked_streams = list(self.flow_control_events.keys()) for stream_id in blocked_streams: event = self.flow_control_events.pop(stream_id) await event.set() return if __name__ == '__main__': host = sys.argv[2] if len(sys.argv) > 2 else "localhost" print("Try GETting:") print( " On OSX after 'brew install curl --with-c-ares --with-libidn --with-nghttp2 --with-openssl':" ) print( "/usr/local/opt/curl/bin/curl --tlsv1.2 --http2 -k https://localhost:5000/bundle.js" ) print("Or open a browser to: https://localhost:5000/") print(" (Accept all the warnings)") run(h2_server((host, 5000), sys.argv[1], "{}.crt.pem".format(host), "{}.key".format(host)), with_monitor=True)
async def echo_client(client, addr): task = await current_task() clients.add(task) print('Connection from', addr) try: while True: data = await client.recv(1000) if not data: break await client.sendall(data) print('Connection closed') except CancelledError: await client.sendall(b'Server going down\n') finally: clients.remove(task) async def main(host, port): while True: async with SignalSet(signal.SIGHUP) as sigset: print('Starting the server') serv_task = await spawn(tcp_server(host, port, echo_client)) await sigset.wait() print('Server shutting down') await serv_task.cancel() for task in list(clients): await task.cancel() if __name__ == '__main__': run(main('', 25000))
# This should work on python 3.6+ import ahip URL = "http://httpbin.org/uuid" async def main(backend=None): with ahip.PoolManager(backend=backend) as http: print("URL:", URL) r = await http.request("GET", URL, preload_content=False) print("Status:", r.status) print("Data:", await r.read()) print("--- Trio ---") import trio trio.run(main) print("\n--- asyncio (via AnyIO) ---") import asyncio loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() print("\n--- Curio (via AnyIO) ---") import curio curio.run(main)
from settings import HOSTNAME, PORT # TIMEOUT_SECONDS = 0.1 async def play_game(client, addr): print('Connection from', addr) async with client: while True: data = await client.recv(1000) if not data: break msg = data.decode() if 'Are you alive' in msg: await client.sendall(bytes('Yes', encoding='utf-8')) continue print(msg) if 'Valid positions:' in msg: await client.sendall(bytes(input(), encoding='utf-8')) print('Game has ended') async def main(): client = await create_connection((HOSTNAME, PORT)) await play_game(client, HOSTNAME) if __name__ == '__main__': run(main)
import curio import yaaredis async def aio_child(): redis = yaaredis.StrictRedis(host='127.0.0.1', port=6379, db=0) await redis.flushdb() await redis.set('bar', 'foo') resp = await redis.get('bar') return resp async def wrapper(): async with curio.bridge.AsyncioLoop() as loop: return await loop.run_asyncio(aio_child) if __name__ == '__main__': print(curio.run(wrapper))
children = list() async with curio.TaskGroup() as f: children.append( await f.spawn(read_nop, proc.stderr) ) children.append( await f.spawn(handle_output, proc.stdout) ) await curio.sleep(100) if proc.poll(): logging.info("Detected that process has terminated") [x.cancel() for x in children] rc = proc.wait() if rc: logging.warn("Returned %d, stderr: %s", rc, proc.stderr.read()) proc.terminate() if __name__ == '__main__': if len(sys.argv) != 3: print("Usage: {} <rekall_profile> <domid>".format(sys.argv[0])) print("Run as root (sudo)!") sys.exit(1) logging.basicConfig(stream=sys.stderr, level=logging.INFO) (profile, domid) = sys.argv[1:] signal.signal(signal.SIGHUP, signal_handler) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGQUIT, signal_handler) signal.signal(signal.SIGABRT, signal_handler) curio.run(spawn_drakvuf, profile, domid)
def test_open_connection(): with pytest.raises(socket.gaierror): curio.run(open_connection("does-not-exists.com", 80))
from curio import run, tcp_server from curio import ssl from socket import * KEYFILE = "ssl_test_rsa" # Private key CERTFILE = "ssl_test.crt" # Certificate (self-signed) async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass s = client.as_stream() while True: data = await s.read(102400) if not data: break await s.write(data) await s.close() print('Connection closed') if __name__ == '__main__': ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE) run(tcp_server, '', 25000, echo_handler, ssl=ssl_context)
def run_connect_many_async(addrs): curio.run(connect_many_async, addrs)
def async_run(self, afunc): return curio.run(afunc)
# Example of launching a subprocess and reading streaming output from curio import subprocess import curio async def main(): p = subprocess.Popen(['ping', 'www.python.org'], stdout=subprocess.PIPE) async for line in p.stdout: print('Got:', line.decode('ascii'), end='') if __name__ == '__main__': try: curio.run(main()) except KeyboardInterrupt: pass
await sock.sendall(data) async def http_next_event(sock): while True: event = httpcon.next_event() if event is h11.NEED_DATA: httpcon.receive_data(await sock.recv(2048)) continue return event async def ws_send(sock, message, type, fin=True, status_code=None): await sock.sendall(wscon.send(ws.Data(message, type, fin, status_code))) async def ws_next_event(sock): while True: event = wscon.next_event() if event is ws.Information.NEED_DATA: stuff = await sock.recv(2048) if not stuff: print('no stuff') raise SystemExit wscon.recv(stuff) continue return event curio.run(main(('localhost', 25000)))
def func_wrapper(*args, **kwargs): return curio.run(func(*args, **kwargs))
def fib(n): if n <= 2: return 1 else: return fib(n-1) + fib(n-2) async def fib_handler(client, addr): print('Connection from', addr) s = client.as_stream() async for line in s: try: n = int(line) result = await run_in_process(fib, n) resp = str(result) + '\n' await s.write(resp.encode('ascii')) except ValueError: await s.write(b'Bad input\n') print('Connection closed') await client.close() if __name__ == '__main__': try: run(tcp_server('', 25000, fib_handler)) except KeyboardInterrupt: pass
await curio.sleep(5) print('Yes, go play.') await start_evt.set() # await curio.sleep(5) await goodbye.wait() del goodbye print("Let's go") count_task = await curio.spawn(countdown, 10) await count_task.join() print("We're leaving!") try: await curio.timeout_after(10, kid_task.join) except curio.TaskTimeout: print('I warned you!') await kid_task.cancel() print('Leaving!') """ Add the curio monitoring framework. """ if __name__ == '__main__': curio.run(parent, with_monitor=True) # EOF # Kid is now running the CPU intensive task in a separate process (thread).
# curiosslecho.py # # Use sslclient.py to test import curio from curio import ssl from curio import network from socket import * KEYFILE = "ssl_test_rsa" # Private key CERTFILE = "ssl_test.crt" # Certificate (self-signed) async def handle(client, addr): print('Connection from', addr) client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) async with client: while True: data = await client.recv(100000) if not data: break await client.sendall(data) print('Connection closed') if __name__ == '__main__': ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE) curio.run(network.tcp_server('', 25000, handle, ssl=ssl_context))
async def spammer(address, port): async with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while True: try: await sock.sendto(b'lol' * 512, (address, port)) await curio.sleep(0) except curio.TaskCancelled: break await sock.close() async def spam(address): tasks = collections.deque() async with curio.TaskGroup(wait=10) as spammers: for i in range(1, 65535): tasks.append(await spammers.spawn(spammer, address, i)) try: for t in tasks: await t.join() except KeyboardInterrupt: for t in tasks: await t.cancel() await spammers.join() if __name__ == '__main__': addr = sys.argv[1] curio.run(spam, addr)
def main(): result = curio.run(supervisor) # <12> print('Answer:', result)
############################################################ # MAIN ENTRY ############################################################ if __name__ == "__main__": folder = '' if len(sys.argv) < 2: logger.debug( "You must specify a path, e.g. dupeFinder.py /home/seed/media/TV") exit() else: folder = sys.argv[1] start_time = timeit.default_timer() results = curio.run(find_dupes(folder), with_monitor=True) time_taken = timeit.default_timer() - start_time logger.debug("Finished looking for dupes!\n") logger.debug("Time taken: %d seconds", time_taken) logger.debug("Videos scanned: %d", len(files) + len(dupes)) logger.debug("Skipped non videos: %d", len(non_videos)) if movies: logger.debug("Movies: %d", movies) if episodes: logger.debug("Episodes: %d", episodes) logger.debug("Non duplicates: %d", len(files)) logger.debug("Duplicates: %d\n", len(dupes)) if len(dupes): logger.debug("Dupes (Oldest):")
def get_team_data(self, team_numbers: List[int], callback: any) -> None: url_list = [ f'https://www.thebluealliance.com/api/v2/team/frc{team_number}' for team_number in team_numbers ] curio.run(self.main(url_list, callback))
# udp_echo # # An example of a simple UDP echo server. import curio from curio import socket async def main(addr): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(addr) while True: data, addr = await sock.recvfrom(10000) print('Received from', addr, data) await sock.sendto(data, addr) if __name__ == '__main__': curio.run(main(('', 26000)))
def get_event_data(self, event_codes: List[str], callback: any) -> None: url_list = [ f'https://www.thebluealliance.com/api/v2/event/{event_code}' for event_code in event_codes ] curio.run(self.main(url_list, callback))
# udp_echo # # An example of a simple UDP echo server. import curio from curio import socket async def main(addr): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(addr) while True: data, addr = await sock.recvfrom(10000) print('Received from', addr, data) await sock.sendto(data, addr) if __name__ == '__main__': curio.run(main, ('', 26000))
# udp_echo # # An example of a simple UDP echo server. import curio from curio import socket async def main(addr): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(addr) while True: data, addr = await sock.recvfrom(10000) print('Received from', addr, data) await sock.sendto(data, addr) if __name__ == '__main__': try: curio.run(main, ('', 26000)) except KeyboardInterrupt: pass
else: bot.db.close() sys.exit(0) def initdb(): '''run this if you wanna init the database''' db = sqlite3.connect('karma.db') cursor = db.cursor() cursor.execute('CREATE TABLE users(id INTEGER PRIMARY KEY, ' 'name TEXT, ' 'karma INTEGER)') try: db.commit() except Exception as error: print('Got error initializing the database', error) db.rollback() db.close() else: db.close() if __name__ == '__main__': if arguments.initdb: initdb() print('Database initialized') server = arguments.server port = arguments.port proxy = arguments.proxy run(main(server, port, proxy), with_monitor=True)
async def echo_server(address): sock = socket(AF_INET, SOCK_STREAM) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind(address) sock.listen(5) print("Server listening at", address) async with sock: while True: client, addr = await sock.accept() print("Connection from", addr) await spawn(echo_client(client)) async def echo_client(client): async with client: while True: data = await client.recv(10000) if not data: break await client.sendall(data) print("Connection closed") if __name__ == "__main__": try: run(echo_server(("", 25000))) except KeyboardInterrupt: pass
while True: client, addr = await sock.accept() await spawn(echo_client, client, addr) async def echo_client(client, addr): print('Connection from', addr) async with client: while True: data = await client.recv(1000) if not data: break await client.sendall(data) print('Connection closed') if __name__ == '__main__': run(echo_server, ('',25000)) from curio import run, spawn, tcp_server async def echo_client(client, addr): print('Connection from', addr) while True: data = await client.recv(1000) if not data: break await client.sendall(data) print('Connection closed')
# ssl_echo # # An example of a simple SSL echo client. Use ssl_echo.py for the server. import curio from curio import ssl from curio import network from curio import socket async def main(host, port): ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE sock = await network.open_connection(host, port, ssl=True, server_hostname=None) for i in range(1000): msg = ("Message %d" % i).encode("ascii") print(msg) await sock.sendall(msg) resp = await sock.recv(1000) assert msg == resp await sock.close() if __name__ == "__main__": try: curio.run(main("localhost", 10000)) except KeyboardInterrupt: pass
# udp_echo # # An example of a UDP echo client import curio async def main(addr): sock = await curio.open_unix_connection(addr) for i in range(1000): msg = ('Message %d' % i).encode('ascii') print(msg) await sock.send(msg) resp = await sock.recv(1000) assert msg == resp await sock.close() if __name__ == '__main__': try: curio.run(main, '/tmp/curiounixecho') except KeyboardInterrupt: pass
# Example: A simple Unix echo server from curio import run, unix_server async def echo_handler(client, address): print('Connection from', address) while True: data = await client.recv(10000) if not data: break await client.sendall(data) print('Connection closed') if __name__ == '__main__': import os try: os.remove('/tmp/curiounixecho') except: pass try: run(unix_server, '/tmp/curiounixecho', echo_handler) except KeyboardInterrupt: pass
print('Connection from', addr) async with client: while True: data = await client.recv(5) if not data: break pin = data[:2].decode() value = data[2:3].decode() try: await run_in_thread(set_data, pin, value) result = "OK" except Exception as e: print("Error: {}".format(e)) result = "ERROR" result += "\r\n" await client.sendall(result.encode()) print('Connection closed') def set_data(pin, value): gpio = mraa.Gpio(int(pin)) gpio.dir(mraa.DIR_OUT) gpio.write(int(value)) return gpio.read() if __name__ == '__main__': try: run(echo_server(('0.0.0.0', 25000))) except KeyboardInterrupt: print("Exit requested via keyboard interrupt")
from curio import run, tcp_server from curio import ssl from socket import * KEYFILE = "ssl_test_rsa" # Private key CERTFILE = "ssl_test.crt" # Certificate (self-signed) async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass s = client.as_stream() while True: data = await s.read(102400) if not data: break await s.write(data) await s.close() print('Connection closed') if __name__ == '__main__': ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE) run(tcp_server('', 25000, echo_handler, ssl=ssl_context))
from ..proto import commands_pb2 as commands, events_pb2 as events from .. import util async def main(): ap = argparse.ArgumentParser() ap.add_argument("host") ap.add_argument("port", type=int) args = ap.parse_args() logging.getLogger().setLevel(logging.DEBUG) logging.getLogger().addHandler( logging.FileHandler("reset.client.log", mode='w')) rules = Rules() protocol = ProtocolUser(logging.getLogger("protocol")) client = Client(logging.getLogger("client"), args.host, args.port, rules, protocol) flags = termios.tcgetattr(1) try: await client.run() except BaseException: termios.tcsetattr(1, termios.TCSANOW, flags) #sys.stdout.write("\x1bc") logging.getLogger().exception("Client crashed.") if __name__ == '__main__': curio.run(main(), with_monitor=True)