运行目录中的所有Python文件

Ger*_*ncy 10 python bash matplotlib

在目录中运行所有Python文件的最佳方法是什么?

python *.py
Run Code Online (Sandbox Code Playgroud)

只执行一个文件.在shell脚本(或make文件)中为每个文件写一行似乎很麻烦.我需要这个b/c我有一系列小的matplotlib脚本,每个脚本创建一个png文件,并希望一次创建所有图像.

PS:我正在使用bash shell.

Cat*_*lus 29

bash有循环:

for f in *.py; do python "$f"; done
Run Code Online (Sandbox Code Playgroud)

  • 我自己应该想到这一点;) (2认同)

Eri*_*erg 15

另一种方法是使用xargs.这允许您并行执行,这在当今的多核处理器上很有用.

ls *.py|xargs -n 1 -P 3 python
Run Code Online (Sandbox Code Playgroud)

所述-n 1使得xargs的给每个进程仅其中一个参数,而-P 3将使xargs的运行多达三个并联处理.