Two lines of code to generate a command line for a Python script

Sometimes we have such a demand:

We define a Python method. The method receives some parameters, but we want to expose these parameters on the command line when calling.

For example, here is a crawling method:

import requests

def scrape(url, timeout=10):
    response = requests.get(url, timeout=timeout)
    print(response.text)
Copy code

Here, a scratch method is defined. The first parameter receives the url, that is, the crawled url, and the second parameter receives the timeout, that is, the specified timeout.

When calling, we may call as follows:

scrape('https:///www.baidu.com', 10)
Copy code

If we want to change the parameters and url, we have to change the code, right.

So sometimes we want to expose these parameters on the command line. At this time, we may use argparse and other libraries to declare the purpose of each parameter one by one. It is very cumbersome. The code is as follows:

parser = argparse.ArgumentParser(description='Scrape Function')
parser.add_argument('url', type=str,
                    help='an integer for the accumulator')
parser.add_argument('timeout',  type=int,
                    help='sum the integers (default: find the max)')

if __name__ == '__main__':
    args = parser.parse_args()
    scrape(args.url, args.timeout)
Copy code

In this way, we can smoothly use the command line to call this script:

python3 main.py https://www.baidu.com 10
 Copy code

Does it feel very troublesome? argparse is smelly and long. It's hard to think about it.

Fire

But next, we will introduce a library. With it, we only need two lines of code to do the above operation.

This library is called Fire. It can quickly add command-line parameter support for a Python method or class.

Let's take a look at the installation method first. Use pip3 to install:

pip3 install fire
 Copy code

So we can install it.

use

Let's look at some examples.

Method support

The first code example is as follows:

import fire

def hello(name="World"):
  return "Hello %s!" % name

if __name__ == '__main__':
  fire.Fire(hello)
Copy code

Here, we define a hello method, then receive a name parameter, the default value is World, and then output the string Hello plus name.

Then we import the fire library, call its fire method and pass in the hello method declaration. What will happen?

We save this code as Demo1 Py, and then run it with Python 3:

python3 demo1.py
 Copy code

The operation results are as follows:

Hello World!
Copy code

It doesn't look any different.

But if we run the following command at this time, we can see some magical things:

python3 demo1.py --help

Copy code

The operation results are as follows:

NAME
    demo1.py

SYNOPSIS
    demo1.py <flags>

FLAGS
    --name=NAME
        Default: 'World'
Copy code

As you can see, here it converts the name parameter into an optional parameter on the command line. We can replace the name parameter with - name.

Let's try:

python3 demo1.py --name 123
 Copy code

Here, we pass in a name parameter of 123. At this time, we find that the running result becomes the following:

Hello 123!
Copy code

Is it very convenient? We can easily support and replace the command line parameters without argparse.

What if we cancel the default value of the name parameter? Rewrite the code as follows:

import fire

def hello(name):
  return "Hello %s!" % name

if __name__ == '__main__':
  fire.Fire(hello)
Copy code

Run again at this time:

python3 demo1.py --help
 Copy code

You can see that the result becomes as follows:

NAME
    demo1.py

SYNOPSIS
    demo1.py NAME

POSITIONAL ARGUMENTS
    NAME

NOTES
    You can also use flags syntax for POSITIONAL ARGUMENTS
 Copy code

At this time, we find that the parameter name becomes a mandatory parameter. We must specify the content of this parameter in the command line, and the call will become the following command:

python3 demo1.py 123
 Copy code

The result is the same.

Class support

Of course, the fire library supports not only adding command line support to methods, but also adding command line support to a class.

Let's take another example:

import fire

class Calculator(object):    
    def double(self, number):
        return 2 * number

if __name__ == '__main__':
    fire.Fire(Calculator)

Copy code

We save this code as demo2 Py, and then run:

python3 demo2.py
 Copy code

The operation results are as follows:

NAME
    demo2.py

SYNOPSIS
    demo2.py COMMAND

COMMANDS
    COMMAND is one of the following:

     double
 Copy code

As you can see, here it identifies the methods in the Calculator class. One of the commands is double. Let's try to call the following:

python3 demo2.py double
 Copy code

The operation results are as follows:

ERROR: The function received no value for the required argument: number
Usage: demo2.py double NUMBER

For detailed information on this command, run:
  demo2.py double --help
 Copy code

Let's say here that another parameter must be specified here, which is called NUMBER. At the same time, this parameter is still a required parameter. Let's try to add:

python3 demo2.py double 4
 Copy code

The operation results are as follows:

8
 Copy code

The correct result can be achieved at this time.

Therefore, in a comprehensive view, fire can be a class command line. Each command corresponds to the name of a method. At the same time, additional optional or required parameters are added after the command line parameters.

Rewrite

Finally, let's go back and add command line parameter support to the scratch method we defined at the beginning:

import requests
import fire

def scrape(url, timeout=10):
    response = requests.get(url, timeout=timeout)
    print(response.text)

if __name__ == '__main__':
    fire.Fire(scrape)
Copy code

That's it! Is it very convenient to omit the lengthy argparse code?

The call is in the following form:

NAME
    main.py

SYNOPSIS
    main.py URL <flags>

POSITIONAL ARGUMENTS
    URL

FLAGS
    --timeout=TIMEOUT
        Default: 10
 Copy code

It is said here that URL is a required parameter and timeout is an optional parameter.

The last call is:

python3 main.py https://www.baidu.com 
Copy code

In this way, we can easily pass the url through the command line.

Of course, timeout is also an optional value. We can specify the timeout parameter through - timeout:

python3 main.py https://www.baidu.com --timeout 5
 Copy code

In this way, the two parameters can be assigned successfully. The final effect is to climb Baidu and timeout for 5 seconds.

What about? Isn't it convenient? Let's use it quickly!

Keywords: Python Back-end

Added by programmingjeff on Fri, 28 Jan 2022 18:11:19 +0200