Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

linux - shell start / stop for python script

I have a simple python script i need to start and stop and i need to use a start.sh and stop.sh script to do it.

I have start.sh:

#!/bin/sh

script='/path/to/my/script.py'
echo 'starting $script with nohup'

nohup /usr/bin/python $script &

and stop.sh

#!/bin/sh

PID=$(ps aux | grep "/path/to/my/script.py" | awk '{print $2}')
echo "killing $PID"
kill -15 $PID

I'm mainly concerned with the stop.sh script. I think that's an appropriate way to find the pid but i wouldn't bet much on it. start.sh successfully starts it. when i run stop.sh, i can no longer find the process by "ps aux | grep 'myscript.py'" but the console outputs:

killing 25052
25058
./stop.sh: 5: kill: No such process

so it seems like it works AND gives an error of sorts with "No such process".

Is this actually an error? Am I approaching this in a sane way? Are there other things I should be paying attention to?

EDIT - I actually ended up with something like this: start.sh

#!/bin/bash
ENVT=$1
COMPONENTS=$2


TARGETS=("/home/user/project/modules/script1.py" "/home/user/project/modules/script2.py")
for target in "${TARGETS[@]}"
do
      PID=$(ps aux | grep -v grep | grep $target | awk '{print $2}')
      echo $PID
      if [[ -z "$PID" ]]
      then
              echo "starting $target with nohup for env't: $ENVT"
              nohup python $target $ENVT $COMPONENTS &
      fi
done

stop.sh

#!/bin/bash
ENVT=$1

TARGETS=("/home/user/project/modules/script1.py" "/home/user/project/modules/script2.py")
for target in "${TARGETS[@]}"
do
     pkill -f $target
     echo "killing process $target"
done
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is because ps aux |grep SOMETHING also finds the grep SOMETHING process, because SOMETHING matches. After the execution the grep is finished, so it cannot find it.

Add a line: ps aux | grep -v grep | grep YOURSCRIPT

Where -v means exclude. More in man grep.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...