The error you're encountering:
python3: can't open file '//test_add.py': [Errno 2] No such file or directory
suggests that when you're writing the file test_add.py using exec_run, it's being created with an unexpected path — specifically, it's ending up as //test_add.py (notice the double slash), which is not a valid or intended location inside the container.
Root Cause
This issue is likely due to how the shell interprets the command string passed to container.exec_run(). When you do:
container.exec_run(f"echo '{tests}' > test_add.py")
you're relying on a shell redirection (>), but exec_run() by default does not run the command through a shell unless you explicitly tell it to by setting shell=True.
Without a shell, the > redirection is passed as an argument to echo, which doesn't interpret it as redirection — instead, the > and the filename are treated literally as arguments, and echo just prints them. However, in many Docker base images, especially minimal ones, echo may be a builtin or behave differently, and the output redirection might end up creating a file with an odd name like //test_add.py, possibly due to how the arguments are parsed or misinterpreted.
Alternatively, some environments may interpret the path strangely when not using a proper shell.
✅ Recommended Fix
Use shell=True to ensure the command is interpreted by a shell, which will correctly handle the redirection:
container.exec_run(f"echo '{tests}' > test_add.py", shell=True)
container.exec_run('python3 test_add.py', shell=True)
However, be cautious with shell=True if tests includes unsanitized user input, as it could lead to shell injection vulnerabilities.
✅ Better Alternative: Use write_file
A safer and cleaner approach is to use Docker SDK’s built-in method to write files into the container, avoiding shell involvement entirely:
container.put_archive("/path/to/dir", ...) # Not ideal for single file
# OR better: use exec_run with echo and a here-string or redirect via a temporary file, but that's clunky.
# Instead, for a single file, you can use a multi-step workaround:
# Write the content to a file locally, then copy into container:
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write(tests)
temp_path = f.name
# Copy the file into the container
with open(temp_path, 'rb') as f:
container.put_archive('/app', (f.read(), 'test_add.py')) # Wait, no: put_archive is for dirs
# Correction: use exec_run with echo via a pipe, or better: use docker's copy mechanism
# But for one file, the cleanest way is to use the container's filesystem directly via exec_run and echo with shell=True
# So, reverting to:
container.exec_run(f"echo '{tests}' > /test_add.py", shell=True)
container.exec_run('python3 /test_add.py', shell=True)
Wait — but again, that uses shell=True.
But even better than both: use container.exec_run to run bash -c or similar, or — better yet — avoid all that and use docker.types.ExecStartCheck and exec_run with stdin, or better: use the container.put_file() workaround... but there's no put_file() in the Docker SDK.
Wait, actually, the SDK has no direct put_file() but you can emulate it:
✅ Best Practice (No Shell, Safe):
Use container.exec_run() to invoke cat with a pipe via stdin:
container.exec_run(
cmd=["sh", "-c", "cat > /test_add.py"],
input=tests.encode('utf-8')
)
container.exec_run(["python3", "/test_add.py"])
Wait, no — input is not directly passed to exec_run like that. My mistake.
Correct way to pass stdin:
container.exec_run(
cmd=["sh", "-c", "cat > /test_add.py"],
stdin=tests.encode('utf-8')
)
container.exec_run(["python3", "/test_add.py"])
BUT: this still doesn’t work as expected because cat > file waits for EOF on stdin — and exec_run's stdin is just a one-time send.
So the correct and reliable way is:
✅ Final Correct Solution
Use echo or printf with shell=True, or use base64 + base64 -d, or — best:
Use Python to write to a file, then copy into container:
import tempfile
import docker
client = docker.from_env()
container = client.containers.get("your_container_id")
# Write test content to a temp file
with tempfile.NamedTemporaryFile(delete=False, mode='w') as f:
f.write(tests)
tmp_path = f.name
# Read it back and upload to container
with open(tmp_path, 'rb') as f:
data = f.read()
# Create the file inside container at desired path
container.put_archive("/tmp", (data, "test_add.py")) # WRONG: put_archive only takes a directory!
# OOPS! put_archive is for directories. So we need to create a tar archive on-the-fly.
import io
import tarfile
# Create an in-memory tar file
tar_buffer = io.BytesIO()
with tarfile.open(fileobj=tar_buffer, mode='w') as tar:
tarinfo = tarfile.TarInfo(name="test_add.py")
tarinfo.size = len(data)
tarinfo.mtime = int(time.time())
tar.addfile(tarinfo, io.BytesIO(data))
tar_buffer.seek(0)
# Copy into container at / (or wherever)
container.put_archive("/", tar_buffer)
# Or more accurately, place it where needed
# Now you can:
container.exec_run(["python3", "/test_add.py"])
Wait — this is getting too complex. For a single file, the best practice is:
✅ Easiest and Correct Way: Use exec_run with shell=True and redirection
container.exec_run(f"echo '{tests}' > /test_add.py", shell=True)
container.exec_run("python3 /test_add.py", shell=True)
But make sure / exists and is writable. If not, choose another existing directory like /app.
✅ TL;DR – Fix Your Code Like This:
container.exec_run(f"echo '{tests}' > /test_add.py", shell=True)
container.exec_run("python3 /test_add.py", shell=True)
Ensure the file is written to an absolute path (like /test_add.py) to avoid confusion from relative paths (like ./test_add.py or unintended //test_add.py).
Also, make sure the working directory is set properly if needed — but exec_run runs commands in / by default unless you specify workdir in the container or use cwd in newer Docker SDK versions (it doesn't support cwd directly, so use full paths).
✅ Bonus Tip: Debug File Location
To debug where the file is being created, you can run:
container.exec_run("find / -name test_add.py 2>/dev/null")
to locate it.
Summary
Problem:
Your file is being written to an unexpected path like //test_add.py likely due to lack of shell handling redirection (>), and possibly because of how the command is tokenized without a shell.
Solution:
Use shell=True to ensure proper redirection, or — better — use container.put_archive() to transfer the file safely. For quick testing, the shell=True method is fine:
container.exec_run(f"echo '{tests}' > /test_add.py", shell=True)
container.exec_run("python3 /test_add.py", shell=True)