Windows上的写作和读取虚拟文件
作为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论