程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

2 lines of code generate command line for Python script, so easy

編輯:Python

Preface

Sometimes we have such a need :

We define a Python Methods , Method receives some parameters , But when calling, you want to expose these parameters on the command line .

For example, here's a crawling method :

Python Exchange of learning Q Group :903971231###
import requests
def scrape(url, timeout=10):
response = requests.get(url, timeout=timeout)
print(response.text)

Here's a definition scrape Method , The first parameter receives url, That is, the URL you crawled , The second parameter receives timeout, That is, specify the timeout .

When calling, we may call :

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

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

So sometimes we just want to expose these parameters on the command line , At this time, we may use argparse Wait, wait, wait , What are the parameters declared one by one ,

Is cumbersome , The code is as follows :

python Exchange of learning Q Group :903971231###
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)

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

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

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

Fire

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

The name of this library is Fire, It can be used quickly for some Python Method or class add command line parameter support .

Let's look at the installation method first , Use pip3 Can be installed :

pip3 install fire

So we can install .

Use

Let's take a look at a few 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)

Here we define a hello Method , Then receive a name Parameters , The default value is World, Then output Hello Add name This string .

Then we imported fire This library , Call it the Fire Method and pass in hello This method declares , What's going to happen ?

We save this code as demo1.py, Then use Python3 Let's run it :

python3 demo1.py

The operation results are as follows :

Hello World!

It doesn't look different .

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

python3 demo1.py --help

The operation results are as follows :

NAME
demo1.py
SYNOPSIS
demo1.py <flags>
FLAGS
--name=NAME
Default: 'World'

You can see , Here it will name This parameter is converted to an optional parameter on the command line , We can go through —-name To replace name Parameters .

Let's try :

python3 demo1.py --name 123

Here we introduce a name Parameter is 123, At this time, we find that the running results become the following contents :

Hello 123!

Is it very convenient ? We didn't have the help of argparse It is easy to complete the support and replacement of command line parameters .

Then if we will name The default value of this parameter is cancelled ? The code is rewritten as follows :

import fire
def hello(name):
return "Hello %s!" % name
if __name__ == '__main__':
fire.Fire(hello)

It's time to rerun :

python3 demo1.py --help

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

At this time we found that name This parameter becomes a mandatory parameter , We must specify the content of this parameter on the command line , The call will become the following command :

python3 demo1.py 123

The running result is the same .

Class supports

Of course fire This library supports more than just adding command lines to methods , It also supports adding a command line 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)

We save this code as demo2.py, And then run :

python3 demo2.py

The operation results are as follows :

NAME
demo2.py
SYNOPSIS
demo2.py COMMAND
COMMANDS
COMMAND is one of the following:
double

You can see , Here it will Calculator The methods in this class are recognized ,COMMAND One of them is double, Let's try to call it :

python3 demo2.py double

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

That's it , Another parameter must be specified here , be called NUMBER, At the same time, this parameter is still a required parameter , Let's try to add :

python3 demo2.py double 4

The operation results are as follows :

8

At this time, the correct result can be achieved .

So , Taken together ,fire Can be a class command line , Each command corresponds to the name of a method , At the same time, add additional optional or required parameters later , Add to life

After the line parameter .

Rewrite

Last , Let's turn around , Give us the definition at the beginning scrape Method to add command line parameter support :

import requests
import fire
def scrape(url, timeout=10):
response = requests.get(url, timeout=timeout)
print(response.text)
if __name__ == '__main__':
fire.Fire(scrape)

That's it ! The lengthy argparse Code for , Is it very convenient ?

The call is in the following form :

NAME
main.py
SYNOPSIS
main.py URL <flags>
POSITIONAL ARGUMENTS
URL
FLAGS
--timeout=TIMEOUT
Default: 10

It's said here ,URL It's a must pass parameter ,timeout Is an optional parameter .

Last call :

 Insert a code chip here
python3 main.py https://www.baidu.com

So we can easily url Passed through the command line .

Of course timeout Or an optional value , We can go through —-timeout To specify the timeout Parameters :

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

Last

In this way, both parameters can be assigned smoothly , The final effect is to climb Baidu ,5 Second timeout .

What about? ? Is it convenient ? Let's use it !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved