shell start / stop for python script

后端 未结 5 1212
青春惊慌失措
青春惊慌失措 2020-12-20 23:42

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

scri         


        
5条回答
  •  忘掉有多难
    2020-12-21 00:18

    init-type scripts are useful for this. This is very similar to one I use. You store the pid in a file, and when you want to check if it's running, look into the /proc filesystem.

    #!/bin/bash
    
    script_home=/path/to/my
    script_name="$script_home/script.py"
    pid_file="$script_home/script.pid"
    
    # returns a boolean and optionally the pid
    running() {
        local status=false
        if [[ -f $pid_file ]]; then
            # check to see it corresponds to the running script
            local pid=$(< "$pid_file")
            local cmdline=/proc/$pid/cmdline
            # you may need to adjust the regexp in the grep command
            if [[ -f $cmdline ]] && grep -q "$script_name" $cmdline; then
                status="true $pid"
            fi
        fi
        echo $status
    }
    
    start() {
        echo "starting $script_name"
        nohup "$script_name" &
        echo $! > "$pid_file"
    }
    
    stop() {
        # `kill -0 pid` returns successfully if the pid is running, but does not
        # actually kill it.
        kill -0 $1 && kill $1
        rm "$pid_file"
        echo "stopped"
    }
    
    read running pid < <(running)
    
    case $1 in 
        start)
            if $running; then
                echo "$script_name is already running with PID $pid"
            else
                start
            fi
            ;;
        stop)
            stop $pid
            ;;
        restart)
            stop $pid
            start
            ;;
        status)
            if $running; then
                echo "$script_name is running with PID $pid"
            else
                echo "$script_name is not running"
            fi
            ;;
        *)  echo "usage: $0 "
            exit
            ;;
    esac
    

提交回复
热议问题