创建临时容器的上下文管理器
(self)
| 133 | |
| 134 | @contextlib.contextmanager |
| 135 | def _temp_container(self): |
| 136 | """创建临时容器的上下文管理器""" |
| 137 | container_id = None |
| 138 | try: |
| 139 | with self._container_lock: |
| 140 | # 创建临时容器 |
| 141 | cmd = f"docker create {self.image_id}" |
| 142 | result = subprocess.run(cmd.split(), capture_output=True, text=True) |
| 143 | if result.returncode != 0: |
| 144 | raise Exception(f"创建临时容器失败: {result.stderr}") |
| 145 | |
| 146 | container_id = result.stdout.strip() |
| 147 | self._active_containers.add(container_id) |
| 148 | |
| 149 | yield container_id |
| 150 | |
| 151 | finally: |
| 152 | if container_id: |
| 153 | with self._container_lock: |
| 154 | try: |
| 155 | # 清理临时容器 |
| 156 | subprocess.run(['docker', 'rm', container_id], |
| 157 | capture_output=True, |
| 158 | check=True) |
| 159 | self._active_containers.remove(container_id) |
| 160 | except Exception as e: |
| 161 | # public.print_log(f"清理临时容器失败 {container_id}: {str(e)}") |
| 162 | pass |
| 163 | |
| 164 | def listdir(self, path): |
| 165 | """列出指定路径下的所有文件和目录""" |