You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python 3.11程序中获取本地Redis服务器的运行端口

获取本地Redis运行端口的Python实现方案

问题背景

我正在开发一个Python 3.11程序,要在多台不同服务器上运行,需要连接本地Redis服务器。每台机器上的Redis运行端口不一定是默认的6379,可能有变化。目前我在Linux和MacOS上可以通过以下命令获取端口:

sudo lsof -n -i -P | grep LISTEN | grep IPv4 | grep redis

执行后输出示例:

redis-ser 60014            bob    8u  IPv4 0x84cd01f56bf0ee21      0t0    TCP *:9001 (LISTEN)

想知道有没有更优的Python函数/库方法来获取Redis的运行端口。


方法1:解析Redis配置文件

Redis的配置文件中明确定义了port参数,直接读取并解析这个文件是最可靠的方式:

def get_redis_port_from_config(config_path="/etc/redis/redis.conf"):
    try:
        with open(config_path, 'r') as f:
            for line in f:
                line = line.strip()
                # 跳过注释和空行
                if not line or line.startswith('#'):
                    continue
                if line.startswith('port '):
                    return int(line.split()[1])
        # 未找到port配置时返回默认值
        return 6379
    except FileNotFoundError:
        # 配置文件不存在时返回默认值,也可根据需求抛出异常
        return 6379

注意:需确保程序有配置文件的读取权限;若Redis启动时指定了自定义配置路径,需将路径传入函数。

方法2:通过Python调用系统命令解析输出

用subprocess模块封装你当前的命令,自动解析输出提取端口:

import subprocess
import re

def get_redis_port_from_lsof():
    try:
        result = subprocess.run(
            ['sudo', 'lsof', '-n', '-i', '-P'],
            capture_output=True,
            text=True,
            check=True
        )
        # 正则匹配Redis监听的IPv4端口
        pattern = re.compile(r'redis-ser.*IPv4.*TCP \*:(\d+) \(LISTEN\)')
        for line in result.stdout.splitlines():
            match = pattern.search(line)
            if match:
                return int(match.group(1))
        return 6379
    except subprocess.CalledProcessError:
        # 命令执行失败(如无sudo权限)时返回默认值
        return 6379

注意:该方法需要程序拥有sudo权限,否则lsof无法获取完整进程信息。

方法3:端口探测连接验证

若不确定配置文件路径或不想使用sudo权限,可尝试连接常见Redis端口,验证可用端口:

import redis

def detect_redis_port():
    # 可根据实际场景扩展常见端口列表
    common_ports = [6379, 9001, 6380, 6381]
    for port in common_ports:
        try:
            r = redis.Redis(host='localhost', port=port, socket_timeout=1)
            # 执行ping命令验证连接有效性
            r.ping()
            return port
        except redis.ConnectionError:
            continue
    # 所有端口连接失败时返回默认值,也可抛出异常
    return 6379

注意:需先安装redis-py库:pip install redis;若Redis设置了密码,需在连接时添加password参数。


内容的提问来源于stack exchange,提问作者Robert Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:15:25