Lash
Lash

Reputation: 168

Terminating a long command and continue the script

I am developing a testing automation tool using Python that opens the CMD and sends a command through it to hear a sound out of the device. Based on that sound, the user can click whether the sound is there or not (i.e. pass/fail). Unfortunately, the command I am passing keeps running endlessly. I would like to stop it in (let's say 5 secs) which is a suitable time for the tester to determine whether there is a sound or not.

Most of the methods online either use multiprocessing exit which will cause the application to shut off completely, which is not what I want, because after the user determine the existence of the sound, the program needs to run another command that tests the LED light for example, or they use signal.SIGALRM which can be used with a timer that kills processes after some time but it's unavailable for Windows. What do you think I should do? If you can paste a code sample that does that, that would be great. Thanks!

Upvotes: 0

Views: 26

Answers (1)

Maciej Wrobel
Maciej Wrobel

Reputation: 660

Probably you could make use of Timer from threading module (https://docs.python.org/3/library/threading.html) . This is simple example:

import subprocess
import threading 

def terminate(process):
    print('terminating process',process)
    process.kill()
    print('done')
   

   
cmd = [<your command>, <your arguments>,...]


process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
kill_timer = threading.Timer(1, terminate, [process])
try:
    kill_timer.start()
    stdout, stderr = process.communicate()
    print(stdout, stderr)
finally:
    kill_timer.cancel()

It should work on windows machine.

Upvotes: 1

Related Questions