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

时间:2017-08-09 19:27:25

标签: python subprocess os.system

我有以下(伪)代码:

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())发生了完全相同的行为。

1 个答案:

答案 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)