Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create Command Line Interface in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to create a command line interface in Python, which is concise and easy to understand. I hope you can get something through the detailed introduction of this article.

Let's first introduce to you what the command line interface (CLI) is:

Command-line interface or command language interpreter, also known as command-line user interface, console user interface and character user interface, is a way to interact with computer programs, in which users issue commands to the program in the form of continuous text lines.

By creating a command line interface (CLI), you can make the program powerful and interactive. CLI allows you to accept command-line arguments (information after the program name on the operating system command line) to add additional features to the program and make the code easy to use and flexible. Depending on the program, these parameters can be used to add other features, such as viewing help documentation, specifying output files, or enabling test features, which may cause problems in normal use.

When we first started programming in Python, most of us only collected user input and interacted like this:

Def main (): first = input ("Enter your first name:") last = input ("Enter your last name:") print (first +''+ last)

Although this code is good for simple scripts, it is not flexible enough. When the user runs the program, they are limited to a set of defined rules. For example, what if I want to record the output to a text file? As a user, you can create a command line interface to provide solutions to these problems.

Important considerations:

When creating a CLI, it is important to consider the following:

Required parameters: which parameters are absolutely necessary for the program to run?

Documentation: it is important to write functions for each option and parameter so that new users can know how your program works.

Handle error situations: let the user know exactly what went wrong

Runtime status: if the task is not completed immediately, you should print out the current progress

Use argparse to read parameters:

Argparse is a Python standard library module for parsing command line parameters. As a programmer, you can define the parameters to accept, and argparse will know how to parse them from sys. When the user provides invalid parameters to the program, Argparse also automatically generates help and usage messages and outputs errors. It is very easy to use, and you can easily write intuitive CLI.

First, create a new file called test_cl .py, import the module, and initialize a new parser:

Import argparseparser = argparse.ArgumentParser () parser.parse_args ()

Now run the code using the-- help option:

Python3 test_cli.py-help

You should get a good default help message, like this:

Usage: test_cli.py [- h] optional arguments:-h,-- help show this help message and exit

Congratulations on creating your first command line interface!

Now let's add a welcome message to briefly let your users know what the program does:

Welcome = "Practicing creating interactive command-line interfaces" parser = argparse.ArgumentParser (description=welcome) parser.parse_args ()

Now run the program with the-h flag. You should be able to see your welcome message.

Add parameters:

Suppose we are writing a program to climb a web page. Some of the parameters we may need are the domain of the web page-domain or-d, the option to output the log to an output file-ofile or-o, and the option to output a specific number of lines to the console-lines or-l. For this example, we set the domain parameter to required, while the ofile and lines parameters will be optional.

By using .add _ argument, we can easily add additional parameters to argparse CLI, which allow us to define usage details. We can add the necessary parameters-- domains, such as:

Parser.add_argument ('- domain','- dudes, required=True, help='domain name of the website you want to scrape. I. e. "https://ahadsheriff.com"')

Now run the program with the-h parameter and view the documentation you wrote!

Because-- domain is a required parameter, try to run a program without any flags, and you will receive the following message:

Usage: test_cli.py [- h]-- domain DOMAINtest_cli.py: error: the following arguments are required:-- domain/-d

Succeed!

Now use argparse to add additional parameters. If you do not specify which parameters are required, argparse assumes that they are optional. You can also set the type of the parameter, and for-- lines, we take an integer. You can also set other useful options for .add _ argument-- such as action=

Parser.add_argument ('--ofile','- oasis, help='define output file to save results of stdout. I.e. "output.txt"') parser.add_argument ('--lines','- help='number of lines of output to print to the console "', type=int)

Now test your code to make sure everything is working properly. A simple way is to store the values of the parameters as variables and then print those values.

Args = parser.parse_args () domain = args.domainofile = args.ofilelines = args.linesprint ("domain:", domain) print ("output file:", ofile) print ("lines:", lines)

The above is how to create a command line interface in Python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report