Bash

在 bash 文件中多次執行 python 腳本

  • November 8, 2021

我想使用各種參數多次執行 python 腳本。為此,我編寫了以下 bash 腳本:

requests=(25 50 75 100)
factors=(3 6)
graphsizes=(25 50 75)

for request in "${requests[@]}"; do
   for factor in "${factors[@]}"; do
       for size in "${graphsizes[@]}"; do
           echo "Now Running: n = ${request}, factor = ${factor}, size = ${size}" >> nohup.out;
           echo nohup python3 -u main.py "$request" 50 "$factor" "$size" > ${request}_${factor}_${size}.log &
           echo "Done Running: n = ${request}, factor = ${factor}, size = ${size}" >> nohup.out;
       done
   done
done

;在第一個和最後一個末尾添加,echo因為我不希望它們並行執行。事實上,我希望對 python 腳本的每次呼叫main.py都按順序而不是並行執行,因為腳本本身已經並行化並且不想要任何競爭條件。

我知道通常我們使用 a;來使作業按順序執行,但是如果我&在 nohup 行之後這樣做,我會收到錯誤

syntax error near unexpected token `;'

如何使循環的每次迭代按順序執行?

您在多行上編寫腳本的方式,’;’ 由換行符暗示。您可以刪除“;” 在最內層循環內的三行中的每一行的末尾,for腳本將按順序執行。你只需要’;’ 如果您在它們之間應該有中斷時將它們移動到同一行,例如當您將它們與規範do放在同一行時。請注意以下重寫腳本中for的替代位置:do

for request in "${requests[@]}" 
do
 for factor in "${factors[@]}"
 do
   for size in "${graphsizes[@]}"
   do
       echo "Now Running: n = ${request}, factor = ${factor}, size = ${size}" >> nohup.out
       echo nohup python3 -u main.py "$request" 50 "$factor" "$size" > ${request}_${factor}_${size}.log 
       echo "Done Running: n = ${request}, factor = ${factor}, size = ${size}" >> nohup.out
   done
 done
done

引用自:https://unix.stackexchange.com/questions/676358