Python 为什么';t os.system()在放入for循环时是否运行?
我有以下(伪)代码: 不幸的是,发生的情况是,与Python 为什么';t os.system()在放入for循环时是否运行?,python,subprocess,os.system,Python,Subprocess,Os.system,我有以下(伪)代码: 不幸的是,发生的情况是,与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
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)
是因为您没有关闭作业\u文件
,所以在运行系统调用时,文件仍处于打开状态(且未刷新)
执行作业\u 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)
我认为问题可能在于,在使用
os.system()
处理作业之前,您没有刷新/关闭作业文件。在这种情况下,您无法保证文件将包含所需的正确条目。在处理完文件后,请尝试关闭该文件,然后再尝试在os.system()
open(“新建文件设置[j].sh”,“w”)
:您正在打开一个名为“新建文件设置[j].sh”的文件,请删除引号……这个问题的标题完全误导了问题所在(不是脚本没有运行,而是它看不到文件内容).我怎么会知道?如果我知道问题的原因,那么我就不会问这个问题。我花了几个小时进行测试和调试,这是我能得出的最好结论。如果只是人们嘲笑提问者不知道什么,那么问答网站有什么用?
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)