0

I have a script that is executed when a certain condition is met. I want to start another script that will do some calculations (and it must be in another script) and save the PID of that process. And then want ot check another condition. When the second condition is met I want to kill that script that I started earlier.

Can anybody allude me to some kind of solution please.

Example:

Script1.py
do some calculation

main_script.py

if [condition]:

create a process in background to call Script1.py

save PID of that process

if [another condition]:

kill that process

Oliver
  • 11,857
  • 2
  • 36
  • 42
Nash
  • 105
  • 1
  • 9
  • Here's two links that might help, [first](http://stackoverflow.com/questions/17686351/shell-start-stop-for-python-script) and [second](http://stackoverflow.com/questions/8281345/how-to-get-current-linux-process-id-pid-from-cmdline-in-shell-and-language-i). – Tony May 17 '17 at 00:46

2 Answers2

3

You can use the subprocess package. Popen returns the instance process, you can save it, and later terminate it under certain condition. For example:

if [condition to init]:
  process = subprocess.Popen("./stuff someargs")


if [condition to stop]:
  process.kill()

You may use either kill or terminate, according to what you are trying to accomplish. Check the subprocess documentation for more details.

bones.felipe
  • 586
  • 6
  • 20
  • 2
    One thing to note in windows, when i tried to execute my script like this: subprocess.Popen("./stuff someargs") It told me that the main module is not loaded, until i did it like this subprocess.Popen(["python", "myscript.py"]) – Nash May 17 '17 at 14:31
0

Try this code:

import os

if [condition]:
    os.system('nohup python script1.py &') #start another script in background

if [another condition]:
    pid = os.popen("ps aux | grep script1.py | awk '{print $2}'").readlines()[0] #call pid
    os.system('kill '+pid) #kill process

I'm using python 2.7.12 and Ubuntu 16.04

ysKim
  • 16
  • 2