Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.run()'s output is empty

Below is the command:

    try:
        op = subprocess.run(['docker', 'login', '-u', 'username', '-p', 'password', 'dockerhub.com'], check=True, stdout=sys.stdout, stderr=subprocess.PIPE)
        print("Docker stdout :", op.stdout)
        print("Docker Error :", op.stderr.decode("utf-8"))
    except:
    traceback.print_exc()

It's working good, when the right password is provided and the 2 print statements are working as expected.

Login Succeeded
Docker stdout : None
Docker Error :

In case of incorrect password, I would like to capture the output as seen while running on the shell(bash), like below:

Error response from daemon: Get https://dockerhub.com/v2/: unknown: Bad credentials

instead I receive the traceback, where the above error message is not seen.

Traceback (most recent call last):
  File "/home/scripts/test.py", line 54, in my_func
    op = subprocess.run(['docker', 'login', '-u', 'username', '-p', 'incorrectpassword', 'dockerhub.com'], check=True, stdout=sys.stdout, stderr=subprocess.PIPE)
  File "/usr/local/lib/python3.5/subprocess.py", line 708, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['docker', 'login', '-u', 'username', '-p', 'incorrectpassword', 'dockerhub.com']' returned non-zero exit status 1
Traceback (most recent call last):
like image 501
Chel MS Avatar asked Apr 02 '26 04:04

Chel MS


1 Answers

You can also catch the subprocess.CalledProcessError Exception. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

try:
    op = subprocess.run(['docker', 'login', '-u', 'username', '-p', 'password', 'dockerhub.com'], check=True, stdout=sys.stdout, stderr=subprocess.PIPE)
    print("Docker stdout :", op.stdout)
except subprocess.CalledProcessError as e:
    exit_code = e.returncode
    stderror = e.stderr
    print(exit_code, stderror)
like image 152
Abdul Niyas P M Avatar answered Apr 08 '26 06:04

Abdul Niyas P M