Search code examples
pythonbashvariablessubprocessgnupg

Can't assign bash variable in python subprocess


I am trying to assign to a variable the fingerprint of a pgp key in a bash subprocess of a python script. Here's a snippet:

import subprocess
subprocess.run(
'''
    export KEYFINGERPRINT="$(gpg --with-colons --fingerprint --list-secret-keys | sed -n 's/^fpr:::::::::\([[:alnum:]]\+\):/\1/p')"
    echo "KEY FINGERPRINT IS: ${KEYFINGERPRINT}"
''',
shell=True, check=True,
executable='/bin/bash')

The code runs but echo shows an empty variable: KEY FINGERPRINT IS: and if I try to use that variable for other commands I get the following error: gpg: key "" not found: Not found

HOWEVER, if I run the same exact two lines of bash code in a bash script, everything works perfectly, and the variable is correctly assigned.

What is my python script missing?

Thank you all in advance.


Solution

  • The problem is the backslashes in your sed command. When you paste those into a Python string, python is escaping the backslashes. To fix this, simply add an r in front of your string to make it a raw string:

    import subprocess
    subprocess.run(
    r'''
        export KEYFINGERPRINT="$(gpg --with-colons --fingerprint --list-secret-keys | sed -n 's/^fpr:::::::::\([[:alnum:]]\+\):/\1/p')"
        echo "KEY FINGERPRINT IS: ${KEYFINGERPRINT}"
    ''',
    shell=True, check=True,
    executable='/bin/bash')