我有以下(伪)代码:
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()
)发生了完全相同的行为。
答案 0 :(得分:5)
该代码的问题:
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)