53 lines
3.0 KiB
Markdown
53 lines
3.0 KiB
Markdown
# Bash 多重处理
|
||
|
||
> 原文:[https://python.land/the-unix-shell/bash-multiprocessing](https://python.land/the-unix-shell/bash-multiprocessing)
|
||
|
||
对于那些到现在还没有得到那种忍者感觉的人,这是给你的。我们将结合所有新学到的超能力,执行多处理,也称为并行计算,所有这些都只需 Bash 中的一个命令!
|
||
|
||
目录
|
||
|
||
|
||
|
||
* xargs
|
||
* [例子](#Example "Example")
|
||
* [更多信息](#More_info "More info")
|
||
|
||
|
||
|
||
## xargs
|
||
|
||
xargs 命令从标准输入中读取项目(也就是说,您可以通过管道将数据传递给它)并执行指定的命令。
|
||
|
||
xargs 的基本语法是:
|
||
|
||
```py
|
||
xargs [options] [command [initial-arguments]]
|
||
```
|
||
|
||
乍一看,你可能看不到这样做的好处。为什么不创建一个 while 循环并运行每个命令呢?xargs 的好处是,它可以批量处理参数,并对许多文件调用一次命令,而不是对每个文件单独调用。
|
||
|
||
*但是`find`也可以这么做!*
|
||
|
||
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these *free* articles, I hope you understand! **Support me by disabling your adblocker on my website** or, alternatively, **[buy me some coffee](https://www.buymeacoffee.com/pythonland)**. It's much appreciated and allows me to keep working on this site!
|
||
|
||
是的,你是对的。尽管如此,还是有更多的优势。Xargs 不需要查找就可以工作。所以这是一个。但是 xargs 有一个特殊的锦囊妙计:它可以与`-P`-选项并行运行命令。
|
||
|
||
该选项采用一个数字来定义需要并行启动多少个进程。你没看错——并行!
|
||
|
||
## 例子
|
||
|
||
使用 xargs 进行 Bash 多处理的一个真实例子是在对大量文件进行视频转换时使用它。让我们一起来剖析下面的命令:
|
||
|
||
```py
|
||
$ find . -name "*.mpeg" | xargs -P 4 -I {} ffmpeg -i {} -o {}.mp4
|
||
```
|
||
|
||
首先,我们找到所有的 mpeg 文件。我们把这些文件交给 xargs。接下来,我们用`-P 4`告诉 xargs 同时使用四个进程。我们还告诉 xargs 用`-I`选项替换所有遇到`{}`的地方的文件名。所以 xargs 得到第一个视频文件,启动 ffmpeg。xargs 没有等待 ffmpeg 完成,而是启动 ffmpeg 的另一个实例来并行处理第二个文件。这种情况一直持续到四个进程。如果所有四个槽都被占用,xargs 在开始下一个进程之前会等待一个槽完成。
|
||
|
||
视频转换主要受 CPU 限制。如果您的计算机有四个 CPU 内核,这种转换将比使用常规 find 或 while 循环快四倍。是不是很牛逼?!
|
||
|
||
## 更多信息
|
||
|
||
有关更多信息,请阅读命令行手册或 web 上的[。维基百科有](https://man7.org/linux/man-pages/man1/xargs.1.html)[一些 xargs 用法的例子](https://en.wikipedia.org/wiki/Xargs#Examples),你可能会觉得有用。
|
||
|
||
如果你更喜欢使用 Python,我们的指南包含了一个关于使用 Python 的[多重处理或并发性的综合章节。](https://python.land/python-concurrency) |