簡體   English   中英

如何在 python 中運行 bash 腳本並使用在該腳本中定義的變量

[英]How to run a bash script in python and use the variables that where defined in that script

我在 Python 腳本中運行 bash 腳本,我需要在 Python 腳本中使用在 bash 腳本內部定義的變量。

對於某些上下文,這里是 bash 腳本:

#!/bin/bash
updates=$(/usr/lib/update-notifier/apt-check 2>&1)
all=${updates%";"*}
security=${updates#*";"}

這是我在 Python 腳本中調用它的方式:

import subprocess
subprocess.call(["/usr/bin/checkupdates"])

我想在此 SQL 更新語句(它是 Python 腳本的一部分)中使用在該 bash 腳本(“all”和“security”)中定義的變量:

cursor.execute("update dbo.updates_preprod set updates_available = ?, securityupdates_available = ? where hostname = ?",(all, security , socket.gethostname()))
cnxn.commit()

是否有可能做到這一點? 如果沒有,我是否可以運行 2 個單獨的腳本(每個腳本都會回顯一個變量)並獲取每個腳本的標准輸出並將其定義為 Python 中的變量?

提前致謝!

最后,直接從 Python 腳本調用該命令要容易得多。

output = subprocess.check_output("usr/lib/update-notifier/apt-check", shell=True) all,sec = output.decode().split(';')

感謝@cdarke 和@furas 的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM