Skip to content

Instantly share code, notes, and snippets.

@ixe013
Created February 20, 2019 04:26
Show Gist options
  • Save ixe013/bcc2ccc2a5601004d4de29076d029c46 to your computer and use it in GitHub Desktop.
Save ixe013/bcc2ccc2a5601004d4de29076d029c46 to your computer and use it in GitHub Desktop.
Python Cmd cmdloop replacement to make it asyncio aware
#See https://stackoverflow.com/q/54425723/591064 for usage
async def adapter_cmdloop(self, intro=None):
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
"""
self.preloop()
#This is the same code as the Python 3.7.2 Cmd class, with the
#following changes
# - Remove dead code caused by forcing use_rawinput=False.
# - Added a readline in front of readline()
if intro is not None:
self.intro = intro
if self.intro:
self.stdout.write(str(self.intro)+"\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = await self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line.rstrip('\r\n')
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
@villekr
Copy link

villekr commented Jul 16, 2020

In https://stackoverflow.com/questions/54425723/using-a-coroutine-for-pythons-cmd-class-input-stream you mention that "Implement write and flush as you see fit, but your readline should look like this:"

async def readline(self):
    return await my_implementation_of_readline()

Can you elaborate or provide example what this my_implementation... should actually be like?

@ixe013
Copy link
Author

ixe013 commented Jul 25, 2020

It is whatever asynchronous function you already have will do. IIRC, I was using AsyncSSH to read the input from the client asynchronously.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment