The mechanic is very similar. You have Cmd superclass, you can override
class method and add yours own.

Features

support command line for Windows and POSIX systems

build-in help or ? command to list all available command

build-in exit command for emergency stop asyncio loop

support repeat last cmd command by sending empty string

Getting started

Simple example

This is very simple example to show you main features and how they can
be used.

First of all, we are create new class and inherited our Cmd class.
Do not instantiate Cmd itself.

Than create instance of this new class and run loop.

classSimpleCommander(Cmd):def__init__(self,mode,intro,prompt):# We need to pass in Cmd class mode of async cmd runningsuper().__init__(mode=mode)self.intro=introself.prompt=promptself.loop=Nonedefdo_tasks(self,arg):"""
Our example method. Type "tasks <arg>"
:param arg: contain args that go after command
:return: None
"""fortaskinasyncio.Task.all_tasks(loop=self.loop):print(task)defstart(self,loop=None):# We pass our loop to Cmd class.# If None it try to get default asyncio loop.self.loop=loop# Create async tasks to run in loop. There is run_loop=false by defaultsuper().cmdloop(loop)# For win system we have only Run mode# For POSIX system Reader mode is preferredifsys.platform=='win32':loop=asyncio.ProactorEventLoop()mode="Run"else:loop=asyncio.get_event_loop()mode="Reader"# create instancecmd=SimpleCommander(mode=mode,intro="This is example",prompt="example> ")cmd.start(loop)# prepaire instancetry:loop.run_forever()# our cmd will run automatilly from this momentexceptKeyboardInterrupt:loop.stop()

General example

We use our simple example, but add some new staff: * sleep_n_print
coroutine that will be called from our cli command * do_sleep new
method (sleep cli command) that add task to event loop

asyncdefsleep_n_print(loop,time_to_sleep=None):"""
This is our simple coroutine.
:param time_to_sleep: time to sleep in seconds
:return: await sleep for time_to_sleep seconds
"""asyncio.set_event_loop(loop)# set correct event loopawaitasyncio.sleep(int(time_to_sleep))print("Wake up! I was slept for {0}s".format(time_to_sleep))

Aiohttp implementation

This is practical example how to control aiohttp instances. We will
create two cli command start and stop. This commands get port
number as only one argument. Let’s make some changes for our general
example: