Package: asynccmd
asynccmdAsync implementation of Cmd Python lib.Asynccmd is a library to build command line interface for you asyncio
project.It’s very simple like original Cmd libhttps://docs.python.org/3.6/library/cmd.html.The mechanic is very similar. You have Cmd superclass, you can override
class method and add yours own.Featuressupport command line for Windows and POSIX systemsbuild-inhelpor?command to list all available commandbuild-inexitcommand for emergency stop asyncio loopsupport repeat last cmd command by sending empty stringGetting startedSimple exampleThis 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 ourCmdclass.
Do not instantiateCmditself.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()Link to
simple.pyGeneral exampleWe use our simple example, but add some new staff: *sleep_n_printcoroutine that will be called from our cli command *do_sleepnew
method (sleep cli command) that add task to event loopasyncdefsleep_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))defdo_sleep(self,arg):"""
    Our example cmd-command-method for sleep. sleep <arg>
    :param arg: contain args that go after command
    :return: None
    """self.loop.create_task(sleep_n_print(self.loop,arg))Link to
main.pyRun our cli and makesleep 10command 3 times. Now we have 3sleep_n_printasync tasks in our event loop. If you usetaskscommand, you see something like that.example>tasks<Taskpendingcoro=<sleep_n_print()runningatasynccmd\examples\main.py:13>wait_for=<Futurependingcb=[Task._wakeup()]>><Taskpendingcoro=<Cmd._read_line()runningatC:\ProgramFiles\Python35\lib\site-packages\asynccmd\asynccmd.py:141>><Taskpendingcoro=<sleep_n_print()runningatasynccmd\examples\main.py:13>wait_for=<Futurependingcb=[Task._wakeup()]>><Taskpendingcoro=<sleep_n_print()runningatasynccmd\examples\main.py:13>wait_for=<Futurependingcb=[Task._wakeup()]>>example>Wakeup!Iwassleptfor10sWakeup!Iwassleptfor10sWakeup!Iwassleptfor10sAiohttp implementationThis is practical example how to control aiohttp instances. We will
create two cli commandstartandstop. This commands get port
number as only one argument. Let’s make some changes for our general
example:Create class helper that will be do all aiohttp staff for us.classAiohttpCmdHelper:"""
    Helper class that do all aiohttp start stop manipulation
    """port=8080# Default portloop=None# By default loop is not setdef__init__(self,loop,port):self.loop=loopself.port=portasyncdefhandle(self,request):"""
        Simple handler that answer http request get with port and name
        """name=request.match_info.get('name',"Anonymous")text='Aiohttp server running on{0}port. Hello,{1}'.format(str(self.port),str(name))returnweb.Response(text=text)asyncdefstart(self):"""
        Start aiohttp web server
        """self.app=web.Application()self.app.router.add_get('/',self.handle)self.app.router.add_get('/{name}',self.handle)self.handler=self.app.make_handler()self.f=self.loop.create_server(self.handler,host='0.0.0.0',port=self.port)# Event loop is already runing, so we await create server instead# of run_until_completeself.srv=awaitself.fasyncdefstop(self):"""
        Stop aiohttp server
        """self.srv.close()awaitself.srv.wait_closed()awaitself.app.shutdown()awaitself.handler.shutdown(60.0)awaitself.app.cleanup()Now we ready to addstartandstopcommand toCommander.# Add property to store helper objectsaiohttp_servers=[]# ...defdo_start(self,arg):"""
    Our example cli-command-method for start aiohttp server. start <arg>
    :param arg: Port number
    :return: None
    """ifnotarg:# we use simple check in our demonstrationprint("Error port is empty")else:test=AiohttpCmdHelper(loop=self.loop,port=int(arg))self.aiohttp_servers.append({'port':int(arg),'server':test})self.loop.create_task(test.start())defdo_stop(self,arg):"""
    Our example cli-command-method for stop aiohttp server. start <arg>
    :param arg: Port number
    :return: None
    """ifnotarg:# we use simple check in our demonstrationprint("Error! Provided port is empty")else:aiohttp_servers=[]forsrvinself.aiohttp_servers:ifsrv['port']==int(arg):self.loop.create_task(srv['server'].stop())else:aiohttp_servers.append({'port':srv['port'],'server':srv['server']})self.aiohttp_servers=aiohttp_serversWe need to addasyncio.set_event_loop(loop)addition to our main
example to prevent aiohttp to create its own loop.ifsys.platform=='win32':loop=asyncio.ProactorEventLoop()mode="Run"else:loop=asyncio.get_event_loop()mode="Reader"asyncio.set_event_loop(loop)# set our event loop for aiohttp (fix for Win32)That’s all. Now we can run multiple aiohttp server from our code.Link to
aiohttp_example.pyDocumentationTBDContributingMain stream is fork project, commit changes and send pull request.
Contributing to lib you could make in form of feedback, bug reports or
pull requests. CONTRIBUTING.md - TBD.RequirementsPython >= 3.5Licenseasynccmdis offered under the Apache 2 license.Source codeThe latest developer version is available athttps://github.com/valentinmk/asynccmd