The title of this post is a bit of a misnomer because it is always necessary to import a gpg key before it can be used to sign/encrypt/etc. anything. However we can create a temporary GPG home directory, use it for the encryption process and discard it afterwards. The example below is written in Python but can easily be ported to other languages.

import subprocess
import os
import tempfile
import re

def encrypt(in_file, out_file, key):
    with tempfile.TemporaryDirectory() as gpg_dir:
        env = os.environ.copy()
        env['GNUPGHOME'] = gpg_dir
        key_id = import_key(env, key)

              'gpg2', '--encrypt', '--cipher-algo', 'AES256',
              '--recipient', key_id, '--trust-model', 'always',
              '--output', '-'
            stdin=in_file, stdout=out_file, env=env

def import_key(env, key):
    with tempfile.NamedTemporaryFile() as key_file:
        output = subprocess.check_output(
            ['gpg2', '--import'],
            stdin=key_file, stderr=subprocess.STDOUT, env=env
        output_lines = output.splitlines()
        # There are significantly cleaner ways to extract the key id, but for illustration this should be enough
        for line in output_lines:
            matches = re.match(r'^gpg: key (.*): .*imported$', line)
            if matches is not None:
                key_id =
                return key_id
        raise Exception('Error extracting key id: ', output_lines)

# For illustration
if __name__ == '__main__':
    with open('/tmp/plain.txt', 'rb') as f_plain, \
         open('/tmp/cipher.gpg', 'wb') as f_cipher, \
         open('/tmp/', 'r') as f_key:
        key =
        encrypt(in_file=f_plain, out_file=f_cipher, key=key)