如何 运行 仅当前一个文件结束时才 运行 下一个文件 运行 使用子进程按顺序排列列表

How to run the next file only when the previous file ends when running the list in order using subprocess

有一些我想使用子进程顺序执行的列表。上一个文件执行完了才想执行下一个文件应该用什么方法?

for index in acnt_df.index:
            os.environ["a"] = str(acnt_df["acnt"][index])
            subprocess.Popen(
                ["python", "start.py"]
            )

我试过了,但它会在第一个文件结束之前打开下一个文件

使用 subprocess.run 代替 subprocess.Popen

for index in acnt_df.index:
    os.environ["a"] = str(acnt_df["acnt"][index])
    p = subprocess.run(["python", "start.py"])

检查 subprocess 模块的文档:

https://docs.python.org/3/library/subprocess.html

关于如何控制另一个 运行 进程有非常细粒度的方法。如果您想使用 Popen 对象的全部功能,您可以选择

for index in acnt_df.index:
    os.environ["a"] = str(acnt_df["acnt"][index])
    p = subprocess.Popen(["python", "start.py"])
    p.wait()

但是,当您调用 python 脚本时,建议将其更改为能够将其作为模块导入,并将您的 a 环境变量作为普通函数参数传递。 IE。改变 start.py 能够做到:

import start

for index in acnt_df.index:
    a = str(acnt_df["acnt"][index])
    start.main(a)