пятница, 6 сентября 2019 г.

Узнать код ошибки при запуске команды из python 3 / run shell command on python 3 and get error code

Вместо старой функции popen() лучше использовать более новую check_output(), которая возвращает результат, если код ошибки равен нулю (то есть нет ошибок) или генерирует исключение, из которого можно получить код ошибки и результат работы команды.

import sys
import subprocess

def runCommand(command):
    output = None

    try:
        # run shell command
        output = subprocess.check_output(command, shell=True)
    except subprocess.CalledProcessError as procErr:                
        # handle exception
        print("command \"{0}\" returned error code \"{1}\"".format(command, procErr.returncode))
        errCommandResult = procErr.output.decode(sys.stdout.encoding).strip()
        print("error output: '{0}' ".format(errCommandResult))
        print(errCommandResult)
        return None

    # no exception - just get output of shell command
    successCommandResult = output.decode(sys.stdout.encoding).strip()
    print(successCommandResult)
    return successCommandResult

runCommand("echo hello error & exit 1")
runCommand("dir")


Результат работы будет, например, такой:

D:\projects\SampleApp>python  my.py
command "echo hello error & exit 1" returned error code "1"
error output: 'hello error'
hello error

Volume in drive D has no label.

Volume Serial Number is 72A1-8BB5

Directory of D:\projects\SampleApp

09/06/2019  01:31 PM    <DIR>          .
09/06/2019  01:31 PM    <DIR>          ..
09/03/2019  12:55 PM    <DIR>          bin
09/02/2019  05:17 PM    <DIR>          data
09/06/2019  02:43 PM    <DIR>          make
09/06/2019  03:14 PM     703           my.py
09/02/2019  06:45 PM    <DIR>          prj
09/02/2019  06:12 PM    <DIR>          source
09/02/2019  05:17 PM    <DIR>          tools
               1 File(s)         11,763 bytes
               8 Dir(s)  543,462,584,320 bytes free
D:\projects\SampleApp>