【问题标题】:Run all Python files in a directory运行目录中的所有 Python 文件
【发布时间】:2011-02-16 10:34:13
【问题描述】:

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

python *.py

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

PS:我正在使用 bash shell。

【问题讨论】:

    标签: python bash matplotlib


    【解决方案1】:

    bash 有循环:

    for f in *.py; do python "$f"; done
    

    【讨论】:

    • 我自己应该想到的 ;)
    • 有没有办法在一个目录中运行所有 Python 脚本?例如:我有一个包含 3 个子文件夹的“主”文件夹,我想在这些文件夹中运行所有 Python 脚本
    【解决方案2】:

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

    ls *.py|xargs -n 1 -P 3 python
    

    -n 1 使 xargs 只给每个进程一个参数,而 -P 3 将使 xargs 最多并行运行三个进程。

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 2023-01-04
      • 2010-10-13
      相关资源
      最近更新 更多