python読み取りファイルの一括インポートredisを実現

1144 ワード

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis  #pip install redis
import os


#    1000ip.txt        redis    10.0.1.137:6379       
def push_redies(redis_svr, filename, db_num):  #redis_svr  10.0.1.138:6379
    count = 0
    svr_lst = redis_svr.split(':')         
    
    
    rds = redis.Redis(host=svr_lst[0],
                    port=svr_lst[1] if len(svr_lst)>1 else 6379,
                    db=db_num)          
    

    #                ,      、       
    # pool = redis.ConnectionPool(host = svr_lst[0],
    #                             port=svr_lst[1] if len(svr_lst)>1 else 6379,
    #                             db=db_num)
    # rds= redis.Redis(connection_pool = pool)

    key = os.path.basename(filename).split('.')[0]   #        
    with open(filename) as fp:
        for line in fp:
            # line = line.strip()
            wlist = line.split(",",1)
            rds.rpush(key, line)
            count += 1
    print count  #      

push_redies("10.0.1.137:6379","2.txt",4)
#  push_redies("10.0.1.137","1000ip.txt",4)