python restart shell_用于python脚本的shell启动/停止

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值