2017-08-09 34 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) 
相關問題