2017-08-09 31 views
-1

我有以下的(伪)代码:为什么os.system()放置在for循环时运行?

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())。

+3

我认为这个问题可能是因为在使用'os.system()'来处理它之前,你没有刷新/关闭'job_file'。在这种情况下,您不能保证文件将包含您想要的正确条目。在尝试在'os.system()'中访问它之前,尝试关闭文件。 –

+1

'open(“new_file_settings [j] .sh”,“w”)':你打开一个名为literally new_file_settings [j] .sh的文件,放下引号... –

+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) 
相关问题