I need to create startup and stop scripts for a python program. My temporary solution was to have the startup.sh:
python -m root.scripts.run
python server.py 'localhost' 42345
This starts my program and a server that is needed to do some computations. Now for stop.sh I just do:
killall -m Python
killall python
killall Python
This works and stops my program. However I need to find a less “brutal” solution, since this obviously kills all python related processes. A solution I’m thinking of (not sure if it is possible) is in the startup.sh to get the PID of the two started processes and store them in a file somewhere. Then for the stop.sh I would just get those pids and kill those processes. Now I have a few questions:
- Is my proposed solution viable? If so how can I get the pid of the recently started processes ? In terms of storing them and then getting them from a file, is this doable and if so how?
- Do you have any other proposed solutions for my problem?
- In terms of cross-platform, how hard would it be to mimic something like this on windows?
Use the
subprocessmodule to start the program from Python (this is the recommended way anyway). The object returned fromsubprocess.Popenhasterminate()andkill()methods as well as apidattribute that you can save and use for stopping the process again.On Unix systems, you might consider saving the PID in a file in
/var/run/<yourscript>.pid(see the Filesystem Hierarchy Standard), then read this file to retrieve the PID when requested to stop.