点击进入图片 (Bringing Click into the Picture)
We’ve looked at how command-line tools work and the basics of creating a command-line interface.
我们已经研究了命令行工具的工作方式以及创建命令行界面的基础。
Now, let’s create our media-convertor-CLI app. Our application should allow us to convert a media file to a format of our choice. We often use video to audio-conversion tools— it will be exciting to have one that we can tweak ourselves.
现在,让我们创建我们的媒体转换器CLI应用。 我们的应用程序应允许我们将媒体文件转换为我们选择的格式。 我们经常使用视频到音频转换工具-拥有一个我们可以自己调整的工具将非常令人兴奋。
应用设置 (App setup)
Our directory structure will look like this:
我们的目录结构如下所示:
| audioConvertor |-convertor
|- __init__.py
|- utils
|- __init__.py |- |- tests
|- __init__.py-
We create the interface of our app in the file .
我们在文件创建应用程序的界面。
添加使用选项 (Adding usage options)
To convert a file, we need to know its location. So we need to allow the user to tell our application where to get this file. We start building our app by creating a simple script that does that.
要转换文件,我们需要知道其位置。 因此,我们需要允许用户告诉我们的应用程序在何处获取此文件。 我们通过创建一个简单的脚本来开始构建我们的应用程序。
We give our users an option --input_directory
to specify which file to convert. We can run the script as follows:
我们为用户提供--input_directory
选项,以指定要转换的文件。 我们可以如下运行脚本:
$ python --input_directory Videos/musicVideo.mp4# Output
Videos/musicVideo.mp4
Our script echoes back the file the user has specified. It works!
我们的脚本回显用户指定的文件。 有用!
How will our users know how to interact with the app? A short help menu works a charm. With Click, we get this easy and for free. Let’s check it out by running:
我们的用户将如何知道如何与该应用进行交互? 短暂的帮助 菜单很有魅力。 用 点击,我们可以轻松,免费地进行此操作。 让我们通过运行检查一下:
$ python --help# OutputUsage: [OPTIONS]audioConvertor is a command-line tool that helps convert video files to audio file : python -i input/file/path -o output/pathOptions:
-i, --input_directory TEXT Location of the media file to be converted
--help Show this message and exit.
Note the convenience. -i
is also interchangeable with --input_directory
. The help example says an output path is necessary too.
注意方便。 -i
也可以与--input_directory
互换。 帮助示例说输出路径也是必需的。
example: python -i input/file/path -o output/path
We can get it working this way by adding the following lines to our script:
我们可以通过在脚本中添加以下几行来使其工作:
The added lines are marked ++
. Adding an option is as easy as calling @
and passing our string to the decorated function. Remember to pass your options to main
in order of creation.
添加的行标记为++
。 添加选项就像调用@
并将我们的字符串传递给装饰函数一样容易。 请记住按创建顺序将选项传递给main
。
解析用户选项 (Parsing user options)
It would be good manners to confirm the existence of a file before we attempt to convert it. We can do so like this:
在尝试转换文件之前,最好先确认文件的存在。 我们可以这样做:
The script should now terminate if a user provides a non-existent media file. But with Click, parsing and validation are handled for us. The snippet of code below serves the same purpose as what we’ve just done above:
现在,如果用户提供的媒体文件不存在,该脚本应终止。 但是使用Click可以为我们处理解析和验证。 以下代码段的目的与上面所做的目的相同:
The magic happens at line six. By supplying the type
parameter to Click’s options command, we can tell Click to ensure the user gives as --input_directory
as a path, and that it exists.
魔术发生在第六行。 通过提供type
Click选项的参数,我们可以告诉Click确保用户输入为--input_directory
作为一条路径,并且它存在。
Click gives us plenty of arguments to use in an option. We get to see more of them in play as we progress.
单击为我们提供了在选项中使用的大量参数 。 随着我们的进步,我们可以看到更多的游戏。
添加命令 (Adding commands)
Using commands will allow us to isolate different features of our application for the convenience of users. It also makes it easier to add new options. For example, we have two options — it would make sense to nest them in a command that describes what they do.
使用命令将使我们能够隔离应用程序的不同功能,以方便用户使用。 它还使添加新选项更加容易。 例如,我们有两个选项-将它们嵌套在描述它们功能的命令中是有意义的。
python convert -i input/file/path -o output/path
We want to bundle our options in a convert
command, so our app can be used as shown. What’s something else we would want our app to do besides converting? If we could play our converted songs, that would be nice. So, if we use it as shown below, something should pop out of our speakers:
我们希望将选项捆绑在convert
命令中,因此可以如图所示使用我们的应用程序。 除了转换外,我们还希望我们的应用程序还要做什么? 如果我们可以播放转换后的歌曲,那就太好了。 因此,如果我们按如下所示使用它,则扬声器中应该弹出一些声音:
python play --playlist path/to/audio
We know how we want our app to work. Let’s get to it.
我们知道我们希望我们的应用程序如何工作。 让我们开始吧。
分组命令 (Grouping the commands)
The first thing we do is add the commands play
and convert
to our app.
我们要做的第一件事是添加命令play
并将其convert
为我们的应用程序。
Let’s go through this script.
让我们来看一下这个脚本。
We have three functions: — main
, load_files
, and load_audio
. The function main
is helping us group our two commands with Click by decorating it with @
. This is our first step.
我们有三个功能: - main
, load_files
和load_audio
。 功能main
通过用@
装饰它来帮助我们将两个命令与Click @
。 这是我们的第一步。
After that, notice how easy it is to add a command — we call @
then specify the options we think will make us happy.
之后,请注意添加命令有多容易-我们调用@
然后指定我们认为会让我们满意的选项。
There’s this line hovering around:
这条线徘徊:
@click.pass_context
Whenever we want to use an argument specified in command but in a different function, we pass its context. This is done by storing it in the click context object dictionary. See what we do in line 21:
每当我们要使用命令中指定的参数但在其他函数中使用时,我们都会传递其上下文。 这是通过将其存储在单击上下文对象字典中来完成的。 看看我们在第21行中所做的事情:
[‘VERBOSE’] = verbose
This allows us to access the value of VERBOSE
in any other function with a click decorator by passing in ctx
. (Remember to call main with the obj
argument as in line 52). For example:
这使我们可以通过传入ctx
来通过单击装饰器访问任何其他函数中的VERBOSE
值。 (请记住,如第52行所示,使用obj
参数调用main)。 例如:
def load_files(ctx, input_directory, output):
"""
: Convert video file input to audio.
"""
if ('VERBOSE'):
# shout a lot
else:
# convert quietly
We introduced some new arguments to our command options too. Here’s what they help us achieve:
我们还在命令选项中引入了一些新参数。 以下是他们帮助我们实现的目标:
-
required
: mandatory input.required
:必填项。 -
multiple
: allow users to add many parameters convert -i video_1 -i video_2.multiple
:允许用户添加许多参数,例如convert- i video_1- i video_2。 -
nargs
: almost same as multiple convert -i video_1 video_2 video_3nargs
:几乎相同的s倍数,例如,转换-i video_1 video_2 video_3
In our case, nargs
would help us specify multiple input files.
就我们而言, nargs
将帮助我们指定多个输入文件。
-
is_flag
: A boolean option that doesn’t need a parameter`.is_flag
:不需要参数的布尔选项。
转换-选项 (Convert — option)
Let’s list out all our decorators for function (load_files)
running the convert command.
让我们列出所有用于运行convert命令的函数( load_files )
装饰器。
That’s a list of options for one command on our CLI. Now let’s dive into processing the parameters received from the user. For easier maintenance, we will isolate all our processing functionality to a new file, in a class called Convertor
.
这是CLI上一个命令的选项列表。 现在,让我们深入研究处理从用户那里收到的参数。 为了简化维护,我们将所有处理功能隔离到一个名为Convertor
的类中的新文件中。
| audioConvertor|-convertor
|- __init__.py
|- utils
|- __init__.py |- |- |- tests
|- __init__.py-
Since our focus is on the CLI, we won’t dwell on the Convertor
class. But I made an effort to document it quite nicely, so don’t worry about it.
由于我们专注于CLI,因此我们将不再关注Convertor
类。 但是我尽力将其很好地记录下来 ,所以不用担心。
Let’s add these lines to the top of our :
让我们将这些行添加到的顶部:
import click
from formats import Convertor # +convertor_instance = Convertor() # +
Let’s toy around a bit on our interface with the above options:
让我们在上面的选项中玩一些玩具:
$ python3 convertor/ convert -i /root/Videos/# Output
/root/Videos/ is a directory. --recursive Needed for a directory
Let’s point our app to a file and attempt to convert it again:
让我们将应用程序指向一个文件,然后尝试再次将其转换:
python3 convertor/ convert -i Videos/snoring_noises.aviInput specified as file name.
.
Conversion Complete
saved: snoring_noises.mp3
The app should prompt us to install ffmpeg
, which is the media convertor library we shall use. This is getting exciting!
该应用程序应提示我们安装ffmpeg
,这是我们将使用的媒体转换器库。 这真令人兴奋!
Next, let’s allow the user to convert multiple video files at once by running:
接下来,让用户通过运行一次转换多个视频文件:
python3 convertor/ convert -i /root/Videos/* -o /root/converted_music
This command should convert for us all video files in the Videos folder to audio and save the output to the directory converted_music
. Adding the following code to the load_files
function should do it:
此命令应为我们将“视频”文件夹中的所有视频文件转换为音频,并将输出保存到目录converted_music
。 将以下代码添加到load_files
函数即可:
播放—选项 (Play — option)
The play command decorates the load_audio
function:
播放命令装饰 load_audio
函数:
The app should now allow us to load a playlist of our choice.
该应用程序现在应允许我们加载我们选择的播放列表。