Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python capture subprocess output after termination

I am trying to get subprocess output (on Windows) at the time the TimeoutExpired exception is raised. Any ideas?

try:
    proc = subprocess.run(cmd,timeout=3)
except subprocess.TimeoutExpired:
    print(???)
like image 998
Ali_G Avatar asked Apr 20 '17 13:04

Ali_G


1 Answers

You need to use Popen and subprocess.PIPE in order to catch the process output when timeout expires. In particular Popen.communicate is what you need. Here is an example

proc = subprocess.Popen(["ping", "192.168.1.1"],
                        stdout=subprocess.PIPE)

try:
    output, error = proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
    proc.kill()
    output, error = proc.communicate()
    print(output)
    print(error)

This will print the process output up to the time out expiration.

like image 120
lch Avatar answered Oct 02 '22 16:10

lch