Python/CLI Tools/
2022-10-17T08:30:06.818479Z
Published on
The efficient way to communicate with the OS(operating system) is by using shell commands. Since CLI tools directly run on the terminal the execution time is faster. when you’re trying to automate the daily repeatable manual tasks a CLI tool is easy to develop, maintain, distribute and use.
In this tutorial, we are going to see how to create a CLI tool using python.
Python has a built-in module for developing CLI tools, Argparse is the default python module for creating command lines programs. It provides all the features you need to build a simple CLI.
Below is the list of tools that are going to use.
Typer is an external python library built on top of the Click library. We will be using this module to build CLI Tools. For more information check out the documentation.
The sample working of Typer is shown below with an example screenshot.
PyInquirer for displaying different types of user inputs like List, Checkbox, Radio button and much more on the CLI. For more check out the documentation.
List user input:
Checkbox user input:
Password user input:
Rich to display colourful text and content on the CLI. For more check out the documentation.
Python language ( https://docs.python.org/3/tutorial/index.html )
How to use libraries in python ( https://docs.python.org/3/tutorial/stdlib.html )
Note:* The operating system used to develop the CLI tool in this article is Ubuntu
Install the following packages using python-pip
Typer
1pip install "typer[all]"
PyInquirer (installation link here)
1pip install PyInquirer
2(if you face any error try the below code)
3pip install prompt_toolkit==1.0.14
rich
1pip install rich
create a python file. For example main.py.
Add the below code to the file and save it.
1import typer
2import subprocess
3from PyInquirer import prompt, print_json, Separator
4from rich import print as rprint
5
6app = typer.Typer()
7
8
9@app.command("hi")
10def sample_func():
11 rprint("[red bold]Hi[/red bold] [yellow]World[yello]")
12
13@app.command("hello")
14def sample_func():
15 rprint("[red bold]Hello[/red bold] [yellow]World[yello]")
16
17
18
19if __name__ == "__main__":
20 app()
Sample code for the above use case can be found in the following GitHub URL.
https://github.com/episyche/python_cli_tool_example/blob/main/main.py
To execute the above return code, follow the command below
1python3 main.py hello
An example output screenshot
In some cases, we need to interact with the Ubuntu OS with shell commands. In Python, there is a built-in module called subprocess to accomplish this process.
import subprocess
1import subprocess
Enter the Bash shell commands within this double quotation shown below.
subprocess.run(f"---- enter shell commands here-------", shell=True)
1import typer
2import subprocess
3from PyInquirer import prompt, print_json, Separator
4from rich import print as rprint
5
6app = typer.Typer()
7
8
9@app.command("list")
10def sample_func():
11 subprocess.run(f"ls -l", shell=True)
12
13@app.command("hello")
14def sample_func():
15 rprint("[red bold]Hello[/red bold] [yellow]World[yello]")
16
17
18
19if __name__ == "__main__":
20 app()
Sample code for the above use case can be found in the following GitHub URL.
https://github.com/episyche/python_cli_tool_example/blob/main/subprocess.py
To check subprocess is working, run the above code where you want to list folders.
1cd /files-directory
2
3for example:
4cd /home/ubuntu/downloads
1python3 /path-to-python-file/subprocess.py list
2
3for example:
4python3 /home/ubuntu/subprocess.py list
Example output screenshot:
Get the username from the user, by using PyInquirer’s List input.
Then after the username is given by the user, prompt for the folder name.
Then combining the username and folder, create the folder on the specified directory using the Python subprocess module.
The code is given below:
1import typer
2import subprocess
3from PyInquirer import prompt, print_json, Separator
4from rich import print as rprint
5
6app = typer.Typer()
7
8
9@app.command("create-folder")
10def sample_func():
11 module_list_question = questions = [
12 {
13 'type': 'list',
14 'name': 'username',
15 'message': 'Select any one username: ',
16 'choices': [
17 {
18 'name': 'Eddie',
19 },
20 {
21 'name': 'Hughie',
22 },
23 {
24 'name': 'Matthew ',
25 },
26 {
27 'name': 'Harvey ',
28 },
29 ],
30 }
31 ]
32
33 username = prompt(module_list_question)
34
35 rprint("[yellow]=============================================[yello]")
36 rprint("[green bold]Enter folder name :[green bold]")
37 folder_name = input()
38
39
40 subprocess.run(f"mkdir {folder_name}_created_by_{username['username']}", shell=True)
41
42@app.command("hello")
43def sample_func():
44 rprint("[red bold]Hello[/red bold] [yellow]World[yello]")
45
46
47
48if __name__ == "__main__":
49 app()
Sample code for the above use case can be found in the following GitHub URL.
https://github.com/episyche/python_cli_tool_example/blob/main/cli_tool.py
Run the above code, to see the results.
1cd /files-directory
2
3for example:
4cd /home/ubuntu/downloads
1python3 /path-to-python-file/cli_tool.py create-folder
2
3for example:
4python3 /home/ubuntu/cli_tool.py create-folder
The example output screenshots are given below:
Before executing the CLI tool
Execute the CLI Tool and Select one username.
Enter folder name and press enter
After executing the CLI tool.
Comments