为什么 os.system() 运行 放在 for 循环中?

why doesn't os.system() run when placed in a for loop?

我有以下(伪)代码:

import os

for s in settings:
    job_file = open("new_file_s.sh", "w")
    job_file.write("stuff that depends on s")
    os.system(command_that_runs_file_s)

不幸的是,s = settings[0]对应的文件没有被执行,而s = settings[1]却被执行了。显然,os.system() 不喜欢最近使用 open() 创建的 运行 文件,尤其是在 for 循环的同一迭代中。

我的解决方法是确保通过 os.system() 执行的任何文件都在 for 循环的先前迭代中初始化:

import os

# Stagger so that writing happens before execution:
job_file = open("new_file_settings[0].sh", "w")
job_file.write("stuff that depends on settings[0]")

for j in range(1, len(settings)):
    job_file = open("new_file_settings[j].sh", "w")
    job_file.write("stuff that depends on settings[j]")

    # Apparently, running a file in the same iteration of a for loop is taboo, so here we make sure that the file being run was created in a previous iteration:
    os.system(command_that_runs_file_settings[j-1])

这显然是荒谬和笨拙的,那么我该怎么做才能解决这个问题呢? (顺便说一句,subprocess.Popen() 会发生完全相同的行为)。

该代码的问题:

import os

for s in settings:
    job_file = open("new_file_s.sh", "w")
    job_file.write("stuff that depends on s")
    os.system(command_that_runs_file_s)

是你没有关闭job_file,所以当你运行系统调用时文件仍然打开(而不是刷新)。

执行 job_file.close(),或更好:使用上下文管理器确保文件已关闭。

import os

for s in settings:
    with open("new_file_s.sh", "w") as job_file:
       job_file.write("stuff that depends on s")
    os.system(command_that_runs_file_s)