with 语句似乎没有正确关闭文件(子进程也使用该文件)

问题描述 投票:0回答:1

我试图在我的程序(这是另一个自动评分器,但在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)
python operating-system subprocess text-files with-statement
1个回答
0
投票

子进程仍然打开了文件,这就是为什么

os.remove
没有删除文件的权限。

使用

output.wait()
1 等待子进程完成会释放文件并允许将其删除。


1Harsha

建议
© www.soinside.com 2019 - 2024. All rights reserved.