Generate command line for python script
1 Introduction
Little Diaosi : Brother Yu, may I ask a question?
Xiaoyu : Can you refuse?
Xiao Diaosi : You can refuse, anyway, the girl asked me to press my feet~
Xiaoyu : ... (I wipe~~ I was attacked to the point of weakness...) Now there is time.
Little Diaosi : Are you sure you have time?
Xiaoyu : Sure, if you have any questions, let's talk about it.
Xiao Diaosi : Hmm... um... I'm sure you can ask now, right?
Xiaoyu : Hurry up, when did you become so inked
Xiaodiaosi : Well, then I'm welcome
Xiaoyu : (⊙o⊙)...
Xiaodiaosi : I was writing a script recently, and found that if I modify a parameter, I have to go to war...Is there any easy way for me to modify the least code to achieve the desired parameters...
Xiaoyu : In detail~
Xiaodiaosi : Well, let's look at the code directly!
2. Conventional method
Define the scrape method to crawl the information of a website, set the timeout to 5 seconds, and
display the code
# -*- coding: utf-8 -*-
# @Time : 2022-01-28
# @Author : carl_DJ
import requests
'''
定义scrape方法,爬取某网站后返回的状态及url,timeout设置为5秒
'''
def scrape(url,timeout = 5):
resp = requests.get(url=url,timeout=timeout)
resp_url = resp.url
resp_code = resp.status_code
print(f'返回状态码:{
resp_code}')
print(f'返回url:{
resp_url}')
Xiao Diaosi : If you call it directly, you can do it directly as follows:
scrape('https://blog.csdn.net/wuyoudeyuer', 5)
Xiao Diaosi : However, if you want to modify the parameters and call them again, you need to change the code
Xiaoyu : You can use argparse and declare each parameter, won't you?
Code display
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)
When calling, just write:
python testscr.py https://blog.csdn.net/wuyoudeyuer 5
Xiao Diaosi : This is also a way, but can it be simpler?
Xiaoyu : Uh... It's too much to eat ready-made... Yes, get in the car!
3. Fire module
3.1 Module introduction
Fire is a nice third-party library that
can quickly add command line parameter support to a python method or class.
Say, the
first step, the old rules, installation:
pip install fire
Other ways to install :
" Python3, choose Python to automatically install third-party libraries, and say goodbye to pip! ! "
" Python3: I only use one line of code to import all Python libraries! ! 》
3.2 Code Examples
3.2.1 Parameter substitution
After the installation is complete, let's start with a brief example, starting
from Hello carl_ Yiran
Example 1
# -*- coding: utf-8 -*-
# @Time : 2022-01-28
# @Author : carl_DJ
import fire
#name直接传入默认参数
def hello(name = 'Carl_奕然'):
return "Hello %s !" %name
if __name__ == '__main__':
fire.Fire(hello)
Running results show :
Hello Carl_奕然 !
The result is nice and what we want,
but how does this work? Let's find out.
Excuting an order:
python test.py --help
Display content:
NAME
test.py
SYNOPSIS
test.py <flags>
FLAGS
--name=NAME
Default: 'Carl_奕然'
As you can see, the name parameter is converted into an optional parameter on the command line, and we can replace the name parameter with --name.
Well, let's try
python test.py --name DJ
Running result :
Hello DJ !
Little Diaosi : I'll go~~ Okay, Brother Yu, Zhennais!
Xiaoyu : Do you think that fire only has this function? ? Come on, go on!
Xiao Diaosi : I can't take it anymore... Well, continue with your performance.
3.2.2 Class Support
The fire library also supports adding command lines to classes.
# -*- coding: utf-8 -*-
# @Time : 2022-01-28
# @Author : carl_DJ
import fire
#定义Calculator类
class Calculator(object):
#double方法
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Excuting an order:
python test.py
operation result:
NAME
test.py
SYNOPSIS
test.py COMMAND
COMMANDS
COMMAND is one of the following:
double
We can see that here it recognizes the methods in the Calculator class, one of the COMMANDs is double, we call double again,
Excuting an order:
python test.py double
operation result:
ERROR: The function received no value for the required argument: number
Usage: test.py double NUMBER
For detailed information on this command, run:
test.py double --help
We can see that the error message is that we need to pass in parameters.
We are adjusting it once.
Excuting an order:
python test.py double 3
operation result
6
Very nice, is the result we want.
3.2.3 Code Examples
Finally, we modify the first scrape function
# -*- coding: utf-8 -*-
# @Time : 2022-01-28
# @Author : carl_DJ
import requests
import fire
'''
定义scrape方法,爬取某网站信息,timeout设置为5秒
'''
def scrape(url,timeout = 5):
resp = requests.get(url=url,timeout=timeout)
resp_url = resp.url
resp_code = resp.status_code
print(f'返回状态码:{
resp_code}')
print(f'返回url:{
resp_url}')
if __name__ == '__main__':
fire.Fire(scrape)
Excuting an order:
python test.py https://blog.csdn.net/wuyoudeyuer --timeout 5
Results of the:
返回状态码:200
返回url:https://blog.csdn.net/wuyoudeyuer
Nice.
4. Summary
Writing here, today's sharing is almost over.
It mainly shares the modification of functions and classes by fire, which saves us the time to modify the code.
The main thing is that we got another new skill.