我正在嘗試將 python 腳本的 bash 子行程中的 pgp 鍵的指紋分配給變數。這是一個片段:
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')
代碼運行但 echo 顯示一個空變數:
KEY FINGERPRINT IS:
如果我嘗試將該變數用于其他命令,則會收到以下錯誤:
gpg: key "" not found: Not found
但是,如果我在 bash 腳本中運行完全相同的兩行 bash 代碼,則一切正常,并且變數已正確分配。
我的 python 腳本缺少什么?
謝謝大家。
uj5u.com熱心網友回復:
問題是您的sed命令中的反斜杠。當您將它們粘貼到 Python 字串中時,python 正在轉義反斜杠。要解決此問題,只需r在字串前面添加一個以使其成為原始字串:
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')
uj5u.com熱心網友回復:
為了在子行程中運行 2 個命令,您需要一個接一個地運行它們或使用 ;
import subprocess
ret = subprocess.run('export KEYFINGERPRINT="$(gpg --with-colons --fingerprint --list-secret-keys | sed -n 's/^fpr:::::::::\([[:alnum:]]\ \):/\1/p')"; echo "KEY FINGERPRINT IS: ${KEYFINGERPRINT}"', capture_output=True, shell=True)
print(ret.stdout.decode())
你可以使用popen:
commands = '''
export KEYFINGERPRINT="$(gpg --with-colons --fingerprint --list-secret-keys | sed -n 's/^fpr:::::::::\([[:alnum:]]\ \):/\1/p')"
echo "KEY FINGERPRINT IS: ${KEYFINGERPRINT}"
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413719.html
標籤:
上一篇:回圈和變數,變數再次更新
