我有一個迭代運行 python 腳本的 for 回圈。python 腳本中有一個條件,如果滿足,則無需繼續運行 python 腳本甚至 for 回圈。例如:
#Bash Script
for i in {1..15}; do
echo "Pre Outside ${i}"
python minimal_test.py $i
echo "Post Outside ${i}"
done
#Python script
import sys
import subprocess
k = int(sys.argv[1])
end_bash = False
if k == 7:
end_bash = True
print("Inside " str(k))
if end_bash:
bashCommand = "break"
process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE)
當 bash 腳本中的回圈 i == 6 和 7 時,程式應列印:
PreOutside 6
PreInside 6
PostOutside 6
Pre Outside 7
Pre Inside 7 #The program must end here
但是,我收到以下錯誤并且程式繼續運行
File "/software/software/Python/3.9.5-GCCcore-10.3.0/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'break'
有沒有辦法告訴 bash 從 python 腳本中結束 for 回圈?
uj5u.com熱心網友回復:
使您的 Python 腳本退出并出現錯誤。那么shell腳本就變成了
for i in {1..15}; do
python minimal_test.py "$i" || break
done
總而言之,您的 Python 腳本應該sys.exit(1)向 shell(或任何呼叫實用程式)發出錯誤信號。確切的數字由您決定;任何非零數字都是失敗代碼。(范圍是 0-255,即無符號char。)
在子行程中運行break沒有意義;您正在啟動一個新的 Bash 實體,該實體獨立于運行回圈的實體,其中當然break沒有做任何有用的事情,實際上只是孤立的語法錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515835.html
標籤:Python重击
