Getting “docker ps” accepts no arguments error in Python Subprocess module

I want to get the output of the command docker ps -a --format '{{json .}}' using Python Subprocess module in Flask web server

But I’m getting the following error
"docker ps" accepts no arguments

Works with docker ps -a command but fails with docker ps -a --format '{{json .}}' command

Here is the code

@app.route('/get_docker_container_details', methods=['GET'])
def get_docker_container_details():

    command = "docker ps -a --format '{{json .}}'"
    cmd = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = cmd.communicate()
    logger.info(output)
    logger.info(error)
    return Response()

Here is the log


INFO:automater_agent:b''
INFO:automater_agent:b'"docker ps" accepts no arguments.\nSee \'docker ps --help\'.\n\nUsage:  docker ps [OPTIONS]\n\nList containers\n'
INFO:werkzeug:172.23.100.228 - - [08/Jan/2024 12:09:51] "GET /get_docker_container_details HTTP/1.1" 200 -

The command in terminal is running ok. But I’m getting error in Flask server

So How to solve it?

Thanks.

  • 2

    Don’t use subprocess.Popen(command.split(). Make the list yourself. The reason it receives a list is exactly to avoid this issue.

    – 

  • 2

    To make it clearer: You will create the list ['docker', 'ps', '-a', '--format', "'{{json", ".}}'"] which makes .}}' a positional argument. And docker ps does not accept positional arguments.

    – 

  • Also consider using the Docker SDK for Python rather than shelling out to docker commands; it will be a more Pythonic interface and you’ll have fewer shell-quoting problems like this.

    – 

It should be

command = ['docker', 'ps', '-a', '--format', "'{{json .}}'"]
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

If we split the list, the list becomes ['docker', 'ps', '-a', '--format', "'{{json", ".}}'"] which makes ‘.}}’ a positional argument. And docker ps does not accept positional arguments.

Thanks @KlausD. and @zvone

Leave a Comment