gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:42:53 25 4
gpt4 key购买 nike

我有以下(伪)代码:

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

最佳答案

该代码的问题:

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)

关于python - 为什么 os.system() 放在 for 循环中时不运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com