从环境变量读取端口,如果未设置或已被占用,则从default_start开始寻找空闲端口
(env_key: str, default_start: int)
| 48 | |
| 49 | |
| 50 | def get_available_port(env_key: str, default_start: int): |
| 51 | """从环境变量读取端口,如果未设置或已被占用,则从default_start开始寻找空闲端口""" |
| 52 | port_str = os.environ.get(env_key) |
| 53 | if port_str and port_str.isdigit(): |
| 54 | port = int(port_str) |
| 55 | if not is_port_in_use(port): |
| 56 | return port |
| 57 | else: |
| 58 | print(f"Warning: Port {port} from {env_key} is in use, searching for a free port...") |
| 59 | |
| 60 | # 从 default_start 开始查找空闲端口 |
| 61 | port = default_start |
| 62 | while is_port_in_use(port): |
| 63 | port += 1 |
| 64 | return port |
| 65 | |
| 66 | |
| 67 | # 默认参数值 |
no test coverage detected