I have a Python code which listens and detects environmental sounds. It is not my project, I found it on web (SoPaRe). With the ./sopare.py -l command, it starts recording sounds but in infinite loop. When I want to stop it, I have to press Ctrl+C.

My purpose is to stop this program automatically after 10 seconds, but when I talked with the author he said that the program does not have a time limiter.

I tried to kill it via kill PID, but PID changes every time when program runs. How can stop it after a time interval via bash?

Alternatively, I can execute this command from python with os.system() command.


2 Answers 2


The simplest solution would be to use timeout from the collection of GNU coreutils (probably installed by default on most Linux systems):

timeout 10 ./sopare.py -l

See the manual for this utility for further options (man timeout). On non-GNU systems, this utility may be installed as gtimeout if GNU coreutils is installed at all.

Another alternative, if GNU coreutils is not available, is to start the process in the background and wait for 10 seconds before sending it a termination signal:

./sopare.py -l &
sleep 10
kill "$!"

$! will be the process ID of the most recently started background process, in this case of your Python script.

In case the waiting time is used for other things:

./sopare.py -l & pid=$!
# whatever code here, as long as it doesn't change the pid variable
kill "$pid"

Try this bash script:

#! /bin/bash
./soapre.py -l
PID=`ps u | awk ' $11 == "./soapre.py" { print $2 }'`
sleep 10
kill $PID

I am making an assumption that the sleep 10 command pause only the bash script while the soapre.py is still runing in the background. Also maybe you the COMMAND of ps u column has a different value than "./soapre/py". make your own simple fixes, but this is suppose to work.

  • You don't start anything in the background. If you did (using &), the PID of that process would be available in "$!".
    – Kusalananda
    Nov 24, 2018 at 17:44
  • I thought "$!" will return the PID of the invoking script... good to learn new things. Thanks! (btw i didn't try it with python, but my script is working with a while(1) C program) Also in your solution, you must consider 10 seconds is a lot of time and maybe $! value is no longer what you wanted...
    – Z E Nir
    Nov 24, 2018 at 18:34
  • You have $$ which would be the PID of the current script. Is that what you're thinking of?
    – Kusalananda
    Nov 24, 2018 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.