python脚本开机自启,python脚本杀死并启动自己

I want to start a new instance of my python script when it reaches a specified time during the hour and kill the current instance.

The python script starts automatically with boot using a crontab. An infinite while loop reads data. If there is data incoming between minute 59 second 30 and minute 59 second 59, the file gets closed and I want the script to start a new instance of itself with a new process ID and kill the old process. At the moment I am doing this by using

subprocess.call(['python', '/home/pi/script.py'])

sys.exit(1)

That starts a new instance of the python script, but the old one is still visible and (it seems) active when I check the processes with top.

Is there a better way to let the program start and kill itself inside the python script?

Another approach using a bash script called by the python script:

#!/bin/sh

PID=`ps -eaf | grep python | grep -v grep | awk '{print $2}'`

if [[ "" != "$PID" ]]; then

echo "killing $PID"

kill -9 $PID

sleep 1

sudo python /home/pi/readserial_V4_RP.py &

exit 1

fi

But that can't work because the python script end, before the bash script can kill it. I could start the python script without killing python

processes, but how can I be sure that no python script is running, before I start the new instance of the python script.

because I have the feeling, when I have more than one same python scripts running, that the first one that was started is doing all the "work" and the others are just in idle...

解决方案

Instead of having a process try to restart itself, have a thin parent script that runs the real script. The parent monitor just restarts the script whenever it exits. Since the parent waits until the child has fully exited, you won't have multiple versions running. In a full implementation, the parent holds any system daemon code you need and the child is focused on the task.

This example runs a very boring program that sleeps for the number of seconds specified on the command line

import multiprocessing

import time

import sys

import os

import traceback

def the_real_work_done_here(sleep_time):

try:

print(os.getpid(), 'start work')

time.sleep(sleep_time)

print(os.getpid(), 'end work')

exit(0)

except Exception:

traceback.print_exc()

exit(2)

def monitor(sleep_time):

while 1:

proc = multiprocessing.Process(target=the_real_work_done_here,

args=(sleep_time,))

proc.start()

proc.join()

if proc.exitcode != 0:

print('something went wrong... terminating')

exit(proc.exitcode)

if __name__ == '__main__':

try:

sleep_time = int(sys.argv[1])

monitor(sleep_time)

except (KeyError, ValueError):

print('usage: test.py sleeptime')

exit(1)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值