How to make subprocess run for 60 sec?

Dan Stromberg drsalists at gmail.com
Fri Dec 12 12:41:45 EST 2014


On Fri, Dec 12, 2014 at 12:48 AM, Robert Clove <cloverobert at gmail.com> wrote:
> Hi All,
>
> I have the following python script that runs.
> I want is to run the subprocess to run for 60 sec and then send the SIGINT
> signal to subprocess and write the output in file.
>
> #!/usr/bin/python
> import os
> import subprocess
> PIPE = subprocess.PIPE
> import signal
> import time
>
> def handler(signum, frame):
>     pass
>
> signal.signal(signal.SIGALRM, handler)
> signal.alarm(60)
> command = "strace -c ./server"
> os.chdir("/root/Desktop/")
> p = subprocess.Popen(command, stdout=PIPE, stderr=PIPE)
> time.sleep(60)
> p.send_signal(signal.SIGINT)
> signal.alarm(0)
> print p.communicate()[1]

Perhaps try something like:

#!/usr/bin/python

#import os
import subprocess
PIPE = subprocess.PIPE
import signal
import time

#def handler(signum, frame):
#    pass

with open('output.txt', 'w') as out_file:
    #signal.signal(signal.SIGALRM, handler)
    #signal.alarm(60)
    #command = "strace -c ./server"
    command = "./test-script"
    #os.chdir("/root/Desktop/")
    p = subprocess.Popen(command, stdout=out_file, stderr=out_file, shell=True)
    time.sleep(5)
    p.send_signal(signal.SIGINT)
    #signal.alarm(0)
    #print p.communicate()[1]

with open('output.txt', 'r') as in_file:
    output = in_file.read()

print(output)


BTW, killing an active strace may leave strace's subprocess stuck in
an unkillable state.

Also note that this will sleep for n seconds whether the subprocess
takes that long or not.

If you just want a program that does this, and it doesn't have to be
in Python, you might try
http://stromberg.dnsalias.org/~strombrg/maxtime.html
It's in C, and is the product of considerable real-world use.  It
exits almost immediately after its subprocess exits, FWIW.



More information about the Python-list mailing list