Архив метки: returncode

python перехват вывода внешней программы

>>> from subprocess import check_output
>>> out = check_output(["ping", "-c3", "8.8.8.8"])
>>> out
b'PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=108 time=152 ms\n64 bytes from 8.8.8.8: icmp_seq=2 ttl=108 time=151 ms\n64 bytes from 8.8.8.8: icmp_seq=3 ttl=108 time=46.9 ms\n\n--- 8.8.8.8 ping statistics ---\n3 packets transmitted, 3 received, 0% packet loss, time 2004ms\nrtt min/avg/max/mdev = 46.872/116.565/152.004/49.283 ms\n'
>>>

Способ работает только если вызванная программа завершилась без ошибок. Если хотим предусмотреть ошибки:

import subprocess as sp

# ok
pipe = sp.Popen( 'ls /bin', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])
for line in res[0].decode(encoding='utf-8').split('\n'):
  print(line)

# with error
pipe = sp.Popen( 'ls /bing', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])


proc = subprocess.Popen(["notepad.exe",],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()