Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 341
Rdrocks09 Avatar asked Aug 03 '17 19:08

Rdrocks09


People also ask

Does Popen have a timeout?

The timeout argument is passed to Popen. communicate() . If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

What is subprocess popen ()?

The subprocess. popen() is one of the most useful methods which is used to create a process. This process can be used to run a command or execute binary. The process creation is also called as spawning a new process which is different from the current process.

Does subprocess call wait for completion?

The subprocess module provides a function named call. This function allows you to call another program, wait for the command to complete and then return the return code.

What is the difference between subprocess run and subprocess Popen?

The main difference is that subprocess. run executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess. communicate yourself to pass and receive data to your process.


1 Answers

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.
like image 135
MOPO3OB Avatar answered Oct 02 '22 21:10

MOPO3OB