Программа для консоли python

python-console-creator 1.2.0

A Python lib that makes creating a console a simple task !

Ссылки проекта

Статистика

Метаданные

Лицензия: GNU Affero General Public License v3

Автор: megat69

Требует: Python >=3.6

Сопровождающие

Классификаторы

Описание проекта

Console Creator

Python lib that makes creating a console a simple task !

This lib enables you to create a console where the user can input commands, with features such as command aliases, automatic help generation, and much, much more !

Install

Install from PyPI

To install the library, just type pip install python-console-creator and this should be ok.

Install from source

Just download the file at this link, and import it in your project.

Usage

This library provides multiple classes.

The Console class

This class is the main console.

How to use it ?
Simply store it in a variable like so :

While constructing the class, you can pass in some of the following parameters (all optionals) :
  • pointer : A string containing the element that will tell the user that he should input a command. By default, >>> .
  • lowercase_commands : A boolean that indicates whether or not commands should match the case. E.g. if False (by default) test and TEST won’t be the same command. Otherwise, they will be the same.
  • exit_aliases : A tuple or list of strings containing the name of the commands that should let the user quit the console. By default, exit , end , and quit .
  • ignore_minor_errors : A boolean that indicates whether or not functions with no arguments should throw an exception if arguments are given. By default, False.
  • optional_args_prefix : The prefix in front of an optional argument. By default, — .
  • end_message : The message to display on console close. Can also be None, and in that case, nothing will be printed. By default, » Console closed. «
  • help_ignore_no_description : Boolean indicating whether or not the help command should print if no description is provided for a command. Default is False.

This class contains a few methods that will help you create your commands.

The launch method

This method will launch the console.

*/!\ Beware ! After this method is called, it is no longer possible to add commands ! /!*

The destroy method

This method will destroy the console.

Past this point, you can add commands again or launch the console again.

The add_command method

The main method of the Console class.

This method allows you to add new commands to the console.

The most important commands should be added first, as they will be checked in the order in which they have been added.
The later you add a command, the further it is situated in the commands list, the longest it takes. (It is just a matter of milliseconds, still)

**/!\ An exception will be raised if you try to create two commands with the same name. /!\ **

This method takes as argument an instance of the Command class, which is described just below.
Otherwise, a command will be created in place, but will no longer be capable of being modified.
This method, even though is working and will be maintained, is not recommended.

The Command class

This class is the class that composes a command.

It takes in as required positional arguments :

  • name : A string that defines the name of the command. Should not contain any space, otherwise an exception will be raised.
  • function_to_call : A callback function to call when the command is triggered.

It can take as non-required keyword arguments the following statements :

  • description : A short description of the function, for the help command.
  • catch_others_args : A boolean indicating whether or not to return all the args inputted by the user as a tuple. False by default.
  • help_args_msg : Whether or not the help command should print that the command does not have any arguments if this is the case. True by default.

It can finally take two other keyword arguments : required_arguments and optional_arguments .

These arguments are a tuple or a list of instances of the Argument class (see below), and for the optional_arguments , each instance should have its parameter optional set to True .

The callback function defined above should take each of the required_arguments as positional arguments, each of the optional_arguments as optional arguments, and another positional argument if the parameter catch_others_args is set to True .

The Argument class

This class requires one argument : name , a string containing the name of the argument. This will mainly be used for the help command if the argument is required.

The class also provides two «optional» arguments (although I recommend you to fill them) :

  • description : A short description of the argument, for the help command.
  • optional : A boolean that indicates whether the argument is required or not. THIS PARAMETER ABSOLUTELY REQUIRES TO BE SET TO True IF THE ARGUMENT IS OPTIONAL !

The convert_type function

As the commands inputted by the user always returns strings, I left you this function to convert a variable to the type that fits it the most among None , bool , int , float , and string .
(The types will be tested in that order)

Examples

Here are some examples of consoles, from simple to more advanced.

Example 1 : A console with only a help command and a way to exit

You just need to import the library, create an instance of Console , and launch it.

Let's say we want this console to be only left if the user types the command leave , where the case of the commands doesn't count, and where no end message is printed when the console is closed.

The code should now look this way :

To do so, we need to create a function with no arguments, and to add a command in the console.

     But this one does not feature an explicit description for users who need it, so let's add one !

Just replace the line 13 with this line :

Here, we will need to add a required argument that will be the name of the user.

     If you do hello , it should respond Hello, ! , and that without any effort, and a clean code.

Example 4 : The same example as above, but this time the name argument is not required

Let’s take the code from the last example, and remake a few lines.

        I let you try it yourself.

Example 5 : Let’s combine both !

Let’s create a command to send a message (required arg) to the user, which can be signed or anonymous (by default).

    If you input send-message "I love you, my friend." David , you should receive in the console the following message :
I love you, my friend. David. 

Now, if you input this instead You’ve been hacked ! (so the second arg is not filled), you should get this :

You've been hacked ! This message was anonymous. 

Example 6 : Keeping the commands in variables to be able to change them

I’ll just leave the code, try for yourself, and have fun understanding it 😉

I hope you like this library as much as I do !

I’ve put some effort in making it, so I would love to hear your thoughts and comments about it on my Discord server.

If you find any bug, or are not sure about something, just post it on the Discord or open an issue.

Источник

Мелкая питонячая радость #9: консольные приложения с человеческим лицом

Философы говорят, что людей нужно оценивать не по тому, как высоко они могут забраться, а по тому, как низко они могут пасть.

В мире есть много прекрасных разработчиков, которые могут выдавать эффектные алгоритмы, изящные архитектуры и прекрасный код. Но эти же программеры берут и пишут весьма посредственно организованный код какого-нибудь маленького консольного скрипта для расчета аналитики или патча данных в базе. Никакой разбивки на классы и функции, корявая передача аргументов, примитивный вывод малопонятной информации с помощью print()

Сегодня мы поговорим о том, как сделать лучше программы, на которые большинству плевать — одноразовые консольные утилитки и скрипты.

image

python-nubia

Библиотека от второй по значимости в мире корпорации добра — Facebook. Тамошних инженеров тоже порядком утомил хаос в консольных приложениях, поэтому они решили снабдить их интерактивным интерфейсом. Конечно же, текстовым.

  • Автокомплит для функций, доступных в вашем консольном скрипте.
  • Можно подключать автокомплит на уровне терминала (работает в bash и zsh).
  • Приятный и красивый статус бар, который покажет пользователю, что же происходит.
  • Подсказки и валидации по наборам аргументов функций и их типам.

Termgraph

С выводом информации в консоль у многих вообще беда. Как говорилось выше, дело часто сводится к простому выводу print() . Читать такое, конечно, не очень удобно.

Для того, чтобы сделать отрисовку того, что происходит в программе, есть либа Termgraph

Она позволяет делать такие вот картинки в терминале

Используя простой бар, можно показывать прогресс выполнения программы в виде красивой полоски — и это уже будет круто и куда приятней вывода непонятных значений принтом.

Fabric

Скрипты для выполнения на удаленных машинах — отдельная боль. Конечно, мы живем в веке DevOps, когда кучи задач решаются с помощью Salt и Ansible. Но бывает и такое, что нужно регулярно логиниться на кластер удаленных тачек и выполнять там пачки команд. Для этого и есть fabric

  • Поддержка разных списков хостов — можно выполнять команды на серверах БД, в кластере приложения — просто пропишите удаленные тачки в скрипт.
  • Разные политики авторизции для тачек — можно юзать и ключи, и пароли.
  • Разбивка скрипта на подкоманды, группировка подкоманд в команды побольше — можно делать сколь угодно сложную логическую структуру кода, который вы хотите запускать.
  • И, конечно же, можно мешать в коде команды терминала и питонячий код!

Fabric построен вокруг Paramiko и вообще вы можете выполнять команды с помощью этой низкоуровневой библиотеки общения по SSH. Но Fabric дает необходимый уровень абстракции, который позволяет делать понятным и легкоиспользуемым.

python-prompt-toolkit

Эта либа превращает простой скрипт в реально мощное консольное приложение.

Например, можно добавить строку запроса команд в текстовый интерфейс.

from prompt_toolkit import prompt while 1: user_input = prompt('>') print(user_input)

А после этого можно добавить историю использованных команд, прямо как в вашем терминале.

 from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory while 1: user_input = prompt('>', history=FileHistory('history.txt'), ) print(user_input)

А можно сделать автоподсказки строк из истории ввода.

 from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory while 1: user_input = prompt('>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), ) print(user_input) 

И научить автоподсказки определенным предустановленным командам.

 from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True) while 1: user_input = prompt('SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter, ) print(user_input) 

Либа крайне простая и дает возможность сделать свой классный и полностью кастомизируемый интерфейс.

Зачем это?

Внимательное отношение к, казалось бы, одноразовым программам позволит вам писать не код на выброс, а консольные инструменты, которые легко можно использовать повторно потом. Это экономит время и, конечно же, делает работу с вашими скриптами намного приятней.

Источник

Читайте также:  Java nio open file
Оцените статью