Current File : //etc/node_exporter/runner_proc3
#!/usr/bin/env python3

import os
import signal
import subprocess
import sys
from threading import Timer

pathScripts = "/etc/node_exporter/scripts"
pathText = "/etc/node_exporter/text"

#pathScripts = "./scripts_test"
#pathText = "./text_test"

f = sys.argv[1]

myCmd = "%s/%s" % (pathScripts,f)

def kill():
    print(p.pid)
    os.kill(os.getpgid(p.pid), signal.SIGTERM)

print("####################")
print("cmd: ", myCmd)

p = subprocess.Popen(myCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

timer = Timer(30, kill)

try:
    timer.start()
    (output, err) = p.communicate()
    p_status = p.wait()

    print("err: ", err.decode('utf-8'))
    print("output: ", output.decode('utf-8'))
    print("exit code: ", p_status)

    if p_status == 0 and len(err) == 0:
        filePath = "%s/%s.prom" % (pathText, f)
        f = open(filePath, "w")
        f.write(output.decode('utf-8'))
        f.close()
    else:
        print(output.decode('utf-8'))
        print(p_status)
finally:
    timer.cancel()