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

Dav*_*rts 0 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)
Run Code Online (Sandbox Code Playgroud)

不幸的是,发生的事情是对应的文件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])
Run Code Online (Sandbox Code Playgroud)

这显然是荒谬和笨拙的,所以我该怎么做才能解决这个问题呢?(顺便说一下,与EXACT相同的行为subprocess.Popen()).

Jea*_*bre 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)
Run Code Online (Sandbox Code Playgroud)

是你没有关闭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)
Run Code Online (Sandbox Code Playgroud)