Created
November 3, 2017 22:56
-
-
Save deeplook/fdb41f2770f5fefbf9dd3e752b831768 to your computer and use it in GitHub Desktop.
Prototype of a 'dynamic' prompt showing CPU load over 10 seconds as a sparkline.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Prototype of a 'dynamic' prompt showing CPU load over 10 seconds as a sparkline. | |
| Requires ``psutil``... | |
| Not finished... | |
| """ | |
| import time | |
| from prompt_toolkit.application import Application | |
| from prompt_toolkit.interface import CommandLineInterface | |
| from prompt_toolkit.layout import Window | |
| from prompt_toolkit.layout.controls import BufferControl | |
| from prompt_toolkit.layout.processors import BeforeInput | |
| from prompt_toolkit.shortcuts import create_eventloop | |
| from prompt_toolkit.token import Token | |
| from psutil import cpu_percent | |
| from sparklines import sparklines | |
| CPU_LOAD_HISTORY = [] | |
| def _clock_tokens(cli): | |
| "Tokens to be shown before the prompt." | |
| CPU_LOAD_HISTORY.append(cpu_percent()) | |
| sparkline = sparklines(CPU_LOAD_HISTORY[-10:])[0] + " (CPU)" | |
| return [ | |
| (Token.Prompt, sparkline), | |
| (Token.Prompt, ' - Enter something: ') | |
| ] | |
| def main(): | |
| eventloop = create_eventloop() | |
| done = [False] # Non local | |
| def on_read_start(cli): | |
| """ | |
| This function is called when we start reading at the input. | |
| (Actually, the start of the read-input event loop.) | |
| """ | |
| # The following function should be run in the background. | |
| # We do it by using an executor thread from the `CommandLineInterface` | |
| # instance. | |
| def run(): | |
| # Send every second a redraw request. | |
| while not done[0]: | |
| time.sleep(1) | |
| cli.request_redraw() | |
| cli.eventloop.run_in_executor(run) | |
| def on_read_stop(cli): | |
| done[0] = True | |
| app = Application( | |
| layout=Window(BufferControl(input_processors=[BeforeInput(_clock_tokens)])), | |
| on_start=on_read_start, | |
| on_stop=on_read_stop) | |
| cli = CommandLineInterface(application=app, eventloop=eventloop) | |
| code_obj = cli.run() | |
| print('You said: %s' % code_obj.text) | |
| eventloop.close() | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment