【问题标题】:Running all Python scripts with the same name across many directories跨多个目录运行具有相同名称的所有 Python 脚本
【发布时间】:2020-09-26 01:24:26
【问题描述】:

我的文件结构看起来像这样:

大师:

  • 第一
    • train.py
    • other1.py
  • 第二
    • train.py
    • other2.py
  • 第三
    • train.py
    • other3.py

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

  • 循环遍历所有子目录(及其子目录,如果存在)
  • 以任何必要的顺序运行每个名为 train.py 的 Python 脚本

我知道如何从另一个文件(给定它的名称)执行给定的 python 脚本,但我想创建一个脚本来执行它遇到的任何train.py 脚本。因为train.py 脚本可能会被移动和复制/删除,所以我想创建一个可调整的脚本来运行它找到的所有脚本。

我该怎么做?

【问题讨论】:

  • 你能发布你到目前为止所做的尝试吗?您可能对os 模块感兴趣,特别是os.walk
  • os.walk 之前用过几次,遇到这个脚本文件怎么执行?

标签: python tensorflow directory subdirectory


【解决方案1】:

您可以使用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()

【讨论】:

    【解决方案2】:

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

    python Test1.py
    python文件夹/Test1.py

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

    【讨论】:

      【解决方案3】:

      您使用的是哪个操作系统?

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

      导入操作系统

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

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

      //接下来执行它们

      python 训练脚本

      【讨论】:

      • ls -p . 只列出当前目录。
      • 我在 macOS 上。我试过了,但没有用。没有错误或任何东西,它只是不运行任何脚本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 2019-09-19
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多