From b0cc18dc8e7331d03e0aa7cff77c4c6be7f38866 Mon Sep 17 00:00:00 2001 From: Digital Studium Date: Sun, 9 Apr 2023 16:36:53 +0300 Subject: [PATCH] Add new post --- .../how-to-easily-write-linux-cli-tool.md | 127 ++++++++++++++++++ .../how-to-easily-write-linux-cli-tool.md | 127 ++++++++++++++++++ themes/ds | 2 +- 3 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 content/en/python-programming/how-to-easily-write-linux-cli-tool.md create mode 100644 content/ru/python-programming/how-to-easily-write-linux-cli-tool.md diff --git a/content/en/python-programming/how-to-easily-write-linux-cli-tool.md b/content/en/python-programming/how-to-easily-write-linux-cli-tool.md new file mode 100644 index 0000000..9c27dc7 --- /dev/null +++ b/content/en/python-programming/how-to-easily-write-linux-cli-tool.md @@ -0,0 +1,127 @@ +--- +title: "Python: How to easily write a CLI tool for Linux using Fire" +date: "2023-04-09" +--- +I want to share the easiest way I know to write a CLI tool for Linux administration +using python and Fire. +## Step 1: Install Fire +```bash +pip install fire +``` +## Step 2. Create a simple CLI tool +Here is an example of a CLI tool that prints the Linux version to the terminal: + +```python +#!/usr/bin/env python3 +import fire +import platform + + +class SysInfo: + """A CLI tool for getting system information about Linux server""" + + def kernel(self): + """A method for getting kernel version""" + version = platform.release() + return f"Kernel version: {version}" + + +if __name__ == "__main__": + obj = SysInfo() + fire.Fire(obj) +``` +Paste this code into a file called `my-cli-tool` and give it permission to execute: +```bash +chmod +x my-cli-tool +``` +Then put this file in the path `/usr/local/bin`: +```bash +sudo cp ./my-cli-tool /usr/local/bin +``` + +To use this tool, just type the command: +```bash +my-cli-tool kernel +``` + +You will see output like this: +```plaintext +❯ my-cli-tool kernel +Kernel version: 6.2.2-060202-generic +``` + +As you can see, it is enough to create a class, a method(s) in it, and pass the class object to the fire.Fire() function - and the cli tool is ready! +This will automatically generate a help page, which can be called using the `--help` flag: +```bash +my-cli-tool --help +``` +You will get this output: +```plaintext +NAME + my-cli-tool - A CLI tool for getting system information about Linux server + +SYNOPSIS + my-cli-tool COMMAND + +DESCRIPTION + A CLI tool for getting system information about Linux server + +COMMANDS + COMMAND is one of the following: + kernel + A method for getting kernel version +``` + +## Making the tool more complex +For example, we also want our tool to be able to print the kernel version in short form, like this: `6.2.2`. +We rewrite the code as follows: +```python +#!/usr/bin/env python3 +import fire +import platform + + +class SysInfo: + """A CLI tool for getting system information about Linux server""" + + def kernel(self, format: ("short", "full") = "full"): + """A method for getting kernel version""" + version = platform.release() + if format == "short": + return version.split("-")[0] + return f"Kernel version: {version}" + + +if __name__ == "__main__": + obj = SysInfo() + fire.Fire(obj) +``` + +Now we can type the following command: +```bash +my-cli-tool kernel --format short +``` +Output: +```plaintext +6.2.2 +``` +This will also automatically update the help page, adding the `--format` flag and its possible values: +```bash +my-cli-tool kernel --help +``` +Output: +```plaintext +NAME + my-cli-tool kernel - A method for getting kernel version + +SYNOPSIS + my-cli-tool kernel + +DESCRIPTION + A method for getting kernel version + +FLAGS + -f, --format=FORMAT + Type: ('short', 'full') + Default: 'full' +``` \ No newline at end of file diff --git a/content/ru/python-programming/how-to-easily-write-linux-cli-tool.md b/content/ru/python-programming/how-to-easily-write-linux-cli-tool.md new file mode 100644 index 0000000..47a5a20 --- /dev/null +++ b/content/ru/python-programming/how-to-easily-write-linux-cli-tool.md @@ -0,0 +1,127 @@ +--- +title: "Python: Как легко написать CLI инструмент для Linux с помощью Fire" +date: "2023-04-09" +--- +Хочу поделиться самым простым из известных мне способов написать CLI инструмент для администрирования Linux +на Python. +## Шаг 1. Установка Fire +```bash +pip install fire +``` +## Шаг 2. Создаём простейший CLI инструмент +Вот пример CLI инструмента, который выводит в терминал версию Linux: + +```python +#!/usr/bin/env python3 +import fire +import platform + + +class SysInfo: + """A CLI tool for getting system information about Linux server""" + + def kernel(self): + """A method for getting kernel version""" + version = platform.release() + return f"Kernel version: {version}" + + +if __name__ == "__main__": + obj = SysInfo() + fire.Fire(obj) +``` +Вставьте этот код в файл с именем `my-cli-tool` и дайте права на выполнение: +```bash +chmod +x my-cli-tool +``` +Затем положите этот файл по пути `/usr/local/bin`: +```bash +sudo cp ./my-cli-tool /usr/local/bin +``` + +Чтобы воспользоваться этим инструментом, достаточно набрать команду: +```bash +my-cli-tool kernel +``` + +Вы увидите такой вывод: +```plaintext +❯ my-cli-tool kernel +Kernel version: 6.2.2-060202-generic +``` + +Как видите, достаточно создать класс, метод(ы) в нём, и передать объект класса внутрь функции fire.Fire() - и cli инструмент готов! +При этом автоматически сгенерируется help страница, вызвать которую можно с помощью флага `--help`: +```bash +my-cli-tool --help +``` +Вы получите такой вывод: +```plaintext +NAME + my-cli-tool - A CLI tool for getting system information about Linux server + +SYNOPSIS + my-cli-tool COMMAND + +DESCRIPTION + A CLI tool for getting system information about Linux server + +COMMANDS + COMMAND is one of the following: + kernel + A method for getting kernel version +``` + +## Усложняем инструмент +Например, мы хотим также, чтобы наш инструмент мог выводить версию ядра в коротком варианте, то есть так: `6.2.2`. +Переписываем код следующим образом: +```python +#!/usr/bin/env python3 +import fire +import platform + + +class SysInfo: + """A CLI tool for getting system information about Linux server""" + + def kernel(self, format: ("short", "full") = "full"): + """A method for getting kernel version""" + version = platform.release() + if format == "short": + return version.split("-")[0] + return f"Kernel version: {version}" + + +if __name__ == "__main__": + obj = SysInfo() + fire.Fire(obj) +``` + +Теперь мы можем набрать такую команду: +```bash +my-cli-tool kernel --format short +``` +На что должен последовать такой вывод: +```plaintext +6.2.2 +``` +При этом автоматически будет скорректирована help страница, туда будет добавлен флаг `--format` и его возможные значения: +```bash +my-cli-tool kernel --help +``` +Вывод: +```plaintext +NAME + my-cli-tool kernel - A method for getting kernel version + +SYNOPSIS + my-cli-tool kernel + +DESCRIPTION + A method for getting kernel version + +FLAGS + -f, --format=FORMAT + Type: ('short', 'full') + Default: 'full' +``` \ No newline at end of file diff --git a/themes/ds b/themes/ds index 3af1ecb..863541e 160000 --- a/themes/ds +++ b/themes/ds @@ -1 +1 @@ -Subproject commit 3af1ecb3833dfd2b4fdbdd712085280c1871c1f2 +Subproject commit 863541e3da6d4a0664236da0df28359feb1a6f1c