4 回答
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
在您的情況下,您想將一個(gè)小整數(shù)傳遞給調(diào)用程序。基本上,你有三種可能性,都有缺點(diǎn)或優(yōu)點(diǎn)。
使用退出代碼
如果整數(shù)始終為非負(fù)且小于 256,您可以通過(guò) Python 將其傳回并使用保存最近執(zhí)行程序的退出代碼的exit變量在調(diào)用方獲取它。$?
python3 your_program.py count=$?
雖然這種方法很簡(jiǎn)單,但我不推薦它,原因有二:
退出代碼旨在傳達(dá)錯(cuò)誤,而不是正常數(shù)據(jù)。
如果有一天你想用
set -e(terminate-on-error) 來(lái)運(yùn)行你的腳本,你就會(huì)有麻煩了。
使用標(biāo)準(zhǔn)輸出
將你要返回的整數(shù)寫(xiě)到stdout,通過(guò)命令替換來(lái)獲取,即
count=$(python3 your_program.py)
缺點(diǎn):如果有一天您想要向您的程序添加額外的輸出(例如,用于診斷),您必須將它寫(xiě)入 stderr,否則它會(huì)污染您的結(jié)果計(jì)數(shù)。
使用文件
讓您的 Python 程序接受文件名,并將計(jì)數(shù)寫(xiě)入該文件:
python3 your_program.py count_file count=$(<countfile)
缺點(diǎn):您必須關(guān)心正在創(chuàng)建的 count_files,例如,如果不再需要,請(qǐng)刪除它們。
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
stdout 的任何輸出都可以捕獲到 bash 變量中。常規(guī)print將打印到標(biāo)準(zhǔn)輸出
hello.py
print('hello')狂歡
RESULT=`python3 hello.py` echo $RESULT # hello
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為你應(yīng)該讓你的 bash 腳本接受命令行參數(shù)。然后,在您的 python 腳本中,執(zhí)行 subprocess.Popen(['your_bash_script', your_variable])。
TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
你可以使用if $1(第一個(gè)參數(shù)的值)并修改你的最后一行error.py你應(yīng)該能夠得到你想要的結(jié)果。
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 行來(lái)完成這一切,會(huì)簡(jiǎn)單得多:
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如果您不打算將上下文管理器與該函數(shù)一起使用open,請(qǐng)確保close在您的file對(duì)象上使用該方法。
添加回答
舉報(bào)
