Run command

2 snippets across 2 stacks - Docker, Python

DKDocker

RUN - Execute Build Commands

DK · Dockerfile
Syntax
RUN <command>
RUN ["executable", "arg1", "arg2"]
Example
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt

Note Each RUN creates a new image layer. Combine related commands with && to reduce layers and image size. Always clean up package manager caches in the same RUN statement, or the cache ends up in a previous layer and is never actually removed.

PYPython

subprocess Module

PY · Common Standard Library
Syntax
import subprocess
subprocess.run([cmd, args], capture_output=True)
Example
import subprocess

result = subprocess.run(
    ["echo", "Hello from subprocess"],
    capture_output=True, text=True
)
print(result.stdout.strip())
print(f"Return code: {result.returncode}")
Output
Hello from subprocess
Return code: 0

Note Always pass commands as a list, not a string. Use shell=True only when absolutely necessary - it introduces shell injection risks.

Frequently asked questions

How do you run command?
This task is covered in 2 stacks on this page: Docker, Python. The "RUN - Execute Build Commands" snippet in Docker uses `RUN <command>`.
Which command does the Docker example use?
The "RUN - Execute Build Commands" snippet uses `RUN <command>`, from the Dockerfile section of the Docker cheat sheet.
Which stacks cover "run command" on this page?
Docker, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "RUN - Execute Build Commands": Each RUN creates a new image layer. Combine related commands with && to reduce layers and image size. Always clean up package manager caches in the same RUN statement, or the cache ends up in a previous layer and is never actually removed.