with语句似乎未正确关闭文件(子进程也在使用该文件)
我在我的程序中想实现一个步骤(这是一个用Python写的自动评分器),就是创建一个临时的txt文件,里面包含外部程序的输出(学生的作业)。我已经成功地用with
语句写入了这个txt文件,但我却无法删除这个文件。为了删除txt文件,我使用了os.remove(file.txt)
,但是总是出现以下错误:
PermissionError: [WinError 32] 该进程无法访问文件,因为它正在被另一个进程使用: 'file.txt'
我猜这可能是因为with
语句没有正确关闭txt文件。为了强制关闭文件,我尝试添加.close()
,但我知道这样做有点多余。我也在考虑可能是subprocess.Popen()
这一行的问题,但我在其他程序中使用过这个方法,并且在尝试操作同一个文件时(比如写入txt文件,然后再读取它)没有遇到问题。不过,为了测试这个,我尝试使用kill()
,但我在让它正常工作上遇到了麻烦。
如果有人能告诉我哪里出错了,并给我一些提示该怎么做,我会非常感激!
hw_file = f"{submissions_folder}\\TaylorDavisOnTime.java" # example of naming style for student assignments
student_txt_file = hw_file.replace(f"{submissions_folder}\\", f"{submissions_folder}\\output\\").replace(".java", "Output.txt")
with open(student_txt_file, "w") as file:
output = subprocess.Popen(["java", hw_file], stdin=subprocess.PIPE, stdout=file, text=True)
for input in input_values:
output.stdin.write(input[0])
output.stdin.write(str(input[1]))
output.stdin.write(str(input[2]))
output.stdin.flush()
output.stdin.close()
# output.kill() # still playing with this
remove = True
file.close() # redundant, but does nothing
if remove:
os.remove(student_txt_file)
2 个回答
0
也许可以使用tempfile模块?
你可以把:
with open(student_txt_file, "w") as file:
换成:
import tempfile
with tempfile.TemporaryFile() as file:
当with
这个上下文管理器结束时,它会自动帮你删除文件。而且它会选择一个合适的位置(比如/var/tmp
)和一个独特的文件名,所以你就不用自己去计算student_txt_file
了。
0