How to make subprocess run for 60 sec?
Akira Li
4kir4.1i at gmail.com
Fri Dec 12 15:41:02 EST 2014
Dan Stromberg <drsalists at gmail.com> writes:
> 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)
You should probably call p.wait() after p.send_signal(), to wait until
the child process exits (possibly properly flushing its stdout buffer).
It might make the output.txt content less garbled.
>
> 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.
The answer on StackOverflow [1] shows how to avoid waiting n seconds if the
subprocess finishes sooner.
[1] http://stackoverflow.com/questions/27443480/how-to-make-subprocess-run-for-60-sec
> 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.
--
Akira
More information about the Python-list
mailing list