close_fds=True
on POSIX systems on Python 3. Use pass_fds
to pass input pipe file descriptor:
#!/usr/bin/env python3
import os
import shlex
import sys
from subprocess import Popen
passphrase = 'passsssphrase'
file_to_encrypt = sys.argv[1] if len(sys.argv) > 1 else 'encrypt_me.py'
in_fd, out_fd = os.pipe()
cmd = 'gpg --passphrase-fd {fd} -c --armor -o -'.format(fd=in_fd)
with Popen(shlex.split(cmd) + [file_to_encrypt], pass_fds=[in_fd]):
os.close(in_fd) # unused in the parent
with open(out_fd, 'w', encoding='utf-8') as out_file:
out_file.write(passphrase)
You could also pass the passphrase via stdin:
#!/usr/bin/env python3
import sys
from subprocess import PIPE, Popen
passphrase = 'passsssphrase'
file_to_encrypt = sys.argv[1] if len(sys.argv) > 1 else __file__
cmd = 'gpg --passphrase-fd 0 -c --armor -o -'.split()
with Popen(cmd + [file_to_encrypt], stdin=PIPE) as process:
process.stdin.write(passphrase.encode('utf-8'))