gpt4 book ai didi

python - 刷新和 fsync 在临时文件中不起作用

转载 作者:行者123 更新时间:2023-11-28 17:46:35 25 4
gpt4 key购买 nike

我正在尝试创建一个文件。在这个文件中,我将所有需要处理的文件放在一个脚本中,并将该文件作为参数传递。我的问题是有时列表的长度不足以填满缓冲区,并且没有任何内容写入磁盘。我尝试刷新和 fsync 临时文件,但没有任何反应。该脚本是第三方脚本,因此我无法更改参数的传递方式。

with tempfile.NamedTemporaryFile(bufsize=0) as list_file:
list_file.write("\n".join(file_list) + "\n")
list_file.flush()
os.fsync(list_file)

command = "python " + os.path.join(SCRIPT_PATH, SCRIPT_NAME) + " --thread --thread_file "
ppss_command = [SCRIPT_PATH + "/ppss", "-f", list_file.name, "-c", command]
p = subprocess.Popen(ppss_command)
out,err = p.communicate()

最终解决方案代码(jterrace Answer):

with tempfile.NamedTemporaryFile(delete=False) as list_file:
list_file.write("\n".join(file_list) + "\n")
list_file.close()
command = "python " + os.path.join(SCRIPT_PATH, SCRIPT_NAME) + " --thread --thread_file "
ppss_command = [SCRIPT_PATH + "/ppss", "-f", list_file.name, "-c", command]
p = subprocess.Popen(ppss_command)
out, err = p.communicate()
list_file.delete = True

最佳答案

来自NamedTemporaryFile docstring :

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

因此,当您仍然打开文件时,它可能无法从子进程中读取。这是我会做的:

fd, tmp_fpath = tempfile.mkstemp()
os.close(fd) # Needed on Windows if you want to access the file in another process

try:
with open(tmp_fpath, "wb") as f:
f.write("\n".join(file_list) + "\n")

# ... subprocess stuff ...
do_stuff_with(tmp_fpath)
finally:
os.remove(tmp_fpath)

关于python - 刷新和 fsync 在临时文件中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370892/

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