内存中的文件,Python

use*_*192 5 python file-io file

我有一个文本字符串,我想用它创建一个 .txt 文件。我不想允许用户访问它(出于安全原因),所以我想将 .txt 文件存储在内存中(如果可能的话)。

例如: 字符串是:

'''
Username: Bob
Password: Coolness

'''
Run Code Online (Sandbox Code Playgroud)

我想将此字符串作为 .txt 文件保存到内存中。然后将其发送到另一个程序。

anotherprogram.exe mytxt.txt
Run Code Online (Sandbox Code Playgroud)

我环顾四周,想知道使用StringIO是否可以做到这一点?它说“将字符串作为文件读取和写入”。我不确定,如果您知道如何执行此操作,请回复。

mgi*_*son 3

如果其他程序可以从标准输入读取,那么subprocess可能是可行的方法。这是一个愚蠢的例子,其中anotherprogram.execat

s='''
Username: Bob
Password: Coolness

'''

from subprocess import Popen,PIPE
p = Popen(['cat','-'], stdin=PIPE, stdout=PIPE)
stdoutdata, _ = p.communicate(s)
Run Code Online (Sandbox Code Playgroud)

许多接受文件输入的实用程序可以通过-作为文件名传递来从 stdin 读取,但不是全部。这是否有效将在很大程度上取决于anotherprogram.exe实际情况。