Windows上的写作和读取虚拟文件

发布于 2025-02-10 04:00:21 字数 970 浏览 1 评论 0原文

作为Windows上Python项目的一部分,我需要使用小文件作为交流不同过程的一种手段。由于必须使用subprocess.run(程序,args ...)来调用外部进程,因此我不能简单地获取文件描述符,而是将其作为参数传递给外部过程。相反,我需要一个可以从普通文件系统访问的名称的文件。因此,我想要一种创建临时文件的简单方法,该文件存储在内存(RAM)而不是磁盘中,并且具有其他外部进程可以使用的名称。在Linux中,此可以使用函数os.mkfifo()来实现。但是,此功能在Windows中不可用。

目前,我只是简单地使用tempfile模块来创建一个临时文件,该文件一旦不再需要,就会存储在磁盘中并删除。这是我的代码的一个小示例:

import tempfile
import subprocess
import os

fd = tempfile.NamedTemporaryFile(mode="w+t", delete=False) # Obtain file descriptor
file_path = fd.name # Obtain file path

# Write data (encoded as str) to the file and close it
fd.write(data)
fd.close()

# Access this same file from an external process
output = subprocess.run( [program, file_path], stdout=subprocess.PIPE).stdout.decode('utf-8')

# Delete the file
os.remove(file_path)

print("External process output:", output)

因此,我的问题是:如何更改此代码,以便在fd.write(data)中将数据写入RAM而不是磁盘而不是磁盘?

As part of a Python project on Windows, I need to use small files as a means to communicate different processes. Since the external process must be called with subprocess.run(program, args...), I can't simply obtain a file descriptor for my file and pass it as a parameter to the external process. Instead, I need a file with a name which can be accessed from the normal filesystem. Thus, I would like a simple way to create a temporary file which is stored in memory (RAM) instead of disk, and which has a name other external processes can use to access it. In Linux, this can be achieved with the function os.mkfifo(). However, this function is not available in Windows.

At the moment, I am simply using the tempfile module to create a temporary file which is stored in disk and deleted once it is no longer needed. Here is a small reproducible example for my code:

import tempfile
import subprocess
import os

fd = tempfile.NamedTemporaryFile(mode="w+t", delete=False) # Obtain file descriptor
file_path = fd.name # Obtain file path

# Write data (encoded as str) to the file and close it
fd.write(data)
fd.close()

# Access this same file from an external process
output = subprocess.run( [program, file_path], stdout=subprocess.PIPE).stdout.decode('utf-8')

# Delete the file
os.remove(file_path)

print("External process output:", output)

So, my question is the following: How can I change this code so that in line fd.write(data) the data is written to RAM instead of disk?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文