summaryrefslogtreecommitdiffstats
path: root/examples/telnet/hello-world-asyncio.py
blob: ccaeb766eafc841c81ecbfbb28185b45abb733b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python
"""
A simple Telnet application that asks for input and responds.

The interaction function is an asyncio coroutine.

WARNING: This is experimental! Prompt_toolkit TaskLocals don't work together
         with asyncio coroutines. This is also why we have to specify the
         output and input manually.
"""
from __future__ import unicode_literals

from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop
from prompt_toolkit.shortcuts import PromptSession

import logging
import asyncio

# Set up logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)

# Tell prompt_toolkit to use the asyncio event loop.
use_asyncio_event_loop()


async def interact(connection):
    session = PromptSession(output=connection.vt100_output, input=connection.vt100_input)

    connection.erase_screen()
    connection.send('Welcome!\n')

    # Ask for input.
    result = await session.prompt(message='Say something: ', async_=True)

    # Send output.
    connection.send('You said: {}\n'.format(result))
    connection.send('Bye.\n')


def main():
    server = TelnetServer(interact=interact, port=2323)
    server.start()
    asyncio.get_event_loop().run_forever()


if __name__ == '__main__':
    main()