Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a subprocess to suspend execution of an external program every 5 seconds?

Given an external program, which for this example is python target.py:

target.py

import time, itertools
A = itertools.count()
while True:
    time.sleep(.1)
    print A.next()

I'm looking for a way to run the command, which we can assume I have no control over other than starting and stopping, for 5 seconds. At that point, I'd like to suspend execution (similar to control-Z on linux, which is my target platform), run some internal code then continue the execution of the subprocess. So far I've got

reader.py

import subprocess, signal, time

cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)

while True:
   time.sleep(5)
   signal.pause(P)  # Not the correct way to suspend P
   print "doing something"
   signal.wakeup(P) # What is called here?
like image 305
Hooked Avatar asked Nov 29 '22 00:11

Hooked


1 Answers

You can also use psutil and avoid the scary-looking os.kill:

import psutil, time, subprocess

cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)
psProcess = psutil.Process(pid=P.pid)

while True:
    time.sleep(5)
    psProcess.suspend()
    print 'I am proactively leveraging my synergies!'
    psProcess.resume()
like image 187
Rolf Andreassen Avatar answered Dec 10 '22 16:12

Rolf Andreassen