Copy a file or directory from a Docker container to the local filesystem. The copy operation is recursive for directories. Be extremely careful with trailing slashes in src_path and dest_path, the behavior of docker cp is also different depending on whether the destination exists.
(
container: DockerEnvironment,
src_path: str | Path,
dest_path: str | Path,
)
| 133 | # If not an absolute path, assume relative to container's cwd |
| 134 | dest_path = f"{container.config.cwd}/{dest_path}" |
| 135 | cmd = [ |
| 136 | "docker", |
| 137 | "cp", |
| 138 | str(src_path), |
| 139 | f"{container.container_id}:{dest_path}", |
| 140 | ] |
| 141 | print(f"Copy to container: cmd={cmd}") |
| 142 | # Ensure destination folder exists |
| 143 | assert_zero_exit_code(container.execute(f"mkdir -p {Path(dest_path).parent}")) |
| 144 | result = subprocess.run(cmd, check=False, capture_output=True, text=True) |
| 145 | if result.returncode != 0: |
| 146 | raise RuntimeError( |
| 147 | f"Failed to copy {src_path} to {container.container_id}:{dest_path}: {result.stdout}{result.stderr}" |
| 148 | ) |
| 149 | return result |
| 150 | |
| 151 | |
| 152 | def copy_from_container( |
| 153 | container: DockerEnvironment, |
| 154 | src_path: str | Path, |
| 155 | dest_path: str | Path, |
| 156 | ): |
| 157 | """ |
| 158 | Copy a file or directory from a Docker container to the local filesystem. |
| 159 | |
| 160 | The copy operation is recursive for directories. |
| 161 | |
| 162 | Be extremely careful with trailing slashes in src_path and dest_path, the behavior |
| 163 | of docker cp is also different depending on whether the destination exists. |
| 164 | """ |