-1

Can some please guide, why command is not timing out. Below is my Python code

python
>>>from subprocess import Popen, PIPE
>>>command="timeout 5 su - user -c \"user admin display_states\""
>>>print command
timeout 5 su - user "user admin display_states"
>>>process=Popen(command, stdout=PIPE, stderr=PIPE, shell=TRUE)
>>>(output,error)=process.communicate()
(Doesn't terminate after 5 seconds)

Execution on cmd prompt:

Linux>timeout 5 su - user -c "user admin display_states"
Session terminated, killing shell... ...killed.

I expect the timeout command to terminate after 5 seconds, which is not happening in my Python code.

user1993412
  • 802
  • 2
  • 15
  • 29

1 Answers1

0

Python has no control over the timeout command. Presumably the subprocess has already buffered much more output than you have been able to consume when it times out, and so it looks like it's still running, even though it's really not.

The workaround is simple in this case, though; use a timeout from Python instead.

process = subprocess.run(["su", "-", "user", "-c", "user admin display_states"], timeout=5, text=True, capture_output=True)
# output, error = process.stdout, process.stderr

You should generally prefer subprocess.run over bare Popen for the cases it can handle, though if you really need to, there is also a timeout parameter for the communicate method of Popen.

Tangentially, notice also how we avoid shell=True by passing the command as a list; you generally want to.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • `subprocess.run` is not available in Python 2; I don't think it supported any sort of timeout mechanism. – tripleee Jan 25 '22 at 20:59