4 回答

TA貢獻1797條經驗 獲得超4個贊
在您的情況下,您想將一個小整數傳遞給調用程序?;旧?,你有三種可能性,都有缺點或優點。
使用退出代碼
如果整數始終為非負且小于 256,您可以通過 Python 將其傳回并使用保存最近執行程序的退出代碼的exit
變量在調用方獲取它。$?
python3 your_program.py count=$?
雖然這種方法很簡單,但我不推薦它,原因有二:
退出代碼旨在傳達錯誤,而不是正常數據。
如果有一天你想用
set -e
(terminate-on-error) 來運行你的腳本,你就會有麻煩了。
使用標準輸出
將你要返回的整數寫到stdout,通過命令替換來獲取,即
count=$(python3 your_program.py)
缺點:如果有一天您想要向您的程序添加額外的輸出(例如,用于診斷),您必須將它寫入 stderr,否則它會污染您的結果計數。
使用文件
讓您的 Python 程序接受文件名,并將計數寫入該文件:
python3 your_program.py count_file count=$(<countfile)
缺點:您必須關心正在創建的 count_files,例如,如果不再需要,請刪除它們。

TA貢獻1786條經驗 獲得超13個贊
stdout 的任何輸出都可以捕獲到 bash 變量中。常規print
將打印到標準輸出
hello.py
print('hello')
狂歡
RESULT=`python3 hello.py` echo $RESULT # hello

TA貢獻1804條經驗 獲得超7個贊
我認為你應該讓你的 bash 腳本接受命令行參數。然后,在您的 python 腳本中,執行 subprocess.Popen(['your_bash_script', your_variable])。

TA貢獻1951條經驗 獲得超3個贊
你可以使用if $1(第一個參數的值)并修改你的最后一行error.py你應該能夠得到你想要的結果。
import subprocess as s
file = open("doubt.txt","r")
Counter = 0
# Reading from file
Content = file.read()
file.close()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
#print("This is the number of lines in the file")
#print(Counter)
if Counter > 1:
print("There is some erroneous value. Please restart the scanner")
s.call(['notify-send', str(Counter), 'Alert!','There is some erroneous value. Please restart the scanner'])
if $1 > 1
then break
fi
你可以用大約 3 行來完成這一切,會簡單得多:
import subprocess as s
with open ("doubt.txt","r") as f:
if len(f.readlines()) > 1:
s.call(['notify-send', Counter, 'Alert!','There is some erroneous value. Please restart the scanner'])
附言。with如果您不打算將上下文管理器與該函數一起使用open,請確保close在您的file對象上使用該方法。
添加回答
舉報