In python I want to start another python script as background process and after few sec I need to kill that spawned process and get the stdout into a variable.
I tried with subprocess.Popen
, I am able to spawn as background process and kill after few secs. But atlast while redirecting stdout to a variable it gets blocked.
Can someone suggest me to fix it ? Or is there any other module available to do this other than subprocess.Popen
?
g_flag = 0
class StartChecking(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
global g_flag
print 'Starting thread'
proc = subprocess.Popen(["./cmd.py"], stdout=subprocess.PIPE, shell=True)
pid = proc.pid
print 'Sniff started ' + str(pid)
if (pid != 0) and (pid != 1):
while g_flag == 0:
sleep(0.1)
os.kill(pid, signal.SIGTERM)
print 'Killed ' + str(pid)
(out, err) = proc.communicate() # Currently its blocking here
print out
th = StartChecking()
th.start()
#Do something else
sleep(5)
g_flag = 1
th.join()
print 'thread joined'
Output is
Starting thread
Sniff started 24294
Killed 24294
Note : Using Python 2.7.12
in ubuntu 16.04
.