Hayat
Hayat

Reputation: 1639

Executing popen with timeout

So am trying to execute Linux command specifically via subprocess.popen(). I want to wait only 30 secs for this command to execute because in certain scenarios my command hangs and program wait's forever. Below is the 2 approaches I used.

Approach 1

cmd = "google-chrome  --headless  --timeout=30000  --ignore-certificate-errors --print-to-pdf out.pdf https://www.google.com/
process = subprocess.call(cmd, shell=True)
process.wait() # Here I want to wait only till 30 secs and not untill process completes

Approach 2

from multiprocessing import Process
p1 = Process(target=subprocess.call, args=(cmd,))
        processTimeout = 50
        p1.start()
        p1.join(processTimeout)
        if p1.is_alive():
            p1.terminate()

In the 2nd approach file is not even being created. Please suggest an option.

Upvotes: 4

Views: 7123

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50096

The Popen.wait takes an optional timeout parameter. You an use this to wait for completion only for a specific time. If the timeout triggers, you can terminate the process.

process = subprocess.call(cmd)
try:
    # if this returns, the process completed
    process.wait(timeout=30)
except subprocess.TimeoutExpired:
    process.terminate()

Since Python 3.5, you can also use the subprocess.run convenience function.

subprocess.run(cmd, timeout=30)

Note that this will still raise TimeoutExpired but automatically terminate the subprocess.

Upvotes: 6

Related Questions