Rdrocks09
Rdrocks09

Reputation: 133

Find execution time for subprocess.Popen python

Here's the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:

proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT,  # Merge stdout and stderr 
stdout=subprocess.PIPE,
shell=True)

The subprocess module does not support execution-time and if it exceeds specific threshold => timeout(ability to kill a process running for more than X number of seconds)

What is the simplest way to implement get_execution_time and timeout in Python2.6 program meant to run on Linux?

Upvotes: 8

Views: 9438

Answers (1)

MOPO3OB
MOPO3OB

Reputation: 403

Good question. Here is the complete code for this:

import time, subprocess                                   # Importing modules.

timeoutInSeconds = 1                                      # Our timeout value.

cmd   =  "sleep 5"                                        # Your desired command.
proc  =  subprocess.Popen(cmd,shell=True)                 # Starting main process.

timeStarted = time.time()                                 # Save start time.

cmdTimer     =  "sleep "+str(timeoutInSeconds)            # Waiting for timeout...
cmdKill      =  "kill "+str(proc.pid)+" 2>/dev/null"      # And killing process.
cmdTimeout   =  cmdTimer+" && "+cmdKill                   # Combine commands above.
procTimeout  =  subprocess.Popen(cmdTimeout,shell=True)   # Start timeout process.

proc.communicate()                                        # Process is finished.

timeDelta = time.time() - timeStarted                     # Get execution time.
print("Finished process in "+str(timeDelta)+" seconds.")  # Output result.

Upvotes: 5

Related Questions