1 単一の py ファイルを実行する
python_path
独自の python インストール パスに変更します
変更されたcd
パス
#!/bin/bash
python_path="/usr/local/bin/python3"
# "statistic.py"
files=("test.py")
start() {
cd /public/home/data/
for i in ${
files[*]}; do
pid=$(ps aux | grep python | grep "${i}" |grep -v grep| awk '{print $2}')
if [ ! "$pid" ]; then
${
python_path} "${i}" &
else
echo "${i} Started!"
fi
done
}
stop() {
pids=()
pid=$(ps aux | grep uvicorn|grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
pid=$(ps aux | grep multiprocessing |grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
pid=$(ps aux | grep main|grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
for i in ${
files[*]}; do
pid=$(ps aux | grep python | grep "${i}"|grep -v grep | awk '{print $2}')
if [ ! "$pid" ]; then
echo "${i} Stopped!"
else
pids[${
#pids[@]}]=$pid
fi
done
for p in ${
pids[*]}; do
kill -9 "${p}"
echo "${p} closed"
done
}
restart() {
stop
start
}
#main function
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
esac
2 複数のpyファイルを実行する
2.1 順次実行
変更されたcd
パス
#!/bin/bash
cd /public/home/data/test/
python3 test1.py
python3 test2.py
python3 test3.py
python3 test4.py
python3 test5.py
python3 test6.py
! Windows から Liunx サーバーにアップロードされた場合、シェル スクリプトは次のエラーを実行します: /bin/bash^M: bad interpreter: No such file or directory Reason
: Windows 環境のファイルは DOS 形式であり、末尾が各行は \r\n でマークされています; linux のファイルは unix 形式で、行末は \n でマークされています。
ファイルを確認してください: 1.
cat -A test.sh
の出力では、行末は ^M であり、これは dos 形式であり、行末がジャストの場合は unix 形式です。
2.vim test.sh、「:set ff」を実行、実行結果がfileformat=dosならdos形式、実行結果がfileformat=unixならunix形式
解決策:
1. sed -i "s/\r//" test.sh または sed -i "s/^M//" test.sh で、キャリッジ リターンを空の文字列に直接置き換えます。
2. vim test.sh、「: set ff=unix」を実行し、ファイルを unix 形式に設定し、保存して終了します。
2.2 マルチプロセス実行
python_path
独自の python インストール パスに変更します
変更されたcd
パス
#!/bin/bash
python_path="/usr/local/bin/python3"
# "statistic.py"
cd /public/home/data/test/
start() {
for dir in $(ls ./);
do
pid=$(ps aux | grep python | grep "${dir}" |grep -v grep| awk '{print $2}')
echo "${pid} Started!"
if [ ! "$pid" ]; then
${
python_path} "${dir}" &
else
echo "${dir} Started!"
fi
done
}
stop() {
pids=()
pid=$(ps aux | grep uvicorn|grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
pid=$(ps aux | grep multiprocessing |grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
pid=$(ps aux | grep main|grep -v grep | awk '{print $2}')
pids[${
#pids[@]}]=$pid
for dir in $(ls ./); do
pid=$(ps aux | grep python | grep "${i}"|grep -v grep | awk '{print $2}')
if [ ! "$pid" ]; then
echo "${dir} Stopped!"
else
pids[${
#pids[@]}]=$pid
fi
done
for p in ${
pids[*]}; do
kill -9 "${p}"
echo "${p} closed"
done
}
restart() {
stop
start
}
#main function
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
esac
注: スクリプトの実行プロセスと実行結果をログに出力する場合は、
./run.sh restart 2>&1 |tee -a mylog.log
run.sh
実行スクリプト用、mylog.log
ログファイル用