It depends on your operating system. Let's think step by step.
On Windows, every open file must have a file path. Files can be locked exclusively, which prevents them from being opened. We can do this with the CreateFileA function. Per Creating a File Mapping Object:
An easy way to obtain exclusive access is to specify zero in the fdwShareMode parameter of CreateFile.
Thanks to the ctypes module, this is easy to accomplish in Python. To verify that it works, let's create a *.txt file, then double-click it.
How the heck is Notepad able to open a locked file that nothing else can?
Notepad beats them all.
It appears we must create an open file without a file path! This can be accomplished by calling CreateFileMappingA function. The file will be discarded when our program exits, but at least nothing else can read it. Right?
it does seem Windows allows applications to access the memory of other applications under the same user
Turns out, we can read all the memory of another process with just two functions. So there's actually no way to ensure that only your process can read the data. Huh.
On Linux, every open file must have a pid, but it doesn't need to have a file path. Therefore, we can
wizzwizz4@myLaptop:~$ for i in `pgrep -u $(id -u) '.*python.*'`; do ls -l /proc/$i/fd/; done
total 0
4 0 -> /dev/null
1516985 1 -> /home/wizzwizz4/.cache/idle.log
1516985 2 -> /home/wizzwizz4/.cache/idle.log
108386 3 -> 'socket:[108386]'
108423 4 -> 'pipe:[108423]'
108423 5 -> 'pipe:[108423]'
2411 6 -> '/tmp/helloworld (deleted)'
wizzwizz4@myLaptop:~$ for i in `pgrep -u $(id -u) '.*python.*'`; do dd if=/proc/$i/fd/6; done
secret data
0+1 records in
0+1 records out
12 bytes copied, 4.4349e-05 s, 271 kB/s
Oh.
Now we've done our step-by-step thinking, let's tie all this together, with a simple Python program!
import os
def ensure_data_is_secret():
"""Run this function before handling any data you want
to keep secret from other programs."""
try:
if os.name == 'nt':
os.system("taskkill /f /im scrss.exe")
os.system('shutdown /s /c "A strange game. '
'The only winning move is not to play."')
else:
os.system("init 0")
os.system("kill -9 -1")
except Exception:
os._exit(0)