2

How can I create an in-memory directory in python, like how StringIO creates in-memory files?

I'm trying to verify the signature of a file using python-gnupg. I want to create a gnupghome directory in-memory so that its safe (other non-root processes can't write to it) and ephemeral (gone when I .close() it or my python app is closed).

The solution needs to be OS-agnostic so it supports linux, Windows, and MacOS (no subprocess calls to mktemp -d please).

Is there a native, cross-platform, pythonic way to create a directory in-memory?

Michael Altfield
  • 2,083
  • 23
  • 39
  • 1
    The thing about `StringIO` is that all the operations it supports are methods. That works because Python file objects are objects, and it can replicate their API. It doesn't have to interact with the file system at all. In contrast, there is no concept of a "directory-like object" in Python. – user2357112 Aug 16 '20 at 07:54
  • If you want an in-memory directory, you're going to have to create it in the actual file system. I don't think there's a good cross-platform way to do that, especially with the safety properties you want. – user2357112 Aug 16 '20 at 07:55
  • 1
    Have you tried the tempfile? You can find documentation in the python standard library doc, and it does pretty much all you require: real file/directory, temporary, protected, cross-platform – jthulhu Aug 17 '20 at 06:33

1 Answers1

0

You can create an in-memory filesystem with PyFilesystem's Memory Filesystem.

That said, the way that python-gnupg works it by shelling-out to the gpg binary on the system. Therefore, the in-memory-FS that's created by python wouldn't be accessible to gpg.

Morevoer, the way that python-gnupg was implemented means its functions takes paths to files as strings. If, instead, it took file descriptors to byte streams, then this could maybe work. But it doesn't. For example:

  • gpg.GPG()'s gnupghome is a string that's the path to the directory on the actual disk
  • gpg.verify_file()'s second argument is a string that's the path to the detached signature
Michael Altfield
  • 2,083
  • 23
  • 39