开发者

Getting pid of the program just started in Python

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:

  1. 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?
  2. Do you have any other proposed solutions for my problem?
  3. In terms of cross-platform, how hard would it be to mimic something like this on windows?


Use the subprocess module to start the program from Python (this is the recommended way anyway). The object returned from subprocess.Popen has terminate() and kill() methods as well as a pid attribute 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.


I would replace your startup.sh for a Python script which runs both scripts. Use subprocess.Popen() for running new processes and terminate() for killing them.

Python solves your third question. Otherwise you have to use cygwin/mingw under Windows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜