使用Python修改docker-compose.yml添加ports配置缩进错误问题
问题根因
原有代码无法生成正确缩进的核心问题有3个:
- 缩进处理逻辑错误:
rjust(count_spaces)的作用是将字符串填充到总长度为count_spaces,而示例中获取的count_spaces是system_frontend下子项的前导空格数(值为4),但ports:\n本身长度为6,大于4,调用rjust不会添加任何空格,自然无法得到正确缩进。 - 操作冗余:先插入无缩进内容再修改缩进,容易引入格式错误。
- 边界场景未处理:如果
system_frontend:是文件最后一行,取lst[index+1]会直接触发索引越界报错。
修正方案
直接在遍历行的时候,匹配到system_frontend:节点后,读取它下一个非空行的前导空格数作为缩进标准,拼接好带正确缩进的ports配置直接插入即可,不需要事后修改缩进。修正后的代码如下:
def make_file(): read_file = r'C:\Users\~\Desktop\sample.yml' write_file = r'C:\Users\~\Desktop\sample_out.yml' with open(read_file, 'r', encoding='utf-8') as f: lines = f.readlines() output_lines = [] found_frontend = False ports_added = False # 可自行修改ports下的端口映射规则,子项缩进比ports层级多2个空格,符合常规YAML写法 ports_content = 'ports:\n - "0.0.0.0:5000:80"\n' for line in lines: output_lines.append(line) # 匹配到system_frontend服务节点 if not found_frontend and "system_frontend:" in line: found_frontend = True continue # 找到节点下第一个非空行,获取同级缩进,插入ports配置 if found_frontend and not ports_added and line.strip(): space_count = len(line) - len(line.lstrip(' ')) indent = ' ' * space_count output_lines.append(f"{indent}{ports_content}") ports_added = True with open(write_file, 'w', encoding='utf-8') as f: f.writelines(output_lines)
执行效果
修改后生成的docker-compose.yml对应片段如下,完全符合YAML语法规范:
services: system_frontend: ports: - "0.0.0.0:5000:80" image: ${DOCKER_REGISTRY}/frontend:${CONTAINER_VERSION} logging: *id001 environment: SSL_CERTIFICATE: ${SSL_CERTIFICATE:-} SSL_CERTIFICATE_KEY: ${SSL_CERTIFICATE_KEY:-} ENABLE_CORS: ${ENABLE_CORS:-} FRONTEND_URL: ${FRONTEND_URL:-} METRICS_PUSHGATEWAY: ${METRICS_PUSHGATEWAY:-} volumes: - ssl-volume:/etc/nginx/ssl networks: system_network: null restart: unless-stopped depends_on: - webapi
如果需要调整ports插入的位置(比如放到depends_on前面),只需要修改插入判断条件即可,缩进逻辑不需要改动。
内容的提问来源于stack exchange,提问作者johnny k
相关产品推荐
相关产品推荐

