运行 所有 Python 个在多个目录中具有相同名称的脚本

Running all Python scripts with the same name across many directories

我的文件结构如下所示:

大师:

我希望能够在 Master 目录中拥有一个 Python 脚本,该脚本在执行时将执行以下操作:

我知道如何从另一个文件(给定其名称)执行给定的 python 脚本,但我想创建一个脚本来执行它遇到的任何 train.py 脚本。因为 train.py 脚本可能会四处移动并成为 duplicated/deleted,我想创建一个适应性强的脚本,它将 运行 它找到的所有脚本。

我该怎么做?

您正在使用哪个OS?

如果Ubuntu/CentOS试试这个组合:

进口os

//把它放在 master 中,这会列出 master + 子目录中的每个文件,然后在管道 greps train.py

之后

train_scripts = os.system("find . -type d | grep train.py ")

//接下来执行它们

python train_scripts

如果您使用的是 Windows,您可以尝试从 PowerShell 脚本 运行连接它们。您可以同时 运行 两个 python 脚本:

python Test1.py
python Folder/Test1.py

然后添加一个循环和/或一个用于搜索文件的函数。因为它是 Windows Powershell,所以在文件系统和一般控制 Windows 方面,您拥有强大的力量。

您可以使用 os.walk 递归收集所有 train.py 脚本,然后 运行 使用 ProcessPoolExecutorsubprocess 模块并行收集它们。

import os
import subprocess

from concurrent.futures import ProcessPoolExecutor

def list_python_scripts(root):
    """Finds all 'train.py' scripts in the given directory recursively."""
    scripts = []
    for root, _, filenames in os.walk(root):
        scripts.extend([
            os.path.join(root, filename) for filename in filenames
            if filename == 'train.py'
        ])
    return scripts


def main():
    # Make sure to change the argument here to the directory you want to scan.
    scripts = list_python_scripts('master')
    with ProcessPoolExecutor(max_workers=len(scripts)) as pool:
        # Run each script in parallel and accumulate CompletedProcess results.
        results = pool.map(subprocess.run,
                           [['python', script] for script in scripts])

    for result in results:
        print(result.returncode, result.stdout)


if __name__ == '__main__':
    main()